The Open Framework for Building Agents
fix(eve): serve remote agent protocol-1 callers (#4042)
Andrew Barba23dc0da1ccaf
diff --git a/.changeset/remote-agent-protocol-1-callers.md b/.changeset/remote-agent-protocol-1-callers.mdnew file mode 100644index 000000000..37f412ecf--- /dev/null+++ b/.changeset/remote-agent-protocol-1-callers.md@@ -0,0 +1,5 @@+---+"eve": patch+---++A remote agent on this release now serves callers on eve 0.66 through 0.68 instead of rejecting them with `REMOTE_AGENT_PROTOCOL_MISMATCH`, so you can upgrade remote agents before the deployments that call them. Those callers' turns, results, follow-ups, and resets work as before, and the remote agent's tool approvals and sign-in requests still reach the caller and accept its answers.diff --git a/docs/guides/remote-agents.md b/docs/guides/remote-agents.mdindex 8d76ce624..5ff72fc41 100644--- a/docs/guides/remote-agents.md+++ b/docs/guides/remote-agents.md@@ -197,7 +197,7 @@ Cancelling the parent turn or the agent task with `task_cancel` also cancels theWhen the workflow run that opened a remote child finishes, eve sends an authenticated `POST /eve/v1/session/:childSessionId/reset` for it. An agent task's run finishes when the parent session ends. Reset retires the parked remote session and recursively cleans up its descendants. The request uses freshly resolved `headers` and `auth`; failures are logged so an unreachable remote cannot block parent finalization.-Both deployments must speak the same eve remote agent protocol version. The parent names its version when it creates the child, and the remote rejects a mismatch; either way the call fails at start with an error naming both versions, so upgrade both deployments to the same eve release. A failed _start_ fails the call immediately. After a remote starts, a terminal failure callback fails the call with the remote's error. Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than completing the call, so the engine retries it.+The parent names its eve remote agent protocol version when it creates the child, and the remote answers with the version it serves. A remote also serves parents on protocol 1 (eve 0.66 through 0.68), including their approvals and sign-in requests, so upgrade remote agents before their callers; see [Upgrade remote agents before their callers](../tools/tasks-upgrade#upgrade-remote-agents-before-their-callers). Any other mismatch fails the call at start with an error naming both versions. A failed _start_ fails the call immediately. After a remote starts, a terminal failure callback fails the call with the remote's error. Terminal callback delivery runs as a durable step on the underlying workflow engine (see [Execution model & durability](../concepts/execution-model-and-durability)). A failed callback POST is rethrown rather than completing the call, so the engine retries it.## What to read nextdiff --git a/docs/tools/tasks-upgrade.md b/docs/tools/tasks-upgrade.mdindex 77e538cb9..3bea4c380 100644--- a/docs/tools/tasks-upgrade.md+++ b/docs/tools/tasks-upgrade.md@@ -178,8 +178,24 @@ The message stream version is now 26. The TypeScript client accepts versions 21client that accepts only versions up to 25 fails the stream with an unsupported-version error. See[Turns wait for their tasks](/docs/tools/tasks#turns-wait-for-their-tasks).-## Upgrade remote agents together+## Upgrade remote agents before their callers-The remote agent protocol is now version 2. Upgrade the calling deployment and every-[remote agent](/docs/guides/remote-agents) it calls to this release together; a mismatch fails the-call at start with an error that names both versions.+The remote agent protocol is now version 2. Deploy each [remote agent](/docs/guides/remote-agents)+before the deployments that call it. A remote agent on this release still serves callers on eve 0.66+through 0.68, which speak protocol 1. It runs their turns, sends each result to their callback, and+accepts their follow-up and reset requests. It also sends the remote agent's tool approvals and+sign-in requests to the caller, and accepts the caller's answers, the same way a 0.66–0.68 remote+agent does. As in 0.66–0.68, this covers agents the caller's model calls, which run as background+tasks. When the caller's own workflow tool code calls an agent, its approvals and sign-in requests+stay on the remote agent's channel.++Two things differ from a remote agent on the caller's own release:++- The caller's channel doesn't show the remote agent's live tool activity nested under the call.+- `ctx.ask()` in the remote agent returns `unavailable`, because protocol-1 callers don't grant the+ remote agent input. That's unchanged from 0.66–0.68.++Each protocol-1 create logs `serving a remote agent protocol 1 caller` with the caller's origin.++Upgrade a caller after every remote agent it calls. A caller on this release fails a call at start,+with an error that names both versions, when the remote agent's deployment speaks protocol 1.diff --git a/packages/eve/src/channel/types.ts b/packages/eve/src/channel/types.tsindex 6f59075eb..616e86c60 100644--- a/packages/eve/src/channel/types.ts+++ b/packages/eve/src/channel/types.ts@@ -1,5 +1,6 @@import type { UserContent } from "ai";+import type { LegacyRemoteAgentCaller } from "#execution/legacy-remote-agent/protocol.js";import type { SessionInboxAddress } from "#execution/session-inbox/address.js";import type { MessageStreamEvent, UnstampedMessageStreamEvent } from "#protocol/message.js";import type { CancelTurnResult as ProtocolCancelTurnResult } from "#protocol/cancel-turn.js";@@ -462,6 +463,8 @@ export interface RunInput {* caller for their own turn.*/readonly callback?: SessionCallback;+ /** Set when {@link callback} belongs to a remote agent protocol 1 caller. */+ readonly legacyRemoteAgentCaller?: LegacyRemoteAgentCaller;/** Private collector capability and current work lineage. */readonly activityObserver?: ActivityObserverConfig;/**diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex a6e84d145..055d48118 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -23,6 +23,7 @@ import {type SessionInboxAddress,} from "#execution/session-inbox/address.js";import { SESSION_CALLBACK_CONTEXT_KEY_NAME } from "#context/key-names.js";+import type { LegacyRemoteAgentCaller } from "#execution/legacy-remote-agent/protocol.js";import type { InstrumentationChannelDeliveryRef } from "#instrumentation/lifecycle.js";import type { UserModelMessage } from "#harness/messages.js";import type { HandleEventFn } from "#harness/types.js";@@ -159,6 +160,11 @@ export const SessionCallbackKey = new ContextKey<SessionCallback>(SESSION_CALLBACK_CONTEXT_KEY_NAME,);+/** Present when a remote agent protocol 1 caller created the session. */+export const LegacyRemoteAgentCallerKey = new ContextKey<LegacyRemoteAgentCaller>(+ "eve.legacyRemoteAgentCaller",+);+// ---------------------------------------------------------------------------// Derived keys — reconstructed by providers each step, never serialized.// ---------------------------------------------------------------------------diff --git a/packages/eve/src/eve-channel/create-request.ts b/packages/eve/src/eve-channel/create-request.tsindex 467b63cb3..bc9fdcedd 100644--- a/packages/eve/src/eve-channel/create-request.ts+++ b/packages/eve/src/eve-channel/create-request.ts@@ -5,6 +5,7 @@ import type {SessionCallback,SessionCapabilities,} from "#channel/types.js";+import type { LegacyRemoteAgentCaller } from "#execution/legacy-remote-agent/protocol.js";import type { JsonObject } from "#shared/json.js";export interface ParsedCreateBody {@@ -15,6 +16,9 @@ export interface ParsedCreateBody {context?: readonly string[];operationId?: string;outputSchema?: JsonObject;+ /** Remote agent protocol of a delegating caller; set only with {@link callback}. */+ protocolVersion?: number;+ legacyRemoteAgentCaller?: LegacyRemoteAgentCaller;}/** Enforces the fields that only make sense when creation also starts a turn. */diff --git a/packages/eve/src/eve-channel/index.ts b/packages/eve/src/eve-channel/index.tsindex 6c348515f..8b4e6b562 100644--- a/packages/eve/src/eve-channel/index.ts+++ b/packages/eve/src/eve-channel/index.ts@@ -23,7 +23,7 @@ import {EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER,} from "#protocol/message.js";-import { REMOTE_AGENT_PROTOCOL_VERSION } from "#protocol/remote-agent-protocol.js";+import { legacyTaskInputRoute } from "#execution/legacy-remote-agent/protocol.js";import {EVE_ACTIVITY_ROUTE_PATTERN,EVE_CALLBACK_ROUTE_PATTERN,@@ -99,7 +99,7 @@ const log = createLogger("eve.channel");* Default-export the result as your `agent/channels/eve.ts` channel; reach for* {@link defineChannel} directly only for a custom transport.*/-/** A delegating caller checks that this deployment speaks its remote agent protocol. */+/** A delegating caller checks that this deployment serves its remote agent protocol. */function createdSessionBody(sessionId: string, body: ParsedCreateBody) {const created: {ok: true;@@ -107,7 +107,7 @@ function createdSessionBody(sessionId: string, body: ParsedCreateBody) {sessionId: string;status: "accepted";} = { ok: true, sessionId, status: "accepted" };- if (body.callback !== undefined) created.protocolVersion = REMOTE_AGENT_PROTOCOL_VERSION;+ if (body.protocolVersion !== undefined) created.protocolVersion = body.protocolVersion;return created;}@@ -152,6 +152,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {POST(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN, handleConnectionCallbackRequest),POST(EVE_ACTIVITY_ROUTE_PATTERN, handleActivityRequest),POST(EVE_CALLBACK_ROUTE_PATTERN, handleSessionCallbackRequest),+ POST(legacyTaskInputRoute.path, legacyTaskInputRoute.handler),GET(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),POST(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),PUT(WORKFLOW_WEBHOOK_ROUTE_PATTERN, handleWorkflowWebhookRequest),@@ -176,6 +177,12 @@ export function eveChannel(input: EveChannelInput): EveChannel {const body = parseCreateBody(payload);if (body instanceof Response) return body;+ if (body.callback !== undefined && body.legacyRemoteAgentCaller !== undefined) {+ log.info("serving a remote agent protocol 1 caller", {+ callerOrigin: new URL(body.callback.url).origin,+ forwarder: authResult.principalId,+ });+ }const forwardedParentSession =body.callback === undefined? "absent"@@ -325,6 +332,7 @@ export function eveChannel(input: EveChannelInput): EveChannel {auth: messageResult.auth,capabilities: body.capabilities ?? { requestInput: true },callback: body.callback,+ legacyRemoteAgentCaller: body.legacyRemoteAgentCaller,continuationToken: operationToken,initiatorAuth: forwarded.accepted ? forwarded.initiatorAuth : undefined,input: attachClientContext(diff --git a/packages/eve/src/eve-channel/request.ts b/packages/eve/src/eve-channel/request.tsindex c350f74fd..b001694e2 100644--- a/packages/eve/src/eve-channel/request.ts+++ b/packages/eve/src/eve-channel/request.ts@@ -31,6 +31,10 @@ import {REMOTE_AGENT_PROTOCOL_VERSION,readRemoteAgentProtocolVersion,} from "#protocol/remote-agent-protocol.js";+import {+ LEGACY_REMOTE_AGENT_PROTOCOL_VERSION,+ splitLegacyTaskFields,+} from "#execution/legacy-remote-agent/protocol.js";import {collectUploadPolicyViolations,formatUploadPolicyViolation,@@ -64,7 +68,9 @@ export async function deriveOperationContinuationToken(input: {return `eve:op:${hex.slice(0, 32)}`;}-export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBody | Response {+export function parseCreateBody(input: Record<string, unknown>): ParsedCreateBody | Response {+ const legacy = splitLegacyTaskFields(input);+ const { payload } = legacy;if (payload.inputResponses !== undefined) {return Response.json({ error: "'inputResponses' is only accepted for an existing session.", ok: false },@@ -79,10 +85,9 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateBconst callback = parseCallbackField(payload.callback);if (callback instanceof Response) return callback;- if (callback !== undefined) {- const protocolRejection = rejectRemoteAgentProtocolMismatch(payload.protocolVersion);- if (protocolRejection !== undefined) return protocolRejection;- }+ const protocolVersion =+ callback === undefined ? undefined : parseProtocolVersionField(payload.protocolVersion);+ if (protocolVersion instanceof Response) return protocolVersion;const capabilities = parseCapabilitiesField(payload.capabilities);if (capabilities instanceof Response) return capabilities;@@ -124,6 +129,10 @@ export function parseCreateBody(payload: Record<string, unknown>): ParsedCreateB};if (message !== undefined) result.message = message;if (typeof rawOperationId === "string") result.operationId = rawOperationId;+ if (protocolVersion !== undefined) result.protocolVersion = protocolVersion;+ if (protocolVersion === LEGACY_REMOTE_AGENT_PROTOCOL_VERSION) {+ result.legacyRemoteAgentCaller = legacy.taskId === undefined ? {} : { taskId: legacy.taskId };+ }return result;}@@ -138,8 +147,9 @@ interface ParsedSessionMessageBody {}export function parseSessionMessageBody(- payload: Record<string, unknown>,+ input: Record<string, unknown>,): ParsedSessionMessageBody | Response {+ const { payload } = splitLegacyTaskFields(input);const tokenRejection = rejectSessionContinuationToken(payload);if (tokenRejection !== null) return tokenRejection;@@ -347,10 +357,22 @@ function parseCallbackField(value: unknown): SessionCallback | Response | undefireturn Response.json({ error: parsed.message, ok: false }, { status: 400 });}-/** Delegating callers must speak this deployment's remote agent protocol. */-function rejectRemoteAgentProtocolMismatch(value: unknown): Response | undefined {+/** Delegating callers must speak a remote agent protocol this deployment serves. */+function parseProtocolVersionField(value: unknown): number | Response {+ // Only an absent version means protocol 1; 0.66–0.68 callers omit the field.+ if (value !== undefined && typeof value !== "number") {+ return Response.json(+ { error: "Expected 'protocolVersion' to be a number.", ok: false },+ { status: 400 },+ );+ }const callerVersion = readRemoteAgentProtocolVersion(value);- if (callerVersion === REMOTE_AGENT_PROTOCOL_VERSION) return undefined;+ if (+ callerVersion === REMOTE_AGENT_PROTOCOL_VERSION ||+ callerVersion === LEGACY_REMOTE_AGENT_PROTOCOL_VERSION+ ) {+ return callerVersion;+ }return Response.json({code: REMOTE_AGENT_PROTOCOL_MISMATCH,diff --git a/packages/eve/src/execution/forward-session-input.ts b/packages/eve/src/execution/forward-session-input.tsindex 8b626372a..f7c8d2ac2 100644--- a/packages/eve/src/execution/forward-session-input.ts+++ b/packages/eve/src/execution/forward-session-input.ts@@ -1,10 +1,12 @@import type { ContextContainer } from "#context/container.js";import {ContinuationTokenKey,+ LegacyRemoteAgentCallerKey,SessionCallbackKey,SessionIdKey,SessionInboxKey,} from "#context/keys.js";+import { forwardLegacySessionInput } from "#execution/legacy-remote-agent/protocol.js";import { postSessionCallbackRequest } from "#execution/session-callback-request.js";import { sessionCommandHookToken } from "#execution/session-inbox/address.js";import type { UnstampedMessageStreamEvent } from "#protocol/message.js";@@ -17,6 +19,8 @@ export async function forwardSessionInput(): Promise<boolean> {const callback = ctx.get(SessionCallbackKey);if (callback === undefined) return false;+ const legacyCaller = ctx.get(LegacyRemoteAgentCallerKey);+ if (legacyCaller !== undefined) return await forwardLegacySessionInput(ctx, legacyCaller, event);if (event.type !== "input.requested" &&event.type !== "authorization.required" &&diff --git a/packages/eve/src/execution/legacy-remote-agent/protocol.test.ts b/packages/eve/src/execution/legacy-remote-agent/protocol.test.tsnew file mode 100644index 000000000..734642097--- /dev/null+++ b/packages/eve/src/execution/legacy-remote-agent/protocol.test.ts@@ -0,0 +1,70 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import { legacyTaskInputRoute } from "#execution/legacy-remote-agent/protocol.js";+import type { RouteContext } from "#public/definitions/channel.js";++const resumeHookMock = vi.fn();+const getHookByTokenMock = vi.fn();++vi.mock("#compiled/@workflow/core/runtime.js", () => ({+ getHookByToken: (token: string) => getHookByTokenMock(token),+ resumeHook: (token: string, payload: unknown) => resumeHookMock(token, payload),+}));++const DIGEST = "0123456789abcdef0123456789abcdef";+const inputResponses = [{ optionId: "approve", requestId: "request-1" }];++// What an eve 0.66–0.68 caller posts to answer a remote agent's question or approval.+function postAnswers(token: string, body: unknown = { inputResponses }) {+ return legacyTaskInputRoute.handler(+ new Request(`https://remote.example.com/eve/v1/task-input/${token}`, {+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ method: "POST",+ }),+ { params: { token }, requestIp: null, waitUntil() {} } satisfies RouteContext,+ );+}++describe("legacy task input route", () => {+ beforeEach(() => {+ resumeHookMock.mockReset();+ getHookByTokenMock.mockReset();+ });++ it("delivers answers to the session behind the capability without replacing its principal", async () => {+ resumeHookMock.mockResolvedValue({ runId: "run-1" });++ const response = await postAnswers(`eve:task-input:${DIGEST}`);++ expect(response.status).toBe(202);+ expect(resumeHookMock).toHaveBeenCalledWith(`eve:inbox:v1:eve:eve:op:${DIGEST}`, {+ kind: "send",+ payload: { inputResponses },+ });+ });++ it("rejects a token that is not a task input capability", async () => {+ const response = await postAnswers(`eve:eve:op:${DIGEST}`);++ expect(response.status).toBe(403);+ expect(resumeHookMock).not.toHaveBeenCalled();+ });++ it("rejects a body without answers", async () => {+ const response = await postAnswers(`eve:task-input:${DIGEST}`, { inputResponses: [] });++ expect(response.status).toBe(400);+ expect(resumeHookMock).not.toHaveBeenCalled();+ });++ it("answers 404 so the caller stops retrying once the session is gone", async () => {+ resumeHookMock.mockRejectedValue(new HookNotFoundError("gone"));+ getHookByTokenMock.mockRejectedValue(new HookNotFoundError("gone"));++ const response = await postAnswers(`eve:task-input:${DIGEST}`);++ expect(response.status).toBe(404);+ });+});diff --git a/packages/eve/src/execution/legacy-remote-agent/protocol.ts b/packages/eve/src/execution/legacy-remote-agent/protocol.tsnew file mode 100644index 000000000..d39c2d28d--- /dev/null+++ b/packages/eve/src/execution/legacy-remote-agent/protocol.ts@@ -0,0 +1,165 @@+/**+ * Remote agent protocol 1: what an eve 0.66–0.68 caller sends a remote agent+ * and expects back. A remote agent keeps serving those callers so it can+ * deploy before them.+ *+ * Everything protocol 1 needs lives here. Guard rule 48 limits imports of this+ * directory to the ingress files that route into it, so removing protocol 1+ * means deleting this directory and fixing the compile errors it leaves.+ */+import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";+import type { ContextContainer } from "#context/container.js";+import { ContinuationTokenKey, SessionCallbackKey, SessionIdKey } from "#context/keys.js";+import { postSessionCallbackRequest } from "#execution/session-callback-request.js";+import { resumeSessionInbox } from "#execution/session-inbox/resume.js";+import { createLogger, logError } from "#internal/logging.js";+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";+import { EVE_ROUTE_PREFIX } from "#protocol/routes.js";+import type { RouteContext } from "#public/definitions/channel.js";+import { isObject } from "#shared/guards.js";+import { isInputResponse } from "#shared/input.js";++const log = createLogger("execution.legacy-remote-agent");++export const LEGACY_REMOTE_AGENT_PROTOCOL_VERSION = 1;++const TASK_INPUT_TOKEN_RE = /^eve:task-input:([a-f0-9]{32})$/;++/** A session created by a protocol-1 caller. */+export interface LegacyRemoteAgentCaller {+ /**+ * The caller's background task; its questions and sign-ins are forwarded+ * only with one. Captured at create: a 0.66–0.68 caller's model-called+ * agents start in a task, and those callers never check it against later turns.+ */+ readonly taskId?: string;+}++/**+ * Removes the fields a protocol-1 caller adds when it delegates from a+ * background task: `callback.taskId` and a `task` activity work identity.+ * Current callers send neither. The task id is returned so the session can+ * name it back to the caller.+ */+export function splitLegacyTaskFields(input: Record<string, unknown>): {+ readonly payload: Record<string, unknown>;+ readonly taskId?: string;+} {+ const { activityObserver, callback } = input;+ const hasTaskId = isObject(callback) && "taskId" in callback;+ const hasTaskObserver =+ isObject(activityObserver) &&+ isObject(activityObserver.workIdentity) &&+ activityObserver.workIdentity.kind === "task";+ if (!hasTaskId && !hasTaskObserver) return { payload: input };++ const payload = { ...input };+ // Nested activity isn't relayed: current activity has no `task` work kind.+ if (hasTaskObserver) delete payload.activityObserver;+ if (!hasTaskId) return { payload };+ const { taskId, ...rest } = callback;+ payload.callback = rest;+ return typeof taskId === "string" && taskId.length > 0 ? { payload, taskId } : { payload };+}++/**+ * Sends a question, approval, or sign-in to a protocol-1 caller in the+ * `task.*` callback it expects. Returns whether the event was forwarded and+ * must stay off this session's own channel.+ */+export async function forwardLegacySessionInput(+ ctx: ContextContainer,+ caller: LegacyRemoteAgentCaller,+ event: UnstampedMessageStreamEvent,+): Promise<boolean> {+ const callback = ctx.get(SessionCallbackKey);+ // The caller answers through the create-once session token it derived its capability from.+ const childContinuationToken = ctx.get(ContinuationTokenKey);+ if (caller.taskId === undefined || callback === undefined || !childContinuationToken) {+ return false;+ }+ let forwarded: { readonly event: unknown; readonly kind: string };+ if (event.type === "input.requested") {+ forwarded = { event: event.data, kind: "task.input-requested" };+ } else if (event.type === "authorization.required" || event.type === "authorization.completed") {+ forwarded = { event, kind: "task.authorization" };+ } else {+ return false;+ }++ const response = await postSessionCallbackRequest({+ body: {+ callId: callback.callId,+ childContinuationToken,+ childSessionId: ctx.require(SessionIdKey),+ event: forwarded.event,+ kind: forwarded.kind,+ subagentName: callback.subagentName,+ taskId: caller.taskId,+ },+ url: callback.url,+ });+ if (!response.ok) {+ throw new Error(`Remote task event callback failed with HTTP ${response.status}.`);+ }+ return true;+}++/** Route a protocol-1 caller posts its answers to a remote agent's question or approval. */+export const legacyTaskInputRoute = {+ handler: handleLegacyTaskInputRequest,+ path: `${EVE_ROUTE_PREFIX}/task-input/:token`,+} as const;++/**+ * Delivers a protocol-1 caller's answers. The token is the capability the+ * caller derived from this session's create-once continuation token, so it+ * authorizes the request on its own, as it did in protocol 1.+ */+async function handleLegacyTaskInputRequest(+ request: Request,+ ctx: RouteContext,+): Promise<Response> {+ const digest = TASK_INPUT_TOKEN_RE.exec(ctx.params.token ?? "")?.[1];+ if (digest === undefined) {+ return Response.json({ error: "Invalid task input token.", ok: false }, { status: 403 });+ }+ let body: unknown;+ try {+ body = await request.json();+ } catch {+ return Response.json({ error: "Invalid JSON body.", ok: false }, { status: 400 });+ }+ const inputResponses = isObject(body) ? body.inputResponses : undefined;+ if (+ !Array.isArray(inputResponses) ||+ inputResponses.length === 0 ||+ !inputResponses.every(isInputResponse)+ ) {+ return Response.json(+ { error: "Expected a non-empty inputResponses array.", ok: false },+ { status: 400 },+ );+ }++ try {+ // No auth: the answer acts as the session's current principal, as in protocol 1.+ await resumeSessionInbox(`eve:eve:op:${digest}`, {+ kind: "send",+ payload: { inputResponses },+ });+ } catch (error) {+ if (HookNotFoundError.is(error)) {+ return Response.json(+ { error: "Task input target is not pending.", ok: false },+ { status: 404 },+ );+ }+ const errorId = logError(log, "legacy task input delivery failed", error);+ return Response.json(+ { error: "Failed to deliver the task input.", errorId, ok: false },+ { status: 500 },+ );+ }+ return Response.json({ ok: true }, { status: 202 });+}diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex 3e2389ffd..f0d755f37 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -17,6 +17,7 @@ import {ActivityObserverKey,ScheduleIdKey,SessionCallbackKey,+ LegacyRemoteAgentCallerKey,SessionTitleKey,} from "#context/keys.js";import { deriveSessionTitle } from "#execution/eve-workflow-attributes.js";@@ -94,6 +95,9 @@ export function buildRunContext(input: {if (run.callback !== undefined) {ctx.set(SessionCallbackKey, run.callback);}+ if (run.legacyRemoteAgentCaller !== undefined) {+ ctx.set(LegacyRemoteAgentCallerKey, run.legacyRemoteAgentCaller);+ }if (run.activityObserver !== undefined) {ctx.set(ActivityObserverKey, run.activityObserver);}diff --git a/packages/eve/src/protocol/remote-agent-protocol.ts b/packages/eve/src/protocol/remote-agent-protocol.tsindex 2640c1de1..94d31de03 100644--- a/packages/eve/src/protocol/remote-agent-protocol.ts+++ b/packages/eve/src/protocol/remote-agent-protocol.ts@@ -1,8 +1,8 @@/*** Version of the protocol a parent deployment speaks with a remote agent's* deployment. A create-session request that delegates work names the caller's- * version, and the receiver's response names its own; both deployments must- * speak the same one. Deployments from before the version existed speak 1.+ * version, and the receiver's response names its own. Deployments from before+ * the version existed speak 1.*/export const REMOTE_AGENT_PROTOCOL_VERSION = 2;diff --git a/packages/eve/src/public/channels/eve.test.ts b/packages/eve/src/public/channels/eve.test.tsindex a65354c06..4b4d23d05 100644--- a/packages/eve/src/public/channels/eve.test.ts+++ b/packages/eve/src/public/channels/eve.test.ts@@ -1376,6 +1376,108 @@ describe("eveChannel — create session (text)", () => {});});+describe("eveChannel — remote agent protocol 1 callers", () => {+ const callback = {+ callId: "call-1",+ subagentName: "research",+ token: "tok123",+ url: "https://caller.example.com/eve/v1/callback/tok123",+ };+ // What an eve 0.66–0.68 background task adds when it delegates.+ const legacyTaskFields = {+ activityObserver: {+ sink: {+ url: "https://caller.example.com/eve/v1/activity/abcdefghijklmnopqrstuvwxyz123456",+ version: 1,+ },+ workIdentity: {+ callId: "call-1",+ id: "work:caller:turn-1:call-1",+ kind: "task",+ name: "research",+ rootSessionId: "caller",+ rootTurnId: "turn-1",+ },+ },+ callback: { ...callback, taskId: "task-1" },+ };++ it.each([+ ["a direct call", { callback }, {}],+ ["a background task", legacyTaskFields, { taskId: "task-1" }],+ ])(+ "serves an unversioned create from %s and answers protocol 1",+ async (_caller, fields, legacyCaller) => {+ const logs = captureLogRecords();+ const handler = createEveCreateHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ capabilities: {}, message: "hi", ...fields }),+ );++ expect(response.status).toBe(202);+ await expect(response.json()).resolves.toEqual({+ ok: true,+ protocolVersion: 1,+ sessionId: "test-session-id",+ status: "accepted",+ });+ const runInput = handler.createSession.mock.calls[0]?.[0];+ expect(runInput?.callback).toEqual(callback);+ expect(runInput?.activityObserver).toBeUndefined();+ expect(runInput?.legacyRemoteAgentCaller).toEqual(legacyCaller);+ expect(logs.records).toContainEqual(+ expect.objectContaining({+ level: "info",+ message: "serving a remote agent protocol 1 caller",+ }),+ );+ },+ );++ it("serves a protocol-1 continuation", async () => {+ const handler = createEveContinueHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ message: "and then?", ...legacyTaskFields }),+ );++ expect(response.status).toBe(202);+ const options = handler.send.mock.calls[0]?.[1];+ expect(options?.callback).toEqual(callback);+ expect(options?.activityObserver).toBeUndefined();+ });++ it("rejects a delegating caller on a protocol this deployment does not serve", async () => {+ const handler = createEveCreateHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ callback, message: "hi", protocolVersion: 3 }),+ );++ expect(response.status).toBe(409);+ await expect(response.json()).resolves.toMatchObject({+ code: "REMOTE_AGENT_PROTOCOL_MISMATCH",+ protocolVersion: REMOTE_AGENT_PROTOCOL_VERSION,+ });+ expect(handler.createSession).not.toHaveBeenCalled();+ });++ it.each([null, "2"])(+ "rejects a delegating create whose protocolVersion is %j instead of treating it as protocol 1",+ async (protocolVersion) => {+ const handler = createEveCreateHandler({ auth: none() });++ const response = await handler.fetch(+ createJsonMessageRequest({ callback, message: "hi", protocolVersion }),+ );++ expect(response.status).toBe(400);+ expect(handler.createSession).not.toHaveBeenCalled();+ },+ );+});+describe("eveChannel — create session (UserContent array)", () => {it("accepts a text+file UserContent array and forwards it to send", async () => {const handler = createEveCreateHandler({ auth: none() });diff --git a/packages/eve/src/subagents/event-proxy-step.integration.test.ts b/packages/eve/src/subagents/event-proxy-step.integration.test.tsindex 39f4fa96c..2b1572f50 100644--- a/packages/eve/src/subagents/event-proxy-step.integration.test.ts+++ b/packages/eve/src/subagents/event-proxy-step.integration.test.ts@@ -6,6 +6,7 @@ import { ContextContainer } from "#context/container.js";import {AuthKey,ContinuationTokenKey,+ LegacyRemoteAgentCallerKey,SessionCallbackKey,SessionIdKey,SessionInboxKey,@@ -14,7 +15,7 @@ import type { DurableSession } from "#execution/durable-session-store.js";import { openSessionEventPublisher } from "#execution/publish-session-events.js";import { createSessionLimitContinuationRequest } from "#harness/session-limit-continuation.js";import { getProxyInputRequests } from "#harness/proxy-input-requests.js";-import type { MessageStreamEvent } from "#protocol/message.js";+import { createAuthorizationRequiredEvent, type MessageStreamEvent } from "#protocol/message.js";import type { HookContext } from "#public/definitions/hook.js";import { createRuntimeHookRegistry } from "#runtime/hooks/registry.js";import {@@ -208,6 +209,79 @@ describe("proxied stream hooks", () => {}});+ it("sends a protocol-1 background task the task callbacks it expects", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ f.ctx.set(LegacyRemoteAgentCallerKey, { taskId: "task-1" });+ const fetchMock = vi.fn(async (_url: string, _init: RequestInit) =>+ Response.json({ ok: true }, { status: 202 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const sink = createSessionEventSink({+ ctx: f.ctx,+ sessionId: "parent-session",+ sessionWritable: f.sessionWritable,+ });+ const signIn = createAuthorizationRequiredEvent({+ description: "Sign in to Datadog",+ name: "datadog",+ sequence: 8,+ stepIndex: 2,+ turnId: "child-turn",+ });+ try {+ await sink.emit({ type: "input.requested", data: f.hookPayload.event });+ await sink.emit(signIn);+ const bodies = fetchMock.mock.calls.map(([, init]) => JSON.parse(init.body as string));+ const envelope = {+ callId: "remote-call",+ childContinuationToken: "http:parent",+ childSessionId: "parent-session",+ subagentName: "remote-child",+ taskId: "task-1",+ };+ expect(bodies).toEqual([+ { ...envelope, event: f.hookPayload.event, kind: "task.input-requested" },+ { ...envelope, event: signIn, kind: "task.authorization" },+ ]);+ expect(f.order).not.toContain("channel:input.requested");+ } finally {+ sink.release();+ vi.unstubAllGlobals();+ }+ });++ it("keeps a protocol-1 caller's input on its own channel outside a background task", async () => {+ const f = fixture();+ f.ctx.set(SessionCallbackKey, {+ callId: "remote-call",+ subagentName: "remote-child",+ token: "parent-reply",+ url: "https://parent.example/eve/v1/callback/parent-reply",+ });+ f.ctx.set(LegacyRemoteAgentCallerKey, {});+ const fetchMock = vi.fn(async () => Response.json({ ok: true }, { status: 202 }));+ vi.stubGlobal("fetch", fetchMock);+ const sink = createSessionEventSink({+ ctx: f.ctx,+ sessionId: "parent-session",+ sessionWritable: f.sessionWritable,+ });+ try {+ await sink.emit({ type: "input.requested", data: f.hookPayload.event });+ expect(fetchMock).not.toHaveBeenCalled();+ expect(f.order).toContain("channel:input.requested");+ } finally {+ sink.release();+ vi.unstubAllGlobals();+ }+ });+it("forwards callback input without an operation ID through the session inbox", async () => {const f = fixture();f.ctx.delete(ContinuationTokenKey);diff --git a/scripts/guard-invariants.mjs b/scripts/guard-invariants.mjsindex 5ee838d4d..46865fffd 100644--- a/scripts/guard-invariants.mjs+++ b/scripts/guard-invariants.mjs@@ -122,6 +122,10 @@* after the turn loop returns, and `execution/session/finalization.ts`* when the session ends. A held turn is still open, so nothing* inside the turn loop or the harness may reply.+ * rule 48 — Remote agent protocol 1 stays in+ * `execution/legacy-remote-agent/`. Only the ingress files that+ * route protocol-1 callers into it may import it, so deleting the+ * directory removes protocol 1 without a search.** Baselines for rules with pre-existing violations live in* `guard-invariants-baseline.json`. Counts and allowlists in that file@@ -221,6 +225,7 @@ function isTsLike(relPath) {* rule45: { allowlist: Set<string>; violations: Violation[] };* rule46: Violation[];* rule47: Violation[];+ * rule48: Violation[];* symlinks: string[];* }} state*/@@ -254,6 +259,7 @@ async function scanRepo(state) {checkRule45(posix, lines, state.rule45);checkRule46(posix, lines, state.rule46);checkRule47(posix, lines, state.rule47);+ checkRule48(posix, lines, state.rule48);}}@@ -460,6 +466,41 @@ function checkRule47(posix, lines, violations) {});}+// ---------- Rule 48: remote agent protocol 1 stays compartmentalized ----------++const LEGACY_REMOTE_AGENT_DIR = "packages/eve/src/execution/legacy-remote-agent/";+const LEGACY_REMOTE_AGENT_INGRESS_FILES = new Set([+ "packages/eve/src/channel/types.ts",+ "packages/eve/src/context/keys.ts",+ "packages/eve/src/eve-channel/create-request.ts",+ "packages/eve/src/eve-channel/index.ts",+ "packages/eve/src/eve-channel/request.ts",+ "packages/eve/src/execution/forward-session-input.ts",+]);+// `from "…"` covers imports and re-exports; `import "…"` and `import("…")` cover side effects and dynamic imports.+const LEGACY_REMOTE_AGENT_IMPORT_RE = /\b(?:from|import)\s*\(?\s*["'][^"']*legacy-remote-agent\//;++/** @param {string} posix @param {string[]} lines @param {Violation[]} violations */+function checkRule48(posix, lines, violations) {+ if (+ !posix.startsWith("packages/eve/src/") ||+ posix.startsWith(LEGACY_REMOTE_AGENT_DIR) ||+ /\.(?:test|integration\.test|scenario\.test)\.ts$/.test(posix) ||+ LEGACY_REMOTE_AGENT_INGRESS_FILES.has(posix)+ )+ return;+ lines.forEach((line, idx) => {+ if (!LEGACY_REMOTE_AGENT_IMPORT_RE.test(line)) return;+ violations.push({+ rule: 48,+ file: posix,+ line: idx + 1,+ message:+ "imports remote agent protocol 1 outside its ingress files. Route protocol-1 behavior through execution/legacy-remote-agent/ from an existing ingress so the legacy path stays removable in one place.",+ });+ });+}+// ---------- Rule 13: spread-ternary object composition ----------/** Matches `...(<expr> ? {} : { ... })` or the mirrored form. */@@ -1516,6 +1557,7 @@ async function main() {},rule46: /** @type {Violation[]} */ ([]),rule47: /** @type {Violation[]} */ ([]),+ rule48: /** @type {Violation[]} */ ([]),symlinks: /** @type {string[]} */ ([]),};@@ -1632,6 +1674,7 @@ async function main() {// Rule 47violations.push(...state.rule47);+ violations.push(...state.rule48);if (violations.length === 0) {process.stdout.write("[eve:guard:invariants] ok — all mechanical lints passed.\n");