feat(cli): auto-steer ping-peer messages into active peer turns (#2298)

* refactor(shared): describe steering support with a per-flavor capability table

Replace the flavor comparison chains in isSteeringSupportedForFlavor and
isSteeringSupportedForSession with a table keyed by flavor, so a protocol
restriction such as legacy Cursor sessions sits next to the flavor it applies
to. Results are unchanged for every flavor and Cursor session shape.

* feat(cli): auto-steer ping-peer messages into active peer turns

Peer messages in auto mode only steered Codex turns. Record each flavor's
active-turn signal in the steering capability table, expose it as
hasActiveSteeringTurn(), and use it in both the peer sender and the waiting
queue's Steer gate, so remote Claude, Pi, OpenCode and Cursor ACP targets with
an active, steerable turn also get the queued message steered into it.

Auto still stores one ordinary queued message first and attempts the existing
steer action at most once. A steer that the hub rejects or that stays
unconfirmed keeps the accepted message without resending, and the receipt now
says which of "not attempted", "rejected by hub" or "not confirmed" applied.
Inactive targets, --wake, explicit steer and explicit queue are unchanged.

* fix(cli): keep ping-peer steer notes accurate when delivery is unresolved

Auto receipts reported every unsuccessful steer response as "rejected by hub"
and promised the message stays queued. Only a refusal before any native steer
is dispatched (an HTTP 4xx, or a Hub failure without a localId) is definitive.
A failure that carries a localId, such as an RPC timeout or an OpenCode steer
that is still being reconciled, now reads "steer not confirmed; delivery
unresolved" without promising queued delivery.

Auto notes for a skipped steer used the explicit-steer refusal text, so an
accepted receipt could say "no message sent". They now use separate reasons
(for example "target is idle"); explicit steer wording is unchanged.
This commit is contained in:
Junmo Kim
2026-11-07 08:13:48 +08:00
committed by GitHub
parent 0b82bd7658
commit 5ce30b20c9
13 changed files with 579 additions and 103 deletions
@@ -0,0 +1,257 @@
import { describe, expect, it, vi } from 'vitest'
import { pingPeer, exitCodeForPingPeerError, PingPeerError, type PingPeerSessionSummary } from './pingPeer'
const sessionId = '99999999-1111-4111-8111-111111111111'
const flavors = ['claude', 'codex', 'opencode', 'pi', 'cursor'] as const
type Flavor = typeof flavors[number]
type Response = { status: number; data: unknown }
type Submission = { text: string; localId: string; deliveryMode?: string }
function target(flavor: Flavor, active = true, steering = true): PingPeerSessionSummary {
return {
id: sessionId, active, thinking: steering,
metadata: {
flavor,
...(flavor === 'pi' ? { piSessionId: 'synthetic-pi' } : {}),
...(flavor === 'cursor' ? { cursorSessionProtocol: 'acp' as const } : {})
},
agentState: { steeringActive: steering }
}
}
function transport(initial: PingPeerSessionSummary, options: {
steer?: Response | Error
send?: Response | Error
live?: PingPeerSessionSummary
afterResume?: PingPeerSessionSummary
} = {}) {
let current = options.live ?? initial
const rows: Submission[] = []
const steers: string[] = []
const http = {
get: vi.fn(async (url: string) => url.endsWith('/api/sessions')
? { status: 200, data: { sessions: [initial] } }
: { status: 200, data: { session: current } }),
post: vi.fn(async (url: string, body?: unknown) => {
if (url.endsWith('/api/auth')) return { status: 200, data: { token: 'synthetic-jwt' } }
if (url.endsWith('/resume')) {
current = options.afterResume ?? { ...current, active: true }
return { status: 200, data: { type: 'success', sessionId } }
}
if (url.endsWith('/messages')) {
rows.push(body as Submission)
if (options.send instanceof Error) throw options.send
return options.send ?? { status: 200, data: { ok: true } }
}
if (url.endsWith('/steer')) {
steers.push(url)
if (options.steer instanceof Error) throw options.steer
return options.steer ?? { status: 200, data: { status: 'steered' } }
}
throw new Error(`Unexpected synthetic route ${url}`)
})
}
return {
rows, steers, http,
input: { sessionIdPrefix: sessionId, message: 'Synthetic peer update',
apiUrl: 'http://hub.test', accessToken: 'synthetic-access', http: http as never }
}
}
describe.each(flavors)('auto delivery to %s', (flavor) => {
it.each([undefined, 'auto'] as const)('steers an eligible active turn with mode %s using one ordinary queued row', async (deliveryMode) => {
const t = transport(target(flavor))
const result = await pingPeer({ ...t.input, deliveryMode })
expect(result.delivery).toBe('steered')
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([`http://hub.test/api/sessions/${sessionId}/messages/${result.localId}/steer`])
})
it('queues an idle target without a steer request', async () => {
const t = transport(target(flavor, true, false))
const result = await pingPeer({ ...t.input, deliveryMode: 'auto' })
expect(result.delivery).toBe('accepted')
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([])
})
it('queues when concurrent control is explicitly disabled for a local target', async () => {
const session = target(flavor)
session.agentState = { steeringActive: true, controlledByUser: true }
session.metadata = { ...session.metadata, capabilities: { concurrentClients: false } }
const t = transport(session)
expect((await pingPeer({ ...t.input, deliveryMode: 'auto' })).delivery).toBe('accepted')
expect(t.rows).toHaveLength(1)
expect(t.steers).toEqual([])
})
it('resumes an inactive target and queues even if the resumed turn reports steering ready', async () => {
const t = transport(target(flavor, false), { afterResume: target(flavor) })
const result = await pingPeer({ ...t.input, deliveryMode: 'auto', wake: true })
expect(result.resumed).toBe(true)
expect(result.delivery).toBe('accepted')
expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(1)
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([])
})
it.each(['auto', 'queue'] as const)('refuses an inactive target by default in %s mode without resume, row or RPC', async (deliveryMode) => {
const t = transport(target(flavor, false))
const error = await pingPeer({ ...t.input, deliveryMode }).catch(error => error)
expect(error).toBeInstanceOf(PingPeerError)
expect(error.code).toBe('inactive')
expect(exitCodeForPingPeerError(error)).toBe(5)
expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(0)
expect(t.rows).toEqual([])
expect(t.steers).toEqual([])
})
it('rejects explicit steer to an inactive target even with wake enabled', async () => {
const t = transport(target(flavor, false))
await expect(pingPeer({ ...t.input, deliveryMode: 'steer', wake: true })).rejects.toMatchObject({ code: 'bad_args' })
expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(0)
expect(t.rows).toEqual([])
expect(t.steers).toEqual([])
})
it.each(['auto', 'queue'] as const)('preserves opt-in wake for an active-list/inactive-live race in %s mode', async (deliveryMode) => {
for (const wake of [false, true]) {
const t = transport(target(flavor), { live: target(flavor, false), afterResume: target(flavor) })
if (wake) {
const result = await pingPeer({ ...t.input, deliveryMode, wake })
expect(result.resumed).toBe(true)
expect(result.delivery).toBe('accepted')
expect(result.steerNote).toBe(deliveryMode === 'auto' ? 'steer not attempted: target was just resumed' : undefined)
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
} else {
await expect(pingPeer({ ...t.input, deliveryMode, wake })).rejects.toMatchObject({ code: 'inactive' })
expect(t.rows).toEqual([])
}
expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(wake ? 1 : 0)
expect(t.steers).toEqual([])
}
})
it.each([
[{ status: 200, data: { status: 'failed', error: 'Session not found', localId: null } }, 'steer rejected by hub: Session not found', 'stays queued'],
[{ status: 409, data: { error: 'Session became inactive' } }, 'steer rejected by hub: Session became inactive', 'stays queued'],
[{ status: 200, data: { status: 'failed', error: 'RPC timeout: steer-queued-message', localId: 'ping-peer-x' } },
'steer not confirmed; delivery unresolved: RPC timeout: steer-queued-message', 'delivery unresolved'],
[{ status: 200, data: { status: 'failed', error: 'Steer outcome is being reconciled', localId: 'ping-peer-x' } },
'steer not confirmed; delivery unresolved: Steer outcome is being reconciled', 'delivery unresolved'],
[{ status: 500, data: { error: 'Hub unavailable' } }, 'steer not confirmed; delivery unresolved: Hub unavailable', 'delivery unresolved'],
[new Error('Synthetic steer ACK lost'), 'steer not confirmed; delivery unresolved: Synthetic steer ACK lost', 'delivery unresolved']
] as const)('retains the one accepted row and words the steer outcome by its evidence: %j', async (steer, steerNote, progressTail) => {
const t = transport(target(flavor), { steer })
const progress: string[] = []
const result = await pingPeer({ ...t.input, deliveryMode: 'auto', onProgress: (m) => progress.push(m) })
expect(result.delivery).toBe('accepted')
expect(result.steerNote).toBe(steerNote)
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([`http://hub.test/api/sessions/${sessionId}/messages/${result.localId}/steer`])
expect(t.http.post.mock.calls).toHaveLength(3)
const line = progress.find((m) => m.startsWith(steerNote))
expect(line).toBeDefined()
expect(line).toContain(progressTail)
if (progressTail === 'delivery unresolved') expect(line).not.toContain('stays queued')
})
it.each([
{ status: 500, data: { error: 'Synthetic hub failure' } },
{ status: 409, data: { error: 'Session is inactive' } }
])('does not hide a non-2xx initial submission or attempt a steer: %j', async (send) => {
const t = transport(target(flavor), { send })
await expect(pingPeer({ ...t.input, deliveryMode: 'auto' })).rejects.toMatchObject({ code: 'send_failed' })
expect(t.rows).toHaveLength(1)
expect(t.steers).toEqual([])
})
it('queues without a steer when the target only became active through waitForInitialActive', async () => {
const t = transport(target(flavor, false), { live: target(flavor, true) })
const result = await pingPeer({ ...t.input, deliveryMode: 'auto', waitForInitialActive: true })
expect(result.delivery).toBe('accepted')
expect(result.steerNote).toBe('steer not attempted: target was not active')
expect(result.resumed).toBe(false)
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([])
expect(t.http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(0)
})
it('keeps authoritative consumption instead of claiming a queue fallback', async () => {
const t = transport(target(flavor), { steer: { status: 200, data: { status: 'invoked' } } })
const result = await pingPeer({ ...t.input, deliveryMode: 'auto' })
expect(result.delivery).toBe('invoked')
expect(t.rows).toHaveLength(1)
expect(t.steers).toHaveLength(1)
})
it('does not hide an unconfirmed initial message submission or attempt a steer', async () => {
const t = transport(target(flavor), { send: new Error('Synthetic message ACK lost') })
await expect(pingPeer({ ...t.input, deliveryMode: 'auto' })).rejects.toThrow(/Send not confirmed.*Do not resend automatically/)
expect(t.rows).toHaveLength(1)
expect(t.steers).toEqual([])
})
it('preserves explicit steer rejection and its existing queued-row payload', async () => {
const t = transport(target(flavor), { steer: { status: 200, data: { status: 'failed', error: 'No active turn' } } })
await expect(pingPeer({ ...t.input, deliveryMode: 'steer' })).rejects.toThrow(/Message accepted.*steer was not confirmed/)
expect(t.rows).toHaveLength(1)
expect(t.rows[0]).toEqual({ text: t.input.message, localId: t.rows[0]?.localId })
expect(t.steers).toHaveLength(1)
})
it('preserves explicit queue without attempting a steer', async () => {
const t = transport(target(flavor))
const result = await pingPeer({ ...t.input, deliveryMode: 'queue' })
expect(result.delivery).toBe('accepted')
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([])
})
})
describe('auto delivery to a legacy Cursor stream-json session', () => {
it('queues without a steer request because the session cannot steer', async () => {
const legacy: PingPeerSessionSummary = {
id: sessionId, active: true, thinking: true,
metadata: { flavor: 'cursor', cursorSessionProtocol: 'stream-json' as never },
agentState: { steeringActive: true }
}
const t = transport(legacy)
const result = await pingPeer({ ...t.input, deliveryMode: 'auto' })
expect(result.delivery).toBe('accepted')
expect(result.steerNote).toMatch(/^steer not attempted: /)
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([])
})
})
describe.each([
['idle', { active: true, steering: false }, 'steer not attempted: target is idle'],
['locally controlled', { active: true, steering: true, local: true }, 'steer not attempted: target is controlled locally'],
] as const)('auto delivery to a %s target', (_label, shape, note) => {
it('accepts the message and explains the skipped steer without claiming nothing was sent', async () => {
const base = target('claude', shape.active, shape.steering)
const peer: PingPeerSessionSummary = 'local' in shape
? { ...base, agentState: { ...base.agentState, controlledByUser: true } }
: base
const t = transport(peer)
const progress: string[] = []
const result = await pingPeer({ ...t.input, deliveryMode: 'auto', onProgress: (m) => progress.push(m) })
expect(result.delivery).toBe('accepted')
expect(result.steerNote).toBe(note)
expect(result.steerNote).not.toMatch(/no message sent/i)
expect(progress.join('\n')).not.toMatch(/no message sent/i)
expect(t.rows).toEqual([{ text: t.input.message, localId: result.localId }])
expect(t.steers).toEqual([])
})
it('still refuses an explicit steer with the pre-send wording', async () => {
const base = target('claude', shape.active, shape.steering)
const peer: PingPeerSessionSummary = 'local' in shape
? { ...base, agentState: { ...base.agentState, controlledByUser: true } }
: base
const t = transport(peer)
await expect(pingPeer({ ...t.input, deliveryMode: 'steer' })).rejects.toThrow(/no message sent/)
expect(t.rows).toEqual([])
})
})
+19 -12
View File
@@ -394,6 +394,7 @@ describe('pingPeer', () => {
name: 'Spawned',
resumed: false,
delivery: 'accepted',
steerNote: expect.stringMatching(/^steer not attempted: /),
localId: expect.stringMatching(/^ping-peer-/),
})
})
@@ -619,10 +620,8 @@ describe('pingPeer delivery modes', () => {
{ name: 'Codex without steering state', session: { ...active, agentState: null } },
{ name: 'local Codex without concurrent control', session: { ...active, agentState: { steeringActive: true, controlledByUser: true } } },
{ name: 'unknown flavor', session: { ...active, metadata: null } },
{ name: 'Pi', session: { ...active, metadata: { flavor: 'pi', piSessionId: 'pi-thread' } } },
{ name: 'Cursor ACP', session: { ...active, metadata: { flavor: 'cursor', cursorSessionProtocol: 'acp' as const } } },
{ name: 'legacy Cursor', session: { ...active, metadata: { flavor: 'cursor', cursorSessionProtocol: 'stream-json' as const } } },
{ name: 'Claude', session: { ...active, metadata: { flavor: 'claude' } } }
{ name: 'idle Claude', session: { ...active, agentState: { steeringActive: false }, metadata: { flavor: 'claude' } } }
])('auto queues for $name', async ({ session }) => {
const { http, options } = setup(session)
expect((await pingPeer({ ...options, deliveryMode: 'auto' })).delivery).toBe('accepted')
@@ -650,7 +649,7 @@ describe('pingPeer delivery modes', () => {
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(steeringActive ? 1 : 0)
})
it.each([true, false])('auto re-evaluates Codex steeringActive=%s after resume', async (steeringActive) => {
it.each([true, false])('auto queues after resume even with Codex steeringActive=%s', async (steeringActive) => {
let resumed = false
const http = createHttpMock({
get: (url) => url.endsWith('/api/sessions')
@@ -672,16 +671,18 @@ describe('pingPeer delivery modes', () => {
apiUrl: 'http://hub.test', accessToken: 'tok', http: http as never
})
expect(result.resumed).toBe(true)
expect(result.delivery).toBe(steeringActive ? 'steered' : 'accepted')
expect(result.delivery).toBe('accepted')
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/resume'))).toHaveLength(1)
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/messages'))).toHaveLength(1)
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(steeringActive ? 1 : 0)
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(0)
})
it.each([
{ flavor: 'codex' },
{ flavor: 'pi', piSessionId: 'pi-thread' },
{ flavor: 'cursor', cursorSessionProtocol: 'acp' as const }
{ flavor: 'cursor', cursorSessionProtocol: 'acp' as const },
{ flavor: 'claude' },
{ flavor: 'opencode' }
])('steers an ackable message in $flavor using its localId', async (metadata) => {
const { http, options } = setup({ ...active, metadata })
const result = await pingPeer({ ...options, deliveryMode: 'steer' })
@@ -726,7 +727,9 @@ describe('pingPeer delivery modes', () => {
{ flavor: 'codex', steeringActive: false },
{ flavor: 'codex', steeringActive: undefined },
{ flavor: 'cursor', steeringActive: false },
{ flavor: 'cursor', steeringActive: undefined }
{ flavor: 'cursor', steeringActive: undefined },
{ flavor: 'opencode', steeringActive: false },
{ flavor: 'opencode', steeringActive: undefined }
])('does not send to a thinking $flavor peer with steeringActive=$steeringActive', async ({ flavor, steeringActive }) => {
const { http, options } = setup({
...active, metadata: { flavor }, agentState: { steeringActive }
@@ -766,11 +769,15 @@ describe('pingPeer delivery modes', () => {
{ status: 200, data: { status: 'failed', error: 'Message not in queue' } },
{ status: 409, data: { error: 'Session inactive' } },
new Error('Request timed out')
])('reports accepted but unconfirmed steer without fallback or resending: %j', async (failure) => {
])('preserves the single submission when steer is unconfirmed: %j', async (failure) => {
const { http, options } = setup(active, failure)
await expect(pingPeer({ ...options, deliveryMode })).rejects.toThrow(
/Message accepted \(localId=ping-peer-.+\), but steer was not confirmed: .*Do not resend automatically/
)
if (deliveryMode === 'steer') {
await expect(pingPeer({ ...options, deliveryMode })).rejects.toThrow(
/Message accepted \(localId=ping-peer-.+\), but steer was not confirmed: .*Do not resend automatically/
)
} else {
expect((await pingPeer({ ...options, deliveryMode })).delivery).toBe('accepted')
}
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/messages'))).toHaveLength(1)
expect(http.post.mock.calls.filter(([url]) => url.endsWith('/steer'))).toHaveLength(1)
})
+76 -27
View File
@@ -16,6 +16,7 @@ import {
getPermissionModesForFlavor,
isObject,
isSteeringSupportedForSession,
hasActiveSteeringTurn,
type MessageDeliveryMode,
} from '@hapi/protocol'
import { normalizeSessionIdPrefix } from '@hapi/protocol/sessionCitation'
@@ -113,6 +114,12 @@ export type PingPeerResult = {
name: string
resumed: boolean
delivery: 'accepted' | 'steered' | 'invoked'
/**
* Auto only: why an `accepted` receipt did not steer. Distinguishes a steer
* that was never attempted from one the hub rejected or that stayed
* unconfirmed. The accepted message itself is never resent.
*/
steerNote?: string
/**
* Known client submit identity for the peer row (`ping-peer-` prefix).
* The recipient runtime's consumption ACK is the only delivery proof;
@@ -430,8 +437,10 @@ async function sendMessage(
message: string,
localId: string,
http: AxiosInstance,
deliveryMode: MessageDeliveryMode
): Promise<PingPeerResult['delivery']> {
deliveryMode: MessageDeliveryMode,
autoSteerFallback = false,
onProgress?: (message: string) => void
): Promise<{ delivery: PingPeerResult['delivery']; steerNote?: string }> {
// The existing queued-message steer action accepts localId as well as id.
// Both modes retain the peer identity so only runtime ACKs prove delivery.
const response = await http.post(
@@ -450,7 +459,8 @@ async function sendMessage(
if (response.status >= 200 && response.status < 300 && response.data?.ok === true) {
// HTTP success means hub-accepted, not proof the row is still queued:
// the recipient runtime's consumption ACK may race this response.
if (deliveryMode === 'queue') return 'accepted'
if (deliveryMode === 'queue') return { delivery: 'accepted' }
let hubRejection: string | null = null
try {
const steer = await http.post(
`${apiUrl}/api/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(localId)}/steer`,
@@ -458,14 +468,34 @@ async function sendMessage(
{ headers: authHeaders(jwt), timeout: 30_000, validateStatus: () => true }
)
if (steer.status >= 200 && steer.status < 300) {
if (steer.data?.status === 'steered') return 'steered'
if (steer.data?.status === 'steered') return { delivery: 'steered' }
// The target consumed the message before the steer request.
// Do not claim it was inserted into the active turn.
if (steer.data?.status === 'invoked') return 'invoked'
if (steer.data?.status === 'invoked') return { delivery: 'invoked' }
}
throw new Error(typeof steer.data?.error === 'string' ? steer.data.error : `HTTP ${steer.status}`)
const rejection: string = typeof steer.data?.error === 'string' ? steer.data.error : `HTTP ${steer.status}`
// Only a refusal before any native request is dispatched is definitive:
// an HTTP 4xx, or a Hub 'failed' reply without a localId. A 'failed' reply
// that carries a localId means the native steer was requested, and its
// timeout or "being reconciled" outcome leaves delivery unresolved.
const refusedBeforeDispatch = (steer.status >= 400 && steer.status < 500)
|| (steer.status >= 200 && steer.status < 300
&& steer.data?.status === 'failed' && steer.data?.localId == null)
if (refusedBeforeDispatch) hubRejection = rejection
throw new Error(rejection)
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
// POST acceptance already owns one row; never resend after a failed or uncertain steer.
// Auto keeps the queued receipt but reports why the steer did not happen.
if (autoSteerFallback) {
const steerNote = hubRejection !== null
? `steer rejected by hub: ${detail}`
: `steer not confirmed; delivery unresolved: ${detail}`
onProgress?.(hubRejection !== null
? `${steerNote}; message stays queued as ${localId}`
: `${steerNote}; message accepted as ${localId}`)
return { delivery: 'accepted', steerNote }
}
throw new PingPeerError(
'send_failed',
`Message accepted (localId=${localId}), but steer was not confirmed: ${detail}. ` +
@@ -646,25 +676,37 @@ export function formatPeerSessionsList(
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 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'
}
if (session.agentState?.controlledByUser && !session.metadata?.capabilities?.concurrentClients) {
return 'Steering is only available for remote sessions; no message sent'
}
const steeringActive = session.metadata?.flavor === 'pi'
? session.thinking
: session.agentState?.steeringActive === true
if (!steeringActive) {
return 'Steering requires an active turn; target is idle, no message sent. Use queue to start a turn'
}
type SteeringIneligibility = 'inactive' | 'unsupported' | 'local' | 'idle'
function getSteeringIneligibility(session: PingPeerSessionSummary): SteeringIneligibility | null {
if (!session.active) return 'inactive'
if (!isSteeringSupportedForSession(session.metadata)) return 'unsupported'
if (session.agentState?.controlledByUser && !session.metadata?.capabilities?.concurrentClients) return 'local'
if (!hasActiveSteeringTurn(session)) return 'idle'
return null
}
// Explicit steer refuses before sending, so these texts say no message was sent.
const EXPLICIT_STEER_REFUSAL: Record<SteeringIneligibility, string> = {
inactive: 'Steering requires an active turn; target is inactive, no message sent. Use queue with wake to resume it',
unsupported: 'Steering is only supported for Claude, Pi, Codex, OpenCode, and Cursor ACP sessions; no message sent',
local: 'Steering is only available for remote sessions; no message sent',
idle: 'Steering requires an active turn; target is idle, no message sent. Use queue to start a turn'
}
// Auto has already accepted the message, so its notes must not claim otherwise.
const AUTO_NOT_ATTEMPTED: Record<SteeringIneligibility, string> = {
inactive: 'target is inactive',
unsupported: 'target does not support steering',
local: 'target is controlled locally',
idle: 'target is idle'
}
function getSteeringUnavailableReason(session: PingPeerSessionSummary): string | null {
const ineligibility = getSteeringIneligibility(session)
return ineligibility === null ? null : EXPLICIT_STEER_REFUSAL[ineligibility]
}
export async function pingPeer(options: PingPeerOptions): Promise<PingPeerResult> {
assertPeerToolsEnabled()
const knownSessionId = (options.sessionId ?? '').trim()
@@ -750,11 +792,12 @@ export async function pingPeer(options: PingPeerOptions): Promise<PingPeerResult
}
}
// Use the live snapshot, not the discovery list. Auto initially steers only
// Codex targets; other flavors retain queue unless steer is explicit.
// Share supported-provider turn policy. Explicitly awakened/new peers queue
// their message rather than opportunistically steering the resumed turn.
const steeringError = getSteeringUnavailableReason(live)
const ineligibility = getSteeringIneligibility(live)
const deliveryMode: MessageDeliveryMode = requestedDeliveryMode === 'auto'
? (live.metadata?.flavor === 'codex' && steeringError === null ? 'steer' : 'queue')
? (matched.active && !resumed && steeringError === null ? 'steer' : 'queue')
: requestedDeliveryMode
if (deliveryMode === 'steer' && steeringError !== null) {
throw new PingPeerError('bad_args', steeringError)
@@ -762,14 +805,20 @@ export async function pingPeer(options: PingPeerOptions): Promise<PingPeerResult
onProgress?.(`sending message (${message.length} chars, ${deliveryMode}${requestedDeliveryMode === 'auto' ? ' via auto' : ''})...`)
const localId = createPeerMessageLocalId()
const delivery = await sendMessage(apiUrl, jwt, matched.id, message, localId, http, deliveryMode)
const sent = await sendMessage(apiUrl, jwt, matched.id, message, localId, http, deliveryMode, requestedDeliveryMode === 'auto', onProgress)
// Auto queued without trying: say why, so a caller can tell it from a steer that failed.
const steerNote = sent.steerNote ?? (requestedDeliveryMode === 'auto' && deliveryMode === 'queue'
? `steer not attempted: ${resumed ? 'target was just resumed' : !matched.active ? 'target was not active' : ineligibility ? AUTO_NOT_ATTEMPTED[ineligibility] : 'steering unavailable'}`
: undefined)
if (steerNote && sent.steerNote === undefined) onProgress?.(`${steerNote}; message queued`)
return {
sessionId: matched.id,
name,
resumed,
localId,
delivery
delivery: sent.delivery,
...(steerNote ? { steerNote } : {})
}
}