From d5d0ceb6e25f7db651bc55d4aa8db889b778e6a3 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 8 Nov 2026 21:46:15 -0500 Subject: [PATCH] feat(orchestration): mail agents on a paired server with send --on, replies come back by themselves --- .../references/messaging-and-gates.md | 4 + .../references/placement-and-remote.md | 21 ++ src/cli/bundled-skill-guides.ts | 25 ++ .../orchestration/agent-server-route.test.ts | 79 ++++++ .../orchestration/agent-server-route.ts | 74 +++++ .../orchestration/message-check-handler.ts | 5 +- .../orchestration/message-inbox-handlers.ts | 1 + .../orchestration/message-send-handler.ts | 6 +- .../orchestration/worker-launch-handler.ts | 5 +- src/cli/index.ts | 26 +- src/cli/runtime/client.ts | 25 +- .../orchestration-compatibility-envelope.ts | 37 +++ .../orchestration-request-evidence.test.ts | 28 ++ src/cli/specs/orchestration.ts | 13 +- src/main/runtime/orca-runtime.ts | 15 + .../db/attach-orchestration-db-methods.ts | 2 + .../db/federation/peer-mail-store.ts | 182 +++++++++++++ .../db/orchestration-db-methods.ts | 2 + .../db/schema/create-graph-tables-sql.ts | 28 ++ .../peer-mail/peer-mail-delivery.ts | 111 ++++++++ .../federation/peer-mail/peer-mail-relay.ts | 174 ++++++++++++ .../federation/peer-mail/peer-mail-waiters.ts | 32 +++ .../mailbox/senders/agent-message-sender.ts | 4 +- src/main/runtime/rpc/errors.ts | 11 +- .../rpc/methods/orchestration/caller-show.ts | 10 +- .../federation/federation-methods.ts | 4 +- .../federation/peer-mail-methods.ts | 148 ++++++++++ .../federation/peer-mail.test.ts | 256 ++++++++++++++++++ .../messaging/peer-mail-reply.ts | 107 ++++++++ .../orchestration/messaging/peer-mail-send.ts | 118 ++++++++ .../orchestration/messaging/reply-method.ts | 21 ++ .../orchestration/messaging/send-methods.ts | 1 + .../orchestration/messaging/send-params.ts | 2 + .../methods/orchestration/orchestration.ts | 3 +- .../orchestration-caller-status.ts | 6 +- .../orchestration-federation-error-codes.ts | 14 + .../orchestration-runtime-capabilities.ts | 5 +- .../rpc-contract/orchestration-params.ts | 4 +- .../orchestration-peer-mail-params.ts | 41 +++ .../rpc-params-catalog.generated.ts | 8 + 40 files changed, 1615 insertions(+), 43 deletions(-) create mode 100644 src/cli/handlers/orchestration/agent-server-route.test.ts create mode 100644 src/cli/handlers/orchestration/agent-server-route.ts create mode 100644 src/cli/runtime/orchestration-request-evidence.test.ts create mode 100644 src/main/runtime/orchestration/db/federation/peer-mail-store.ts create mode 100644 src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts create mode 100644 src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts create mode 100644 src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts create mode 100644 src/shared/orchestration/orchestration-federation-error-codes.ts create mode 100644 src/shared/rpc-contract/orchestration-peer-mail-params.ts diff --git a/skill-guides/orchestration/references/messaging-and-gates.md b/skill-guides/orchestration/references/messaging-and-gates.md index d59db8e4bb8..6840971af67 100644 --- a/skill-guides/orchestration/references/messaging-and-gates.md +++ b/skill-guides/orchestration/references/messaging-and-gates.md @@ -5,3 +5,7 @@ Handle a whole `check` batch before the next `check`. Groups (`@all`, `@idle`, `@codex`, ...) reach the live workers of your Run; `@worktree:` also reaches coordinators in that workspace. Use groups only for deliberate fan-out. + +To reach an agent on a paired server, use `send --on `; a reply to mail +from another server needs no flag. See +[Placement and remote execution](placement-and-remote.md). diff --git a/skill-guides/orchestration/references/placement-and-remote.md b/skill-guides/orchestration/references/placement-and-remote.md index e633f12bd90..2bcb680d989 100644 --- a/skill-guides/orchestration/references/placement-and-remote.md +++ b/skill-guides/orchestration/references/placement-and-remote.md @@ -35,3 +35,24 @@ workspace, and the start output names the workspace it created. After start, address a remote worker only by Dispatch ID, never by a terminal handle. + +## Agents on another server + +To message an agent that already runs on a paired server, send with `--on`, +using the same server names as `worker-start --on`: + +```bash +ORCA orchestration send --on --to --subject "" --body "" +``` + +Your own Orca carries the mail and keeps the conversation. Replies come back to +your own `check`, and they wake you like local mail. The other agent answers +with a plain `reply --id --body `; no flag is needed on either +side. Mail from another server names its sender as ` on `. + +`--server ` runs one command on that server and delivers nothing back +to you, so an agent never mails with it. Your mailbox stays on your own Orca: +`check` takes no server flag. Read-only commands such as `inbox` or +`worker-list` with `--server` show that server's records. A server whose Orca +is too old answers `peer_mail_unsupported` and nothing is sent. Pair servers +with `orca pair` or in Settings. diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index c5d92714523..5fa5d6b5fc2 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -4092,6 +4092,10 @@ const ORCHESTRATION_MESSAGING_AND_GATES_REFERENCE_MARKDOWN = [ "`@worktree:` also reaches coordinators in that workspace. Use groups only", "for deliberate fan-out.", "", + "To reach an agent on a paired server, use `send --on `; a reply to mail", + "from another server needs no flag. See", + "[Placement and remote execution](placement-and-remote.md).", + "", ].join('\n') // oxfmt-ignore @@ -4134,6 +4138,27 @@ const ORCHESTRATION_PLACEMENT_AND_REMOTE_REFERENCE_MARKDOWN = [ "After start, address a remote worker only by Dispatch ID, never by a terminal", "handle.", "", + "## Agents on another server", + "", + "To message an agent that already runs on a paired server, send with `--on`,", + "using the same server names as `worker-start --on`:", + "", + "```bash", + "ORCA orchestration send --on --to --subject \"\" --body \"\"", + "```", + "", + "Your own Orca carries the mail and keeps the conversation. Replies come back to", + "your own `check`, and they wake you like local mail. The other agent answers", + "with a plain `reply --id --body `; no flag is needed on either", + "side. Mail from another server names its sender as ` on `.", + "", + "`--server ` runs one command on that server and delivers nothing back", + "to you, so an agent never mails with it. Your mailbox stays on your own Orca:", + "`check` takes no server flag. Read-only commands such as `inbox` or", + "`worker-list` with `--server` show that server's records. A server whose Orca", + "is too old answers `peer_mail_unsupported` and nothing is sent. Pair servers", + "with `orca pair` or in Settings.", + "", ].join('\n') // oxfmt-ignore diff --git a/src/cli/handlers/orchestration/agent-server-route.test.ts b/src/cli/handlers/orchestration/agent-server-route.test.ts new file mode 100644 index 00000000000..e4fdab972ae --- /dev/null +++ b/src/cli/handlers/orchestration/agent-server-route.test.ts @@ -0,0 +1,79 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as RuntimeClientModule from '../../runtime-client' +import { refuseAgentServerRoute } from './agent-server-route' + +const { callerShow } = vi.hoisted(() => ({ callerShow: vi.fn() })) +vi.mock('../../runtime-client', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + RuntimeClient: class { + call = callerShow + } + } +}) + +function ctx(command: string[], flags: [string, string | boolean][]) { + return { + flags: new Map(flags), + client: { isRemote: true }, + cwd: '/', + json: false, + rawArgs: [...command, ...flags.flatMap(([name, value]) => [`--${name}`, String(value)])] + } as unknown as Parameters[1] +} + +describe('an agent pointing mail at another server', () => { + beforeEach(() => { + vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', 'launch-token') + vi.stubEnv('ORCA_AGENT_SESSION_ID', '') + vi.stubEnv('ORCA_CLI_COMMAND', 'orca') + callerShow.mockResolvedValue({ result: { caller: null, terminal: true } }) + }) + + afterEach(() => { + vi.unstubAllEnvs() + callerShow.mockReset() + }) + + it('is refused with the --on command to run instead', async () => { + await expect( + refuseAgentServerRoute( + 'send', + ctx( + ['orchestration', 'send'], + [ + ['environment', 'devB'], + ['to', 'term_b'], + ['subject', 'hi'] + ] + ) + ) + ).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' + }) + }) + + it('refuses a check against another server: the mailbox is local', async () => { + await expect( + refuseAgentServerRoute('check', ctx(['orchestration', 'check'], [['environment', 'devB']])) + ).rejects.toMatchObject({ code: 'mailbox_is_local' }) + }) + + it('leaves a person in a shell running the command on that server', async () => { + vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', '') + await expect( + refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']])) + ).resolves.toBeUndefined() + expect(callerShow).not.toHaveBeenCalled() + }) + + it('leaves a launch its own Orca does not verify running on that server', async () => { + callerShow.mockResolvedValue({ result: { caller: null, terminal: false } }) + await expect( + refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']])) + ).resolves.toBeUndefined() + }) +}) diff --git a/src/cli/handlers/orchestration/agent-server-route.ts b/src/cli/handlers/orchestration/agent-server-route.ts new file mode 100644 index 00000000000..f3c2c952c1b --- /dev/null +++ b/src/cli/handlers/orchestration/agent-server-route.ts @@ -0,0 +1,74 @@ +import type { HandlerContext } from '../../dispatch' +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' + +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 { + const explicit = flags.get('environment') ?? flags.get('server') + return typeof explicit === 'string' ? explicit : process.env.ORCA_ENVIRONMENT?.trim() || undefined +} + +/** Only an agent its own Orca verifies counts; a person's shell keeps --server = run it there. */ +async function isOrcaVerifiedAgent(): Promise { + if (!readInjectedAgentSessionId() && !process.env.ORCA_AGENT_LAUNCH_TOKEN?.trim()) { + return false + } + try { + const local = new RuntimeClient(undefined, 10_000, null, null) + const { result } = await local.call('orchestration.callerShow') + return result.caller !== null || result.terminal === true + } catch { + return false + } +} + +/** The same command with the server moved from --server to --on. */ +function withOn(rawArgs: readonly string[] | undefined, server: string): string { + const args = rawArgs ?? [] + const kept: string[] = [] + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]! + const [name] = arg.split('=', 1) + if (SERVER_FLAGS.has(name!)) { + if (!arg.includes('=')) { + index += 1 + } + continue + } + kept.push(arg) + } + const at = kept.findIndex((arg) => arg === 'send' || arg === 'worker-start') + kept.splice(at + 1, 0, '--on', server) + return renderOrchestrationArgv(kept) ?? '' +} + +/** An agent's mail and workers live on its own Orca; pointing them at another server reaches nobody. */ +export async function refuseAgentServerRoute( + command: AgentServerRoutedCommand, + ctx: HandlerContext +): Promise { + if (!ctx.client.isRemote || ctx.flags.has('on')) { + return + } + const server = serverSelector(ctx.flags) + if (!server || !(await isOrcaVerifiedAgent())) { + return + } + if (command === 'check') { + throw new RuntimeClientError( + 'mailbox_is_local', + `Your mailbox is on this Orca; replies from ${server} arrive here. Drop --server.` + ) + } + 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)}` + ) +} diff --git a/src/cli/handlers/orchestration/message-check-handler.ts b/src/cli/handlers/orchestration/message-check-handler.ts index bf707cfb64b..aa3869fa383 100644 --- a/src/cli/handlers/orchestration/message-check-handler.ts +++ b/src/cli/handlers/orchestration/message-check-handler.ts @@ -1,4 +1,5 @@ import type { CommandHandler } from '../../dispatch' +import { refuseAgentServerRoute } from './agent-server-route' import { printResult } from '../../format' import { withReceiptNext } from './receipt-next-text' import { printOrchestrationResult } from './agent-view' @@ -32,7 +33,9 @@ type CheckResult = { } export const ORCHESTRATION_CHECK_HANDLER: Record = { - 'orchestration check': async ({ flags, client, cwd, json }) => { + 'orchestration check': async (ctx) => { + const { flags, client, cwd, json } = ctx + await refuseAgentServerRoute('check', ctx) const wait = flags.has('wait') const peek = flags.has('peek') // Older runtimes ignore peek, making --unread --peek destructive. diff --git a/src/cli/handlers/orchestration/message-inbox-handlers.ts b/src/cli/handlers/orchestration/message-inbox-handlers.ts index 32d35acfb4b..07214590d7c 100644 --- a/src/cli/handlers/orchestration/message-inbox-handlers.ts +++ b/src/cli/handlers/orchestration/message-inbox-handlers.ts @@ -27,6 +27,7 @@ export const ORCHESTRATION_INBOX_HANDLERS: Record = { id: getRequiredStringFlag(flags, 'id'), body: getRequiredStringFlag(flags, 'body'), run: getOptionalStringFlag(flags, 'run'), + on: getOptionalStringFlag(flags, 'on'), from }) if (!flags.has('full')) { diff --git a/src/cli/handlers/orchestration/message-send-handler.ts b/src/cli/handlers/orchestration/message-send-handler.ts index 9288dd50d87..11f11ff772f 100644 --- a/src/cli/handlers/orchestration/message-send-handler.ts +++ b/src/cli/handlers/orchestration/message-send-handler.ts @@ -12,6 +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 { resolveOrchestrationTerminalHandle, throwNoActiveSenderTerminal @@ -70,7 +71,9 @@ function rejectLifecycleGroupRecipient(type: string | undefined, to: string): vo } export const ORCHESTRATION_SEND_HANDLER: Record = { - 'orchestration send': async ({ flags, client, cwd, json }) => { + 'orchestration send': async (ctx) => { + const { flags, client, cwd, json } = ctx + await refuseAgentServerRoute('send', ctx) const to = getOptionalStringFlag(flags, 'to') const type = getOptionalStringFlag(flags, 'type') if (to) { @@ -99,6 +102,7 @@ export const ORCHESTRATION_SEND_HANDLER: Record = { from, to, run: getOptionalStringFlag(flags, 'run'), + on: getOptionalStringFlag(flags, 'on'), subject: getRequiredStringFlag(flags, 'subject'), body: getOptionalStringFlag(flags, 'body'), type, diff --git a/src/cli/handlers/orchestration/worker-launch-handler.ts b/src/cli/handlers/orchestration/worker-launch-handler.ts index e03c4a523fa..d26ab6a669a 100644 --- a/src/cli/handlers/orchestration/worker-launch-handler.ts +++ b/src/cli/handlers/orchestration/worker-launch-handler.ts @@ -19,9 +19,12 @@ import { import { explainOlderRuntimeRunRequired } from './older-runtime-run-binding' import { withResolvedNextCommands } from '../../orchestration-mutation-recovery' import { readTextOrFileFlag } from '../../command-body-input' +import { refuseAgentServerRoute } from './agent-server-route' export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record = { - 'orchestration worker-start': async ({ flags, client, cwd, json }) => { + 'orchestration worker-start': async (ctx) => { + const { flags, client, cwd, json } = ctx + await refuseAgentServerRoute('worker-start', ctx) const terminal = getPresentStringFlag(flags, 'terminal') const model = getOptionalStringFlag(flags, 'model') const effort = getOptionalStringFlag(flags, 'effort') diff --git a/src/cli/index.ts b/src/cli/index.ts index 10ce7052964..1e0e1744094 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -105,7 +105,20 @@ export async function main( refuseConflictingSessionCallerFlags(commandSpec, parsed.flags) await refuseLocalManagementSelector(parsed.commandPath, parsed.flags) const RuntimeClientClass = await loadRuntimeClientClass() - const ignoreRemoteSelection = ignoresRemoteSelection(parsed.commandPath) + // `--on` mail is carried by the caller's own Orca; an inherited server selection never reroutes it. + const peerMail = isPeerMailCommand(parsed.commandPath, parsed.flags) + if ( + peerMail && + (parsed.flags.has('pairing-code') || + (parsed.flags.has('environment') && + !isLocalEnvironmentSelector(parsed.flags.get('environment')))) + ) { + throw new RuntimeClientError( + 'invalid_argument', + '--on already names the server the mail goes to; drop --server. Your own Orca carries it.' + ) + } + const ignoreRemoteSelection = peerMail || ignoresRemoteSelection(parsed.commandPath) const pairingCode = ignoreRemoteSelection ? null : parsed.flags.get('pairing-code') const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('environment') // An explicit local route suppresses ambient ORCA_ENVIRONMENT and pairing codes. @@ -192,6 +205,17 @@ export async function main( } } +function isPeerMailCommand( + commandPath: readonly string[], + flags: ReadonlyMap +): boolean { + return ( + commandPath[0] === 'orchestration' && + (commandPath[1] === 'send' || commandPath[1] === 'reply') && + flags.has('on') + ) +} + async function runClaudeTeams(argv: string[], cwd: string): Promise { try { // Forward Claude Code arguments verbatim so new flags work without Orca changes. diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index 1425d23af36..40b8c360b35 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -38,10 +38,7 @@ import { ORCHESTRATION_CONTRACT_VERSION } from '../../shared/orchestration/orchestration-runtime-capabilities' import { RemoteRuntimeCompatGate } from './remote-runtime-compat-gate' -import { - createAgentLaunchCallerEvidence, - createOrchestrationCompatibilityEnvelope -} from './orchestration-compatibility-envelope' +import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope' import { getTimeoutMsParam, isWaitingCheck } from './runtime-request-timeout' import { isWorkerStartTimeoutWithinTimerLimit, @@ -56,7 +53,6 @@ import { const LONG_POLL_CLIENT_GRACE_MS = 10_000 // The host records the launched agent in the caller's chat; older hosts ignore the evidence. -const AGENT_LAUNCH_METHODS: ReadonlySet = new Set(['agent.launch', 'agent.launchReplay']) const loadWebSocketTransport = async () => await import('./websocket-transport.js') @@ -68,10 +64,7 @@ export class RuntimeClient { private readonly originalArgs: readonly string[] | undefined private readonly remoteCompat: RemoteRuntimeCompatGate private orchestrationContractCheck: Promise | null = null - private readonly orchestrationCompatibility = createOrchestrationCompatibilityEnvelope( - process.env - ) - private readonly agentLaunchCaller = createAgentLaunchCallerEvidence(process.env) + private readonly requestEvidence = new OrchestrationRequestEvidence(process.env) private readonly runtimeSourceFence: RuntimeSourceFence // Browser session cold starts can take 15–30 seconds; allow time for initialization. @@ -139,15 +132,11 @@ export class RuntimeClient { : error } } - const compatibilityEnvelope = method.startsWith('orchestration.') - ? { - ...this.orchestrationCompatibility, - compatibilityInvocationId: - orchestrationRequestId ?? this.orchestrationCompatibility.compatibilityInvocationId - } - : AGENT_LAUNCH_METHODS.has(method) && !this.remote && this.agentLaunchCaller - ? { orchestrationCompatibilityEvidence: this.agentLaunchCaller } - : {} + const compatibilityEnvelope = this.requestEvidence.envelopeFor(method, { + remote: this.remote !== null, + mutation: orchestrationMutation, + requestId: orchestrationRequestId + }) const envelope = { orchestrationCapability: options?.orchestrationCapability, orchestrationContractVersion: method.startsWith('orchestration.') diff --git a/src/cli/runtime/orchestration-compatibility-envelope.ts b/src/cli/runtime/orchestration-compatibility-envelope.ts index a40fe6868ab..be78e8dee2f 100644 --- a/src/cli/runtime/orchestration-compatibility-envelope.ts +++ b/src/cli/runtime/orchestration-compatibility-envelope.ts @@ -26,3 +26,40 @@ export function createAgentLaunchCallerEvidence( } return { agentSessionId } } + +const AGENT_LAUNCH_METHODS: ReadonlySet = new Set(['agent.launch', 'agent.launchReplay']) + +/** The caller evidence one request carries, read from this process's environment once. */ +export class OrchestrationRequestEvidence { + private readonly orchestration: RuntimeOrchestrationEnvelope + // A chat's session id means nothing on another server, so reads there go like a shell's. + private readonly remoteRead: RuntimeOrchestrationEnvelope + private readonly agentLaunchCaller: RuntimeOrchestrationEnvelope['orchestrationCompatibilityEvidence'] + + constructor(env: NodeJS.ProcessEnv) { + this.orchestration = createOrchestrationCompatibilityEnvelope(env) + const { agentSessionId: _session, ...shell } = + this.orchestration.orchestrationCompatibilityEvidence ?? {} + this.remoteRead = { + ...this.orchestration, + orchestrationCompatibilityEvidence: Object.keys(shell).length > 0 ? shell : undefined + } + this.agentLaunchCaller = createAgentLaunchCallerEvidence(env) + } + + envelopeFor( + method: string, + request: { remote: boolean; mutation: boolean; requestId: string | undefined } + ): RuntimeOrchestrationEnvelope { + if (method.startsWith('orchestration.')) { + const base = request.remote && !request.mutation ? this.remoteRead : this.orchestration + return { + ...base, + compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId + } + } + return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller + ? { orchestrationCompatibilityEvidence: this.agentLaunchCaller } + : {} + } +} diff --git a/src/cli/runtime/orchestration-request-evidence.test.ts b/src/cli/runtime/orchestration-request-evidence.test.ts new file mode 100644 index 00000000000..aceef390bc2 --- /dev/null +++ b/src/cli/runtime/orchestration-request-evidence.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope' + +const CHAT = { ORCA_AGENT_SESSION_ID: '11111111-1111-4111-8111-111111111111' } + +describe('caller evidence on requests to another server', () => { + it('sends a chat read there like a shell, with no session id', () => { + const evidence = new OrchestrationRequestEvidence(CHAT) + expect( + evidence.envelopeFor('orchestration.inbox', { + remote: true, + mutation: false, + requestId: undefined + }).orchestrationCompatibilityEvidence + ).toBeUndefined() + }) + + it('keeps the session id on writes there, so that server still refuses them', () => { + const evidence = new OrchestrationRequestEvidence(CHAT) + expect( + evidence.envelopeFor('orchestration.taskCreate', { + remote: true, + mutation: true, + requestId: 'request_1' + }).orchestrationCompatibilityEvidence + ).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' }) + }) +}) diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 5de2e60ef2a..e5380209f1e 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -49,10 +49,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'send'], summary: 'Send an inter-agent message', usage: - 'orca orchestration send --subject [--to ] [--run ] [--from ] [--body ] [--type ] [--priority ] [--thread-id ] [--payload ] [--task-id ] [--dispatch-id ] [--outcome ] [--files-modified ] [--report-path ] [--phase ] [--retry-request ] [--json]', + 'orca orchestration send --subject [--to ] [--on ] [--run ] [--from ] [--body ] [--type ] [--priority ] [--thread-id ] [--payload ] [--task-id ] [--dispatch-id ] [--outcome ] [--files-modified ] [--report-path ] [--phase ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'to', + 'on', 'run', 'from', 'subject', @@ -82,7 +83,8 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'From a worker, an omitted recipient defaults to its coordinator, also after it finished; mail sent after finishing, worker_done included, leaves the finished task unchanged.', 'Use --to dispatch: for attempt-specific coordinator guidance; Orca durably relays it to a connected worker server.', 'A worker_done with the active task/dispatch IDs completes that task only from the dispatched pane. When stable pane identity is unavailable, the sender handle must exactly match the dispatch assignee; injected preambles include the correct --from value.', - 'Prefer --task-id/--dispatch-id/etc. over raw --payload JSON in worker commands; PowerShell strips JSON quotes easily.' + 'Prefer --task-id/--dispatch-id/etc. over raw --payload JSON in worker commands; PowerShell strips JSON quotes easily.', + '--on mails a terminal or chat agent on a paired server (--to term_… or orca_session_id:…). Your own Orca carries it, and replies come back to your own check. From an agent, --server runs the command on that server and delivers no mail.' ] }, { @@ -126,8 +128,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ summary: 'Reply to a message', usage: 'orca orchestration reply --id --body [--run ] [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'id', 'body', 'run', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } + allowedFlags: [...GLOBAL_FLAGS, 'id', 'body', 'run', 'from', 'on', 'retry-request'], + identityFlagRoles: { from: 'caller' }, + notes: [ + 'A reply to mail from an agent on another server goes back to that server by itself; no flag is needed.' + ] }, { path: ['orchestration', 'inbox'], diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 8c28e659ffb..3aa8d1a4cc9 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -61,6 +61,7 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contrac import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' import type { OrchestrationDb } from './orchestration/db/orchestration-db' import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through' +import { PeerMailRelay } from './orchestration/federation/peer-mail/peer-mail-relay' const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN ? OrcaRuntimeWithSidebarTemporal @@ -68,6 +69,20 @@ const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDE // oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- SAFETY: The existing Linear installer supplies the canonical prototype surface. class OrcaRuntimeService extends OrcaRuntimeSidebarBase { + // Lazy: the database can open, and arm relays, while the runtime is still constructing. + declare private peerMailRelay: PeerMailRelay | undefined + + override ensureOrchestrationFederationRelay(runId?: string): void { + super.ensureOrchestrationFederationRelay(runId) + this.peerMailRelay ??= new PeerMailRelay(this, () => this.orchestrationEnvironmentTransport) + this.peerMailRelay.ensure() + } + + override stopOrchestrationFederationRelay(): void { + super.stopOrchestrationFederationRelay() + this.peerMailRelay?.stop() + } + /** Sidebar facts are absent unless ORCA_SIDEBAR_INPUTS=main. */ get sidebarFacts() { return sidebarFactsRuntime(this) diff --git a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts index f15cb9c577a..a8d353e63a1 100644 --- a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts @@ -18,6 +18,7 @@ import { attachRemoteDispatchAttachmentCreate } from './federation/remote-dispat import { attachRemoteDispatchAttachmentRelease } from './federation/remote-dispatch-attachment-release' import { attachRemoteDispatchAttachmentStop } from './federation/remote-dispatch-attachment-stop' import { attachRemoteQuestionStore } from './federation/remote-question-store' +import { attachPeerMailStore } from './federation/peer-mail-store' import { attachLegacyAskOperation } from './legacy/legacy-ask-operation' import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates' import { attachLegacyCompatibilityPrincipals } from './legacy/legacy-compatibility-principals' @@ -122,6 +123,7 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void attachFederationRelayAck(ctor) attachFederationRelayImport(ctor) attachRemoteQuestionStore(ctor) + attachPeerMailStore(ctor) attachFederationRelayItem(ctor) attachWorkerTerminalResourceStore(ctor) attachWorkerTerminalTransfer(ctor) diff --git a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts new file mode 100644 index 00000000000..b47a1b0b393 --- /dev/null +++ b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts @@ -0,0 +1,182 @@ +import type { MessageRow } from '../orchestration-records' +import type { MessageInsert } from '../messages/message-insert' +import { OrchestrationError } from '../../orchestration-error' +import { generateId } from '../generated-id' +import type { OrchestrationDb } from '../orchestration-db' + +export type PeerMailConversationRow = { + conversation_id: string + role: 'home' | 'peer' + environment_id: string | null + peer_fingerprint: string + local_party: string | null + local_pane_key: string | null + created_at: string +} + +export type PeerMailMessageRow = { + message_id: string + conversation_id: string + sender_label: string + remote_party: string | null +} + +/** The conversation this Orca opened for one local agent with one paired server; reused for every send. */ +export function openHomePeerMailConversation( + this: OrchestrationDb, + params: { + environmentId: string + peerFingerprint: string + localParty: string + localPaneKey: string | null + } +): PeerMailConversationRow { + this.db + .prepare( + `INSERT INTO peer_mail_conversations ( + conversation_id, role, environment_id, peer_fingerprint, local_party, local_pane_key + ) VALUES (?, 'home', ?, ?, ?, ?) + ON CONFLICT(environment_id, local_party) WHERE role = 'home' + DO UPDATE SET peer_fingerprint = excluded.peer_fingerprint, + local_pane_key = COALESCE(excluded.local_pane_key, local_pane_key)` + ) + .run( + generateId('peerconv'), + params.environmentId, + params.peerFingerprint, + params.localParty, + params.localPaneKey + ) + return this.db + .prepare( + `SELECT * FROM peer_mail_conversations + WHERE role = 'home' AND environment_id = ? AND local_party = ?` + ) + .get(params.environmentId, params.localParty) as PeerMailConversationRow +} + +export function getPeerMailConversation( + this: OrchestrationDb, + conversationId: string +): PeerMailConversationRow | undefined { + return this.db + .prepare('SELECT * FROM peer_mail_conversations WHERE conversation_id = ?') + .get(conversationId) as PeerMailConversationRow | undefined +} + +export function listHomePeerMailEnvironments(this: OrchestrationDb): string[] { + return ( + this.db + .prepare( + `SELECT DISTINCT environment_id FROM peer_mail_conversations + WHERE role = 'home' AND environment_id IS NOT NULL` + ) + .all() as { environment_id: string }[] + ).map((row) => row.environment_id) +} + +export function listPeerConversationIds(this: OrchestrationDb, peerFingerprint: string): string[] { + return ( + this.db + .prepare( + `SELECT conversation_id FROM peer_mail_conversations + WHERE role = 'peer' AND peer_fingerprint = ?` + ) + .all(peerFingerprint) as { conversation_id: string }[] + ).map((row) => row.conversation_id) +} + +export function getPeerMailMessage( + this: OrchestrationDb, + messageId: string +): PeerMailMessageRow | undefined { + return this.db.prepare('SELECT * FROM peer_mail_messages WHERE message_id = ?').get(messageId) as + | PeerMailMessageRow + | undefined +} + +export function isPeerMailSenderLabel(this: OrchestrationDb, label: string): boolean { + return ( + this.db + .prepare('SELECT 1 FROM peer_mail_messages WHERE sender_label = ? LIMIT 1') + .get(label) !== undefined + ) +} + +/** Stores mail that crossed from a paired Orca once; a replayed id returns the stored row. */ +export function insertPeerMailMessage( + this: OrchestrationDb, + params: { + conversationId: string + /** Only a 'peer' conversation is created here, by the paired Orca that opened it. */ + peerFingerprint?: string + remoteParty: string | null + message: MessageInsert & { id: string; from: string } + } +): { message: MessageRow; duplicate: boolean } { + this.db.exec('SAVEPOINT peer_mail_insert') + try { + if (params.peerFingerprint !== undefined) { + const conversation = this.getPeerMailConversation(params.conversationId) + if ( + conversation && + (conversation.role !== 'peer' || conversation.peer_fingerprint !== params.peerFingerprint) + ) { + throw new OrchestrationError( + 'request_mismatch', + `Conversation ${params.conversationId} belongs to another paired Orca. Nothing was delivered.`, + { effectsApplied: false } + ) + } + if (!conversation) { + this.db + .prepare( + `INSERT INTO peer_mail_conversations (conversation_id, role, peer_fingerprint) + VALUES (?, 'peer', ?)` + ) + .run(params.conversationId, params.peerFingerprint) + } + } + const existing = this.getPeerMailMessage(params.message.id) + const stored = existing ? this.getMessageById(params.message.id) : undefined + if (existing && stored) { + this.db.exec('RELEASE peer_mail_insert') + return { message: stored, duplicate: true } + } + const message = this.insertMessage(params.message) + this.db + .prepare( + `INSERT INTO peer_mail_messages (message_id, conversation_id, sender_label, remote_party) + VALUES (?, ?, ?, ?)` + ) + .run(message.id, params.conversationId, params.message.from, params.remoteParty) + this.db.exec('RELEASE peer_mail_insert') + return { message, duplicate: false } + } catch (error) { + this.db.exec('ROLLBACK TO peer_mail_insert') + this.db.exec('RELEASE peer_mail_insert') + throw error + } +} + +export type PeerMailStoreMethods = { + openHomePeerMailConversation: typeof openHomePeerMailConversation + getPeerMailConversation: typeof getPeerMailConversation + listHomePeerMailEnvironments: typeof listHomePeerMailEnvironments + listPeerConversationIds: typeof listPeerConversationIds + getPeerMailMessage: typeof getPeerMailMessage + isPeerMailSenderLabel: typeof isPeerMailSenderLabel + insertPeerMailMessage: typeof insertPeerMailMessage +} + +export function attachPeerMailStore(ctor: { prototype: object }): void { + Object.assign(ctor.prototype, { + openHomePeerMailConversation, + getPeerMailConversation, + listHomePeerMailEnvironments, + listPeerConversationIds, + getPeerMailMessage, + isPeerMailSenderLabel, + insertPeerMailMessage + }) +} diff --git a/src/main/runtime/orchestration/db/orchestration-db-methods.ts b/src/main/runtime/orchestration/db/orchestration-db-methods.ts index 1de24dd9a41..824b031a2ee 100644 --- a/src/main/runtime/orchestration/db/orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/orchestration-db-methods.ts @@ -17,6 +17,7 @@ import type { RemoteDispatchAttachmentCreateMethods } from './federation/remote- import type { RemoteDispatchAttachmentReleaseMethods } from './federation/remote-dispatch-attachment-release' import type { RemoteDispatchAttachmentStopMethods } from './federation/remote-dispatch-attachment-stop' import type { RemoteQuestionStoreMethods } from './federation/remote-question-store' +import type { PeerMailStoreMethods } from './federation/peer-mail-store' import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation' import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates' import type { LegacyCompatibilityPrincipalsMethods } from './legacy/legacy-compatibility-principals' @@ -119,6 +120,7 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods & FederationRelayAckMethods & FederationRelayImportMethods & RemoteQuestionStoreMethods & + PeerMailStoreMethods & FederationRelayItemMethods & StructuredMailSendStoreMethods & WorkerTerminalResourceStoreMethods & diff --git a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts index 9d0faa09527..3099bdb9aba 100644 --- a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts +++ b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts @@ -115,6 +115,34 @@ CREATE TABLE IF NOT EXISTS remote_questions ( CREATE INDEX IF NOT EXISTS idx_remote_questions_dispatch_status ON remote_questions(dispatch_id, status); +-- Agent mail between paired Orcas. 'home': this Orca opened it for local_party and pulls replies +-- from environment_id. 'peer': the paired Orca peer_fingerprint opened it here; its replies wait in +-- federation_relay_items under dispatch_id = conversation_id until that Orca pulls them. +CREATE TABLE IF NOT EXISTS peer_mail_conversations ( + conversation_id TEXT PRIMARY KEY, + role TEXT NOT NULL CHECK(role IN ('home', 'peer')), + environment_id TEXT, + peer_fingerprint TEXT NOT NULL, + local_party TEXT, + local_pane_key TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_peer_mail_home_party + ON peer_mail_conversations(environment_id, local_party) WHERE role = 'home'; +CREATE INDEX IF NOT EXISTS idx_peer_mail_peer_fingerprint + ON peer_mail_conversations(peer_fingerprint, role); + +-- A message that crossed between paired Orcas: its reply goes back over its conversation, to remote_party. +CREATE TABLE IF NOT EXISTS peer_mail_messages ( + message_id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL, + sender_label TEXT NOT NULL, + remote_party TEXT +); + +CREATE INDEX IF NOT EXISTS idx_peer_mail_messages_sender ON peer_mail_messages(sender_label); + -- Deletes from tasks, dispatch_contexts and worker tables are recorded in removed_orchestration_work -- (removed-orchestration-work-store.ts). CREATE TABLE IF NOT EXISTS tasks ( diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts new file mode 100644 index 00000000000..9db442c4f85 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts @@ -0,0 +1,111 @@ +import { createHash } from 'node:crypto' +import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RuntimeStatus } from '../../../../../shared/runtime-session-contracts' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { PeerMailConversationRow } from '../../db/federation/peer-mail-store' +import { generateId } from '../../db/generated-id' +import { OrchestrationError } from '../../orchestration-error' +import type { OrchestrationWorkerServer } from '../environment-transport' + +export type PeerMailRuntime = Pick< + OrcaRuntimeService, + | 'getOrchestrationDb' + | 'resolveOrchestrationWorkerServer' + | 'callOrchestrationWorkerServer' + | 'notifyMessageArrived' + | 'readMachineName' + | 'getTerminalHandleForPaneKey' +> + +const NOTHING_SENT = { effectsApplied: false } as const +const DELIVER_TIMEOUT_MS = 15_000 + +/** "term_9f3c on Jinwoo's Mac": who sent it, and the Orca server it came from. */ +export function peerMailSenderLabel(runtime: PeerMailRuntime, sender: string): string { + return `${sender} on ${runtime.readMachineName()}` +} + +/** A retried mutation reuses its message id, so the server stores the mail once. */ +export function peerMailMessageId( + mutation: { callerFingerprint: string; requestId: string } | undefined +): string { + if (!mutation) { + return generateId('msg') + } + const digest = createHash('sha256') + .update(`${mutation.callerFingerprint}\0${mutation.requestId}`) + .digest('hex') + return `msg_${digest.slice(0, 12)}` +} + +/** Refuses before any effect when the server's Orca cannot receive mail or queue its replies. */ +export async function requirePeerMailServer( + runtime: PeerMailRuntime, + selector: string +): Promise { + const server = runtime.resolveOrchestrationWorkerServer(selector) + const status = (await runtime.callOrchestrationWorkerServer( + server.environmentId, + 'status.get', + undefined, + DELIVER_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + )) as RuntimeStatus + if (!status.capabilities?.includes(ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY)) { + throw new OrchestrationError( + 'peer_mail_unsupported', + `Server ${server.name} runs an older Orca that cannot receive agent mail from another server. Update Orca on ${server.name}, then send again. Nothing was sent.`, + { ...NOTHING_SENT, server: server.name } + ) + } + return server +} + +/** Hands one message to the paired server; it stores it once and delivers it with its own mail code. */ +export async function deliverPeerMail( + runtime: PeerMailRuntime, + server: OrchestrationWorkerServer, + conversation: PeerMailConversationRow, + message: { + id: string + to: string + senderLabel: string + subject: string + body?: string + type?: 'status' | 'handoff' + priority?: 'normal' | 'high' | 'urgent' + threadId?: string + } +): Promise { + await runtime.callOrchestrationWorkerServer( + server.environmentId, + 'orchestration.peerMailDeliver', + { + conversationId: conversation.conversation_id, + messageId: message.id, + to: message.to, + senderLabel: message.senderLabel, + subject: message.subject, + ...(message.body !== undefined ? { body: message.body } : {}), + ...(message.type ? { type: message.type } : {}), + ...(message.priority ? { priority: message.priority } : {}), + ...(message.threadId ? { threadId: message.threadId } : {}) + }, + DELIVER_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + ) +} + +/** Where a pulled reply lands: the opener's current mailbox, following a terminal's remint by pane. */ +export function peerMailLocalRecipient( + runtime: PeerMailRuntime, + conversation: PeerMailConversationRow +): string { + const party = conversation.local_party ?? '' + const reminted = conversation.local_pane_key + ? runtime.getTerminalHandleForPaneKey(conversation.local_pane_key) + : null + return reminted ?? party +} diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts new file mode 100644 index 00000000000..6db09b5bb25 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts @@ -0,0 +1,174 @@ +import { z } from 'zod' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { PeerMailRelayPayload } from '../../../../../shared/rpc-contract/orchestration-peer-mail-params' +import { resolveBareOrchestrationRecipient } from '../../../rpc/methods/orchestration/messaging/recipient-routing' +import type { OrchestrationDb } from '../../db/orchestration-db' +import type { MessageRow } from '../../db/orchestration-records' +import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler' +import type { OrchestrationEnvironmentTransport } from '../environment-transport' +import { peerMailLocalRecipient } from './peer-mail-delivery' + +// Under the relay edge's idle cutoff, so an idle pull ends by itself instead of being dropped. +const PULL_WAIT_MS = 20_000 +const PULL_TIMEOUT_MS = PULL_WAIT_MS + 15_000 + +const PulledPeerMail = z.object({ + items: z.array( + z.object({ + conversationId: z.string(), + sequence: z.number().int().positive(), + messageId: z.string(), + payload: z.string() + }) + ) +}) + +type Loop = { db: OrchestrationDb; stopped: boolean } + +/** One pull loop per paired server this Orca opened conversations with. The server never dials + * back: each pull waits there for a reply, stores it as local mail, then acknowledges it. */ +export class PeerMailRelay { + private readonly loops = new Map() + + constructor( + private readonly runtime: OrcaRuntimeService, + private readonly transport: () => OrchestrationEnvironmentTransport | null + ) {} + + ensure(): void { + if (!this.transport()) { + return + } + const db = this.runtime.getOrchestrationDb() + for (const environmentId of db.listHomePeerMailEnvironments()) { + const current = this.loops.get(environmentId) + if (current && !current.stopped && current.db === db) { + continue + } + const loop: Loop = { db, stopped: false } + this.loops.set(environmentId, loop) + void this.run(environmentId, loop) + } + } + + stop(): void { + for (const loop of this.loops.values()) { + loop.stopped = true + } + this.loops.clear() + } + + private isCurrent(environmentId: string, loop: Loop): boolean { + return ( + !loop.stopped && + this.loops.get(environmentId) === loop && + this.runtime.getOrchestrationDb() === loop.db + ) + } + + private async run(environmentId: string, loop: Loop): Promise { + let failures = 0 + while (this.isCurrent(environmentId, loop)) { + try { + await this.pullOnce(environmentId, loop) + failures = 0 + } catch { + if (this.transport()?.hasEnvironment?.(environmentId) === false) { + // A removed server cannot answer; the next ensure re-arms it if it is added back. + break + } + failures += 1 + await new Promise((resolve) => { + setTimeout(resolve, federationRelayRetryDelayMs(failures)).unref?.() + }) + } + } + if (this.loops.get(environmentId) === loop) { + this.loops.delete(environmentId) + } + } + + private async pullOnce(environmentId: string, loop: Loop): Promise { + const response = await this.runtime.callOrchestrationWorkerServer( + environmentId, + 'orchestration.peerMailPull', + { waitMs: PULL_WAIT_MS }, + PULL_TIMEOUT_MS + ) + if (!this.isCurrent(environmentId, loop)) { + return + } + const { items } = PulledPeerMail.parse(response) + if (items.length === 0) { + return + } + const through = new Map() + for (const item of items) { + const stored = this.importReply(loop.db, environmentId, item) + // Wake before the ack: a replay after a failed ack finds the row stored and stays quiet. + if (stored) { + this.runtime.notifyMessageArrived(stored.to_handle, stored.type) + } + through.set( + item.conversationId, + Math.max(through.get(item.conversationId) ?? 0, item.sequence) + ) + } + await this.runtime.callOrchestrationWorkerServer( + environmentId, + 'orchestration.peerMailAck', + { + acknowledgments: [...through].map(([conversationId, throughSequence]) => ({ + conversationId, + throughSequence + })) + }, + 15_000 + ) + } + + /** Stores a pulled reply once; a replay after a crash before the ack finds the stored row. */ + private importReply( + db: OrchestrationDb, + environmentId: string, + item: z.infer['items'][number] + ): MessageRow | undefined { + const conversation = db.getPeerMailConversation(item.conversationId) + const payload = PeerMailRelayPayload.safeParse(safeJson(item.payload)) + if ( + conversation?.role !== 'home' || + conversation.environment_id !== environmentId || + !payload.success + ) { + // Nothing here can read it; acknowledging keeps the server's queue moving. + console.warn( + `[orchestration] Dropped unreadable reply ${item.messageId} from ${environmentId}` + ) + return undefined + } + const handle = peerMailLocalRecipient(this.runtime, conversation) + const recipient = resolveBareOrchestrationRecipient({ runtime: this.runtime, db, handle }) + const stored = db.insertPeerMailMessage({ + conversationId: conversation.conversation_id, + remoteParty: payload.data.fromAddress, + message: { + id: item.messageId, + from: payload.data.senderLabel, + to: recipient.ok ? recipient.to : handle, + subject: payload.data.subject, + body: payload.data.body, + threadId: payload.data.threadId ?? undefined, + runId: recipient.ok ? recipient.runId : undefined + } + }) + return stored.duplicate ? undefined : stored.message + } +} + +function safeJson(value: string): unknown { + try { + return JSON.parse(value) + } catch { + return null + } +} diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts new file mode 100644 index 00000000000..0e2b13c329d --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts @@ -0,0 +1,32 @@ +import type { OrchestrationDb } from '../../db/orchestration-db' + +const waiters = new WeakMap void>>() + +/** Wakes every pull waiting on this store; each re-reads its own conversations. */ +export function notifyPeerMailQueued(db: OrchestrationDb): void { + for (const wake of waiters.get(db) ?? []) { + wake() + } +} + +/** Resolves when a reply is queued, the wait ends, or the caller goes away. */ +export function waitForPeerMail( + db: OrchestrationDb, + timeoutMs: number, + signal?: AbortSignal +): Promise { + return new Promise((resolve) => { + const set = waiters.get(db) ?? new Set<() => void>() + waiters.set(db, set) + const done = (): void => { + clearTimeout(timer) + set.delete(done) + signal?.removeEventListener('abort', done) + resolve() + } + const timer = setTimeout(done, timeoutMs) + timer.unref?.() + set.add(done) + signal?.addEventListener('abort', done, { once: true }) + }) +} diff --git a/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts b/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts index 119c42b73cf..117f61bab8a 100644 --- a/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts +++ b/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts @@ -43,9 +43,11 @@ export function agentMessageSender( ): AgentMessageSender { const party = senderParty(address, db) const snapshot = snapshotSender(senderSnapshot, party, reportedDispatchId) + // Mail from another server is named by its label: "term_9f3c on Jinwoo's Mac". + const peerLabel = !snapshot.name && db?.isPeerMailSenderLabel(address) ? address : null return { party, - name: agentMessageSenderName(snapshot.name), + name: agentMessageSenderName(snapshot.name ?? peerLabel), ...(snapshot.agent ? { agent: snapshot.agent } : {}) } } diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index 4fe418b297c..5cc90053ad2 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -14,6 +14,7 @@ import { import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from './core' import { CONNECTOR_REPLY_ERROR_CODES } from '../../../shared/rpc-contract/connector-params' import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES } from '../../../shared/orchestration/orchestration-session-caller-codes' +import { ORCHESTRATION_FEDERATION_ERROR_CODES } from '../../../shared/orchestration/orchestration-federation-error-codes' import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery' import { COMPUTER_ERROR_CODES } from '../../../shared/computer-use-runtime-types' import { TerminalSplitOutcomeError } from '../../../shared/workspace-layout/terminal-split-outcome' @@ -143,15 +144,7 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ 'cursor_dispatch_mismatch', 'source_changed', 'transcript_required', - 'server_required', - 'worktree_not_found_on_server', - 'resource_server_mismatch', - 'peer_changed', - 'remote_runtime_unavailable', - 'runtime_timeout', - 'invalid_runtime_response', - 'capability_unsupported', - 'relay_quota_exceeded', + ...ORCHESTRATION_FEDERATION_ERROR_CODES, 'dispatch_capability_invalid', 'agent_unconfigured', 'worker_prompt_too_large', diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index 0d5f0856807..aa0c428653f 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -69,10 +69,16 @@ export const ORCHESTRATION_CALLER_METHODS = [ permission: 'workspace', params: null, // Dispatch already admitted the environment's session; do not resolve another caller from params. - handler: (_params, { orchestrationCaller }): OrchestrationCallerShowResult => ({ + handler: ( + _params, + { orchestrationCaller, orchestrationCompatibilityEvidence, runtime } + ): OrchestrationCallerShowResult => ({ caller: orchestrationCaller ? { orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), live: true } - : null + : null, + terminal: + !orchestrationCaller && + runtime.verifyOrchestrationCompatibilityCaller(orchestrationCompatibilityEvidence) !== null }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts index 589b69f3934..39c02e08332 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts @@ -1,9 +1,11 @@ import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './federation-control' import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './federation-relay' import { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './federation' +import { ORCHESTRATION_PEER_MAIL_METHODS } from './peer-mail-methods' export const ORCHESTRATION_FEDERATION_METHODS = [ ...ORCHESTRATION_FEDERATION_ATTACH_METHODS, ...ORCHESTRATION_FEDERATION_RELAY_METHODS, - ...ORCHESTRATION_FEDERATION_CONTROL_METHODS + ...ORCHESTRATION_FEDERATION_CONTROL_METHODS, + ...ORCHESTRATION_PEER_MAIL_METHODS ] 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 new file mode 100644 index 00000000000..32a6f4d76d3 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -0,0 +1,148 @@ +import { defineMethod, type RpcContext } from '../../../core' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { isGeneratedId } from '../../../../orchestration/db/generated-id' +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { FederationRelayItemRow } from '../../../../orchestration/db/orchestration-records' +import { resolveBareOrchestrationRecipient } from '../messaging/recipient-routing' +import { mayNameSession } from '../messaging/session-recipient' +import { waitForPeerMail } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters' +import { + PeerMailAckParams, + PeerMailDeliverParams, + PeerMailPullParams +} from '../../../../../../shared/rpc-contract/orchestration-peer-mail-params' + +const NOTHING_DELIVERED = { effectsApplied: false } as const +const MAX_PULL_WAIT_MS = 25_000 +const PULL_PAGE_SIZE = 50 + +/** Peer mail comes only from a paired computer's Orca, never a phone or this Orca's own clients. */ +function requireRuntimePairing( + ctx: Pick +): string { + if ( + ctx.clientKind !== 'runtime' || + ctx.pairedDeviceId === undefined || + !ctx.authenticatedCallerFingerprint + ) { + throw new OrchestrationError( + 'peer_mail_requires_server_pairing', + 'Agent mail between Orca servers comes only from a paired computer. Nothing was delivered.', + NOTHING_DELIVERED + ) + } + return ctx.authenticatedCallerFingerprint +} + +function pendingReplies(db: OrchestrationDb, peerFingerprint: string): FederationRelayItemRow[] { + const items: FederationRelayItemRow[] = [] + for (const conversationId of db.listPeerConversationIds(peerFingerprint)) { + if (items.length >= PULL_PAGE_SIZE) { + break + } + items.push( + ...db.listPendingFederationRelay(conversationId, 'to_home', PULL_PAGE_SIZE - items.length) + ) + } + return items +} + +export const ORCHESTRATION_PEER_MAIL_METHODS = [ + defineMethod({ + name: 'orchestration.peerMailDeliver', + permission: 'workspace', + params: PeerMailDeliverParams, + handler: async (params, ctx) => { + const peerFingerprint = requireRuntimePairing(ctx) + const { runtime } = ctx + const db = runtime.getOrchestrationDb() + if (!isGeneratedId(params.messageId, 'msg')) { + throw new OrchestrationError('invalid_argument', 'Peer mail needs a message ID.') + } + const to = params.to + if (/^(run|dispatch|task):/.test(to) || to.startsWith('@')) { + throw new OrchestrationError( + 'invalid_argument', + `--on sends to one terminal or chat agent on this server; ${to} is a mailbox. Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + if (mayNameSession(to)) { + // Recipient routing reads the session record store, which the host opens lazily. + await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + } + const recipient = resolveBareOrchestrationRecipient({ runtime, db, handle: to }) + if (!recipient.ok) { + throw new OrchestrationError( + recipient.code, + `${recipient.message} Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + const stored = db.insertPeerMailMessage({ + conversationId: params.conversationId, + peerFingerprint, + remoteParty: null, + message: { + id: params.messageId, + from: params.senderLabel, + to: recipient.to, + subject: params.subject, + body: params.body, + type: params.type, + priority: params.priority, + threadId: params.threadId, + runId: recipient.runId + } + }) + if (!stored.duplicate) { + runtime.notifyMessageArrived(stored.message.to_handle, stored.message.type) + } + return { message: { id: stored.message.id, to } } + } + }), + defineMethod({ + name: 'orchestration.peerMailPull', + permission: 'workspace', + params: PeerMailPullParams, + handler: async (params, ctx) => { + const peerFingerprint = requireRuntimePairing(ctx) + const db = ctx.runtime.getOrchestrationDb() + let items = pendingReplies(db, peerFingerprint) + const waitMs = Math.min(Math.max(params.waitMs ?? 0, 0), MAX_PULL_WAIT_MS) + if (items.length === 0 && waitMs > 0) { + await waitForPeerMail(db, waitMs, ctx.signal) + items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint) + } + return { + items: items.map((item) => ({ + conversationId: item.dispatch_id, + sequence: item.sequence, + messageId: item.message_id, + payload: item.payload + })) + } + } + }), + defineMethod({ + name: 'orchestration.peerMailAck', + permission: 'workspace', + params: PeerMailAckParams, + handler: (params, ctx) => { + const peerFingerprint = requireRuntimePairing(ctx) + const db = ctx.runtime.getOrchestrationDb() + for (const ack of params.acknowledgments) { + const conversation = db.getPeerMailConversation(ack.conversationId) + if (conversation?.role !== 'peer' || conversation.peer_fingerprint !== peerFingerprint) { + continue + } + db.acknowledgeFederationRelay({ + dispatchId: ack.conversationId, + direction: 'to_home', + throughSequence: ack.throughSequence + }) + } + return { acknowledged: params.acknowledgments.length } + } + }) +] 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 new file mode 100644 index 00000000000..39e48a2caaf --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts @@ -0,0 +1,256 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + ORCHESTRATION_CONTRACT_VERSION, + ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY +} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RuntimeRpcResponse } from '../../../../../../shared/runtime-rpc-envelope' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationEnvironmentTransport } from '../../../../orchestration/federation/environment-transport' +import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import { RpcDispatcher } from '../../../dispatcher' +import type { RpcContext } from '../../../core' +import { ORCHESTRATION_METHODS } from '../orchestration' +import { ORCHESTRATION_REPLY_METHOD } from '../messaging/reply-method' + +const A_PANE = 'tab_a:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' +const B_PANE = 'tab_b:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +const CHAT_ON_A = 'orca_session_id:11111111-1111-4111-8111-111111111111' +const CHAT_ON_B = 'orca_session_id:22222222-2222-4222-8222-222222222222' + +type Side = { db: OrchestrationDb; runtime: OrcaRuntimeService; dispatcher: RpcDispatcher } + +describe('agent mail between paired Orca servers', () => { + let dir: string + let a: Side + let b: Side + let bCapabilities: (capabilities: string[]) => string[] + let bClientKind: 'runtime' | 'mobile' + + function openSide(name: string, machine: string, transport?: OrchestrationEnvironmentTransport) { + const db = new OrchestrationDb(join(dir, `${name}.db`)) + const runtime = new OrcaRuntimeService(null, undefined, { + orchestrationEnvironmentTransport: transport + }) + vi.spyOn(runtime, 'readMachineName').mockReturnValue(machine) + vi.spyOn(runtime, 'getTerminalHandleForPaneKey').mockReturnValue(null) + const panes: Record = { term_a: A_PANE, term_b: B_PANE } + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation( + (handle) => panes[handle] ?? null + ) + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => panes[handle] ?? null) + runtime.setOrchestrationDb(db) + return { + db, + runtime, + dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + } + } + + const transport: OrchestrationEnvironmentTransport = { + resolve: () => ({ environmentId: 'env_b', name: 'devB', peerFingerprint: 'fingerprint_b' }), + hasEnvironment: () => true, + call: async (_selector, method, params) => { + if (method === 'status.get') { + const status = b.runtime.getStatus() + return { + id: 'status', + ok: true, + result: { ...status, capabilities: bCapabilities(status.capabilities ?? []) }, + _meta: { runtimeId: b.runtime.getRuntimeId() } + } + } + return (await b.dispatcher.dispatch( + { + id: `from_a_${method}`, + authToken: 'a-device-token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }, + { + authenticatedCallerFingerprint: 'fingerprint_a', + pairedDeviceId: 'device_a', + clientKind: bClientKind + } + )) as RuntimeRpcResponse + } + } + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-peer-mail-')) + bCapabilities = (capabilities) => capabilities + bClientKind = 'runtime' + b = openSide('b', 'Build Box') + a = openSide('a', "Jinwoo's Mac", transport) + }) + + afterEach(() => { + a.runtime.stopOrchestrationFederationRelay() + b.runtime.stopOrchestrationFederationRelay() + a.db.close() + b.db.close() + rmSync(dir, { recursive: true, force: true }) + }) + + let requestCount = 0 + function mutation(side: Side, method: string, params: Record) { + requestCount += 1 + return side.dispatcher.dispatch({ + id: `${method}_${requestCount}`, + authToken: 'local', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: `request_${requestCount}`, + method, + params + }) + } + + function chatReply(side: Side, caller: string, params: { id: string; body: string }) { + const orchestrationCaller = { + address: caller, + terminalHandle: null, + orcaSessionId: caller.slice('orca_session_id:'.length), + paneKey: null + } as unknown as OrchestrationSessionCaller + return ORCHESTRATION_REPLY_METHOD.handler(params, { + runtime: side.runtime, + orchestrationCaller + } as RpcContext) + } + + function mailFor(side: Side, handle: string) { + return side.db.getUnreadMessages(handle) + } + + it('carries a terminal agent mail to the paired server and its flagless reply back', async () => { + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Check the build', + body: 'Is main green?' + }) + expect(sent).toMatchObject({ ok: true, result: { server: 'devB', message: { to: 'term_b' } } }) + + const [onB] = mailFor(b, 'term_b') + expect(onB).toMatchObject({ from_handle: "term_a on Jinwoo's Mac", subject: 'Check the build' }) + + const replied = await mutation(b, 'orchestration.reply', { + id: onB!.id, + body: 'Green.', + from: 'term_b' + }) + expect(replied).toMatchObject({ + ok: true, + result: { message: { subject: 'Re: Check the build' } } + }) + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1)) + const [back] = mailFor(a, 'term_a') + expect(back).toMatchObject({ + from_handle: 'term_b on Build Box', + subject: 'Re: Check the build', + body: 'Green.', + thread_id: onB!.id + }) + + // The opener can keep answering, and the reply reaches the same agent again. + await expect( + mutation(a, 'orchestration.reply', { id: back!.id, body: 'Thanks.', from: 'term_a' }) + ).resolves.toMatchObject({ ok: true }) + expect(mailFor(b, 'term_b').map((message) => message.body)).toEqual(['Thanks.']) + }) + + it('returns a chat agent reply to the chat on the opening server', async () => { + const send = ORCHESTRATION_METHODS.find((method) => method.name === 'orchestration.send')! + await send.handler({ from: CHAT_ON_A, on: 'devB', to: 'term_b', subject: 'Plan?' }, { + runtime: a.runtime, + orchestrationCaller: { + address: CHAT_ON_A, + terminalHandle: null, + orcaSessionId: CHAT_ON_A.slice(16), + paneKey: null + } + } as unknown as RpcContext) + const [onB] = mailFor(b, 'term_b') + expect(onB!.from_handle).toBe(`${CHAT_ON_A} on Jinwoo's Mac`) + + await chatReply(b, CHAT_ON_B, { id: onB!.id, body: 'Plan attached.' }) + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, CHAT_ON_A)).toHaveLength(1)) + expect(mailFor(a, CHAT_ON_A)[0]).toMatchObject({ + from_handle: `${CHAT_ON_B} on Build Box`, + body: 'Plan attached.' + }) + expect(a.db.getPeerMailMessage(mailFor(a, CHAT_ON_A)[0]!.id)?.remote_party).toBe(CHAT_ON_B) + }) + + it('delivers a reply queued before both servers restart exactly once', async () => { + await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Long job' + }) + const [onB] = mailFor(b, 'term_b') + await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Done.', from: 'term_b' }) + + a.runtime.stopOrchestrationFederationRelay() + a.db.close() + b.db.close() + b = openSide('b', 'Build Box') + a = openSide('a', "Jinwoo's Mac", transport) + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1)) + const [conversationId] = b.db.listPeerConversationIds('fingerprint_a') + expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([]) + + // A second loop after another restart finds nothing new. + a.runtime.stopOrchestrationFederationRelay() + a.runtime.ensureOrchestrationFederationRelay() + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(a.db.getInbox(10).filter((message) => message.to_handle === 'term_a')).toHaveLength(1) + }) + + it('refuses an older server before sending anything', async () => { + bCapabilities = (capabilities) => + capabilities.filter((capability) => capability !== ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY) + + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Hello' + }) + + expect(sent).toMatchObject({ + ok: false, + error: { code: 'peer_mail_unsupported', data: { effectsApplied: false } } + }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('takes peer mail only from a paired computer, not a phone', async () => { + bClientKind = 'mobile' + + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Hello' + }) + + expect(sent).toMatchObject({ + ok: false, + error: { code: 'peer_mail_requires_server_pairing' } + }) + expect(b.db.getInbox(10)).toEqual([]) + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts new file mode 100644 index 00000000000..c83e728ac52 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts @@ -0,0 +1,107 @@ +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { PeerMailMessageRow } from '../../../../orchestration/db/federation/peer-mail-store' +import type { MessageRow } from '../../../../orchestration/db/orchestration-records' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { + deliverPeerMail, + peerMailMessageId, + peerMailSenderLabel, + requirePeerMailServer +} from '../../../../orchestration/federation/peer-mail/peer-mail-delivery' +import { notifyPeerMailQueued } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters' +import { recordReceiptBeforeNudge } from './mutation-replay-nudge' + +const NOTHING_SENT = { effectsApplied: false } as const + +/** A reply to mail that came from another Orca goes back over that mail's conversation. */ +export async function replyOverPeerMail(args: { + runtime: OrcaRuntimeService + original: MessageRow + route: PeerMailMessageRow + params: { body: string; from?: string; on?: string } + orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined + recordMutationReceipt: ((receipt: unknown) => void) | undefined +}): Promise { + const { runtime, original, route, params } = args + const db = runtime.getOrchestrationDb() + const conversation = db.getPeerMailConversation(route.conversation_id) + if (!conversation) { + throw new OrchestrationError( + 'request_mismatch', + `The conversation ${original.id} came on is gone from this Orca. No reply was sent.`, + NOTHING_SENT + ) + } + const replier = args.orchestrationCaller?.address ?? params.from ?? original.to_handle + const id = peerMailMessageId(args.orchestrationMutation) + const subject = original.subject.startsWith('Re: ') ? original.subject : `Re: ${original.subject}` + const threadId = original.thread_id ?? original.id + const senderLabel = peerMailSenderLabel(runtime, replier) + + if (conversation.role === 'peer') { + if (params.on !== undefined) { + throw new OrchestrationError( + 'request_mismatch', + `${original.id} came from ${original.from_handle}; its reply goes back there by itself. Drop --on. No reply was sent.`, + NOTHING_SENT + ) + } + db.enqueueFederationRelay({ + dispatchId: conversation.conversation_id, + direction: 'to_home', + kind: 'peer_mail', + messageId: id, + payload: JSON.stringify({ + senderLabel, + fromAddress: replier, + subject, + body: params.body, + threadId + }) + }) + db.markAsRead([original.id]) + return recordReceiptBeforeNudge( + args.recordMutationReceipt, + { message: { id, subject }, to: original.from_handle }, + () => notifyPeerMailQueued(db), + { kind: 'messages', targets: [] } + ) + } + + const environmentId = conversation.environment_id ?? '' + if (params.on !== undefined) { + const named = runtime.resolveOrchestrationWorkerServer(params.on) + if (named.environmentId !== environmentId) { + throw new OrchestrationError( + 'request_mismatch', + `${original.id} came from server ${original.from_handle}, not ${named.name}. Drop --on; the reply goes back there by itself. No reply was sent.`, + NOTHING_SENT + ) + } + } + if (!route.remote_party) { + throw new OrchestrationError( + 'request_mismatch', + `${original.id} does not say who sent it. No reply was sent.`, + NOTHING_SENT + ) + } + const server = await requirePeerMailServer(runtime, environmentId) + await deliverPeerMail(runtime, server, conversation, { + id, + to: route.remote_party, + senderLabel, + subject, + body: params.body, + threadId + }) + db.markAsRead([original.id]) + return recordReceiptBeforeNudge( + args.recordMutationReceipt, + { message: { id, subject }, to: original.from_handle, server: server.name }, + () => runtime.ensureOrchestrationFederationRelay(), + { kind: 'federation' } + ) +} 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 new file mode 100644 index 00000000000..bddad9d851f --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts @@ -0,0 +1,118 @@ +import type { z } from 'zod' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationCompatibilityCallerAuthority } from '../../../../orchestration/terminal-authority/orchestration-compatibility-authority' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { + deliverPeerMail, + peerMailMessageId, + peerMailSenderLabel, + requirePeerMailServer +} from '../../../../orchestration/federation/peer-mail/peer-mail-delivery' +import type { RpcContext } from '../../../core' +import { recordReceiptBeforeNudge } from './mutation-replay-nudge' +import type { SendParams } from './send-params' +import type { ORCHESTRATION_SEND_METHODS } from './send-methods' + +const NOTHING_SENT = { effectsApplied: false } as const + +/** The agent on this Orca that mail sent elsewhere answers to: a chat by its session, a terminal by its live pane. */ +export function peerMailLocalCaller(args: { + runtime: OrcaRuntimeService + from: string | undefined + orchestrationCaller: OrchestrationSessionCaller | undefined + attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined +}): { address: string; paneKey: string | null } { + if (args.orchestrationCaller) { + return { address: args.orchestrationCaller.address, paneKey: null } + } + const paneKey = + args.from === undefined + ? null + : (args.attestedCaller?.paneKey ?? args.runtime.getLiveTerminalPaneKey(args.from)) + if (!args.from || !paneKey) { + throw new OrchestrationError( + 'caller_required', + '--on needs a terminal or chat agent on this Orca to receive the replies. Run it from that agent. Nothing was sent.', + NOTHING_SENT + ) + } + return { address: args.from, paneKey } +} + +/** `send --on `: this Orca carries the mail and keeps the conversation the replies come back on. */ +export async function sendPeerMail(args: { + params: z.infer & { on: string } + runtime: OrcaRuntimeService + orchestrationCaller: OrchestrationSessionCaller | undefined + attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined + orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined + recordMutationReceipt: ((receipt: unknown) => void) | undefined +}): Promise { + const { params, runtime } = args + const to = params.to + if (!to || /^(run|dispatch|task):/.test(to) || to.startsWith('@')) { + throw new OrchestrationError( + 'invalid_argument', + `--on sends to one terminal or chat agent on that server: --to term_… or --to orca_session_id:…${to ? `, not ${to}` : ''}. Nothing was sent.`, + NOTHING_SENT + ) + } + const type = params.type ?? 'status' + if (type !== 'status' && type !== 'handoff') { + throw new OrchestrationError( + 'invalid_argument', + `--on carries --type status or handoff, not ${type}. Nothing was sent.`, + NOTHING_SENT + ) + } + const caller = peerMailLocalCaller({ ...args, from: params.from }) + const server = await requirePeerMailServer(runtime, params.on) + const conversation = runtime.getOrchestrationDb().openHomePeerMailConversation({ + environmentId: server.environmentId, + peerFingerprint: server.peerFingerprint, + localParty: caller.address, + localPaneKey: caller.paneKey + }) + const id = peerMailMessageId(args.orchestrationMutation) + await deliverPeerMail(runtime, server, conversation, { + id, + to, + senderLabel: peerMailSenderLabel(runtime, caller.address), + subject: params.subject, + body: params.body, + type, + priority: params.priority, + threadId: params.threadId + }) + return recordReceiptBeforeNudge( + args.recordMutationReceipt, + { message: { id, to }, server: server.name }, + () => runtime.ensureOrchestrationFederationRelay(), + { kind: 'federation' } + ) +} + +/** `orchestration.send` with `on` set goes to the paired server; every other send runs unchanged. */ +export function withPeerMailSend( + methods: typeof ORCHESTRATION_SEND_METHODS +): typeof ORCHESTRATION_SEND_METHODS { + return methods.map((method) => ({ + ...method, + handler: (params: Parameters[0], ctx: RpcContext) => { + const on = params.on + if (on === undefined || ctx.replayedMutationReceipt !== undefined) { + return method.handler(params, ctx) + } + const attested = ctx.orchestrationCompatibilityCallerAuthority + return sendPeerMail({ + params: { ...params, on }, + runtime: ctx.runtime, + orchestrationCaller: ctx.orchestrationCaller, + attestedCaller: attested?.terminalHandle === params.from ? attested : undefined, + orchestrationMutation: ctx.orchestrationMutation, + recordMutationReceipt: ctx.recordMutationReceipt + }) + } + })) +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts index b0bd4ec708f..f0ea51d87e7 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -14,6 +14,7 @@ import { recordReceiptBeforeNudge, replayMutationNudge } from './mutation-replay import { resolveReplyRecipient } from './recipient-routing' import { helperQuestionAnswerer } from './helper-question-answerer' import { replyToRemoteRunHome } from './reply-remote' +import { replyOverPeerMail } from './peer-mail-reply' import { withAnswerNext } from '../receipt-next' import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' import { @@ -35,6 +36,7 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ legacyCoordinatorRunId, recordMutationReceipt, replayedMutationReceipt, + orchestrationMutation, signal } ) => { @@ -157,6 +159,25 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ ) } + const peerRoute = db.getPeerMailMessage(original.id) + if (peerRoute) { + return await replyOverPeerMail({ + runtime, + original, + route: peerRoute, + params, + orchestrationCaller, + orchestrationMutation, + recordMutationReceipt + }) + } + if (params.on !== undefined) { + throw new OrchestrationError( + 'invalid_argument', + `${params.id} did not come from another server, so its reply stays on this Orca. Drop --on. No reply was sent.`, + { effectsApplied: false } + ) + } if (db.getRun(original.run_id)?.home_database === 'remote') { return await replyToRemoteRunHome({ runtime, db, original, params, signal }) } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index c9ba10ffe59..4c40eac6996 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -38,6 +38,7 @@ import { settledDispatchId } from './settled-worker-follow-through' +// `send --on ` is carried by withPeerMailSend (peer-mail-send.ts) before this handler runs. export const ORCHESTRATION_SEND_METHODS = [ defineMethod({ name: 'orchestration.send', diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts index 27bed5c0e56..cce983c33e3 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts @@ -33,6 +33,8 @@ export const SendParams = z // Use remint-stable pane keys to attest worker_done/heartbeat; from handles only route. senderPaneKey: OptionalString, run: OptionalString, + // A paired server: this Orca carries the mail there and the replies back (`send --on`). + on: OptionalString, waitForLifecycleSettlement: OptionalBoolean, devMode: OptionalBoolean }) diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration.ts b/src/main/runtime/rpc/methods/orchestration/orchestration.ts index 57ab816b30d..a9d551e8555 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration.ts @@ -5,6 +5,7 @@ import { ORCHESTRATION_WORKER_METHODS } from './worker/worker-methods' import { ORCHESTRATION_FEDERATION_METHODS } from './federation/federation-methods' import { ORCHESTRATION_MUTATION_REQUEST_METHODS } from './runs/mutation-request-show' import { ORCHESTRATION_SEND_METHODS } from './messaging/send-methods' +import { withPeerMailSend } from './messaging/peer-mail-send' import { ORCHESTRATION_CHECK_METHODS } from './messaging/check-methods' import { ORCHESTRATION_MESSAGE_METHODS } from './messaging/message-methods' import { ORCHESTRATION_DISPATCH_METHODS } from './runs/dispatch-methods' @@ -20,7 +21,7 @@ export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ ...ORCHESTRATION_WORKER_METHODS, ...ORCHESTRATION_FEDERATION_METHODS, ...ORCHESTRATION_MUTATION_REQUEST_METHODS, - ...ORCHESTRATION_SEND_METHODS, + ...withPeerMailSend(ORCHESTRATION_SEND_METHODS), ...ORCHESTRATION_CHECK_METHODS, ...ORCHESTRATION_MESSAGE_METHODS, ...ORCHESTRATION_DISPATCH_METHODS, diff --git a/src/shared/orchestration/orchestration-caller-status.ts b/src/shared/orchestration/orchestration-caller-status.ts index 09247dac759..fab82154b71 100644 --- a/src/shared/orchestration/orchestration-caller-status.ts +++ b/src/shared/orchestration/orchestration-caller-status.ts @@ -15,7 +15,11 @@ export type OrchestrationCallerRefusal = { export type CliStatusCaller = OrchestrationCallerSession | OrchestrationCallerRefusal /** `null`: the caller is not an Orca session. */ -export type OrchestrationCallerShowResult = { caller: OrchestrationCallerSession | null } +export type OrchestrationCallerShowResult = { + caller: OrchestrationCallerSession | null + /** True when this Orca verified the calling terminal agent's launch. Absent from older Orcas. */ + terminal?: boolean +} /** `orchestration.sessionAddress`: a session's Orca session ID, its `/clear` root's. */ export type OrchestrationSessionAddressResult = { orcaSessionId: string } diff --git a/src/shared/orchestration/orchestration-federation-error-codes.ts b/src/shared/orchestration/orchestration-federation-error-codes.ts new file mode 100644 index 00000000000..b9ecdabc899 --- /dev/null +++ b/src/shared/orchestration/orchestration-federation-error-codes.ts @@ -0,0 +1,14 @@ +/** Codes a paired-server call keeps end to end, so callers can tell a stale pairing from an old or unreachable server. */ +export const ORCHESTRATION_FEDERATION_ERROR_CODES = [ + 'server_required', + 'worktree_not_found_on_server', + 'resource_server_mismatch', + 'peer_changed', + 'remote_runtime_unavailable', + 'runtime_timeout', + 'invalid_runtime_response', + 'capability_unsupported', + 'relay_quota_exceeded', + 'peer_mail_unsupported', + 'peer_mail_requires_server_pairing' +] as const diff --git a/src/shared/orchestration/orchestration-runtime-capabilities.ts b/src/shared/orchestration/orchestration-runtime-capabilities.ts index 0fc0d688aa5..9aac5d474e3 100644 --- a/src/shared/orchestration/orchestration-runtime-capabilities.ts +++ b/src/shared/orchestration/orchestration-runtime-capabilities.ts @@ -38,6 +38,8 @@ export const ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION = 2 as const export const ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION = 3 as const export const ORCHESTRATION_CONTRACT_VERSION = 1 as const export const ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY = 'orchestration.contract.v1' as const +/** Receives agent mail a paired Orca carries for its agents, and queues replies for it to pull. */ +export const ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY = 'orchestration.peer-mail.v1' as const export const ORCHESTRATION_RUNTIME_CAPABILITIES = [ ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY, @@ -55,5 +57,6 @@ export const ORCHESTRATION_RUNTIME_CAPABILITIES = [ ORCHESTRATION_RETAINED_RUN_BINDINGS_RUNTIME_CAPABILITY, ORCHESTRATION_WORKER_TURN_STOP_REPORTS_RUNTIME_CAPABILITY, ORCHESTRATION_ASK_RETURNS_AT_ONCE_RUNTIME_CAPABILITY, - ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY + ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, + ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY ] as const diff --git a/src/shared/rpc-contract/orchestration-params.ts b/src/shared/rpc-contract/orchestration-params.ts index 74996c05da3..cedac9622cb 100644 --- a/src/shared/rpc-contract/orchestration-params.ts +++ b/src/shared/rpc-contract/orchestration-params.ts @@ -66,7 +66,9 @@ export const ReplyParams = z.object({ id: requiredString('Missing --id'), body: requiredString('Missing --body'), from: OptionalString, - run: OptionalString + run: OptionalString, + // Optional check: mail from a paired server always answers there. + on: OptionalString }) export const InboxParams = z.object({ diff --git a/src/shared/rpc-contract/orchestration-peer-mail-params.ts b/src/shared/rpc-contract/orchestration-peer-mail-params.ts new file mode 100644 index 00000000000..a0fca4764df --- /dev/null +++ b/src/shared/rpc-contract/orchestration-peer-mail-params.ts @@ -0,0 +1,41 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +/** Agent mail one Orca carries to an agent on a paired Orca, inside a conversation the sender's Orca opened. */ +export const PeerMailDeliverParams = z.object({ + conversationId: requiredString('Missing conversation ID'), + messageId: requiredString('Missing message ID'), + to: requiredString('Missing --to'), + senderLabel: requiredString('Missing sender label'), + subject: requiredString('Missing --subject'), + body: OptionalString, + type: z.enum(['status', 'handoff']).optional(), + priority: z.enum(['normal', 'high', 'urgent']).optional(), + threadId: OptionalString +}) + +/** The opening Orca pulls replies queued for its conversations; waits up to waitMs for one. */ +export const PeerMailPullParams = z.object({ + waitMs: OptionalFiniteNumber +}) + +export const PeerMailAckParams = z.object({ + acknowledgments: z + .array( + z.object({ + conversationId: requiredString('Missing conversation ID'), + throughSequence: z.number().int().nonnegative() + }) + ) + .max(50) +}) + +/** One reply on the wire: the fields the opening Orca stores as mail for its agent. */ +export const PeerMailRelayPayload = z.object({ + senderLabel: z.string().min(1), + /** The replier on the paired Orca, where a reply to this one goes. */ + fromAddress: z.string().min(1), + subject: z.string(), + body: z.string(), + threadId: z.string().nullable() +}) diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts index 7a3d4daf21b..6ab57e2f1b8 100644 --- a/src/shared/rpc-contract/rpc-params-catalog.generated.ts +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -505,6 +505,11 @@ import { TaskCreateParams, TaskListParams } from './orchestration-params' +import { + PeerMailAckParams, + PeerMailDeliverParams, + PeerMailPullParams +} from './orchestration-peer-mail-params' import { RequestShowParams } from './orchestration-runs-mutation-request-show-params' import { RunCreateParams, @@ -1355,6 +1360,9 @@ export const RPC_PARAMS_BY_METHOD = { 'orchestration.inbox': InboxParams, 'orchestration.partyLocation': PartyLocationParams, 'orchestration.partyOpen': PartyLocationParams, + 'orchestration.peerMailAck': PeerMailAckParams, + 'orchestration.peerMailDeliver': PeerMailDeliverParams, + 'orchestration.peerMailPull': PeerMailPullParams, 'orchestration.reply': ReplyParams, 'orchestration.requestShow': RequestShowParams, 'orchestration.reset': ResetParams,