From 9b2a9bfb873611bb463572cd95ced7455ef33d88 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 8 Nov 2026 21:58:44 -0500 Subject: [PATCH] fix(orchestration): gate --on on the carrying Orca, ack retried deliveries, refuse payloads and federated workers --- .../orchestration/agent-server-route.test.ts | 24 +++++++++- .../orchestration/agent-server-route.ts | 31 ++++++++++-- .../orchestration/message-inbox-handlers.ts | 5 +- .../orchestration/message-send-handler.ts | 3 +- .../rpc/methods/orchestration/caller-show.ts | 5 +- .../federation/peer-mail-methods.ts | 25 ++++++++++ .../federation/peer-mail.test.ts | 47 +++++++++++++++++++ .../orchestration/messaging/peer-mail-send.ts | 16 ++++++- 8 files changed, 146 insertions(+), 10 deletions(-) diff --git a/src/cli/handlers/orchestration/agent-server-route.test.ts b/src/cli/handlers/orchestration/agent-server-route.test.ts index e4fdab972ae..8f3de266115 100644 --- a/src/cli/handlers/orchestration/agent-server-route.test.ts +++ b/src/cli/handlers/orchestration/agent-server-route.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as RuntimeClientModule from '../../runtime-client' -import { refuseAgentServerRoute } from './agent-server-route' +import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route' const { callerShow } = vi.hoisted(() => ({ callerShow: vi.fn() })) vi.mock('../../runtime-client', async (importOriginal) => { @@ -52,7 +52,7 @@ describe('an agent pointing mail at another server', () => { ).rejects.toMatchObject({ code: 'agent_server_route_refused', message: - 'send --server devB runs on devB and nothing comes back to you. To message an agent on devB, use: orca orchestration send --on devB --to term_b --subject hi' + 'send with --server devB runs on devB and nothing comes back to you. To message an agent on devB, use: orca orchestration send --on devB --to term_b --subject hi' }) }) @@ -77,3 +77,23 @@ describe('an agent pointing mail at another server', () => { ).resolves.toBeUndefined() }) }) + +describe('send --on from an older Orca', () => { + it('is refused before anything is sent', async () => { + const call = vi + .fn() + .mockResolvedValue({ result: { capabilities: ['orchestration.contract.v1'] } }) + const context = { + flags: new Map([['on', 'devB']]), + client: { call }, + cwd: '/', + json: false + } as unknown as Parameters[0] + + await expect(requirePeerMailCarrier(context)).rejects.toMatchObject({ + code: 'peer_mail_unsupported' + }) + expect(call).toHaveBeenCalledTimes(1) + expect(call).toHaveBeenCalledWith('status.get') + }) +}) diff --git a/src/cli/handlers/orchestration/agent-server-route.ts b/src/cli/handlers/orchestration/agent-server-route.ts index f3c2c952c1b..27a2a804087 100644 --- a/src/cli/handlers/orchestration/agent-server-route.ts +++ b/src/cli/handlers/orchestration/agent-server-route.ts @@ -3,15 +3,23 @@ import { RuntimeClient, RuntimeClientError } from '../../runtime-client' import { readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env' import type { OrchestrationCallerShowResult } from '../../../shared/orchestration/orchestration-caller-status' import { renderOrchestrationArgv } from './agent-view' +import type { RuntimeStatus } from '../../../shared/runtime-types' +import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities' type AgentServerRoutedCommand = 'send' | 'worker-start' | 'check' const SERVER_FLAGS = new Set(['--environment', '--server']) /** The server a remote client was pointed at, as the caller spelled it. */ -function serverSelector(flags: HandlerContext['flags']): string | undefined { +function serverSelector( + flags: HandlerContext['flags'] +): { name: string; route: string } | undefined { const explicit = flags.get('environment') ?? flags.get('server') - return typeof explicit === 'string' ? explicit : process.env.ORCA_ENVIRONMENT?.trim() || undefined + if (typeof explicit === 'string') { + return { name: explicit, route: `--server ${explicit}` } + } + const inherited = process.env.ORCA_ENVIRONMENT?.trim() + return inherited ? { name: inherited, route: `ORCA_ENVIRONMENT=${inherited}` } : undefined } /** Only an agent its own Orca verifies counts; a person's shell keeps --server = run it there. */ @@ -60,15 +68,30 @@ export async function refuseAgentServerRoute( if (!server || !(await isOrcaVerifiedAgent())) { return } + const { name, route } = server if (command === 'check') { throw new RuntimeClientError( 'mailbox_is_local', - `Your mailbox is on this Orca; replies from ${server} arrive here. Drop --server.` + `Your mailbox is on this Orca; replies from ${name} arrive here. Drop ${route}.` ) } const verb = command === 'send' ? 'message an agent' : 'start a worker' throw new RuntimeClientError( 'agent_server_route_refused', - `${command} --server ${server} runs on ${server} and nothing comes back to you. To ${verb} on ${server}, use: ${withOn(ctx.rawArgs, server)}` + `${command} with ${route} runs on ${name} and nothing comes back to you. To ${verb} on ${name}, use: ${withOn(ctx.rawArgs, name)}` ) } + +/** An older Orca would drop --on and send the mail to an agent here, so it must carry peer mail first. */ +export async function requirePeerMailCarrier(ctx: HandlerContext): Promise { + if (!ctx.flags.has('on')) { + return + } + const { result } = await ctx.client.call('status.get') + if (!result.capabilities?.includes(ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY)) { + throw new RuntimeClientError( + 'peer_mail_unsupported', + 'The Orca running here is too old to carry mail to another server. Update or restart Orca here, then send again. Nothing was sent.' + ) + } +} diff --git a/src/cli/handlers/orchestration/message-inbox-handlers.ts b/src/cli/handlers/orchestration/message-inbox-handlers.ts index 07214590d7c..66ba2a23a13 100644 --- a/src/cli/handlers/orchestration/message-inbox-handlers.ts +++ b/src/cli/handlers/orchestration/message-inbox-handlers.ts @@ -11,13 +11,16 @@ import { type OrchestrationMessageSummary as MessageSummary } from '../../../shared/orchestration/mailbox/orchestration-check-output' import { callOrchestrationMutation } from './mutation-request' +import { requirePeerMailCarrier } from './agent-server-route' import { resolveOrchestrationTerminalHandle } from './terminal-identity' import { withReceiptNext } from './receipt-next-text' import { printOrchestrationResult } from './agent-view' import { formatMessageViewText, toMessageView, type MessageView } from './message-agent-views' export const ORCHESTRATION_INBOX_HANDLERS: Record = { - 'orchestration reply': async ({ flags, client, cwd, json }) => { + 'orchestration reply': async (ctx) => { + const { flags, client, cwd, json } = ctx + await requirePeerMailCarrier(ctx) const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from') const result = await callOrchestrationMutation<{ message: { id: string } diff --git a/src/cli/handlers/orchestration/message-send-handler.ts b/src/cli/handlers/orchestration/message-send-handler.ts index 11f11ff772f..3fb76f51562 100644 --- a/src/cli/handlers/orchestration/message-send-handler.ts +++ b/src/cli/handlers/orchestration/message-send-handler.ts @@ -12,7 +12,7 @@ import { requireWorkerDoneSettlement } from '../orchestration-worker-settlement' import { getOptionalStructuredMessagePayload } from './message-payload' import { callOrchestrationMutation } from './mutation-request' import { isDevCliInvocation } from './runtime-compatibility' -import { refuseAgentServerRoute } from './agent-server-route' +import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route' import { resolveOrchestrationTerminalHandle, throwNoActiveSenderTerminal @@ -74,6 +74,7 @@ export const ORCHESTRATION_SEND_HANDLER: Record = { 'orchestration send': async (ctx) => { const { flags, client, cwd, json } = ctx await refuseAgentServerRoute('send', ctx) + await requirePeerMailCarrier(ctx) const to = getOptionalStringFlag(flags, 'to') const type = getOptionalStringFlag(flags, 'type') if (to) { diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index aa0c428653f..1b34a65bf3c 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -76,9 +76,12 @@ export const ORCHESTRATION_CALLER_METHODS = [ caller: orchestrationCaller ? { orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), live: true } : null, + // An Orca-launched agent's own pane and launch secret prove it is one; no hook needs to have fired. terminal: !orchestrationCaller && - runtime.verifyOrchestrationCompatibilityCaller(orchestrationCompatibilityEvidence) !== null + runtime.verifyOrchestrationCompatibilityCaller(orchestrationCompatibilityEvidence, { + currentRuntimeLaunchSufficient: true + }) !== null }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts index 32a6f4d76d3..7f5f4569967 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -67,6 +67,22 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ NOTHING_DELIVERED ) } + // A retry after a lost answer is acknowledged even if the recipient has since gone. + const delivered = db.getPeerMailMessage(params.messageId) + if (delivered) { + const conversation = db.getPeerMailConversation(delivered.conversation_id) + if ( + delivered.conversation_id !== params.conversationId || + conversation?.peer_fingerprint !== peerFingerprint + ) { + throw new OrchestrationError( + 'request_mismatch', + `Message ${params.messageId} already belongs to another conversation. Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + return { message: { id: params.messageId, to } } + } if (mayNameSession(to)) { // Recipient routing reads the session record store, which the host opens lazily. await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) @@ -79,6 +95,15 @@ export const ORCHESTRATION_PEER_MAIL_METHODS = [ NOTHING_DELIVERED ) } + const paneKey = runtime.getLiveTerminalPaneKey(recipient.to) + if (paneKey && db.findActiveRemoteAttachmentForPane(paneKey)) { + // Its mailbox is its Dispatch, which only its Run home writes to. + throw new OrchestrationError( + 'invalid_argument', + `${to} is a worker for another Orca's Run; message it through that Run's coordinator. Nothing was delivered.`, + NOTHING_DELIVERED + ) + } const stored = db.insertPeerMailMessage({ conversationId: params.conversationId, peerFingerprint, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts index 39e48a2caaf..5230af634f5 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts @@ -253,4 +253,51 @@ describe('agent mail between paired Orca servers', () => { }) expect(b.db.getInbox(10)).toEqual([]) }) + + it('acknowledges a retried delivery after its recipient is gone, storing it once', async () => { + const deliver = { + conversationId: 'peerconv_aaaaaaaaaaaa', + messageId: 'msg_aaaaaaaaaaaa', + to: 'term_b', + senderLabel: "term_a on Jinwoo's Mac", + subject: 'Once' + } + const first = await transport.call('devB', 'orchestration.peerMailDeliver', deliver) + vi.mocked(b.runtime.getLiveTerminalPaneKey).mockReturnValue(null) + + const retried = await transport.call('devB', 'orchestration.peerMailDeliver', deliver) + + expect(first).toMatchObject({ ok: true }) + expect(retried).toMatchObject({ ok: true, result: { message: { id: 'msg_aaaaaaaaaaaa' } } }) + expect(b.db.getInbox(10).filter((message) => message.subject === 'Once')).toHaveLength(1) + }) + + it('refuses payload fields before sending anything', async () => { + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Report', + payload: '{"taskId":"task_1"}' + }) + + expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('refuses mail to a worker another Orca coordinates', async () => { + vi.spyOn(b.db, 'findActiveRemoteAttachmentForPane').mockImplementation((paneKey) => + paneKey === B_PANE ? ({ dispatch_id: 'ctx_remote' } as never) : undefined + ) + + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Side mail' + }) + + expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(b.db.getInbox(10)).toEqual([]) + }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts index bddad9d851f..e656af704de 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts @@ -32,11 +32,18 @@ export function peerMailLocalCaller(args: { : (args.attestedCaller?.paneKey ?? args.runtime.getLiveTerminalPaneKey(args.from)) if (!args.from || !paneKey) { throw new OrchestrationError( - 'caller_required', + 'invalid_argument', '--on needs a terminal or chat agent on this Orca to receive the replies. Run it from that agent. Nothing was sent.', NOTHING_SENT ) } + if (args.runtime.getOrchestrationDb().findActiveRemoteAttachmentForPane(paneKey)) { + throw new OrchestrationError( + 'invalid_argument', + "This terminal is a worker for another Orca's Run; its mail goes to that Run's coordinator, not to other servers. Nothing was sent.", + NOTHING_SENT + ) + } return { address: args.from, paneKey } } @@ -66,6 +73,13 @@ export async function sendPeerMail(args: { NOTHING_SENT ) } + if (params.payload !== undefined) { + throw new OrchestrationError( + 'invalid_argument', + '--on carries a subject and body; payload fields such as --task-id or --report-path name work on this Orca only. Nothing was sent.', + NOTHING_SENT + ) + } const caller = peerMailLocalCaller({ ...args, from: params.from }) const server = await requirePeerMailServer(runtime, params.on) const conversation = runtime.getOrchestrationDb().openHomePeerMailConversation({