Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): keep sessions live while authorization waits for its callback (#1830)

Rui50f2d9696a33
diff --git a/.changeset/nonblocking-authorization-wait.md b/.changeset/nonblocking-authorization-wait.md
new file mode 100644
index 000000000..1e542715b
--- /dev/null
+++ b/.changeset/nonblocking-authorization-wait.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Conversation sessions no longer stall while an interactive authorization challenge is open: ordinary messages run as normal turns, while tasks defer unrelated input until their blocked authorization completes. Callbacks are bound to the exact challenge attempt and initiating connection principal, remain live across parked activity, and start a valid callback turn after the authorization park closes its boundary. Session timeouts are also honored during an open challenge, and `client.fetch` preserves query strings embedded in the request path.
diff --git a/e2e/fixtures/agent-tools-hitl/agent/agent.ts b/e2e/fixtures/agent-tools-hitl/agent/agent.ts
index 384bb0e2a..92456fc1b 100644
--- a/e2e/fixtures/agent-tools-hitl/agent/agent.ts
+++ b/e2e/fixtures/agent-tools-hitl/agent/agent.ts
@@ -1,7 +1,41 @@
import { e2eAgentConfig } from "@eve-e2e/config";
import { defineAgent } from "eve";
+import type { MockModelRequest, MockModelResponse } from "eve/evals";
+
+const AUTH_PROBE_DIRECTIVE = /call the auth-probe tool exactly once with marker "([^"]+)"/iu;
+const REPLY_DIRECTIVE = /reply with exactly ([A-Z0-9-]+)/iu;
+
+/**
+ * Scripted mock for the world suites: untagged evals in this fixture phrase
+ * every prompt as an explicit directive, so the responder executes exactly
+ * the requested tool call and replies from its output. A tool message after
+ * the latest user message means this turn's call already ran.
+ */
+function respond(request: MockModelRequest): MockModelResponse | string {
+ const message = request.lastUserMessage ?? "";
+
+ const reply = REPLY_DIRECTIVE.exec(message);
+ if (reply?.[1] !== undefined) {
+ return reply[1];
+ }
+
+ const authProbe = AUTH_PROBE_DIRECTIVE.exec(message);
+ if (authProbe?.[1] !== undefined) {
+ const roles = request.messages.map((entry) => entry.role);
+ const turnHasToolResult = roles.lastIndexOf("tool") > roles.lastIndexOf("user");
+ if (!turnHasToolResult) {
+ return { toolCalls: [{ input: { marker: authProbe[1] }, name: "auth-probe" }] };
+ }
+ const output = [...request.toolResults]
+ .reverse()
+ .find((result) => result.name === "auth-probe")?.output;
+ return `auth-probe result: ${typeof output === "string" ? output : JSON.stringify(output ?? "")}`;
+ }
+
+ return `Mock reply: ${message}`;
+}
export default defineAgent({
- ...e2eAgentConfig(),
+ ...e2eAgentConfig({ mock: respond }),
reasoning: "high",
});
diff --git a/e2e/fixtures/agent-tools-hitl/agent/channels/eve.ts b/e2e/fixtures/agent-tools-hitl/agent/channels/eve.ts
new file mode 100644
index 000000000..389c206f2
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/agent/channels/eve.ts
@@ -0,0 +1,23 @@
+import type { AuthFn } from "eve/channels/auth";
+import { eveChannel } from "eve/channels/eve";
+import type { SessionAuthContext } from "eve/context";
+
+/**
+ * Authored eve channel for the interactive-authorization evals. Interactive
+ * authorizations are always `principalType: "user"`, and the eval driver is
+ * otherwise anonymous (`local-dev` on the local world), which fails principal
+ * resolution before a challenge can open. Every caller maps to one fixed end
+ * user (fixture-only; do not pattern production channels off this).
+ */
+const authenticateDefaultUser: AuthFn<Request> = (): SessionAuthContext => ({
+ attributes: {},
+ authenticator: "e2e-fixture",
+ issuer: "e2e",
+ principalId: "e2e-user",
+ principalType: "user",
+ subject: "e2e-user",
+});
+
+export default eveChannel({
+ auth: [authenticateDefaultUser],
+});
diff --git a/e2e/fixtures/agent-tools-hitl/agent/tools/auth-probe.ts b/e2e/fixtures/agent-tools-hitl/agent/tools/auth-probe.ts
new file mode 100644
index 000000000..94b92212b
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/agent/tools/auth-probe.ts
@@ -0,0 +1,41 @@
+import {
+ ConnectionAuthorizationRequiredError,
+ defineInteractiveAuthorization,
+} from "eve/connections";
+import { defineTool } from "eve/tools";
+import { z } from "zod";
+
+const TOKEN = "interactive-auth-token-H6P3";
+
+const auth = defineInteractiveAuthorization<{ marker: string }>({
+ async getToken() {
+ throw new ConnectionAuthorizationRequiredError("auth-probe");
+ },
+ async startAuthorization({ callbackUrl }) {
+ const url = new URL(callbackUrl);
+ url.searchParams.set("code", "fixture-ok");
+ return {
+ challenge: { displayName: "Fixture Auth", url: url.href },
+ resume: { marker: "fixture-resume" },
+ };
+ },
+ async completeAuthorization({ callback, resume }) {
+ if (callback.params.code !== "fixture-ok" || resume?.marker !== "fixture-resume") {
+ throw new Error("Fixture authorization state mismatch.");
+ }
+ return { token: TOKEN };
+ },
+});
+
+export default defineTool({
+ description: "Interactive authorization lifecycle probe. Call only when explicitly requested.",
+ inputSchema: z.object({ marker: z.string() }),
+ async execute(input, ctx) {
+ const token = await ctx.getToken(auth, { authKey: "auth-probe", displayName: "Fixture Auth" });
+ return {
+ actor: ctx.session.auth.current?.principalId ?? "none",
+ marker: input.marker,
+ token: token.token,
+ };
+ },
+});
diff --git a/e2e/fixtures/agent-tools-hitl/evals/auth/authorization-nonblocking.eval.ts b/e2e/fixtures/agent-tools-hitl/evals/auth/authorization-nonblocking.eval.ts
new file mode 100644
index 000000000..fce4a7686
--- /dev/null
+++ b/e2e/fixtures/agent-tools-hitl/evals/auth/authorization-nonblocking.eval.ts
@@ -0,0 +1,77 @@
+import { defineEval } from "eve/evals";
+import type { EveEvalContext, EveEvalSession, EveEvalTurn } from "eve/evals";
+
+/**
+ * An open authorization challenge must not wedge the session: an ordinary
+ * message runs as a normal turn while the challenge waits, and the callback
+ * still completes it afterwards. Tool re-execution after the callback is
+ * covered deterministically by `workflow-entry.integration.test.ts`.
+ */
+export default defineEval({
+ description: "An ordinary message runs while an authorization challenge stays open.",
+ async test(t) {
+ const parked = await t.send(
+ 'Call the auth-probe tool exactly once with marker "nonblocking". Include its result.',
+ );
+ parked.event("authorization.required", { count: 1 });
+ parked.notEvent("authorization.completed");
+ parked.event("session.waiting", { count: 1 });
+
+ // The wedge case: a message while the challenge is open runs as a
+ // normal turn instead of queueing behind the callback.
+ const message = await t.send("Do not call any tools. Reply with exactly AUTH-OPEN-MESSAGE-OK.");
+ message.expectOk();
+ if (message.sessionId !== parked.sessionId) {
+ throw new Error("Message while authorization was open changed session identity.");
+ }
+ message.event("message.received", { count: 1 });
+ message.event("message.completed", { count: 1 });
+ message.notEvent("authorization.completed");
+ message.event("session.waiting", { count: 1 });
+ message.messageIncludes("AUTH-OPEN-MESSAGE-OK");
+ message.usedNoTools();
+
+ // The callback still lands and closes the challenge exactly once.
+ const resumed = await invokeCallback(t, parked);
+ resumed.turn.event("authorization.completed", {
+ count: 1,
+ data: { outcome: "authorized" },
+ });
+ resumed.turn.notEvent("session.failed");
+
+ // The session stays conversational after the whole sequence.
+ const followUp = await resumed.session.send(
+ "Do not call tools. Reply with exactly AUTH-OPEN-FOLLOW-UP-OK.",
+ );
+ followUp.expectOk();
+ if (followUp.sessionId !== parked.sessionId) {
+ throw new Error("Follow-up after the callback changed session identity.");
+ }
+ followUp.event("message.completed", { count: 1 });
+ followUp.event("session.waiting", { count: 1 });
+ followUp.messageIncludes("AUTH-OPEN-FOLLOW-UP-OK");
+ followUp.usedNoTools();
+ },
+});
+
+function authorizationUrl(turn: EveEvalTurn): URL {
+ for (const event of turn.events) {
+ if (event.type !== "authorization.required") continue;
+ const url = event.data.authorization?.url;
+ if (url !== undefined) return new URL(url);
+ }
+ throw new Error("authorization.required did not expose a callback URL.");
+}
+
+async function invokeCallback(
+ t: EveEvalContext,
+ turn: EveEvalTurn,
+): Promise<{ readonly session: EveEvalSession; readonly turn: EveEvalTurn }> {
+ const state = t.state as { readonly streamIndex?: unknown } | undefined;
+ if (typeof state?.streamIndex !== "number") throw new Error("Missing auth callback cursor.");
+ const url = authorizationUrl(turn);
+ const response = await t.target.fetch(`${url.pathname}${url.search}`);
+ if (!response.ok) throw new Error(`Authorization callback failed (${String(response.status)}).`);
+ const live = t.target.watchTurn(turn.sessionId, { startIndex: state.streamIndex });
+ return { session: live.session, turn: await live.result() };
+}
diff --git a/packages/eve/src/client/url.test.ts b/packages/eve/src/client/url.test.ts
index bc1dd4985..8bc2d60c4 100644
--- a/packages/eve/src/client/url.test.ts
+++ b/packages/eve/src/client/url.test.ts
@@ -49,4 +49,29 @@ describe("createClientUrl", () => {
"/api/eve/v1/session?token=secret",
);
});
+
+ it("splits a query string embedded in the route path instead of encoding it", () => {
+ expect(
+ createClientUrl(
+ "https://agent.example.com",
+ "/eve/v1/connections/auth-probe/callback/attempt_1/wrun_1%3Aauth?code=ok",
+ ),
+ ).toBe(
+ "https://agent.example.com/eve/v1/connections/auth-probe/callback/attempt_1/wrun_1%3Aauth?code=ok",
+ );
+ });
+
+ it("splits embedded route queries on same-origin proxy prefixes", () => {
+ expect(createClientUrl("/api", "/eve/v1/session/123/stream?startIndex=4")).toBe(
+ "/api/eve/v1/session/123/stream?startIndex=4",
+ );
+ });
+
+ it("prefers explicit search parameters over embedded route queries", () => {
+ expect(
+ createClientUrl("https://agent.example.com", "/eve/v1/session/123/stream?startIndex=stale", {
+ startIndex: "4",
+ }),
+ ).toBe("https://agent.example.com/eve/v1/session/123/stream?startIndex=4");
+ });
});
diff --git a/packages/eve/src/client/url.ts b/packages/eve/src/client/url.ts
index 2ba4861b5..e3b36a8e9 100644
--- a/packages/eve/src/client/url.ts
+++ b/packages/eve/src/client/url.ts
@@ -4,18 +4,27 @@
* `host` may be an absolute origin (`https://agent.example.com`) or a
* same-origin prefix (`/api`). Prefixes are important for browser clients that
* talk to an app-owned proxy instead of the eve deployment directly.
+ *
+ * `routePath` may carry its own query string (`/path?a=1`); it is split off
+ * before path joining — assigning it through `URL.pathname` would percent-
+ * encode the `?` into the final path segment. Explicit `searchParams` win
+ * over same-named embedded query params.
*/
export function createClientUrl(
host: string,
routePath: string,
searchParams?: Readonly<Record<string, string>>,
): string {
- const normalizedRoute = routePath.startsWith("/") ? routePath : `/${routePath}`;
+ const queryIndex = routePath.indexOf("?");
+ const pathOnly = queryIndex === -1 ? routePath : routePath.slice(0, queryIndex);
+ const embeddedQuery = queryIndex === -1 ? "" : routePath.slice(queryIndex + 1);
+ const normalizedRoute = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
if (isAbsoluteUrl(host)) {
const url = new URL(host);
const basePath = trimTrailingSlash(url.pathname);
url.pathname = `${basePath}${normalizedRoute}`;
+ mergeEmbeddedQuery(url.searchParams, embeddedQuery);
mergeSearchParams(url.searchParams, searchParams);
url.hash = "";
return url.toString();
@@ -23,10 +32,19 @@ export function createClientUrl(
const url = new URL(host, "http://eve.local");
const basePath = trimTrailingSlash(url.pathname);
+ mergeEmbeddedQuery(url.searchParams, embeddedQuery);
mergeSearchParams(url.searchParams, searchParams);
return `${basePath}${normalizedRoute}${formatSearch(url.searchParams)}`;
}
+function mergeEmbeddedQuery(target: URLSearchParams, embeddedQuery: string): void {
+ if (embeddedQuery.length === 0) return;
+
+ for (const [name, value] of new URLSearchParams(embeddedQuery)) {
+ target.append(name, value);
+ }
+}
+
function isAbsoluteUrl(value: string): boolean {
return /^[a-z][a-z\d+\-.]*:/i.test(value);
}
diff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.ts
new file mode 100644
index 000000000..ade9e9b1a
--- /dev/null
+++ b/packages/eve/src/execution/authorization-callback-match.ts
@@ -0,0 +1,68 @@
+import type { DeliverPayload } from "#channel/types.js";
+import type { AuthorizationResult, PendingAuthorizationState } from "#harness/authorization.js";
+import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
+import type { AuthorizationCallback } from "#runtime/connections/types.js";
+
+export interface MatchedAuthorizationCallback {
+ readonly authorization: ConnectionAuthorizationChallenge;
+ readonly result: { readonly name: string } & AuthorizationResult;
+}
+
+/** Matches current callbacks by attempt ID and legacy callbacks only to legacy state. */
+export function matchAuthorizationCallbacks(
+ pending: PendingAuthorizationState,
+ payloads: readonly DeliverPayload[],
+): {
+ readonly matches: readonly MatchedAuthorizationCallback[];
+ readonly remainingPayloads: readonly DeliverPayload[];
+} {
+ const matches: MatchedAuthorizationCallback[] = [];
+ const remainingPayloads: DeliverPayload[] = [];
+ const matchedAttemptKeys = new Set<string>();
+
+ for (const payload of payloads) {
+ const callback = payload["authorizationCallback"] as
+ | {
+ attemptId?: string;
+ callback: AuthorizationCallback;
+ connectionName: string;
+ legacy?: true;
+ }
+ | undefined;
+ if (callback === undefined) {
+ remainingPayloads.push(payload);
+ continue;
+ }
+
+ const challenge = pending.challenges.find((candidate) => {
+ if (candidate.name !== callback.connectionName) return false;
+ return callback.legacy === true
+ ? candidate.attemptId === undefined
+ : candidate.attemptId === callback.attemptId;
+ });
+ const attemptKey = challenge?.attemptId ?? challenge?.name;
+ if (
+ challenge === undefined ||
+ attemptKey === undefined ||
+ (challenge.principal === undefined && callback.legacy !== true) ||
+ matchedAttemptKeys.has(attemptKey)
+ ) {
+ continue;
+ }
+
+ matchedAttemptKeys.add(attemptKey);
+ matches.push({
+ authorization: challenge.challenge,
+ result: {
+ attemptId: challenge.attemptId,
+ callback: callback.callback,
+ hookUrl: challenge.hookUrl,
+ name: challenge.name,
+ principal: challenge.principal,
+ resume: challenge.resume,
+ },
+ });
+ }
+
+ return { matches, remainingPayloads };
+}
diff --git a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
index e96938117..fa5c91aa0 100644
--- a/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
+++ b/packages/eve/src/execution/multi-agent-callback-routing.scenario.test.ts
@@ -156,6 +156,7 @@ describe("multi-agent callback routing", () => {
let remoteAgentOrigin: string;
beforeAll(async () => {
+ const authorizationAttemptId = "attempt-linear";
const nextRoot = await mkdtemp(join(tmpdir(), "eve-callback-routing-"));
for (const agent of DEPLOYMENT_AGENTS) {
@@ -210,7 +211,11 @@ describe("multi-agent callback routing", () => {
routed.servicePath === createEveCallbackRoutePath(callbackToken)) ||
(request.method === "GET" &&
routed.servicePath ===
- createEveConnectionCallbackRoutePath("linear", authHookToken(sessionId)));
+ createEveConnectionCallbackRoutePath(
+ "linear",
+ authorizationAttemptId,
+ authHookToken(sessionId),
+ ));
if (!servesPath) {
response.writeHead(404).end();
@@ -354,11 +359,13 @@ describe("multi-agent callback routing", () => {
ctx.set(SessionIdKey, sessionId);
ctx.set(CallbackBaseUrlKey, resolveWorkflowCallbackBaseUrl(deploymentOrigin));
- const hookUrl = contextStorage.run(ctx, () => getHookUrl("linear"));
+ const attemptId = "attempt-linear";
+ const hookUrl = contextStorage.run(ctx, () => getHookUrl("linear", attemptId));
expect(hookUrl).toBe(
`${deploymentOrigin}${agent.publicRoutePrefix}${createEveConnectionCallbackRoutePath(
"linear",
+ attemptId,
authHookToken(sessionId),
)}`,
);
@@ -368,7 +375,11 @@ describe("multi-agent callback routing", () => {
expect(response.status).toBe(200);
expect(serviceRequests.get(agent.serviceName)).toContainEqual({
method: "GET",
- servicePath: createEveConnectionCallbackRoutePath("linear", authHookToken(sessionId)),
+ servicePath: createEveConnectionCallbackRoutePath(
+ "linear",
+ attemptId,
+ authHookToken(sessionId),
+ ),
});
});
}
diff --git a/packages/eve/src/execution/next-driver-action.ts b/packages/eve/src/execution/next-driver-action.ts
index c7f48bf22..5671ceca3 100644
--- a/packages/eve/src/execution/next-driver-action.ts
+++ b/packages/eve/src/execution/next-driver-action.ts
@@ -36,6 +36,7 @@ export type NextDriverAction =
readonly kind: "park";
readonly sessionState: DurableSessionState;
readonly serializedContext: Record<string, unknown>;
+ readonly authorizationAttemptIds?: readonly string[];
readonly authorizationNames?: readonly string[];
/**
* Set when the parked turn was cancelled: the driver runs
diff --git a/packages/eve/src/execution/parked-delivery-wait.test.ts b/packages/eve/src/execution/parked-delivery-wait.test.ts
new file mode 100644
index 000000000..1051dbf07
--- /dev/null
+++ b/packages/eve/src/execution/parked-delivery-wait.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it } from "vitest";
+
+import type { DeliverHookPayload } from "#channel/types.js";
+import { nextTurnDelivery } from "#execution/parked-delivery-wait.js";
+import type {
+ SessionCommandInbox,
+ SessionInboxPayload,
+ SessionInboxSource,
+} from "#execution/session-command-inbox.js";
+import type { DurableSessionState } from "#execution/durable-session-store.js";
+
+interface ScriptedRead {
+ readonly result: IteratorResult<SessionInboxPayload>;
+ readonly source: SessionInboxSource;
+}
+
+interface MockInbox extends SessionCommandInbox {
+ readonly windowTransitions: boolean[];
+}
+
+/**
+ * Scripted inbox: serves reads in order and records every authorization
+ * window transition so tests can assert the window spans the whole wait.
+ */
+function createMockInbox(reads: readonly ScriptedRead[], authorizationReady = false): MockInbox {
+ const remaining = [...reads];
+ const windowTransitions: boolean[] = [];
+
+ return {
+ windowTransitions,
+ async claimAuthorization() {},
+ async claimStable() {},
+ consumeNext() {},
+ hasReadyAuthorization() {
+ return authorizationReady;
+ },
+ async next() {
+ const read = remaining.shift();
+ if (read === undefined) throw new Error("Mock inbox exhausted.");
+ return read.result;
+ },
+ async nextWithSource() {
+ const read = remaining.shift();
+ if (read === undefined) throw new Error("Mock inbox exhausted.");
+ return read;
+ },
+ async rekeyContinuation() {},
+ setAuthorizationWindow(open: boolean) {
+ windowTransitions.push(open);
+ },
+ };
+}
+
+function authorizationRead(): ScriptedRead {
+ return {
+ result: {
+ done: false,
+ value: {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ callback: { method: "GET", params: { code: "abc" } },
+ connectionName: "weather",
+ },
+ },
+ ],
+ } satisfies DeliverHookPayload,
+ },
+ source: "authorization",
+ };
+}
+
+function cancelRead(): ScriptedRead {
+ return {
+ result: { done: false, value: { kind: "cancel" } },
+ source: "session",
+ };
+}
+
+function messageRead(message: string): ScriptedRead {
+ return {
+ result: { done: false, value: { kind: "send", payload: { message } } },
+ source: "session",
+ };
+}
+
+// Routing never runs in these tests: scripted reads stop at authorization
+// instructions or exhaust before any deliver-kind turn payload.
+const sessionState = { sessionId: "ses-parked-wait" } as DurableSessionState;
+
+function waitInput(inbox: SessionCommandInbox): Parameters<typeof nextTurnDelivery>[0] {
+ return {
+ awaitAuthorizationCallbacks: true,
+ bufferedDeliveries: [],
+ bufferedSessionControls: [],
+ commandInbox: inbox,
+ driverWritable: new WritableStream<Uint8Array>(),
+ sessionState,
+ };
+}
+
+describe("nextTurnDelivery", () => {
+ it("surfaces an authorization callback as its own instruction", async () => {
+ const inbox = createMockInbox([authorizationRead()]);
+
+ const next = await nextTurnDelivery(waitInput(inbox));
+
+ expect(next.kind).toBe("authorization");
+ if (next.kind !== "authorization") throw new Error("unreachable");
+ expect(next.closed).toBe(false);
+ expect(next.payloads).toHaveLength(1);
+ expect(inbox.windowTransitions).toEqual([true, false]);
+ });
+
+ it("keeps the authorization window open across a consumed no-op cancel", async () => {
+ // A cancel with no active turn is consumed without producing a parent
+ // turn; the wait continues and the callback must still surface within
+ // the same window instead of stashing until unrelated activity.
+ const inbox = createMockInbox([cancelRead(), authorizationRead()]);
+
+ const next = await nextTurnDelivery(waitInput(inbox));
+
+ expect(next.kind).toBe("authorization");
+ expect(inbox.windowTransitions).toEqual([true, false]);
+ });
+
+ it("does not let buffered deliveries bypass a ready authorization callback", async () => {
+ const inbox = createMockInbox([authorizationRead()], true);
+ const bufferedDeliveries: DeliverHookPayload[] = [
+ { kind: "deliver", payloads: [{ message: "later" }] },
+ ];
+
+ const next = await nextTurnDelivery({
+ ...waitInput(inbox),
+ bufferedDeliveries,
+ });
+
+ expect(next.kind).toBe("authorization");
+ expect(bufferedDeliveries).toHaveLength(1);
+ });
+
+ it("buffers task deliveries until the authorization callback arrives", async () => {
+ const inbox = createMockInbox([messageRead("deferred"), authorizationRead()]);
+ const bufferedDeliveries: DeliverHookPayload[] = [];
+
+ const next = await nextTurnDelivery({
+ ...waitInput(inbox),
+ bufferedDeliveries,
+ deferDeliveries: true,
+ });
+
+ expect(next.kind).toBe("authorization");
+ expect(bufferedDeliveries).toMatchObject([
+ { kind: "deliver", payloads: [{ message: "deferred" }] },
+ ]);
+ });
+
+ it("reports a closed authorization hook", async () => {
+ const inbox = createMockInbox([
+ { result: { done: true, value: undefined }, source: "authorization" },
+ ]);
+
+ const next = await nextTurnDelivery(waitInput(inbox));
+
+ expect(next).toMatchObject({ closed: true, kind: "authorization", payloads: [] });
+ });
+
+ it("never opens the window without an open challenge", async () => {
+ const inbox = createMockInbox([cancelRead(), cancelRead()]);
+
+ await expect(
+ nextTurnDelivery({ ...waitInput(inbox), awaitAuthorizationCallbacks: false }),
+ ).rejects.toThrow("Mock inbox exhausted.");
+ expect(inbox.windowTransitions).toEqual([]);
+ });
+});
diff --git a/packages/eve/src/execution/parked-delivery-wait.ts b/packages/eve/src/execution/parked-delivery-wait.ts
index c779057a9..fcabb2fb2 100644
--- a/packages/eve/src/execution/parked-delivery-wait.ts
+++ b/packages/eve/src/execution/parked-delivery-wait.ts
@@ -10,11 +10,20 @@ type NextSessionAction =
| { readonly kind: "compact" }
| { readonly kind: "expired" }
| { readonly kind: "reset" }
+ | AuthorizationCallbackInstruction
| {
readonly delivery: DeliverHookPayload | null;
readonly kind: "delivery";
};
+/** One authorization-callback read surfaced during a parked wait. */
+export interface AuthorizationCallbackInstruction {
+ readonly kind: "authorization";
+ /** True when the authorization hook closed; no further callbacks can arrive. */
+ readonly closed: boolean;
+ readonly payloads: readonly DeliverPayload[];
+}
+
/** What the parked driver should do with the next session activity. */
export type NextTurnInstruction =
| { readonly kind: "clear" }
@@ -23,6 +32,7 @@ export type NextTurnInstruction =
| { readonly kind: "reset" }
| { readonly kind: "closed" }
| { readonly kind: "cancel-turn" }
+ | AuthorizationCallbackInstruction
| {
readonly kind: "turn";
readonly deliver: DeliverHookPayload;
@@ -35,11 +45,39 @@ export type NextTurnInstruction =
* no turn to run, so this keeps waiting until a delivery produces a parent
* turn, a cancellation, expiry, or hook closure. The wait is unbounded by
* design: a parked session lives until something addresses it.
+ *
+ * With `awaitAuthorizationCallbacks`, the inbox's authorization window stays
+ * open for the whole wait — including iterations that consume activity
+ * without producing a parent turn (no-op cancels, fully-routed descendant
+ * deliveries) — so an open challenge's callback surfaces as an
+ * `"authorization"` instruction no matter when it arrives.
*/
export async function nextTurnDelivery(input: {
+ readonly awaitAuthorizationCallbacks?: boolean;
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
readonly commandInbox: SessionCommandInbox;
+ readonly deferDeliveries?: boolean;
+ readonly driverWritable: WritableStream<Uint8Array>;
+ readonly sessionState: DurableSessionState;
+}): Promise<NextTurnInstruction> {
+ if (input.awaitAuthorizationCallbacks !== true) {
+ return await awaitNextTurnDelivery(input);
+ }
+
+ input.commandInbox.setAuthorizationWindow(true);
+ try {
+ return await awaitNextTurnDelivery(input);
+ } finally {
+ input.commandInbox.setAuthorizationWindow(false);
+ }
+}
+
+async function awaitNextTurnDelivery(input: {
+ readonly bufferedDeliveries: DeliverHookPayload[];
+ readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
+ readonly commandInbox: SessionCommandInbox;
+ readonly deferDeliveries?: boolean;
readonly driverWritable: WritableStream<Uint8Array>;
readonly sessionState: DurableSessionState;
}): Promise<NextTurnInstruction> {
@@ -48,8 +86,13 @@ export async function nextTurnDelivery(input: {
bufferedDeliveries: input.bufferedDeliveries,
bufferedSessionControls: input.bufferedSessionControls,
commandInbox: input.commandInbox,
+ deferDeliveries: input.deferDeliveries,
});
+ if (nextAction.kind === "authorization") {
+ return nextAction;
+ }
+
if (nextAction.kind !== "delivery") {
return { kind: nextAction.kind };
}
@@ -83,13 +126,18 @@ async function waitForNextSessionAction(input: {
readonly bufferedDeliveries: DeliverHookPayload[];
readonly bufferedSessionControls: Array<"clear" | "compact" | "expired" | "reset">;
readonly commandInbox: SessionCommandInbox;
+ readonly deferDeliveries?: boolean;
}): Promise<NextSessionAction> {
const pendingSessionControl = input.bufferedSessionControls.shift();
if (pendingSessionControl !== undefined) {
return { kind: pendingSessionControl };
}
- if (input.bufferedDeliveries.length > 0) {
+ if (
+ input.deferDeliveries !== true &&
+ !input.commandInbox.hasReadyAuthorization() &&
+ input.bufferedDeliveries.length > 0
+ ) {
return {
delivery: takeBufferedTurnDelivery(input.bufferedDeliveries),
kind: "delivery",
@@ -97,9 +145,20 @@ async function waitForNextSessionAction(input: {
}
while (true) {
- const first = await input.commandInbox.next();
+ const { result: first, source } = await input.commandInbox.nextWithSource();
input.commandInbox.consumeNext();
+ if (source === "authorization") {
+ if (first.done) {
+ return { closed: true, kind: "authorization", payloads: [] };
+ }
+ return {
+ closed: false,
+ kind: "authorization",
+ payloads: first.value.kind === "deliver" ? first.value.payloads : [],
+ };
+ }
+
if (first.done) {
return { delivery: null, kind: "delivery" };
}
@@ -121,10 +180,19 @@ async function waitForNextSessionAction(input: {
}
if (first.value.kind === "deliver") {
+ if (input.deferDeliveries === true) {
+ input.bufferedDeliveries.push(first.value);
+ continue;
+ }
return { delivery: first.value, kind: "delivery" };
}
- return { delivery: sendCommandToDelivery(first.value), kind: "delivery" };
+ const delivery = sendCommandToDelivery(first.value);
+ if (input.deferDeliveries === true) {
+ input.bufferedDeliveries.push(delivery);
+ continue;
+ }
+ return { delivery, kind: "delivery" };
}
}
diff --git a/packages/eve/src/execution/session-command-inbox.test.ts b/packages/eve/src/execution/session-command-inbox.test.ts
index 35d739bd0..dcf224867 100644
--- a/packages/eve/src/execution/session-command-inbox.test.ts
+++ b/packages/eve/src/execution/session-command-inbox.test.ts
@@ -139,8 +139,147 @@ describe("createSessionCommandInbox", () => {
expect(stable.return).not.toHaveBeenCalled();
expect(alias.return).not.toHaveBeenCalled();
});
+
+ it("stashes authorization callbacks while the window is closed", async () => {
+ const sessionRead = createDeferred<IteratorResult<SessionInboxPayload>>();
+ installHooks(
+ createMockHook({ reads: [sessionRead.promise], token: "stable" }),
+ createMockHook({
+ reads: [Promise.resolve(resolved(authCallback("weather")))],
+ token: "session:auth",
+ }),
+ );
+ const inbox = createSessionCommandInbox();
+ await inbox.claimStable("stable");
+ await inbox.claimAuthorization("session:auth");
+
+ // The callback resolves first, but only session activity surfaces.
+ const pending = inbox.nextWithSource();
+ sessionRead.resolve(resolved(send("while closed")));
+ await expect(pending).resolves.toEqual({
+ result: resolved(send("while closed")),
+ source: "session",
+ });
+ inbox.consumeNext();
+
+ inbox.setAuthorizationWindow(true);
+ await expect(inbox.nextWithSource()).resolves.toEqual({
+ result: resolved(authCallback("weather")),
+ source: "authorization",
+ });
+ inbox.consumeNext();
+ inbox.setAuthorizationWindow(false);
+ await inbox.dispose();
+ });
+
+ it("re-stashes an unconsumed authorization read when the window closes", async () => {
+ installHooks(
+ createMockHook({ reads: [Promise.resolve(resolved(send("first")))], token: "stable" }),
+ createMockHook({
+ reads: [Promise.resolve(resolved(authCallback("weather")))],
+ token: "session:auth",
+ }),
+ );
+ const inbox = createSessionCommandInbox();
+ await inbox.claimStable("stable");
+ await inbox.claimAuthorization("session:auth");
+
+ // Window open: the session read arrives first and is offered; the
+ // callback read resolves behind it and waits enqueued.
+ inbox.setAuthorizationWindow(true);
+ await expect(inbox.nextWithSource()).resolves.toEqual({
+ result: resolved(send("first")),
+ source: "session",
+ });
+ expect(inbox.hasReadyAuthorization()).toBe(false);
+ inbox.setAuthorizationWindow(false);
+ inbox.consumeNext();
+
+ // Window closed: the stashed callback never surfaces as session activity.
+ const closedRead = inbox.nextWithSource();
+ let settled = false;
+ void closedRead.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ // Reopening surfaces the same stashed callback exactly once.
+ inbox.setAuthorizationWindow(true);
+ await expect(closedRead).resolves.toEqual({
+ result: resolved(authCallback("weather")),
+ source: "authorization",
+ });
+ inbox.consumeNext();
+ await inbox.dispose();
+ });
+
+ it("lets an older callback supersede an unconsumed offered session read", async () => {
+ const sessionRead = createDeferred<IteratorResult<SessionInboxPayload>>();
+ installHooks(
+ createMockHook({ reads: [sessionRead.promise], token: "stable" }),
+ createMockHook({
+ reads: [Promise.resolve(resolved(authCallback("weather")))],
+ token: "session:auth",
+ }),
+ );
+ const inbox = createSessionCommandInbox();
+ await inbox.claimStable("stable");
+ await inbox.claimAuthorization("session:auth");
+
+ const losingRead = inbox.nextWithSource();
+ await Promise.resolve();
+ sessionRead.resolve(resolved(send("later session read")));
+ await expect(losingRead).resolves.toEqual({
+ result: resolved(send("later session read")),
+ source: "session",
+ });
+
+ inbox.setAuthorizationWindow(true);
+ expect(inbox.hasReadyAuthorization()).toBe(true);
+ await expect(inbox.nextWithSource()).resolves.toEqual({
+ result: resolved(authCallback("weather")),
+ source: "authorization",
+ });
+ inbox.consumeNext();
+ inbox.setAuthorizationWindow(false);
+
+ await expect(inbox.nextWithSource()).resolves.toEqual({
+ result: resolved(send("later session read")),
+ source: "session",
+ });
+ inbox.consumeNext();
+ await inbox.dispose();
+ });
+
+ it("disposes the authorization hook with the inbox", async () => {
+ const auth = createMockHook({ token: "session:auth" });
+ installHooks(createMockHook({ token: "stable" }), auth);
+ const inbox = createSessionCommandInbox();
+
+ await inbox.claimStable("stable");
+ await inbox.claimAuthorization("session:auth");
+ await inbox.dispose();
+
+ expect(auth.dispose).toHaveBeenCalledOnce();
+ expect(auth.return).not.toHaveBeenCalled();
+ });
});
+function authCallback(connectionName: string): SessionInboxPayload {
+ return {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ callback: { method: "GET", params: { code: "abc" } },
+ connectionName,
+ },
+ },
+ ],
+ };
+}
+
interface MockHook {
readonly dispose: ReturnType<typeof vi.fn>;
readonly hook: unknown;
diff --git a/packages/eve/src/execution/session-command-inbox.ts b/packages/eve/src/execution/session-command-inbox.ts
index 12ef3fcad..afc436f21 100644
--- a/packages/eve/src/execution/session-command-inbox.ts
+++ b/packages/eve/src/execution/session-command-inbox.ts
@@ -34,12 +34,38 @@ interface SessionCommandHookState {
resolved?: HookRead;
}
-/** Multiplexes one stable session hook and one rekeyable channel alias. */
+/** Which hook family produced an inbox read. */
+export type SessionInboxSource = "authorization" | "session";
+
+/**
+ * Multiplexes one stable session hook, one rekeyable channel alias, and one
+ * window-gated authorization-callback hook.
+ */
export interface SessionCommandInbox {
+ /**
+ * Claims the session's authorization-callback hook as an inbox source.
+ * Its reads stay stashed until {@link setAuthorizationWindow} opens, so
+ * callbacks never surface as ordinary session activity.
+ */
+ claimAuthorization(token: string): Promise<void>;
claimStable(token: string): Promise<void>;
consumeNext(): void;
+ /** Whether an authorization read is already eligible to be consumed. */
+ hasReadyAuthorization(): boolean;
next(): Promise<IteratorResult<SessionInboxPayload>>;
+ /**
+ * Like {@link next} but reports which hook family produced the read.
+ * Reads surface in one arrival order across every source, which keeps
+ * waits that interleave authorization callbacks with ordinary session
+ * activity deterministic under workflow replay.
+ */
+ nextWithSource(): Promise<{
+ result: IteratorResult<SessionInboxPayload>;
+ source: SessionInboxSource;
+ }>;
rekeyContinuation(token: string): Promise<void>;
+ /** Opens or closes the surfacing window for authorization-callback reads. */
+ setAuthorizationWindow(open: boolean): void;
}
/** Adds workflow-entry lifecycle ownership to a session command inbox. */
@@ -57,6 +83,7 @@ export interface SessionCommandInboxHandle extends SessionCommandInbox {
export function createSessionCommandInbox(): SessionCommandInboxHandle {
let stable: SessionCommandHookState | undefined;
let continuation: SessionCommandHookState | undefined;
+ let authorization: SessionCommandHookState | undefined;
const retired: SessionCommandHookState[] = [];
const ready: HookRead[] = [];
let nextOrder = 0;
@@ -111,11 +138,58 @@ export function createSessionCommandInbox(): SessionCommandInboxHandle {
};
const states = (): readonly SessionCommandHookState[] =>
- [stable, continuation, ...retired].filter(
+ [stable, continuation, authorization, ...retired].filter(
(state): state is SessionCommandHookState => state !== undefined,
);
+ const nextRead = (): Promise<IteratorResult<SessionInboxPayload>> => {
+ if (stable === undefined) {
+ throw new Error("Cannot wait for session commands before claiming the stable inbox.");
+ }
+
+ if (offered !== null) return offered;
+
+ const current = states();
+ for (const state of current) arm(state);
+
+ if (current.every((state) => state.closed)) {
+ offeredRead = {
+ order: nextOrder++,
+ result: { done: true, value: undefined },
+ state: stable,
+ };
+ offered = Promise.resolve(offeredRead.result);
+ return offered;
+ }
+
+ offered = (async () => {
+ while (ready.length === 0) {
+ await new Promise<void>((resolve) => {
+ wake = resolve;
+ });
+ }
+
+ const read = ready.shift()!;
+ offeredRead = read;
+ return read.result;
+ })();
+ return offered;
+ };
+
return {
+ async claimAuthorization(token: string): Promise<void> {
+ if (authorization !== undefined) {
+ if (authorization.hook.token === token) return;
+ throw new Error("A session command inbox cannot change its authorization token.");
+ }
+
+ const candidate = createState(token);
+ await claimHookOwnership(candidate.hook);
+ // Stays disabled until the driver opens the authorization window;
+ // resolved reads stash on the state and enqueue when it opens.
+ authorization = candidate;
+ },
+
async claimStable(token: string): Promise<void> {
if (stable !== undefined) {
if (stable.hook.token === token) return;
@@ -141,46 +215,68 @@ export function createSessionCommandInbox(): SessionCommandInboxHandle {
},
async dispose(): Promise<void> {
- const active = [continuation, stable].filter(
+ // Disposed without closing iterators: a session cancelled while a
+ // durable read is in flight only honors `return()` after that read
+ // settles, so hooks are swept instead.
+ const active = [continuation, stable, authorization].filter(
(state): state is SessionCommandHookState => state !== undefined,
);
continuation = undefined;
stable = undefined;
+ authorization = undefined;
await Promise.all(active.map(async (state) => await disposeHook(state.hook)));
},
- next(): Promise<IteratorResult<SessionInboxPayload>> {
- if (stable === undefined) {
- throw new Error("Cannot wait for session commands before claiming the stable inbox.");
- }
+ hasReadyAuthorization(): boolean {
+ if (authorization?.enabled !== true || authorization.resolved === undefined) return false;
+ if (offeredRead !== undefined) return offeredRead.state === authorization;
+ return ready[0]?.state === authorization;
+ },
- if (offered !== null) return offered;
+ next: nextRead,
- const current = states();
- for (const state of current) arm(state);
+ async nextWithSource(): Promise<{
+ result: IteratorResult<SessionInboxPayload>;
+ source: SessionInboxSource;
+ }> {
+ const result = await nextRead();
+ return {
+ result,
+ source:
+ offeredRead !== undefined && offeredRead.state === authorization
+ ? "authorization"
+ : "session",
+ };
+ },
- if (current.every((state) => state.closed)) {
- offeredRead = {
- order: nextOrder++,
- result: { done: true, value: undefined },
- state: stable,
- };
- offered = Promise.resolve(offeredRead.result);
- return offered;
+ setAuthorizationWindow(open: boolean): void {
+ if (authorization === undefined) {
+ if (open) {
+ throw new Error("Cannot open the authorization window before claiming its hook.");
+ }
+ return;
}
-
- offered = (async () => {
- while (ready.length === 0) {
- await new Promise<void>((resolve) => {
- wake = resolve;
- });
+ if (open) {
+ if (!authorization.enabled) enable(authorization);
+ if (
+ offeredRead !== undefined &&
+ offeredRead.state !== authorization &&
+ authorization.resolved !== undefined &&
+ authorization.resolved.order < offeredRead.order
+ ) {
+ enqueue(offeredRead);
+ offeredRead = undefined;
+ offered = null;
}
-
- const read = ready.shift()!;
- offeredRead = read;
- return read.result;
- })();
- return offered;
+ if (offered !== null) arm(authorization);
+ return;
+ }
+ authorization.enabled = false;
+ // Un-surface a stashed read that was enqueued but not consumed so it
+ // re-enqueues when the window reopens. Callers close the window only
+ // after consuming any authorization read they were offered.
+ const enqueued = ready.findIndex((read) => read.state === authorization);
+ if (enqueued !== -1) ready.splice(enqueued, 1);
},
async rekeyContinuation(token: string): Promise<void> {
diff --git a/packages/eve/src/execution/tool-auth.integration.test.ts b/packages/eve/src/execution/tool-auth.integration.test.ts
index f83f7d17b..2ffa32270 100644
--- a/packages/eve/src/execution/tool-auth.integration.test.ts
+++ b/packages/eve/src/execution/tool-auth.integration.test.ts
@@ -52,6 +52,12 @@ function seedUserPrincipal(): void {
});
}
+const TEST_USER_PRINCIPAL = {
+ id: "user-1",
+ issuer: "test-idp",
+ type: "user",
+} as const;
+
function authoredTool(input: {
readonly name: string;
readonly execute: (toolInput: unknown, ctx: ToolContext) => unknown;
@@ -283,7 +289,7 @@ describe("tool-hosted authorization", () => {
expect(isAuthorizationSignal(result)).toBe(true);
if (!isAuthorizationSignal(result)) throw new Error("expected signal");
expect(receivedCallbackUrl).toBe(
- "http://localhost:2000/eve/v1/connections/search_notion__mcp.notion.com_notion/callback/session_auth%3Aauth",
+ `http://localhost:2000/eve/v1/connections/search_notion__mcp.notion.com_notion/callback/${result.challenges[0]?.attemptId}/session_auth%3Aauth`,
);
expect(result.challenges[0]?.hookUrl).toBe(receivedCallbackUrl);
});
@@ -459,8 +465,10 @@ describe("tool-hosted authorization", () => {
loadContext().set(CallbackBaseUrlKey, "https://app.example");
loadContext().set(PendingAuthorizationResultKey, [
{
+ attemptId: "attempt-list-groups",
name: "list_groups__inline_auth",
hookUrl: "https://app.example/callback",
+ principal: TEST_USER_PRINCIPAL,
callback: {
params: { code: "abc" },
method: "GET",
@@ -503,8 +511,10 @@ describe("tool-hosted authorization", () => {
loadContext().set(CallbackBaseUrlKey, "https://app.example");
loadContext().set(PendingAuthorizationResultKey, [
{
+ attemptId: "attempt-sync-ticket",
name: "sync_ticket__oauth_linear",
hookUrl: "https://app.example/callback",
+ principal: TEST_USER_PRINCIPAL,
callback: {
params: { code: "abc" },
method: "GET",
@@ -591,8 +601,10 @@ describe("tool-hosted authorization", () => {
loadContext().set(CallbackBaseUrlKey, "https://app.example");
loadContext().set(PendingAuthorizationResultKey, [
{
+ attemptId: "attempt-list-groups",
name: "list_groups__inline_auth",
hookUrl: "https://app.example/callback",
+ principal: TEST_USER_PRINCIPAL,
callback: {
params: { code: "abc" },
method: "GET",
@@ -638,8 +650,10 @@ describe("tool-hosted authorization", () => {
loadContext().set(CallbackBaseUrlKey, "https://app.example");
loadContext().set(PendingAuthorizationResultKey, [
{
+ attemptId: "attempt-sync-ticket",
name: "sync_ticket__oauth_github",
hookUrl: "https://app.example/callback",
+ principal: TEST_USER_PRINCIPAL,
callback: {
params: { code: "abc" },
method: "GET",
diff --git a/packages/eve/src/execution/turn-control-receiver.test.ts b/packages/eve/src/execution/turn-control-receiver.test.ts
index 3668d0b42..928b85676 100644
--- a/packages/eve/src/execution/turn-control-receiver.test.ts
+++ b/packages/eve/src/execution/turn-control-receiver.test.ts
@@ -202,15 +202,21 @@ function createCommandInbox(
): SessionCommandInbox {
const queue = [...values];
return {
+ claimAuthorization: vi.fn(),
claimStable: vi.fn(),
consumeNext: vi.fn(),
+ hasReadyAuthorization: vi.fn(() => false),
next: vi.fn(() => {
const value = queue.shift();
return value === undefined
? new Promise<IteratorResult<SessionInboxPayload>>(() => {})
: Promise.resolve({ done: false, value });
}),
+ nextWithSource: vi.fn(() =>
+ Promise.reject(new Error("nextWithSource is not modeled by this test inbox.")),
+ ),
rekeyContinuation: vi.fn(),
+ setAuthorizationWindow: vi.fn(),
...overrides,
};
}
diff --git a/packages/eve/src/execution/turn-dispatch.test.ts b/packages/eve/src/execution/turn-dispatch.test.ts
index 10a3373ec..214522ad0 100644
--- a/packages/eve/src/execution/turn-dispatch.test.ts
+++ b/packages/eve/src/execution/turn-dispatch.test.ts
@@ -222,10 +222,16 @@ describe("dispatchAndAwaitTurn", () => {
function createCommandInbox(overrides: Partial<SessionCommandInbox> = {}): SessionCommandInbox {
return {
+ claimAuthorization: vi.fn(),
claimStable: vi.fn(),
consumeNext: vi.fn(),
+ hasReadyAuthorization: vi.fn(() => false),
next: vi.fn(() => new Promise<IteratorResult<SessionInboxPayload>>(() => {})),
+ nextWithSource: vi.fn(() =>
+ Promise.reject(new Error("nextWithSource is not modeled by this test inbox.")),
+ ),
rekeyContinuation: vi.fn(),
+ setAuthorizationWindow: vi.fn(),
...overrides,
};
}
diff --git a/packages/eve/src/execution/turn-execution-cursor.ts b/packages/eve/src/execution/turn-execution-cursor.ts
index c3c4b085a..bec37131a 100644
--- a/packages/eve/src/execution/turn-execution-cursor.ts
+++ b/packages/eve/src/execution/turn-execution-cursor.ts
@@ -23,6 +23,7 @@ type TurnTerminalAction =
readonly usageDelta?: TokenUsage;
}
| {
+ readonly authorizationAttemptIds?: readonly string[];
readonly authorizationNames?: readonly string[];
readonly cancelled?: true;
readonly kind: "park";
diff --git a/packages/eve/src/execution/turn-workflow.ts b/packages/eve/src/execution/turn-workflow.ts
index bfbe57f75..4f1b7e004 100644
--- a/packages/eve/src/execution/turn-workflow.ts
+++ b/packages/eve/src/execution/turn-workflow.ts
@@ -197,6 +197,7 @@ async function runTurnOwnedWorkflow(input: TurnWorkflowInput): Promise<void> {
await cursor.finish(
result,
{
+ authorizationAttemptIds: result.authorizationAttemptIds,
authorizationNames: result.authorizationNames,
kind: "park",
settled: result.settled,
@@ -435,6 +436,7 @@ async function runLegacyTurnWorkflow(input: TurnWorkflowInput): Promise<void> {
kind: "park",
serializedContext: result.serializedContext,
sessionState: result.sessionState,
+ authorizationAttemptIds: result.authorizationAttemptIds,
authorizationNames: result.authorizationNames,
settled: result.settled,
};
diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.ts
index fc1858c84..9f8f2c9f2 100644
--- a/packages/eve/src/execution/workflow-entry.integration.test.ts
+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts
@@ -20,7 +20,11 @@ import { ConnectionAuthorizationRequiredError } from "#public/connections/errors
import type { MessageStreamEvent } from "#protocol/message.js";
import { isEventId } from "#protocol/event-id.js";
import type { ToolContext } from "#public/definitions/tool.js";
-import type { AuthorizationDefinition, TokenResult } from "#runtime/connections/types.js";
+import type {
+ AuthorizationDefinition,
+ ConnectionPrincipal,
+ TokenResult,
+} from "#runtime/connections/types.js";
import type { ResolvedToolDefinition } from "#runtime/types.js";
import { toInputSchema } from "#shared/tool-schema.js";
@@ -55,81 +59,128 @@ function buildSerializedContext(overrides: {
return context;
}
-describe("workflowEntry integration", () => {
- it("resumes normal follow-ups after an interactive authorization callback", async () => {
- let completeCalls = 0;
- const weatherAuth: AuthorizationDefinition<{ nonce: string }> = {
- principalType: "user",
- async getToken(): Promise<TokenResult> {
- throw new ConnectionAuthorizationRequiredError("weather");
- },
- async startAuthorization({ callbackUrl }) {
+interface WeatherAuthRuntime {
+ completeCalls(): number;
+ completedPrincipals(): readonly ConnectionPrincipal[];
+ runtime: ReturnType<typeof createTestRuntime>;
+}
+
+/**
+ * A get_weather tool behind an interactive authorization: getToken always
+ * requires sign-in, and completeAuthorization mints `weather-token` from the
+ * `oauth-code` callback. Shared by the callback-resume and
+ * challenge-stays-open driver tests.
+ */
+function createWeatherAuthRuntime(agentName: string): WeatherAuthRuntime {
+ let completeCalls = 0;
+ const completedPrincipals: ConnectionPrincipal[] = [];
+ const weatherAuth: AuthorizationDefinition<{ nonce: string }> = {
+ principalType: "user",
+ async getToken(): Promise<TokenResult> {
+ throw new ConnectionAuthorizationRequiredError("weather");
+ },
+ async startAuthorization({ callbackUrl }) {
+ return {
+ challenge: {
+ displayName: "Weather",
+ instructions: "Sign in to continue.",
+ url: `https://idp.example/authorize?callback=${encodeURIComponent(callbackUrl)}`,
+ },
+ resume: { nonce: "weather-nonce" },
+ };
+ },
+ async completeAuthorization({ callback, principal, resume }): Promise<TokenResult> {
+ completeCalls += 1;
+ completedPrincipals.push(principal);
+ expect(callback.params.code).toBe("oauth-code");
+ expect(resume).toEqual({ nonce: "weather-nonce" });
+ return { token: "weather-token" };
+ },
+ };
+ const getWeatherTool: ResolvedToolDefinition = {
+ description: "Get the current weather for a city.",
+ execute: createToolExecuteWithAuth({
+ scope: "get_weather",
+ async execute(rawInput, rawCtx) {
+ const ctx = rawCtx as ToolContext;
+ const token = await ctx.getToken(weatherAuth, {
+ authKey: "weather",
+ displayName: "Weather",
+ });
+ const city =
+ typeof rawInput === "object" &&
+ rawInput !== null &&
+ typeof (rawInput as { city?: unknown }).city === "string"
+ ? (rawInput as { city: string }).city
+ : "Lisbon";
return {
- challenge: {
- displayName: "Weather",
- instructions: "Sign in to continue.",
- url: `https://idp.example/authorize?callback=${encodeURIComponent(callbackUrl)}`,
- },
- resume: { nonce: "weather-nonce" },
+ city,
+ condition: "Sunny",
+ summary: `authorized with ${token.token}`,
+ temperatureF: 72,
};
},
- async completeAuthorization({ callback, resume }): Promise<TokenResult> {
- completeCalls += 1;
- expect(callback.params.code).toBe("oauth-code");
- expect(resume).toEqual({ nonce: "weather-nonce" });
- return { token: "weather-token" };
- },
- };
- const getWeatherTool: ResolvedToolDefinition = {
- description: "Get the current weather for a city.",
- execute: createToolExecuteWithAuth({
- scope: "get_weather",
- async execute(rawInput, rawCtx) {
- const ctx = rawCtx as ToolContext;
- const token = await ctx.getToken(weatherAuth, {
- authKey: "weather",
- displayName: "Weather",
- });
- const city =
- typeof rawInput === "object" &&
- rawInput !== null &&
- typeof (rawInput as { city?: unknown }).city === "string"
- ? (rawInput as { city: string }).city
- : "Lisbon";
- return {
- city,
- condition: "Sunny",
- summary: `authorized with ${token.token}`,
- temperatureF: 72,
- };
- },
- }),
- inputSchema: toInputSchema({
- additionalProperties: false,
- properties: {
- city: { type: "string" },
- },
- required: ["city"],
- type: "object",
- }),
- logicalPath: "tools/get_weather.ts",
- name: "get_weather",
- sourceId: "tools/get_weather.ts",
- sourceKind: "module",
- };
- const runtime = createTestRuntime({
- agent: { name: "workflow-entry-auth-followup" },
- tools: [getWeatherTool],
- });
- const manifestTool = runtime.manifest.tools.find((tool) => tool.name === getWeatherTool.name);
- if (manifestTool === undefined) {
- throw new Error("Expected get_weather to be present in the test manifest.");
- }
- runtime.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[manifestTool.sourceId] = {
- default: {
- execute: getWeatherTool.execute,
+ }),
+ inputSchema: toInputSchema({
+ additionalProperties: false,
+ properties: {
+ city: { type: "string" },
},
- };
+ required: ["city"],
+ type: "object",
+ }),
+ logicalPath: "tools/get_weather.ts",
+ name: "get_weather",
+ sourceId: "tools/get_weather.ts",
+ sourceKind: "module",
+ };
+ const runtime = createTestRuntime({
+ agent: { name: agentName },
+ tools: [getWeatherTool],
+ });
+ const manifestTool = runtime.manifest.tools.find((tool) => tool.name === getWeatherTool.name);
+ if (manifestTool === undefined) {
+ throw new Error("Expected get_weather to be present in the test manifest.");
+ }
+ runtime.moduleMap.nodes[ROOT_COMPILED_AGENT_NODE_ID]!.modules[manifestTool.sourceId] = {
+ default: {
+ execute: getWeatherTool.execute,
+ },
+ };
+ return {
+ completeCalls: () => completeCalls,
+ completedPrincipals: () => completedPrincipals,
+ runtime,
+ };
+}
+
+function authorizationAttemptId(events: readonly MessageStreamEvent[]): string {
+ const required = filterEventsByType(events, "authorization.required")[0];
+ const webhookUrl = required?.data.webhookUrl;
+ if (webhookUrl === undefined) throw new Error("Missing authorization callback URL.");
+ const segments = new URL(webhookUrl).pathname.split("/");
+ const callbackIndex = segments.lastIndexOf("callback");
+ const attemptId = segments[callbackIndex + 1];
+ if (callbackIndex === -1 || attemptId === undefined) {
+ throw new Error("Authorization callback URL is missing its attempt ID.");
+ }
+ return decodeURIComponent(attemptId);
+}
+
+function expectSingleTurn(events: readonly MessageStreamEvent[], turnId: string): void {
+ expect(filterEventsByType(events, "turn.started")).toHaveLength(1);
+ const eventTurnIds = events.flatMap((event) => {
+ if (!("data" in event) || typeof event.data !== "object" || event.data === null) return [];
+ if (!("turnId" in event.data) || typeof event.data.turnId !== "string") return [];
+ return [event.data.turnId];
+ });
+ expect(eventTurnIds.length).toBeGreaterThan(0);
+ expect(new Set(eventTurnIds)).toEqual(new Set([turnId]));
+}
+
+describe("workflowEntry integration", () => {
+ it("resumes normal follow-ups after an interactive authorization callback", async () => {
+ const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-auth-followup");
const continuationToken = "http:workflow-entry-auth-followup";
await runtime.run(async () => {
@@ -167,11 +218,20 @@ describe("workflowEntry integration", () => {
authorization: { displayName: "Weather" },
});
+ // The authorization park closes its turn boundary so stream
+ // consumers do not hang on the parked turn.
+ const parkBoundary = await stream.nextUntil(
+ "authorization park boundary",
+ (event) => event.type === "session.waiting",
+ );
+ expect(parkBoundary.at(-1)?.type).toBe("session.waiting");
+
await resumeHook(`${run.runId}:auth`, {
kind: "deliver",
payloads: [
{
authorizationCallback: {
+ attemptId: authorizationAttemptId(firstTurn),
callback: {
method: "GET",
params: { code: "oauth-code" },
@@ -188,7 +248,8 @@ describe("workflowEntry integration", () => {
);
const completed = filterEventsByType(authorizedTurn, "authorization.completed");
- expect(completeCalls).toBe(1);
+ expect(completeCalls()).toBe(1);
+ expectSingleTurn(authorizedTurn, "turn_1");
expect(authorizedTurn.at(-1)?.type).toBe("session.waiting");
expect(completed).toHaveLength(1);
expect(completed[0]?.data).toMatchObject({
@@ -234,6 +295,377 @@ describe("workflowEntry integration", () => {
});
});
+ it("runs ordinary deliveries while an authorization challenge stays open", async () => {
+ const { completeCalls, completedPrincipals, runtime } = createWeatherAuthRuntime(
+ "workflow-entry-auth-open",
+ );
+ const continuationToken = "http:workflow-entry-auth-open";
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: "Use the get_weather tool to check the weather in Lisbon." },
+ serializedContext: buildSerializedContext({
+ auth: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-1",
+ principalType: "user",
+ },
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ },
+ ]);
+
+ const stream = captureEvents(run);
+
+ try {
+ const firstTurn = await stream.nextUntil(
+ "initial auth-required event",
+ (event) => event.type === "authorization.required",
+ );
+ // Consume the park's own turn boundary so the next wait delimits
+ // the intervening message turn.
+ await stream.nextUntil(
+ "authorization park boundary",
+ (event) => event.type === "session.waiting",
+ );
+
+ // An ordinary message while the challenge is open runs as a normal
+ // turn instead of queueing behind the callback.
+ await waitForHook({ runId: run.runId }, { token: continuationToken });
+ await resumeHook(continuationToken, {
+ auth: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-2",
+ principalType: "user",
+ },
+ kind: "send",
+ payload: { message: "Quick status note while I sign in." },
+ });
+
+ const interveningTurn = await stream.nextUntil(
+ "intervening message turn",
+ (event) => event.type === "session.waiting",
+ );
+ expect(
+ interveningTurn.some(
+ (event) =>
+ event.type === "message.completed" &&
+ event.data.message?.includes("Quick status note while I sign in.") === true,
+ ),
+ ).toBe(true);
+ expect(filterEventsByType(interveningTurn, "authorization.completed")).toHaveLength(0);
+ expect(completeCalls()).toBe(0);
+
+ // The callback still lands on the retained read and closes the
+ // challenge exactly once.
+ await resumeHook(`${run.runId}:auth`, {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ attemptId: authorizationAttemptId(firstTurn),
+ callback: {
+ method: "GET",
+ params: { code: "oauth-code" },
+ },
+ connectionName: "weather",
+ },
+ },
+ ],
+ });
+
+ const callbackTurn = await stream.nextUntil(
+ "authorization callback turn",
+ (event) => event.type === "session.waiting",
+ );
+ const completed = filterEventsByType(callbackTurn, "authorization.completed");
+ expectSingleTurn(callbackTurn, "turn_2");
+ expect(completed).toHaveLength(1);
+ expect(completed[0]?.data).toMatchObject({
+ name: "weather",
+ outcome: "authorized",
+ });
+
+ // The granted authorization serves the next explicit tool request.
+ // (No waitForHook here: it only reports never-received hooks, and
+ // the continuation hook already received the intervening message.)
+ await resumeHook(continuationToken, {
+ auth: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-1",
+ principalType: "user",
+ },
+ kind: "send",
+ payload: { message: "Use the get_weather tool to check the weather in Lisbon." },
+ });
+
+ const toolTurn = await stream.nextUntil(
+ "post-authorization tool turn",
+ (event) => event.type === "session.waiting",
+ );
+ expect(completeCalls()).toBe(1);
+ expect(completedPrincipals()).toEqual([
+ expect.objectContaining({ id: "user-1", type: "user" }),
+ ]);
+ expect(
+ toolTurn.some(
+ (event) =>
+ event.type === "message.completed" &&
+ event.data.message?.includes("Used local weather tool for Lisbon") === true &&
+ event.data.message.includes("authorized with weather-token"),
+ ),
+ ).toBe(true);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ });
+
+ it("defers ordinary deliveries while a task waits for authorization", async () => {
+ const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-task-auth-open");
+ const continuationToken = "http:workflow-entry-task-auth-open";
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: "Use the get_weather tool to check the weather in Lisbon." },
+ serializedContext: buildSerializedContext({
+ auth: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-1",
+ principalType: "user",
+ },
+ channelKind: "http",
+ continuationToken,
+ mode: "task",
+ }),
+ },
+ ]);
+ const stream = captureEvents(run);
+
+ try {
+ const firstTurn = await stream.nextUntil(
+ "initial task auth-required event",
+ (event) => event.type === "authorization.required",
+ );
+
+ await waitForHook({ runId: run.runId }, { token: continuationToken });
+ await resumeHook(continuationToken, {
+ kind: "send",
+ payload: { message: "This must not become a second task turn." },
+ });
+ await resumeHook(`${run.runId}:auth`, {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ attemptId: authorizationAttemptId(firstTurn),
+ callback: { method: "GET", params: { code: "oauth-code" } },
+ connectionName: "weather",
+ },
+ },
+ ],
+ });
+
+ const completion = await stream.nextUntil(
+ "authorized task completion",
+ (event) => event.type === "session.completed",
+ );
+ const allEvents = [...firstTurn, ...completion];
+ expect(filterEventsByType(allEvents, "turn.started")).toHaveLength(1);
+ expect(filterEventsByType(allEvents, "message.received")).toHaveLength(1);
+ expect(filterEventsByType(allEvents, "authorization.completed")).toHaveLength(1);
+ expect(filterEventsByType(allEvents, "session.waiting")).toHaveLength(0);
+ expect(completeCalls()).toBe(1);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ });
+
+ it("ignores stale and duplicate callbacks after a challenge is replaced", async () => {
+ const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-auth-replaced");
+ const continuationToken = "http:workflow-entry-auth-replaced";
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: "Use the get_weather tool to check the weather in Lisbon." },
+ serializedContext: buildSerializedContext({
+ auth: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-1",
+ principalType: "user",
+ },
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ },
+ ]);
+ const stream = captureEvents(run);
+
+ try {
+ const firstAttempt = await stream.nextUntil(
+ "first auth-required event",
+ (event) => event.type === "authorization.required",
+ );
+ await stream.nextUntil(
+ "first authorization park",
+ (event) => event.type === "session.waiting",
+ );
+
+ await waitForHook({ runId: run.runId }, { token: continuationToken });
+ await resumeHook(continuationToken, {
+ kind: "send",
+ payload: { message: "Use the get_weather tool to check the weather in Lisbon." },
+ });
+ const replacementAttempt = await stream.nextUntil(
+ "replacement auth-required event",
+ (event) => event.type === "authorization.required",
+ );
+ expect(filterEventsByType(replacementAttempt, "authorization.completed")).toMatchObject([
+ { data: { name: "weather", outcome: "failed" } },
+ ]);
+ await stream.nextUntil(
+ "replacement authorization park",
+ (event) => event.type === "session.waiting",
+ );
+
+ const stalePayload = {
+ authorizationCallback: {
+ attemptId: authorizationAttemptId(firstAttempt),
+ callback: { method: "GET", params: { code: "stale-oauth-code" } },
+ connectionName: "weather",
+ },
+ };
+ await resumeHook(`${run.runId}:auth`, { kind: "deliver", payloads: [stalePayload] });
+ await resumeHook(`${run.runId}:auth`, { kind: "deliver", payloads: [stalePayload] });
+
+ await resumeHook(`${run.runId}:auth`, {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ attemptId: authorizationAttemptId(replacementAttempt),
+ callback: { method: "GET", params: { code: "oauth-code" } },
+ connectionName: "weather",
+ },
+ },
+ ],
+ });
+
+ const callbackTurn = await stream.nextUntil(
+ "replacement authorization callback turn",
+ (event) => event.type === "session.waiting",
+ );
+ expect(filterEventsByType(callbackTurn, "authorization.completed")).toHaveLength(1);
+ expect(completeCalls()).toBe(1);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ });
+
+ it("completes the challenge after a no-op cancel consumed the parked wait", async () => {
+ const { completeCalls, runtime } = createWeatherAuthRuntime("workflow-entry-auth-cancel");
+ const continuationToken = "http:workflow-entry-auth-cancel";
+
+ await runtime.run(async () => {
+ const run = await start(workflowEntry, [
+ {
+ input: { message: "Use the get_weather tool to check the weather in Lisbon." },
+ serializedContext: buildSerializedContext({
+ auth: {
+ attributes: {},
+ authenticator: "test-idp",
+ issuer: "test-idp",
+ principalId: "user-1",
+ principalType: "user",
+ },
+ channelKind: "http",
+ continuationToken,
+ mode: "conversation",
+ }),
+ },
+ ]);
+
+ const stream = captureEvents(run);
+
+ try {
+ const firstTurn = await stream.nextUntil(
+ "initial auth-required event",
+ (event) => event.type === "authorization.required",
+ );
+ await stream.nextUntil(
+ "authorization park boundary",
+ (event) => event.type === "session.waiting",
+ );
+
+ // A cancel with no active turn is consumed by the parked wait
+ // without producing a parent turn. The callback must still surface
+ // in the continued wait instead of stalling until unrelated
+ // session activity re-parks the driver.
+ await waitForHook({ runId: run.runId }, { token: continuationToken });
+ await resumeHook(continuationToken, { kind: "cancel" });
+ // Let the driver consume the no-op cancel and re-enter the parked
+ // wait before the callback fires; back-to-back resumes could
+ // otherwise surface the callback in the first wait iteration and
+ // mask a wait that ignores callbacks after a consumed cancel.
+ await new Promise((resolve) => setTimeout(resolve, 250));
+
+ await resumeHook(`${run.runId}:auth`, {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ attemptId: authorizationAttemptId(firstTurn),
+ callback: {
+ method: "GET",
+ params: { code: "oauth-code" },
+ },
+ connectionName: "weather",
+ },
+ },
+ ],
+ });
+
+ const callbackTurn = await stream.nextUntil(
+ "authorization callback turn",
+ (event) => event.type === "session.waiting",
+ );
+ const completed = filterEventsByType(callbackTurn, "authorization.completed");
+
+ expect(completeCalls()).toBe(1);
+ expect(completed).toHaveLength(1);
+ expect(completed[0]?.data).toMatchObject({
+ name: "weather",
+ outcome: "authorized",
+ });
+ expect(filterEventsByType(callbackTurn, "turn.cancelled")).toHaveLength(0);
+ } finally {
+ stream.dispose();
+ await run.cancel();
+ }
+ });
+ });
+
it("parks in conversation mode and resumes via runtime delivery", async () => {
const runtime = createTestRuntime({ agent: { name: "workflow-entry-conversation" } });
const continuationToken = "http:workflow-entry-conversation";
diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.ts
index 7db5ba710..0402be17b 100644
--- a/packages/eve/src/execution/workflow-entry.ts
+++ b/packages/eve/src/execution/workflow-entry.ts
@@ -1,4 +1,4 @@
-import { createHook, getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";
+import { getWorkflowMetadata, getWritable } from "#compiled/@workflow/core/index.js";
import type {
DeliverHookPayload,
@@ -22,7 +22,7 @@ import {
} from "#execution/delegated-parent-result.js";
import type { DurableSessionState } from "#execution/durable-session-store.js";
import type { NextDriverAction } from "#execution/next-driver-action.js";
-import { nextTurnDelivery } from "#execution/parked-delivery-wait.js";
+import { nextTurnDelivery, type NextTurnInstruction } from "#execution/parked-delivery-wait.js";
import { cancelDescendantTurnsStep } from "#execution/cancel-descendant-turns-step.js";
import { dispatchAndAwaitTurn } from "#execution/turn-dispatch.js";
import type { TurnDriverAction } from "#execution/turn-control-receiver.js";
@@ -31,7 +31,6 @@ import { createSessionStep } from "#execution/create-session-step.js";
import { settleCancelledTurnStep } from "#execution/settle-cancelled-turn-step.js";
import { emitTerminalSessionFailureStep } from "#execution/terminal-session-failure-step.js";
import { fireSessionCallbackStep } from "#execution/session-callback-step.js";
-import { disposeHook } from "#execution/hook-ownership.js";
import { createSessionCommandInbox } from "#execution/session-command-inbox.js";
import { sessionCommandHookToken } from "#execution/session-command-token.js";
import { DEFAULT_SESSION_TIMEOUT_MS } from "#execution/session-timeout.js";
@@ -291,13 +290,73 @@ async function runDriverLoop(input: {
readonly sessionState: DurableSessionState;
readonly sessionTimeoutDeadline?: Date;
}): Promise<DriverLoopOutcome> {
- // Per-session auth hook. Created before any turns so it exists
- // when authorization.required events trigger OAuth callbacks.
- // getHookUrl() builds callback URLs with this token.
- const authHook = createHook<HookPayload>({
- token: `${input.sessionState.sessionId}:auth`,
- });
- const authIterator: AsyncIterator<HookPayload> = authHook[Symbol.asyncIterator]();
+ // One payload per exact authorization attempt accumulates across
+ // intervening turns. Replaced attempts are pruned at each park.
+ const collectedAuthPayloads = new Map<string, DeliverPayload>();
+ /**
+ * Waits for the next parked-session activity. While an authorization
+ * challenge is open (`expected > 0`), callback reads surface through the
+ * same single FIFO wait as ordinary session activity — one arrival order,
+ * which keeps the wait deterministic under workflow replay — and keep
+ * surfacing across wait iterations that produce no parent turn (no-op
+ * cancels, fully-routed descendant deliveries). Callbacks accumulate
+ * across intervening turns; once every expected challenge has reported
+ * (or the hook closed), the collected payloads resume the challenge.
+ */
+ const nextParkedActivity = async (park: {
+ readonly expectedAttemptIds: readonly string[];
+ readonly sessionState: DurableSessionState;
+ }): Promise<
+ | { readonly kind: "authorization-resume"; readonly payloads: DeliverPayload[] }
+ | Exclude<NextTurnInstruction, { kind: "authorization" }>
+ > => {
+ const expectedAttemptIds = new Set(park.expectedAttemptIds);
+ for (const attemptId of collectedAuthPayloads.keys()) {
+ if (!expectedAttemptIds.has(attemptId)) collectedAuthPayloads.delete(attemptId);
+ }
+
+ while (true) {
+ if (
+ expectedAttemptIds.size > 0 &&
+ [...expectedAttemptIds].every((attemptId) => collectedAuthPayloads.has(attemptId))
+ ) {
+ const payloads = [...expectedAttemptIds].map(
+ (attemptId) => collectedAuthPayloads.get(attemptId)!,
+ );
+ collectedAuthPayloads.clear();
+ return { kind: "authorization-resume", payloads };
+ }
+
+ const next = await nextTurnDelivery({
+ awaitAuthorizationCallbacks: expectedAttemptIds.size > 0,
+ bufferedDeliveries,
+ bufferedSessionControls,
+ commandInbox,
+ deferDeliveries: input.mode === "task" && expectedAttemptIds.size > 0,
+ driverWritable: input.driverWritable,
+ sessionState: park.sessionState,
+ });
+ if (next.kind !== "authorization") return next;
+
+ for (const payload of next.payloads) {
+ const callback = payload["authorizationCallback"] as
+ | { readonly attemptId?: unknown }
+ | undefined;
+ if (
+ typeof callback?.attemptId === "string" &&
+ expectedAttemptIds.has(callback.attemptId) &&
+ !collectedAuthPayloads.has(callback.attemptId)
+ ) {
+ collectedAuthPayloads.set(callback.attemptId, payload);
+ }
+ }
+ if (next.closed) {
+ const payloads = [...collectedAuthPayloads.values()];
+ collectedAuthPayloads.clear();
+ return { kind: "authorization-resume", payloads };
+ }
+ }
+ };
// Fast descendant resumes can start the next turn before the prior
// control hook disposal is persisted by the Workflow SDK, so each
// turn needs its own session-scoped token.
@@ -310,6 +369,12 @@ async function runDriverLoop(input: {
const commandInbox = createSessionCommandInbox();
const stableCommandToken = sessionCommandHookToken(input.sessionState.sessionId);
await commandInbox.claimStable(stableCommandToken);
+ // Per-session authorization-callback hook. Claimed before any turns so it
+ // exists when authorization.required events trigger OAuth callbacks;
+ // getHookUrl() builds callback URLs with this token (see authHookToken —
+ // inlined here because the workflow driver body cannot import the
+ // harness module).
+ await commandInbox.claimAuthorization(`${input.sessionState.sessionId}:auth`);
const sessionTimeout =
input.sessionTimeoutDeadline === undefined
? undefined
@@ -394,30 +459,6 @@ async function runDriverLoop(input: {
await commandInbox.rekeyContinuation(action.sessionState.continuationToken);
}
- if (action.authorizationNames && action.authorizationNames.length > 0) {
- const expected = action.authorizationNames.length;
- const allPayloads: DeliverPayload[] = [];
-
- while (allPayloads.length < expected) {
- const next = await authIterator.next();
- if (next.done) break;
- if (next.value.kind === "deliver") {
- allPayloads.push(...next.value.payloads);
- }
- }
-
- action = await runTurn({
- delivery: {
- kind: "deliver",
- payloads: allPayloads,
- },
- serializedContext: action.serializedContext,
- sessionState: action.sessionState,
- });
- input.crashCleanupState.lastSessionState = action.sessionState;
- continue;
- }
-
// `settled` rides the typed park arm exclusively; `run-step` preserves
// the full StepResult so no state-key fallback exists anymore.
const settled = action.settled;
@@ -433,14 +474,27 @@ async function runDriverLoop(input: {
input.crashCleanupState.caller = undefined;
}
- const next = await nextTurnDelivery({
- bufferedDeliveries,
- bufferedSessionControls,
- commandInbox,
- driverWritable: input.driverWritable,
+ // An open authorization challenge must not wedge the session:
+ // ordinary deliveries keep starting normal turns while the challenge
+ // waits for its callback, and the callback surfaces through the same
+ // parked wait as everything else. The pending challenge survives
+ // intervening turns because every park re-derives
+ // `authorizationNames` from durable session state.
+ const next = await nextParkedActivity({
+ expectedAttemptIds: action.authorizationAttemptIds ?? [],
sessionState: action.sessionState,
});
+ if (next.kind === "authorization-resume") {
+ action = await runTurn({
+ delivery: { kind: "deliver", payloads: next.payloads },
+ serializedContext: action.serializedContext,
+ sessionState: action.sessionState,
+ });
+ input.crashCleanupState.lastSessionState = action.sessionState;
+ continue;
+ }
+
if (next.kind === "expired") {
return {
kind: "expired",
@@ -511,10 +565,6 @@ async function runDriverLoop(input: {
await disposeSettledTurnControl?.();
await sessionTimeout?.dispose();
await commandInbox.dispose();
- // Dispose without closing the iterator: a session cancelled while
- // awaiting authorization can leave a durable read in flight, and an
- // async iterator only honors `return()` after that read settles.
- await disposeHook(authHook);
}
}
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index 9429bdd26..e1e0261e9 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -1202,12 +1202,14 @@ describe("turnStep", () => {
state: setPendingAuthorization(session.state, {
challenges: [
{
+ attemptId: "attempt-statuspage",
challenge: {
instructions: "Sign in to continue",
url: "https://idp.example/authorize",
},
hookUrl: "https://app.example/callback",
name: "statuspage",
+ principal: { type: "app" },
},
],
}),
@@ -1667,7 +1669,7 @@ describe("turnStep", () => {
]);
});
- it("clears pending authorization after a matching callback resumes the turn", async () => {
+ it("resumes a legacy pending authorization without attempt metadata", async () => {
const challenge = {
challenge: {
instructions: "Sign in to continue",
@@ -1719,6 +1721,7 @@ describe("turnStep", () => {
authorizationCallback: {
callback: { code: "oauth-code" },
connectionName: "statuspage",
+ legacy: true,
},
},
],
@@ -1744,12 +1747,14 @@ describe("turnStep", () => {
it("clears pending authorization after a matching callback resumes the turn", async () => {
const challenge = {
+ attemptId: "attempt-statuspage",
challenge: {
instructions: "Sign in to continue",
url: "https://idp.example/authorize",
},
hookUrl: "https://app.example/eve/v1/connections/statuspage/callback/sess-test:auth",
name: "statuspage",
+ principal: { type: "app" } as const,
resume: { nonce: "n1" },
};
const session = createStubSession({
@@ -1792,6 +1797,7 @@ describe("turnStep", () => {
payloads: [
{
authorizationCallback: {
+ attemptId: "attempt-statuspage",
callback: { code: "oauth-code" },
connectionName: "statuspage",
},
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 4d9ee6590..4916c31bc 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -23,8 +23,14 @@ import {
import { BundleKey, ChannelKey } from "#runtime/sessions/runtime-context-keys.js";
import { runStep } from "#context/run-step.js";
import { deserializeContext, serializeContext } from "#context/serialize.js";
-import { getHarnessEmissionState } from "#harness/emission.js";
+import {
+ emitTurnPreamble,
+ getHarnessEmissionState,
+ isHarnessBetweenTurns,
+ setHarnessEmissionState,
+} from "#harness/emission.js";
import { preserveSerializedAgentTraceState } from "#tracing/agent-trace-context-store.js";
+import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";
import { readTurnSleepDurationMs } from "#harness/turn-sleep.js";
import { isTurnCancellation, throwIfTurnAborted } from "#harness/turn-cancellation.js";
import { setChannelContext } from "#execution/channel-context.js";
@@ -56,11 +62,8 @@ import {
clearPendingAuthorization,
getPendingAuthorization,
PendingAuthorizationResultKey,
- type AuthorizationResult,
} from "#harness/authorization.js";
import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
-import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
-import type { AuthorizationCallback } from "#runtime/connections/types.js";
import {
createDurableSessionState,
type DurableSessionState,
@@ -90,10 +93,8 @@ import { resumeHook } from "#internal/workflow/runtime.js";
/**
* Result of one durable harness step, consumed by the turn workflow.
*
- * `park` carries `hasPendingInputBatch`, `hasPendingAuthorization`, and
- * `pendingRuntimeActionKeys` so the turn workflow can pick the right
- * {@link import("#execution/next-driver-action.js").NextDriverAction}
- * arm without re-reading the session.
+ * `park` carries the pending fields needed to choose a
+ * {@link import("#execution/next-driver-action.js").NextDriverAction} without re-reading state.
*
* `cancelled` converts the harness's cancellation throw into a *returned*
* result so workflow-core never classifies the abort as a step failure or
@@ -127,6 +128,7 @@ export type DurableStepResult =
}
| {
readonly action: "park";
+ readonly authorizationAttemptIds?: readonly string[];
readonly authorizationNames?: readonly string[];
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
@@ -180,46 +182,27 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
// Completion event names are collected here; emission happens after
// the `emit` function is created below.
const pendingAuth = getPendingAuthorization(durableSession.state);
- let completedAuths:
- | Array<{ name: string; authorization: ConnectionAuthorizationChallenge }>
- | undefined;
+ let completedAuths: ReturnType<typeof matchAuthorizationCallbacks>["matches"] | undefined;
if (pendingAuth && input.input?.kind === "deliver") {
- const authResults: Array<{ name: string } & AuthorizationResult> = [];
- const completed: Array<{ name: string; authorization: ConnectionAuthorizationChallenge }> = [];
- const remainingPayloads: DeliverPayload[] = [];
- for (const payload of input.input.payloads) {
- const cb = payload["authorizationCallback"] as
- | { connectionName: string; callback: AuthorizationCallback }
- | undefined;
- if (cb) {
- const challenge = pendingAuth.challenges.find((c) => c.name === cb.connectionName);
- if (challenge) {
- authResults.push({
- name: challenge.name,
- resume: challenge.resume,
- callback: cb.callback,
- hookUrl: challenge.hookUrl,
- });
- completed.push({ name: challenge.name, authorization: challenge.challenge });
- }
- } else {
- remainingPayloads.push(payload);
- }
- }
- if (authResults.length > 0) {
+ const { matches, remainingPayloads } = matchAuthorizationCallbacks(
+ pendingAuth,
+ input.input.payloads,
+ );
+ input = { ...input, input: { ...input.input, payloads: remainingPayloads } };
+ if (matches.length > 0) {
+ const authResults = matches.map((match) => match.result);
ctx.set(PendingAuthorizationResultKey, authResults);
durableSession = {
...durableSession,
state: clearPendingAuthorization(
durableSession.state,
- authResults.map((result) => result.name),
+ authResults.map((result) => result.attemptId ?? result.name),
),
};
- completedAuths = completed;
- input =
- remainingPayloads.length > 0
- ? { ...input, input: { ...input.input, payloads: remainingPayloads } }
- : { ...input, input: undefined };
+ completedAuths = matches;
+ if (remainingPayloads.length === 0) {
+ input = { ...input, input: undefined };
+ }
}
}
@@ -393,19 +376,23 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
// or the pending batch would re-park and later re-dispatch.
throwIfTurnAborted(input.abortSignal);
stepResult = await runStep(ctx, initialSession, async (enrichedSession) => {
- const schemaSession = resolveEffectiveOutputSchema({
+ let schemaSession = resolveEffectiveOutputSchema({
agentOutputSchema: effectiveAgent.turnAgent.outputSchema,
input: resolved,
mode,
session: enrichedSession,
});
if (completedAuths) {
- const emissionState = getHarnessEmissionState(schemaSession.state);
- for (const { name, authorization } of completedAuths) {
+ let emissionState = getHarnessEmissionState(schemaSession.state);
+ if (isHarnessBetweenTurns(schemaSession)) {
+ emissionState = await emitTurnPreamble(handleEvent, {}, emissionState, runtimeIdentity);
+ schemaSession = setHarnessEmissionState(schemaSession, emissionState);
+ }
+ for (const { authorization, result } of completedAuths) {
await handleEvent(
createAuthorizationCompletedEvent({
authorization,
- name,
+ name: result.name,
outcome: "authorized",
sequence: emissionState.sequence,
stepIndex: emissionState.stepIndex,
@@ -565,6 +552,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
* the right `NextDriverAction` arm at the park boundary.
*/
function derivePendingState(session: HarnessSession): {
+ readonly authorizationAttemptIds?: readonly string[];
readonly authorizationNames?: readonly string[];
readonly hasPendingAuthorization: boolean;
readonly hasPendingInputBatch: boolean;
@@ -573,6 +561,9 @@ function derivePendingState(session: HarnessSession): {
const batch = getPendingRuntimeActionBatch(session.state);
const pendingAuth = getPendingAuthorization(session.state);
const base = {
+ authorizationAttemptIds: pendingAuth?.challenges.flatMap((challenge) =>
+ challenge.attemptId === undefined ? [] : [challenge.attemptId],
+ ),
authorizationNames: pendingAuth?.challenges.map((c) => c.name),
hasPendingAuthorization: pendingAuth !== undefined,
hasPendingInputBatch: hasPendingInputBatch(session.state),
diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.ts
index 386d922e8..e6d019ead 100644
--- a/packages/eve/src/harness/authorization.test.ts
+++ b/packages/eve/src/harness/authorization.test.ts
@@ -2,23 +2,31 @@ import { describe, expect, it } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
import {
+ clearPendingAuthorization,
consumeAuthorizationResult,
+ getPendingAuthorization,
PendingAuthorizationResultKey,
+ setPendingAuthorization,
} from "#harness/authorization.js";
+import type { ConnectionPrincipal } from "#runtime/connections/types.js";
describe("authorization callback results", () => {
it("consumes each callback result once", () => {
const ctx = new ContextContainer();
ctx.set(PendingAuthorizationResultKey, [
{
+ attemptId: "attempt-notion",
callback: { method: "GET", params: { code: "notion-code" } },
hookUrl: "https://agent.example.com/notion",
name: "notion",
+ principal: { type: "app" },
},
{
+ attemptId: "attempt-linear",
callback: { method: "GET", params: { code: "linear-code" } },
hookUrl: "https://agent.example.com/linear",
name: "linear",
+ principal: { type: "app" },
},
]);
@@ -36,3 +44,58 @@ describe("authorization callback results", () => {
});
});
});
+
+describe("pending authorization attempts", () => {
+ const challenge = (
+ name: string,
+ attemptId: string,
+ principal: ConnectionPrincipal = { type: "app" },
+ ) => ({
+ attemptId,
+ challenge: { url: `https://idp.example/${attemptId}` },
+ hookUrl: `https://agent.example/${attemptId}`,
+ name,
+ principal,
+ });
+
+ it("keeps same-name attempts owned by different principals", () => {
+ const userA = { id: "user-a", issuer: "idp", type: "user" } as const;
+ const userB = { id: "user-b", issuer: "idp", type: "user" } as const;
+ const first = setPendingAuthorization(undefined, {
+ challenges: [challenge("linear", "linear-a", userA)],
+ });
+ const second = setPendingAuthorization(first, {
+ challenges: [challenge("linear", "linear-b", userB)],
+ });
+
+ expect(getPendingAuthorization(second)?.challenges).toEqual([
+ challenge("linear", "linear-a", userA),
+ challenge("linear", "linear-b", userB),
+ ]);
+ });
+
+ it("merges distinct names and replaces only the same name", () => {
+ const first = setPendingAuthorization(undefined, {
+ challenges: [challenge("linear", "linear-1"), challenge("github", "github-1")],
+ });
+ const replaced = setPendingAuthorization(first, {
+ challenges: [challenge("linear", "linear-2")],
+ });
+
+ expect(getPendingAuthorization(replaced)?.challenges).toEqual([
+ challenge("github", "github-1"),
+ challenge("linear", "linear-2"),
+ ]);
+ });
+
+ it("clears by exact attempt identity", () => {
+ const state = setPendingAuthorization(undefined, {
+ challenges: [challenge("linear", "linear-2"), challenge("github", "github-1")],
+ });
+
+ expect(clearPendingAuthorization(state, ["linear-1"])).toEqual(state);
+ expect(
+ getPendingAuthorization(clearPendingAuthorization(state, ["linear-2"]))?.challenges,
+ ).toEqual([challenge("github", "github-1")]);
+ });
+});
diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.ts
index da03dae37..61d0580d8 100644
--- a/packages/eve/src/harness/authorization.ts
+++ b/packages/eve/src/harness/authorization.ts
@@ -4,12 +4,13 @@
* Public API:
* - {@link requestAuthorization} — return from execute to suspend for auth
* - {@link getAuthorizationResult} — read the callback on resume
- * - {@link getHookUrl} — build a callback URL for external systems
+ * - {@link createAuthorizationAttempt} — mint one correlated callback URL
* - {@link isAuthorizationSignal} — type guard
*
* ## Resume lifecycle
*
- * `resume` is how an interactive strategy carries data from
+ * `attemptId` binds the callback to one challenge generation, while `resume`
+ * carries strategy data from
* `startAuthorization` to `completeAuthorization` across the park:
*
* 1. `startAuthorization` returns `{ challenge, resume? }`. The runtime
@@ -34,9 +35,10 @@ import { loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
import { SessionIdKey } from "#context/keys.js";
import type { ConnectionAuthorizationChallenge } from "#public/connections/errors.js";
-import type { AuthorizationCallback } from "#runtime/connections/types.js";
+import type { AuthorizationCallback, ConnectionPrincipal } from "#runtime/connections/types.js";
import type { JsonValue } from "#public/types/json.js";
import { createEveConnectionCallbackRoutePath } from "#protocol/routes.js";
+import { createUlid } from "#shared/ulid.js";
const AUTHORIZATION_BRAND = "__eveAuthorization" as const;
const AUTHORIZATION_PENDING_BRAND = "__eveAuthorizationPending" as const;
@@ -46,9 +48,13 @@ const AUTHORIZATION_PENDING_BRAND = "__eveAuthorizationPending" as const;
// ---------------------------------------------------------------------------
export interface AuthorizationChallenge {
+ /** Opaque identity of this exact authorization attempt. */
+ readonly attemptId?: string;
readonly name: string;
readonly challenge: ConnectionAuthorizationChallenge;
readonly hookUrl: string;
+ /** Principal passed to `startAuthorization`; omitted from model-facing copies. */
+ readonly principal?: ConnectionPrincipal;
/**
* Opaque resume value from the strategy's `startAuthorization`,
* journaled across the park. Absent for provider-owned flows.
@@ -71,9 +77,11 @@ export interface AuthorizationPendingModelOutput {
}
export interface AuthorizationResult {
+ readonly attemptId?: string;
readonly resume?: JsonValue;
readonly callback: AuthorizationCallback;
readonly hookUrl: string;
+ readonly principal?: ConnectionPrincipal;
}
// ---------------------------------------------------------------------------
@@ -104,6 +112,7 @@ export function requestAuthorization(
export function redactSignalResume(signal: AuthorizationSignal): AuthorizationSignal {
return requestAuthorization(
signal.challenges.map((entry) => ({
+ attemptId: entry.attemptId,
name: entry.name,
challenge: entry.challenge,
hookUrl: entry.hookUrl,
@@ -150,23 +159,31 @@ export function consumeAuthorizationResult(name: string): AuthorizationResult |
}
/**
- * Builds a callback URL for external systems. `name` identifies the
- * callback in the URL path (e.g. a connection name or custom label).
+ * Builds a callback URL for external systems. `name` and `attemptId` identify
+ * the exact challenge in the URL path.
*
- * The URL embeds a per-authorization hook token derived from the
- * session ID and name (`${sessionId}:auth:${name}`). This token is
- * independent of the continuation token, so channel re-keying
- * mid-turn does not invalidate the callback URL.
+ * The URL embeds the session's authorization hook token (`${sessionId}:auth`).
+ * It is independent of the continuation token, so channel re-keying mid-turn
+ * does not invalidate the callback URL.
*
* Returns `undefined` if the session context isn't available.
*/
-export function getHookUrl(name: string): string | undefined {
+export function getHookUrl(name: string, attemptId: string): string | undefined {
const ctx = loadContext();
const sessionId = ctx.get(SessionIdKey);
const baseUrl = ctx.get(CallbackBaseUrlKey);
if (!sessionId || !baseUrl) return undefined;
const token = authHookToken(sessionId);
- return `${baseUrl}${createEveConnectionCallbackRoutePath(name, token)}`;
+ return `${baseUrl}${createEveConnectionCallbackRoutePath(name, attemptId, token)}`;
+}
+
+/** Mints the identity and callback URL for one interactive authorization attempt. */
+export function createAuthorizationAttempt(
+ name: string,
+): { readonly attemptId: string; readonly hookUrl: string } | undefined {
+ const attemptId = createUlid();
+ const hookUrl = getHookUrl(name, attemptId);
+ return hookUrl === undefined ? undefined : { attemptId, hookUrl };
}
export function isAuthorizationSignal(value: unknown): value is AuthorizationSignal {
@@ -264,25 +281,59 @@ export function setPendingAuthorization(
sessionState: Record<string, unknown> | undefined,
value: PendingAuthorizationState,
): Record<string, unknown> {
- return { ...sessionState, [PENDING_AUTHORIZATION_KEY]: value };
+ const previous = getPendingAuthorization(sessionState)?.challenges ?? [];
+ const superseded = getSupersededAuthorizationChallenges(sessionState, value.challenges);
+ return {
+ ...sessionState,
+ [PENDING_AUTHORIZATION_KEY]: {
+ challenges: [
+ ...previous.filter((challenge) => !superseded.includes(challenge)),
+ ...value.challenges,
+ ],
+ },
+ };
+}
+
+/** Existing same-scope attempts replaced by newer attempts for the same principal. */
+export function getSupersededAuthorizationChallenges(
+ sessionState: Record<string, unknown> | undefined,
+ replacements: readonly AuthorizationChallenge[],
+): readonly AuthorizationChallenge[] {
+ const previous = getPendingAuthorization(sessionState)?.challenges ?? [];
+ return previous.filter((candidate) =>
+ replacements.some(
+ (replacement) =>
+ candidate.name === replacement.name &&
+ samePrincipal(candidate.principal, replacement.principal),
+ ),
+ );
+}
+
+function samePrincipal(
+ left: ConnectionPrincipal | undefined,
+ right: ConnectionPrincipal | undefined,
+): boolean {
+ if (left === undefined || right === undefined) return left === right;
+ if (left.type === "app" || right.type === "app") return left.type === right.type;
+ return left.id === right.id && left.issuer === right.issuer;
}
export function clearPendingAuthorization(
sessionState: Record<string, unknown> | undefined,
- names?: readonly string[],
+ attemptIds?: readonly string[],
): Record<string, unknown> | undefined {
if (sessionState === undefined || sessionState[PENDING_AUTHORIZATION_KEY] === undefined) {
return sessionState;
}
- if (names !== undefined) {
- if (names.length === 0) return sessionState;
+ if (attemptIds !== undefined) {
+ if (attemptIds.length === 0) return sessionState;
const pending = getPendingAuthorization(sessionState);
if (pending !== undefined) {
- const completedNames = new Set(names);
+ const completedAttemptIds = new Set(attemptIds);
const challenges = pending.challenges.filter(
- (challenge) => !completedNames.has(challenge.name),
+ (challenge) => !completedAttemptIds.has(challenge.attemptId ?? challenge.name),
);
if (challenges.length > 0) {
return {
diff --git a/packages/eve/src/harness/tool-interrupts.test.ts b/packages/eve/src/harness/tool-interrupts.test.ts
index b608b3d85..ff91ab659 100644
--- a/packages/eve/src/harness/tool-interrupts.test.ts
+++ b/packages/eve/src/harness/tool-interrupts.test.ts
@@ -20,9 +20,11 @@ import { ToolOutputSerializationError } from "#harness/tool-output-serialization
function signalWithVerifier(): AuthorizationSignal {
return requestAuthorization([
{
+ attemptId: "attempt-linear",
name: "linear",
challenge: { url: "https://idp.example/auth" },
hookUrl: "https://app.example/cb",
+ principal: { id: "user-1", type: "user" },
resume: { verifier: "pkce-secret" },
},
]);
@@ -66,11 +68,13 @@ describe("redactSignalResume", () => {
const redacted = redactSignalResume(signalWithVerifier());
expect(isAuthorizationSignal(redacted)).toBe(true);
expect(redacted.challenges[0]).toEqual({
+ attemptId: "attempt-linear",
name: "linear",
challenge: { url: "https://idp.example/auth" },
hookUrl: "https://app.example/cb",
});
expect(redacted.challenges[0]).not.toHaveProperty("resume");
+ expect(redacted.challenges[0]).not.toHaveProperty("principal");
});
});
diff --git a/packages/eve/src/harness/tool-loop.test.ts b/packages/eve/src/harness/tool-loop.test.ts
index 3099ef7e7..415925923 100644
--- a/packages/eve/src/harness/tool-loop.test.ts
+++ b/packages/eve/src/harness/tool-loop.test.ts
@@ -5325,6 +5325,7 @@ describe("createToolLoopHarness", () => {
function createAuthSignals() {
const full = requestAuthorization([
{
+ attemptId: "attempt-protected-action",
name: "protected_action",
challenge: {
url: "https://idp.example/auth",
@@ -5332,6 +5333,7 @@ describe("createToolLoopHarness", () => {
userCode: "GFI-QLM",
},
hookUrl: "https://app.example/callback",
+ principal: { type: "app" },
resume: { nonce: "n1" },
},
]);
diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.ts
index 9796c763b..441cccf54 100644
--- a/packages/eve/src/harness/tool-loop.ts
+++ b/packages/eve/src/harness/tool-loop.ts
@@ -137,11 +137,15 @@ import { normalizeUserContent, resolveAssistantStepText } from "#harness/message
import { normalizeProviderToolHistory } from "#harness/provider-tool-history.js";
import {
type AuthorizationSignal,
+ getSupersededAuthorizationChallenges,
isAuthorizationSignal,
setPendingAuthorization,
} from "#harness/authorization.js";
import { readToolInterrupt } from "#harness/tool-interrupts.js";
-import { createAuthorizationRequiredEvent } from "#protocol/message.js";
+import {
+ createAuthorizationCompletedEvent,
+ createAuthorizationRequiredEvent,
+} from "#protocol/message.js";
import {
classifyModelCallError,
EmptyModelResponseError,
@@ -2174,6 +2178,22 @@ async function handleStepResult(input: {
const { challenges } = authSignal;
if (emit) {
+ for (const superseded of getSupersededAuthorizationChallenges(
+ baseSession.state,
+ challenges,
+ )) {
+ await emit(
+ createAuthorizationCompletedEvent({
+ authorization: superseded.challenge,
+ name: superseded.name,
+ outcome: "failed",
+ reason: "Superseded by a newer authorization attempt.",
+ sequence: emissionState.sequence,
+ stepIndex: emissionState.stepIndex,
+ turnId: emissionState.turnId,
+ }),
+ );
+ }
for (const ch of challenges) {
await emit(
createAuthorizationRequiredEvent({
@@ -2187,6 +2207,14 @@ async function handleStepResult(input: {
}),
);
}
+
+ // An authorization park is a between-turn wait like the input park
+ // above: the session keeps serving ordinary turns while the challenge
+ // is open, so the stream must close its turn boundary — clients wait
+ // on `session.waiting` and would otherwise hang on the parked turn.
+ if (config.mode === "conversation") {
+ emissionState = await emitTurnEpilogue(emit, emissionState, config.mode);
+ }
}
return {
diff --git a/packages/eve/src/protocol/message.test.ts b/packages/eve/src/protocol/message.test.ts
index 3ccf07422..c391b5d96 100644
--- a/packages/eve/src/protocol/message.test.ts
+++ b/packages/eve/src/protocol/message.test.ts
@@ -141,6 +141,7 @@ describe("message stream protocol", () => {
const webhookUrl = `https://eve.example.com${createEveConnectionCallbackRoutePath(
"linear",
+ "attempt-1",
"abc",
)}`;
const full = createAuthorizationRequiredEvent({
diff --git a/packages/eve/src/protocol/routes.ts b/packages/eve/src/protocol/routes.ts
index ec4b339e6..3b8cef40d 100644
--- a/packages/eve/src/protocol/routes.ts
+++ b/packages/eve/src/protocol/routes.ts
@@ -87,9 +87,9 @@ export function createEveDevDispatchSchedulePath(scheduleId: string): string {
* Stable framework-owned route pattern for receiving inbound IdP redirects
* during in-turn interactive connection authorization.
*
- * `:name` is the connection name; `:token` is the workflow hook token minted
- * by the workflow body so the route handler can resume the suspended turn
- * via `resumeHook(token, payload)`.
+ * `:name` is the connection name, `:attemptId` identifies the exact challenge,
+ * and `:token` is the workflow hook token minted by the workflow body so the
+ * route handler can resume the suspended turn via `resumeHook(token, payload)`.
*
* The route is unauthenticated by design: an OAuth IdP follows this URL
* via a 3xx redirect from the user's browser with no eve credentials
@@ -97,7 +97,10 @@ export function createEveDevDispatchSchedulePath(scheduleId: string): string {
* resume; anyone who has it can deliver the callback payload, which is
* exactly what the IdP needs to do.
*/
-export const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`;
+export const EVE_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:attemptId/:token`;
+
+/** Callback shape minted by deployments before authorization attempt IDs. */
+export const EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN = `${EVE_ROUTE_PREFIX}/connections/:name/callback/:token`;
/**
* Stable framework-owned route pattern for terminal session callbacks.
@@ -139,7 +142,7 @@ export function createEveSessionStreamRoutePath(sessionId: string): string {
/**
* Creates the stable framework-owned connection callback route path for
- * one (`name`, `token`) pair.
+ * one (`name`, `attemptId`, `token`) tuple.
*
* The workflow body builds this path against {@link EVE_ROUTE_PREFIX} when
* minting the redirect URL it hands to the IdP via `startAuthorization`.
@@ -147,8 +150,12 @@ export function createEveSessionStreamRoutePath(sessionId: string): string {
* pattern and forwards the projected request payload into
* `resumeHook(token, payload)`.
*/
-export function createEveConnectionCallbackRoutePath(name: string, token: string): string {
- return `${EVE_ROUTE_PREFIX}/connections/${encodeURIComponent(name)}/callback/${encodeURIComponent(token)}`;
+export function createEveConnectionCallbackRoutePath(
+ name: string,
+ attemptId: string,
+ token: string,
+): string {
+ return `${EVE_ROUTE_PREFIX}/connections/${encodeURIComponent(name)}/callback/${encodeURIComponent(attemptId)}/${encodeURIComponent(token)}`;
}
/**
diff --git a/packages/eve/src/runtime/connections/callback-route.test.ts b/packages/eve/src/runtime/connections/callback-route.test.ts
index 81c237291..4b2d05116 100644
--- a/packages/eve/src/runtime/connections/callback-route.test.ts
+++ b/packages/eve/src/runtime/connections/callback-route.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import {
EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
createEveConnectionCallbackRoutePath,
} from "#protocol/routes.js";
import type { RouteContext } from "#public/definitions/channel.js";
@@ -29,15 +30,20 @@ function buildRouteContext(params: Readonly<Record<string, string>>): RouteConte
describe("getConnectionCallbackChannelDefinitions", () => {
it("registers GET and POST entries at the framework callback route pattern", () => {
const definitions = getConnectionCallbackChannelDefinitions();
- expect(definitions).toHaveLength(2);
+ expect(definitions).toHaveLength(4);
const methods = definitions.map((d) => d.method);
expect(methods).toEqual(expect.arrayContaining(["GET", "POST"]));
for (const def of definitions) {
- expect(def.urlPath).toBe(EVE_CONNECTION_CALLBACK_ROUTE_PATTERN);
+ expect([
+ EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ ]).toContain(def.urlPath);
expect(def.name.startsWith(HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX)).toBe(true);
expect(def.name).not.toContain(".well-known");
expect(def.sourceKind).toBe("module");
- expect(def.fetch).toBe(handleConnectionCallbackRequest);
+ if (def.urlPath === EVE_CONNECTION_CALLBACK_ROUTE_PATTERN) {
+ expect(def.fetch).toBe(handleConnectionCallbackRequest);
+ }
}
});
@@ -82,15 +88,24 @@ describe("handleConnectionCallbackRequest", () => {
expect(resumeHookMock).not.toHaveBeenCalled();
});
+ it("rejects requests with a missing authorization attempt ID with 400", async () => {
+ const response = await handleConnectionCallbackRequest(
+ new Request("https://app.example.com/eve/v1/connections/linear/callback/tok"),
+ buildRouteContext({ name: "linear", token: "tok" }),
+ );
+ expect(response.status).toBe(400);
+ expect(resumeHookMock).not.toHaveBeenCalled();
+ });
+
it("forwards a GET callback into resumeHook as parsed params with no request headers", async () => {
resumeHookMock.mockResolvedValueOnce(undefined);
- const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "tok123")}?code=abc&state=xyz`;
+ const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "tok123")}?code=abc&state=xyz`;
const response = await handleConnectionCallbackRequest(
new Request(url, {
headers: { "x-probe": "1" },
method: "GET",
}),
- buildRouteContext({ name: "linear", token: "tok123" }),
+ buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "tok123" }),
);
expect(response.status).toBe(200);
@@ -108,6 +123,7 @@ describe("handleConnectionCallbackRequest", () => {
payloads: [
{
authorizationCallback: {
+ attemptId: "attempt-1",
connectionName: "linear",
callback: {
params: { code: "abc", state: "xyz" },
@@ -119,16 +135,45 @@ describe("handleConnectionCallbackRequest", () => {
});
});
+ it("keeps pre-attempt callback URLs resumable for pinned workflows", async () => {
+ resumeHookMock.mockResolvedValueOnce(undefined);
+ const legacy = getConnectionCallbackChannelDefinitions().find(
+ (definition) =>
+ definition.method === "GET" &&
+ definition.urlPath === EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ );
+ if (legacy?.fetch === undefined) throw new Error("Missing legacy callback route.");
+
+ const response = await legacy.fetch(
+ new Request("https://app.example.com/eve/v1/connections/linear/callback/tok123?code=abc"),
+ buildRouteContext({ name: "linear", token: "tok123" }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(resumeHookMock).toHaveBeenCalledWith("tok123", {
+ kind: "deliver",
+ payloads: [
+ {
+ authorizationCallback: {
+ callback: { method: "GET", params: { code: "abc" } },
+ connectionName: "linear",
+ legacy: true,
+ },
+ },
+ ],
+ });
+ });
+
it("captures form-encoded POST bodies before resuming the hook", async () => {
resumeHookMock.mockResolvedValueOnce(undefined);
- const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "tok123")}`;
+ const url = `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "tok123")}`;
await handleConnectionCallbackRequest(
new Request(url, {
body: "code=abc&state=xyz",
headers: { "content-type": "application/x-www-form-urlencoded" },
method: "POST",
}),
- buildRouteContext({ name: "linear", token: "tok123" }),
+ buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "tok123" }),
);
const [, payload] = resumeHookMock.mock.calls[0] ?? [];
@@ -137,6 +182,7 @@ describe("handleConnectionCallbackRequest", () => {
payloads: [
{
authorizationCallback: {
+ attemptId: "attempt-1",
connectionName: "linear",
callback: {
params: { code: "abc", state: "xyz" },
@@ -156,9 +202,9 @@ describe("handleConnectionCallbackRequest", () => {
resumeHookMock.mockRejectedValueOnce(new Error("hook not found"));
const response = await handleConnectionCallbackRequest(
new Request(
- `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "tok")}`,
+ `https://app.example.com${createEveConnectionCallbackRoutePath("linear", "attempt-1", "tok")}`,
),
- buildRouteContext({ name: "linear", token: "tok" }),
+ buildRouteContext({ attemptId: "attempt-1", name: "linear", token: "tok" }),
);
expect(response.status).toBe(404);
const body = await response.json();
diff --git a/packages/eve/src/runtime/connections/callback-route.ts b/packages/eve/src/runtime/connections/callback-route.ts
index d98fbf520..a84686d44 100644
--- a/packages/eve/src/runtime/connections/callback-route.ts
+++ b/packages/eve/src/runtime/connections/callback-route.ts
@@ -23,7 +23,10 @@
*/
import { resumeHook } from "#internal/workflow/runtime.js";
-import { EVE_CONNECTION_CALLBACK_ROUTE_PATTERN } from "#protocol/routes.js";
+import {
+ EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
+} from "#protocol/routes.js";
import type { ChannelMethod, RouteContext } from "#public/definitions/channel.js";
import type { ResolvedChannelDefinition } from "#runtime/types.js";
import { buildAuthorizationCompletePage } from "#runtime/connections/authorization-complete-page.js";
@@ -45,19 +48,22 @@ export const HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX = "eve/v1/connections/
* methods route through the same handler.
*/
const HANDLED_METHODS: readonly ChannelMethod[] = ["GET", "POST"];
+const ROUTE_KINDS = ["attempt", "legacy"] as const;
+type CallbackRouteKind = (typeof ROUTE_KINDS)[number];
/**
* Returns the framework-shipped channel definitions that mount the
* connection callback route at {@link EVE_CONNECTION_CALLBACK_ROUTE_PATTERN}.
*
- * Returns one definition per accepted HTTP method (see
- * {@link HANDLED_METHODS}). The framework channel resolver mounts each
- * `(method, urlPath)` pair as a separate Nitro route; sharing one URL
- * pattern across multiple methods is not supported by the channel
- * model.
+ * Returns one definition per accepted HTTP method and route generation. The
+ * legacy shape remains mounted for callbacks minted by already-pinned runs.
+ * The framework channel resolver mounts each `(method, urlPath)` pair as a
+ * separate Nitro route.
*/
export function getConnectionCallbackChannelDefinitions(): readonly ResolvedChannelDefinition[] {
- return HANDLED_METHODS.map((method) => buildCallbackChannelDefinition(method));
+ return ROUTE_KINDS.flatMap((kind) =>
+ HANDLED_METHODS.map((method) => buildCallbackChannelDefinition(method, kind)),
+ );
}
/**
@@ -67,24 +73,34 @@ export function getConnectionCallbackChannelDefinitions(): readonly ResolvedChan
* of a silent no-op.
*/
export function getConnectionCallbackChannelNames(): ReadonlySet<string> {
- return new Set(HANDLED_METHODS.map(channelNameForMethod));
+ return new Set(getConnectionCallbackChannelDefinitions().map((definition) => definition.name));
}
-function buildCallbackChannelDefinition(method: ChannelMethod): ResolvedChannelDefinition {
- const name = channelNameForMethod(method);
+function buildCallbackChannelDefinition(
+ method: ChannelMethod,
+ kind: CallbackRouteKind,
+): ResolvedChannelDefinition {
+ const name = channelNameForMethod(method, kind);
return {
name,
method,
- urlPath: EVE_CONNECTION_CALLBACK_ROUTE_PATTERN,
- fetch: handleConnectionCallbackRequest,
+ urlPath:
+ kind === "attempt"
+ ? EVE_CONNECTION_CALLBACK_ROUTE_PATTERN
+ : EVE_LEGACY_CONNECTION_CALLBACK_ROUTE_PATTERN,
+ fetch:
+ kind === "attempt" ? handleConnectionCallbackRequest : handleLegacyConnectionCallbackRequest,
logicalPath: `framework://channels/${name}`,
- sourceId: `eve:framework:connection-callback-${method.toLowerCase()}`,
+ sourceId: `eve:framework:connection-callback-${kind}-${method.toLowerCase()}`,
sourceKind: "module",
};
}
-function channelNameForMethod(method: ChannelMethod): string {
- return `${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/${method.toLowerCase()}`;
+function channelNameForMethod(method: ChannelMethod, kind: CallbackRouteKind): string {
+ const suffix = method.toLowerCase();
+ return kind === "attempt"
+ ? `${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/${suffix}`
+ : `${HTTP_CONNECTION_CALLBACK_CHANNEL_NAME_PREFIX}/legacy/${suffix}`;
}
/**
@@ -95,8 +111,24 @@ function channelNameForMethod(method: ChannelMethod): string {
export async function handleConnectionCallbackRequest(
request: Request,
ctx: RouteContext,
+): Promise<Response> {
+ return handleCallbackRequest(request, ctx, false);
+}
+
+async function handleLegacyConnectionCallbackRequest(
+ request: Request,
+ ctx: RouteContext,
+): Promise<Response> {
+ return handleCallbackRequest(request, ctx, true);
+}
+
+async function handleCallbackRequest(
+ request: Request,
+ ctx: RouteContext,
+ legacy: boolean,
): Promise<Response> {
const name = ctx.params.name;
+ const attemptId = ctx.params.attemptId;
const token = ctx.params.token;
if (typeof name !== "string" || name.length === 0) {
return Response.json({ error: "Missing connection name.", ok: false }, { status: 400 });
@@ -104,6 +136,12 @@ export async function handleConnectionCallbackRequest(
if (typeof token !== "string" || token.length === 0) {
return Response.json({ error: "Missing callback token.", ok: false }, { status: 400 });
}
+ if (!legacy && (typeof attemptId !== "string" || attemptId.length === 0)) {
+ return Response.json(
+ { error: "Missing authorization attempt ID.", ok: false },
+ { status: 400 },
+ );
+ }
const callback = await projectAuthorizationCallback(request);
@@ -112,9 +150,12 @@ export async function handleConnectionCallbackRequest(
// this hook upfront (before any turns run) so it always exists
// when the callback arrives.
try {
+ const authorizationCallback = legacy
+ ? { callback, connectionName: name, legacy: true as const }
+ : { attemptId: attemptId!, callback, connectionName: name };
await resumeHook(token, {
kind: "deliver" as const,
- payloads: [{ authorizationCallback: { connectionName: name, callback } }],
+ payloads: [{ authorizationCallback }],
});
} catch {
return Response.json({ error: "Connection callback not pending.", ok: false }, { status: 404 });
diff --git a/packages/eve/src/runtime/connections/scoped-authorization.ts b/packages/eve/src/runtime/connections/scoped-authorization.ts
index 1bc9f8144..a4b816043 100644
--- a/packages/eve/src/runtime/connections/scoped-authorization.ts
+++ b/packages/eve/src/runtime/connections/scoped-authorization.ts
@@ -15,7 +15,7 @@ import type { ConnectionAuthorizationChallenge } from "#public/connections/error
import {
type AuthorizationSignal,
consumeAuthorizationResult,
- getHookUrl,
+ createAuthorizationAttempt,
requestAuthorization,
} from "#harness/authorization.js";
import type { JsonValue } from "#public/types/json.js";
@@ -141,7 +141,7 @@ export async function completeScopedAuthorization(input: ScopedAuthorization): P
const interactive = authorization as InteractiveAuthorizationDefinition<JsonValue>;
const ctx: AlsContext = loadContext();
- const principal = resolveConnectionPrincipal(scope, interactive, ctx);
+ const principal = result.principal ?? resolveConnectionPrincipal(scope, interactive, ctx);
const token = await interactive.completeAuthorization({
callbackUrl: result.hookUrl,
connection,
@@ -167,12 +167,15 @@ export async function startScopedAuthorization(
const { scope, authorization, connection } = input;
if (!supportsInteractiveAuthorization(authorization)) return undefined;
- const hookUrl = getHookUrl(scope);
- if (hookUrl === undefined) return undefined;
+ const attempt = createAuthorizationAttempt(scope);
+ if (attempt === undefined) return undefined;
const interactive = authorization as InteractiveAuthorizationDefinition<JsonValue>;
const principal = resolveConnectionPrincipal(scope, interactive);
- const callbackUrl = resolveAuthorizationCallbackUrl({ authorization, callbackUrl: hookUrl });
+ const callbackUrl = resolveAuthorizationCallbackUrl({
+ authorization,
+ callbackUrl: attempt.hookUrl,
+ });
const { challenge, resume } = await interactive.startAuthorization({
callbackUrl,
connection,
@@ -180,9 +183,11 @@ export async function startScopedAuthorization(
});
return requestAuthorization([
{
+ attemptId: attempt.attemptId,
challenge: stampChallengeDisplayName(challenge, authorization),
hookUrl: callbackUrl,
name: scope,
+ principal,
resume,
},
]);
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
index 2fecb4622..c16f5fbfd 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts
@@ -326,9 +326,11 @@ describe("connection_search", () => {
(ctx) => {
ctx.set(PendingAuthorizationResultKey, [
{
+ attemptId: "attempt-notion",
callback: { method: "GET", params: {} },
hookUrl: "https://agent.example.com/eve/v1/connections/notion/callback/auth",
name: "notion",
+ principal: { type: "app" },
},
]);
},
diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
index a8ee653d0..e01799eec 100644
--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts
@@ -6,7 +6,7 @@ import {
type AuthorizationChallenge,
type AuthorizationSignal,
consumeAuthorizationResult,
- getHookUrl,
+ createAuthorizationAttempt,
requestAuthorization,
} from "#harness/authorization.js";
import {
@@ -158,7 +158,7 @@ async function completePendingAuthorizations(
if (!result) continue;
const auth = await resolveInteractiveAuth(registry, conn.connectionName);
if (!auth) continue;
- const principal = resolveConnectionPrincipal(conn.connectionName, auth);
+ const principal = result.principal ?? resolveConnectionPrincipal(conn.connectionName, auth);
const token = await (
auth as InteractiveAuthorizationDefinition<JsonValue>
).completeAuthorization({
@@ -228,12 +228,12 @@ async function executeConnectionSearch(
const auth = await resolveInteractiveAuth(registry, conn.connectionName);
if (auth) {
- const hookUrl = getHookUrl(conn.connectionName);
- if (hookUrl) {
+ const attempt = createAuthorizationAttempt(conn.connectionName);
+ if (attempt) {
const principal = resolveConnectionPrincipal(conn.connectionName, auth);
const callbackUrl = resolveAuthorizationCallbackUrl({
authorization: auth,
- callbackUrl: hookUrl,
+ callbackUrl: attempt.hookUrl,
});
try {
const { challenge, resume } = await auth.startAuthorization({
@@ -242,9 +242,11 @@ async function executeConnectionSearch(
principal,
});
authChallenges.push({
+ attemptId: attempt.attemptId,
name: conn.connectionName,
challenge: stampChallengeDisplayName(challenge, auth),
hookUrl: callbackUrl,
+ principal,
resume,
});
} catch (startErr) {
@@ -453,7 +455,9 @@ const connectionSearchDynamicDefinition = defineDynamic({
if (authResult) {
justCompletedAuth = true;
const ctx = loadContext();
- const principal = resolveConnectionPrincipal(connectionName, interactiveAuth);
+ const principal =
+ authResult.principal ??
+ resolveConnectionPrincipal(connectionName, interactiveAuth);
const token = await interactiveAuth.completeAuthorization({
callbackUrl: authResult.hookUrl,
connection: { url: conn?.url ?? "" },
@@ -486,13 +490,13 @@ const connectionSearchDynamicDefinition = defineDynamic({
});
}
- const hookUrl = getHookUrl(connectionName);
- if (!hookUrl) throw err;
+ const attempt = createAuthorizationAttempt(connectionName);
+ if (!attempt) throw err;
const principal = resolveConnectionPrincipal(connectionName, interactiveAuth);
const callbackUrl = resolveAuthorizationCallbackUrl({
authorization: interactiveAuth,
- callbackUrl: hookUrl,
+ callbackUrl: attempt.hookUrl,
});
const { challenge, resume } = await interactiveAuth.startAuthorization({
callbackUrl,
@@ -502,9 +506,11 @@ const connectionSearchDynamicDefinition = defineDynamic({
return requestAuthorization([
{
+ attemptId: attempt.attemptId,
name: connectionName,
challenge: stampChallengeDisplayName(challenge, interactiveAuth),
hookUrl: callbackUrl,
+ principal,
resume,
},
]);
diff --git a/packages/eve/test/tui-client/tui-connection-auth-states.ts b/packages/eve/test/tui-client/tui-connection-auth-states.ts
index 04720cf62..8a693c5be 100644
--- a/packages/eve/test/tui-client/tui-connection-auth-states.ts
+++ b/packages/eve/test/tui-client/tui-connection-auth-states.ts
@@ -126,6 +126,7 @@ const firstTurn: UnstampedMessageStreamEvent[] = [
];
const firstCallbackTurn: UnstampedMessageStreamEvent[] = [
+ { type: "turn.started", data: { sequence: next(), turnId: "turn-1" } },
{
type: "authorization.completed",
data: {
@@ -133,20 +134,21 @@ const firstCallbackTurn: UnstampedMessageStreamEvent[] = [
outcome: "authorized",
sequence: next(),
stepIndex,
- turnId,
+ turnId: "turn-1",
},
},
{
type: "step.completed",
- data: { finishReason: "stop", sequence: next(), stepIndex, turnId },
+ data: { finishReason: "stop", sequence: next(), stepIndex, turnId: "turn-1" },
},
+ { type: "turn.completed", data: { sequence: next(), turnId: "turn-1" } },
{
type: "session.waiting",
data: { continuationToken: "session-id", wait: "next-user-message" },
},
];
-const secondTurnId = "turn-1";
+const secondTurnId = "turn-2";
const secondTurn: UnstampedMessageStreamEvent[] = [
{ type: "turn.started", data: { sequence: next(), turnId: secondTurnId } },
{ type: "step.started", data: { sequence: next(), stepIndex, turnId: secondTurnId } },
@@ -175,6 +177,7 @@ const secondTurn: UnstampedMessageStreamEvent[] = [
];
const secondCallbackTurn: UnstampedMessageStreamEvent[] = [
+ { type: "turn.started", data: { sequence: next(), turnId: "turn-3" } },
{
type: "authorization.completed",
data: {
@@ -183,13 +186,14 @@ const secondCallbackTurn: UnstampedMessageStreamEvent[] = [
reason: "access_denied",
sequence: next(),
stepIndex,
- turnId: secondTurnId,
+ turnId: "turn-3",
},
},
{
type: "step.completed",
- data: { finishReason: "stop", sequence: next(), stepIndex, turnId: secondTurnId },
+ data: { finishReason: "stop", sequence: next(), stepIndex, turnId: "turn-3" },
},
+ { type: "turn.completed", data: { sequence: next(), turnId: "turn-3" } },
{
type: "session.waiting",
data: { continuationToken: "session-id", wait: "next-user-message" },
diff --git a/packages/eve/test/tui-client/tui-connection-auth-user.ts b/packages/eve/test/tui-client/tui-connection-auth-user.ts
index 58147bcad..26007b490 100644
--- a/packages/eve/test/tui-client/tui-connection-auth-user.ts
+++ b/packages/eve/test/tui-client/tui-connection-auth-user.ts
@@ -222,7 +222,7 @@ runEnvironment("tui-connection-auth-user", async ({ cleanup, target: resolveTarg
}
if (
- event.type === "session.waiting" ||
+ (event.type === "session.waiting" && completedEvent !== undefined) ||
event.type === "session.completed" ||
event.type === "session.failed"
) {