Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

tweak(eve): keep activity rendering grouped across resumed turns (#3193)

Ben Pankow51c47192a1ca
diff --git a/.changeset/warm-ravens-report.md b/.changeset/warm-ravens-report.md
new file mode 100644
index 000000000..5e3367931
--- /dev/null
+++ b/.changeset/warm-ravens-report.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Keep experimental channel activity grouped with the user request that originated it across background task reporting, human approval and question resumes, and authorization callbacks.
diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.ts
index 85da9d034..dd0d03632 100644
--- a/packages/eve/src/context/keys.ts
+++ b/packages/eve/src/context/keys.ts
@@ -135,6 +135,12 @@ export const OtelTraceEnabledKey = new ContextKey<boolean>("eve.otelTraceEnabled
*/
export const CapabilitiesKey = new ContextKey<SessionCapabilities>("eve.capabilities");
export const ActivityObserverKey = new ContextKey<ActivityObserverConfig>("eve.activityObserver");
+/** Originating root turn that owns the current user-visible activity artifact. */
+export const ActivityRootTurnIdKey = new ContextKey<string>("eve.activityRootTurnId");
+/** Pending HITL request identities that keep the current activity artifact open. */
+export const ActivityPendingBlockersKey = new ContextKey<readonly string[]>(
+ "eve.activityPendingBlockers",
+);
/**
* Optional framework-owned caller callback captured when the session is created.
diff --git a/packages/eve/src/execution/activity-cohort.test.ts b/packages/eve/src/execution/activity-cohort.test.ts
new file mode 100644
index 000000000..08d81ed23
--- /dev/null
+++ b/packages/eve/src/execution/activity-cohort.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+
+import { ContextContainer } from "#context/container.js";
+import { ActivityPendingBlockersKey, ActivityRootTurnIdKey } from "#context/keys.js";
+import { restoreAuthorizationActivity } from "#execution/activity-cohort.js";
+import { matchAuthorizationCallbacks } from "#execution/authorization-callback-match.js";
+
+describe("restoreAuthorizationActivity", () => {
+ it("restores candidate authorization activity by candidate ID", () => {
+ const ctx = new ContextContainer();
+ const pending = {
+ activityRootTurnIds: { "candidate-1": "turn-origin" },
+ challenges: [
+ {
+ candidateId: "candidate-1",
+ challenge: { url: "https://auth.example.com" },
+ hookUrl: "https://app.example.com/callback",
+ name: "github",
+ principal: { type: "app" as const },
+ },
+ ],
+ };
+ const { matches } = matchAuthorizationCallbacks(pending, [
+ {
+ authorizationCallback: {
+ callback: { params: { code: "callback-code" } },
+ connectionName: "github",
+ },
+ },
+ ]);
+
+ const ids = restoreAuthorizationActivity({ ctx, matches, pending });
+
+ expect(ids).toEqual(["candidate-1"]);
+ expect(ctx.get(ActivityRootTurnIdKey)).toBe("turn-origin");
+ expect(ctx.get(ActivityPendingBlockersKey)).toBeUndefined();
+ });
+});
diff --git a/packages/eve/src/execution/activity-cohort.ts b/packages/eve/src/execution/activity-cohort.ts
new file mode 100644
index 000000000..0dd82aad8
--- /dev/null
+++ b/packages/eve/src/execution/activity-cohort.ts
@@ -0,0 +1,122 @@
+import type { DeliverHookPayload } from "#channel/types.js";
+import type { MatchedAuthorizationCallback } from "#execution/authorization-callback-match.js";
+import type { PendingAuthorizationState } from "#harness/authorization.js";
+import type { ContextContainer } from "#context/container.js";
+import {
+ ActivityObserverKey,
+ ActivityPendingBlockersKey,
+ ActivityRootTurnIdKey,
+} from "#context/keys.js";
+import {
+ activityRequestIdsForRootTurn,
+ activityRootTurnIdForInputResponses,
+} from "#harness/pending-input-batches.js";
+import type { SessionStateMap } from "#harness/types.js";
+import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
+
+export function updateActivityRootForDelivery(input: {
+ readonly activeTurnId: string;
+ readonly ctx: ContextContainer;
+ readonly delivery?: DeliverHookPayload;
+ readonly sessionState: SessionStateMap | undefined;
+ readonly taskRootTurnId?: string;
+}): void {
+ if (!input.ctx.has(ActivityObserverKey)) return;
+ if (input.taskRootTurnId !== undefined) {
+ input.ctx.set(ActivityRootTurnIdKey, input.taskRootTurnId);
+ return;
+ }
+ const delivery = input.delivery;
+ if (delivery === undefined) return;
+ const hasMessage = delivery.payloads.some((payload) => payload.message !== undefined);
+ if (hasMessage && delivery.taskDeliveryId === undefined) {
+ input.ctx.set(ActivityRootTurnIdKey, input.activeTurnId);
+ input.ctx.delete(ActivityPendingBlockersKey);
+ return;
+ }
+ const responseIds = new Set(
+ delivery.payloads.flatMap((payload) =>
+ (payload.inputResponses ?? []).map((response) => response.requestId),
+ ),
+ );
+ if (responseIds.size === 0) return;
+ const rootTurnId =
+ activityRootTurnIdForInputResponses(input.sessionState, responseIds) ??
+ input.ctx.get(ActivityRootTurnIdKey) ??
+ input.activeTurnId;
+ input.ctx.set(ActivityRootTurnIdKey, rootTurnId);
+ input.ctx.set(
+ ActivityPendingBlockersKey,
+ activityRequestIdsForRootTurn(input.sessionState, rootTurnId),
+ );
+}
+
+export function restoreAuthorizationActivity(input: {
+ readonly ctx: ContextContainer;
+ readonly matches: readonly MatchedAuthorizationCallback[];
+ readonly pending: PendingAuthorizationState;
+}): readonly string[] {
+ const ids = input.matches.map(
+ (match) => match.result.attemptId ?? match.candidateId ?? match.result.name,
+ );
+ const rootTurnId = ids.map((id) => input.pending.activityRootTurnIds?.[id]).find(Boolean);
+ if (rootTurnId !== undefined) {
+ input.ctx.set(ActivityRootTurnIdKey, rootTurnId);
+ input.ctx.set(
+ ActivityPendingBlockersKey,
+ Object.entries(input.pending.activityRootTurnIds ?? {}).flatMap(([id, candidateRoot]) =>
+ candidateRoot === rootTurnId ? [id] : [],
+ ),
+ );
+ }
+ clearActivityBlockers(input.ctx, ids);
+ return ids;
+}
+
+export function updateActivityBlockers(
+ ctx: ContextContainer,
+ event: UnstampedMessageStreamEvent,
+): void {
+ if (!ctx.has(ActivityObserverKey)) return;
+ if (event.type === "input.requested") {
+ addActivityBlockers(
+ ctx,
+ event.data.requests.map((request) => request.requestId),
+ );
+ } else if (event.type === "input.resolved") {
+ clearActivityBlockers(
+ ctx,
+ event.data.resolutions.map((resolution) => resolution.requestId),
+ );
+ } else if (event.type === "authorization.required") {
+ addActivityBlockers(ctx, [authorizationBlockerId(event)]);
+ } else if (event.type === "authorization.completed") {
+ clearActivityBlockers(ctx, [authorizationBlockerId(event)]);
+ }
+}
+
+export function clearActivityBlockers(ctx: ContextContainer, ids: readonly string[]): void {
+ const cleared = new Set(ids);
+ const remaining = (ctx.get(ActivityPendingBlockersKey) ?? []).filter((id) => !cleared.has(id));
+ if (remaining.length === 0) ctx.delete(ActivityPendingBlockersKey);
+ else ctx.set(ActivityPendingBlockersKey, remaining);
+}
+
+function addActivityBlockers(ctx: ContextContainer, ids: readonly string[]): void {
+ ctx.set(ActivityPendingBlockersKey, [
+ ...new Set([...(ctx.get(ActivityPendingBlockersKey) ?? []), ...ids]),
+ ]);
+}
+
+function authorizationBlockerId(
+ event: Extract<
+ UnstampedMessageStreamEvent,
+ { readonly type: "authorization.required" | "authorization.completed" }
+ >,
+): string {
+ return (
+ event.data.attemptId ??
+ event.data.candidateId ??
+ `${event.data.turnId}:${String(event.data.stepIndex)}:${event.data.name}`
+ );
+}
diff --git a/packages/eve/src/execution/authorization-callback-match.ts b/packages/eve/src/execution/authorization-callback-match.ts
index 9cccc7ea2..6f7a37469 100644
--- a/packages/eve/src/execution/authorization-callback-match.ts
+++ b/packages/eve/src/execution/authorization-callback-match.ts
@@ -5,6 +5,7 @@ import type { AuthorizationCallback } from "#shared/connection-types.js";
export interface MatchedAuthorizationCallback {
readonly authorization: ConnectionAuthorizationChallenge;
+ readonly candidateId?: string;
readonly result: { readonly name: string } & AuthorizationResult;
}
@@ -40,7 +41,7 @@ export function matchAuthorizationCallbacks(
? candidate.attemptId === undefined
: candidate.attemptId === callback.attemptId;
});
- const attemptKey = challenge?.attemptId ?? challenge?.name;
+ const attemptKey = challenge?.attemptId ?? challenge?.candidateId ?? challenge?.name;
if (
challenge === undefined ||
attemptKey === undefined ||
@@ -53,6 +54,7 @@ export function matchAuthorizationCallbacks(
matchedAttemptKeys.add(attemptKey);
matches.push({
authorization: challenge.challenge,
+ candidateId: challenge.candidateId,
result: {
attemptId: challenge.attemptId,
callback: callback.callback,
diff --git a/packages/eve/src/execution/session-activity-projection.test.ts b/packages/eve/src/execution/session-activity-projection.test.ts
index 1b051b13d..01cda2031 100644
--- a/packages/eve/src/execution/session-activity-projection.test.ts
+++ b/packages/eve/src/execution/session-activity-projection.test.ts
@@ -72,6 +72,37 @@ describe("projectSessionActivity", () => {
]);
});
+ it("groups a resumed turn with its originating root work", () => {
+ const sessionId = "session-1";
+ const started = projectSessionActivity({
+ event: turnEvent("turn.started", "turn-2"),
+ rootTurnId: "turn-1",
+ sessionId,
+ });
+ expect(started).toEqual([
+ expect.objectContaining({
+ kind: "work.started",
+ work: expect.objectContaining({
+ id: deriveRootTurnActivityWorkId({ sessionId, turnId: "turn-1" }),
+ rootTurnId: "turn-1",
+ turnId: "turn-2",
+ }),
+ }),
+ ]);
+ });
+
+ it("keeps an originating root open while HITL or background work is pending", () => {
+ const event = turnEvent("turn.completed", "turn-1");
+ expect(
+ projectSessionActivity({
+ event,
+ rootTurnId: "turn-1",
+ sessionId: "session-1",
+ suppressRootSettlement: true,
+ }),
+ ).toEqual([]);
+ });
+
it("reduces replayed root events to one completed work summary", () => {
const sequence = [turnEvent("turn.started"), turnEvent("turn.completed")];
const snapshot = reduceProjection({
diff --git a/packages/eve/src/execution/session-activity-projection.ts b/packages/eve/src/execution/session-activity-projection.ts
index 7b8f5364b..80c860eb9 100644
--- a/packages/eve/src/execution/session-activity-projection.ts
+++ b/packages/eve/src/execution/session-activity-projection.ts
@@ -1,5 +1,10 @@
import type { ContextContainer } from "#context/container.js";
-import { ActivityObserverKey, TurnTaskDeliveryKey } from "#context/keys.js";
+import {
+ ActivityObserverKey,
+ ActivityPendingBlockersKey,
+ ActivityRootTurnIdKey,
+ TurnTaskDeliveryKey,
+} from "#context/keys.js";
import { projectActivityEvents } from "#execution/activity-events.js";
import { deriveRootTurnActivityWorkId } from "#execution/activity-work-id.js";
import { submitActivity } from "#execution/submit-activity.js";
@@ -17,13 +22,19 @@ export async function observeSessionActivity(input: {
const taskDelivery = input.ctx.get(TurnTaskDeliveryKey);
if (
observer.workIdentity === undefined &&
+ input.ctx.get(ActivityRootTurnIdKey) === undefined &&
(taskDelivery === "pending" || taskDelivery === "settled")
)
return;
await submitActivity({
events: projectSessionActivity({
event: input.event,
+ rootTurnId: input.ctx.get(ActivityRootTurnIdKey),
sessionId: input.sessionId,
+ suppressRootSettlement:
+ taskDelivery === "initiating" ||
+ taskDelivery === "pending" ||
+ (input.ctx.get(ActivityPendingBlockersKey)?.length ?? 0) > 0,
workIdentity: observer.workIdentity,
}),
sink: observer.sink,
@@ -32,7 +43,9 @@ export async function observeSessionActivity(input: {
export function projectSessionActivity(input: {
readonly event: MessageStreamEvent;
+ readonly rootTurnId?: string;
readonly sessionId: string;
+ readonly suppressRootSettlement?: boolean;
readonly workIdentity?: ActivityWorkIdentityV1;
}): readonly ActivityEventV1[] {
const work = workFor(input);
@@ -51,6 +64,15 @@ export function projectSessionActivity(input: {
work,
});
}
+ if (
+ input.suppressRootSettlement === true &&
+ work.kind === "root-turn" &&
+ (input.event.type === "turn.completed" ||
+ input.event.type === "turn.failed" ||
+ input.event.type === "turn.cancelled")
+ ) {
+ return events;
+ }
events.push(
...projectActivityEvents({
at: input.event.meta.at,
@@ -64,6 +86,7 @@ export function projectSessionActivity(input: {
function workFor(input: {
readonly event: MessageStreamEvent;
+ readonly rootTurnId?: string;
readonly sessionId: string;
readonly workIdentity?: ActivityWorkIdentityV1;
}): ActivityWorkIdentityV1 | undefined {
@@ -76,11 +99,12 @@ function workFor(input: {
};
}
if (turnId === undefined) return undefined;
+ const rootTurnId = input.rootTurnId ?? turnId;
return {
- id: deriveRootTurnActivityWorkId({ sessionId: input.sessionId, turnId }),
+ id: deriveRootTurnActivityWorkId({ sessionId: input.sessionId, turnId: rootTurnId }),
kind: "root-turn",
rootSessionId: input.sessionId,
- rootTurnId: turnId,
+ rootTurnId,
sessionId: input.sessionId,
turnId,
};
diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.ts
index f6bc9a437..68dd25948 100644
--- a/packages/eve/src/execution/workflow-steps.test.ts
+++ b/packages/eve/src/execution/workflow-steps.test.ts
@@ -10,6 +10,7 @@ import { ContextContainer, contextStorage, loadContext } from "#context/containe
import { ContextKey } from "#context/key.js";
import {
ActivityObserverKey,
+ ActivityRootTurnIdKey,
AuthKey,
ChannelInstrumentationKey,
ContinuationTokenKey,
@@ -2224,6 +2225,7 @@ describe("turnStep", () => {
it("sets task-delivery provenance only when the runtime supplies owned task state", async () => {
const observedTaskDeliveries: unknown[] = [];
+ const observedActivityRoots: unknown[] = [];
const metadata = { kind: "report-probe", name: "report_probe" } as const;
const session = createStubSession({
state: {
@@ -2251,11 +2253,18 @@ describe("turnStep", () => {
vi.mocked(createExecutionNodeStep).mockImplementation(() => {
return async (stepSession): Promise<StepResult> => {
observedTaskDeliveries.push(contextStorage.getStore()?.get(TurnTaskDeliveryKey));
+ observedActivityRoots.push(contextStorage.getStore()?.get(ActivityRootTurnIdKey));
return { next: { done: true, output: "ok" }, session: stepSession };
};
});
const initialSerializedContext = createSerializedContext();
+ initialSerializedContext[ActivityObserverKey.name] = {
+ sink: {
+ url: "https://agent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz",
+ version: 1,
+ },
+ };
const first = await turnStep({
input: {
@@ -2285,6 +2294,7 @@ describe("turnStep", () => {
});
expect(observedTaskDeliveries).toEqual(["settled", "none", "none"]);
+ expect(observedActivityRoots).toEqual(["turn-parent", "turn-parent", "turn_0"]);
});
it.each(["none", "initiating"] as const)("sets initiating task phase (%s)", async (phase) => {
diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.ts
index 86ed25447..9b3b83f44 100644
--- a/packages/eve/src/execution/workflow-steps.ts
+++ b/packages/eve/src/execution/workflow-steps.ts
@@ -97,6 +97,7 @@ import { createWorkflowRuntime } from "#execution/workflow-runtime.js";
import { bindDynamicConnections } from "#execution/dynamic-connections.js";
import { preserveCancelledTurnMessage } from "#execution/cancelled-turn-message.js";
import { deferMismatchedInlineTurnStep } from "#execution/accepted-delivery-deployment.js";
+import * as activityCohort from "#execution/activity-cohort.js";
const TASK_DONE_WITH_PENDING_INPUT_ERROR_MESSAGE =
"Task mode cannot complete while input requests remain pending.";
@@ -149,7 +150,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
// Outside a workflow context (e.g. tests) — getHookUrl will return undefined.
}
- // Resolve authorization callbacks before the adapter sees the delivery.
const pendingAuth = getPendingAuthorization(durableSession.state);
let completedAuths: ReturnType<typeof matchAuthorizationCallbacks>["matches"] | undefined;
if (pendingAuth && input.input?.kind === "deliver") {
@@ -159,14 +159,16 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
);
input = { ...input, input: { ...input.input, payloads: remainingPayloads } };
if (matches.length > 0) {
+ const matchedAttemptIds = activityCohort.restoreAuthorizationActivity({
+ ctx,
+ matches,
+ pending: pendingAuth,
+ });
const authResults = matches.map((match) => match.result);
ctx.set(PendingAuthorizationResultKey, authResults);
durableSession = {
...durableSession,
- state: clearPendingAuthorization(
- durableSession.state,
- authResults.map((result) => result.attemptId ?? result.name),
- ),
+ state: clearPendingAuthorization(durableSession.state, matchedAttemptIds),
};
completedAuths = matches;
if (remainingPayloads.length === 0) {
@@ -264,6 +266,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
resolved = { runtimeActionResults: input.input.results };
}
+ let taskRootTurnId: string | undefined;
if (
resolved !== undefined &&
rawInput.input?.kind === "deliver" &&
@@ -275,6 +278,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
});
if (taskContext !== undefined) {
ctx.set(TurnTaskDeliveryKey, taskContext.phase);
+ taskRootTurnId = taskContext.rootTurnId;
resolved = {
...resolved,
context: [...(resolved.context ?? []), taskContext.context],
@@ -282,6 +286,14 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
}
}
+ activityCohort.updateActivityRootForDelivery({
+ activeTurnId: activeTurnId(initialEmissionState),
+ ctx,
+ delivery: rawInput.input?.kind === "deliver" ? rawInput.input : undefined,
+ sessionState: durableSession.state,
+ taskRootTurnId,
+ });
+
const taskDeliveryPhase = ctx.get(TurnTaskDeliveryKey);
if (taskDeliveryPhase === "none" || taskDeliveryPhase === "initiating") {
const taskContext = resolveInitiatingTaskContext({
@@ -293,13 +305,11 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
}
}
- // Persist adapter-state mutations across the step boundary.
if (input.input?.kind === "deliver") {
const updatedAdapter = { ...adapter, state: { ...adapterCtx.state } };
setChannelContext(ctx, updatedAdapter);
}
- // Adapter handled the delivery inline; re-park and skip unchanged snapshot writes.
if (input.input?.kind === "deliver" && resolved === undefined) {
await contextStorage.run(ctx, () =>
instrumentation?.instrumentChannelDelivery({
@@ -380,7 +390,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
const writer = input.parentWritable.getWriter();
- // Persisted chunks and hooks must agree on the stamped id.
const emit = async (event: UnstampedMessageStreamEvent): Promise<MessageStreamEvent> => {
const toEmit = await callAdapterEventHandler(adapter, event, adapterCtx);
setChannelContext(ctx, { ...adapter, state: { ...adapterCtx.state } });
@@ -389,6 +398,7 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResu
return stamped;
};
const handleEvent: HandleEventFn = async (event, messages): Promise<void> => {
+ activityCohort.updateActivityBlockers(ctx, event);
// A remote task's parent owns its HITL. Forward blocking events over
// the task callback and keep them out of the child's local channel;
// otherwise two TUIs can present and answer the same request.
diff --git a/packages/eve/src/harness/authorization.test.ts b/packages/eve/src/harness/authorization.test.ts
index 267f60868..5ad78963f 100644
--- a/packages/eve/src/harness/authorization.test.ts
+++ b/packages/eve/src/harness/authorization.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { ContextContainer, contextStorage } from "#context/container.js";
-import { SessionIdKey } from "#context/keys.js";
+import { ActivityObserverKey, ActivityRootTurnIdKey, SessionIdKey } from "#context/keys.js";
import {
CallbackBaseUrlKey,
clearPendingAuthorization,
@@ -107,6 +107,23 @@ function candidateChallenge(name: string, candidateId: string) {
}
describe("pending authorization state", () => {
+ it("captures the originating activity turn", () => {
+ const ctx = new ContextContainer();
+ ctx.set(ActivityObserverKey, {
+ sink: { url: "https://agent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz", version: 1 },
+ });
+ ctx.set(ActivityRootTurnIdKey, "turn-origin");
+ const state = contextStorage.run(ctx, () =>
+ setPendingAuthorization(undefined, {
+ challenges: [candidateChallenge("github", "candidate-1")],
+ }),
+ );
+
+ expect(getPendingAuthorization(state)?.activityRootTurnIds).toEqual({
+ "candidate-1": "turn-origin",
+ });
+ });
+
it("merges concurrent candidate challenges by authorization name", () => {
const first = setPendingAuthorization(undefined, {
challenges: [candidateChallenge("candidate-1:github", "candidate-1")],
@@ -138,6 +155,14 @@ describe("pending authorization state", () => {
expect.objectContaining({ hookUrl: "https://eve.example/refreshed" }),
]);
});
+
+ it("clears by candidate ID", () => {
+ const state = setPendingAuthorization(undefined, {
+ challenges: [candidateChallenge("github", "candidate-1")],
+ });
+
+ expect(clearPendingAuthorization(state, ["candidate-1"])).toBeUndefined();
+ });
});
describe("pending authorization attempts", () => {
diff --git a/packages/eve/src/harness/authorization.ts b/packages/eve/src/harness/authorization.ts
index 649603313..3a20eed92 100644
--- a/packages/eve/src/harness/authorization.ts
+++ b/packages/eve/src/harness/authorization.ts
@@ -31,9 +31,9 @@
* nonce that re-derives it) from start to finish.
*/
-import { loadContext } from "#context/container.js";
+import { contextStorage, loadContext } from "#context/container.js";
import { ContextKey } from "#context/key.js";
-import { SessionIdKey } from "#context/keys.js";
+import { ActivityRootTurnIdKey, SessionIdKey } from "#context/keys.js";
import { createWorkflowCallbackUrl } from "#execution/workflow-callback-url.js";
import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";
import type { AuthorizationCallback, ConnectionPrincipal } from "#shared/connection-types.js";
@@ -306,6 +306,7 @@ export const AuthorizationHookKey = new ContextKey<string>("eve.authorizationHoo
const PENDING_AUTHORIZATION_KEY = "eve.runtime.pendingAuthorization";
export interface PendingAuthorizationState {
+ readonly activityRootTurnIds?: Readonly<Record<string, string>>;
readonly challenges: readonly AuthorizationChallenge[];
}
@@ -314,11 +315,21 @@ export function setPendingAuthorization(
value: PendingAuthorizationState,
): Record<string, unknown> {
const active = resolveActiveAuthorizationChallenges(value.challenges);
- const previous = getPendingAuthorization(sessionState)?.challenges ?? [];
+ const pending = getPendingAuthorization(sessionState);
+ const previous = pending?.challenges ?? [];
const superseded = getSupersededAuthorizationChallenges(sessionState, active);
+ const rootTurnId = contextStorage.getStore()?.get(ActivityRootTurnIdKey);
+ const activityRootTurnIds = { ...pending?.activityRootTurnIds };
+ for (const challenge of superseded)
+ delete activityRootTurnIds[authorizationAttemptKey(challenge)];
+ if (rootTurnId !== undefined) {
+ for (const challenge of active)
+ activityRootTurnIds[authorizationAttemptKey(challenge)] = rootTurnId;
+ }
return {
...sessionState,
[PENDING_AUTHORIZATION_KEY]: {
+ ...(Object.keys(activityRootTurnIds).length === 0 ? {} : { activityRootTurnIds }),
challenges: [...previous.filter((challenge) => !superseded.includes(challenge)), ...active],
},
};
@@ -379,12 +390,12 @@ export function clearPendingAuthorization(
if (pending !== undefined) {
const completedAttemptIds = new Set(attemptIds);
const challenges = pending.challenges.filter(
- (challenge) => !completedAttemptIds.has(challenge.attemptId ?? challenge.name),
+ (challenge) => !completedAttemptIds.has(authorizationAttemptKey(challenge)),
);
if (challenges.length > 0) {
return {
...sessionState,
- [PENDING_AUTHORIZATION_KEY]: { challenges },
+ [PENDING_AUTHORIZATION_KEY]: pendingAuthorizationValue(pending, challenges),
};
}
}
@@ -395,6 +406,27 @@ export function clearPendingAuthorization(
return Object.keys(state).length > 0 ? state : undefined;
}
+function pendingAuthorizationValue(
+ pending: PendingAuthorizationState,
+ challenges: readonly AuthorizationChallenge[],
+): PendingAuthorizationState {
+ const activityRootTurnIds = Object.fromEntries(
+ challenges.flatMap((challenge) => {
+ const key = authorizationAttemptKey(challenge);
+ const rootTurnId = pending.activityRootTurnIds?.[key];
+ return rootTurnId === undefined ? [] : [[key, rootTurnId]];
+ }),
+ );
+ return {
+ ...(Object.keys(activityRootTurnIds).length === 0 ? {} : { activityRootTurnIds }),
+ challenges,
+ };
+}
+
+function authorizationAttemptKey(challenge: AuthorizationChallenge): string {
+ return challenge.attemptId ?? challenge.candidateId ?? challenge.name;
+}
+
export function getPendingAuthorization(
sessionState: Record<string, unknown> | undefined,
): PendingAuthorizationState | undefined {
diff --git a/packages/eve/src/harness/pending-input-batches.test.ts b/packages/eve/src/harness/pending-input-batches.test.ts
index 9bcd653eb..b82b45002 100644
--- a/packages/eve/src/harness/pending-input-batches.test.ts
+++ b/packages/eve/src/harness/pending-input-batches.test.ts
@@ -1,8 +1,14 @@
import { describe, expect, it } from "vitest";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { ActivityObserverKey, ActivityRootTurnIdKey } from "#context/keys.js";
import type { InputRequest } from "#shared/input.js";
import { resolvePendingInput } from "#harness/input-requests.js";
-import { appendPendingInputBatch, getPendingInputBatches } from "#harness/pending-input-batches.js";
+import {
+ activityRequestIdsForRootTurn,
+ appendPendingInputBatch,
+ getPendingInputBatches,
+} from "#harness/pending-input-batches.js";
import type { HarnessSession } from "#harness/types.js";
const DUPLICATE_ID_ERROR =
@@ -38,6 +44,26 @@ function question(requestId: string, callId: string): InputRequest {
};
}
+describe("pending input activity provenance", () => {
+ it("captures the originating turn with a parked request", () => {
+ const ctx = new ContextContainer();
+ ctx.set(ActivityObserverKey, {
+ sink: { url: "https://agent.example/eve/v1/activity/abcdefghijklmnopqrstuvwxyz", version: 1 },
+ });
+ ctx.set(ActivityRootTurnIdKey, "turn-origin");
+ const parked = contextStorage.run(ctx, () =>
+ appendPendingInputBatch({
+ requests: [approval("approval-1", "call-1")],
+ responseMessages: [],
+ session: session(),
+ }),
+ );
+
+ expect(getPendingInputBatches(parked.state)[0]?.activityRootTurnId).toBe("turn-origin");
+ expect(activityRequestIdsForRootTurn(parked.state, "turn-origin")).toEqual(["approval-1"]);
+ });
+});
+
describe("pending input request ID uniqueness", () => {
it("rejects duplicate IDs within a newly appended batch", () => {
expect(() =>
diff --git a/packages/eve/src/harness/pending-input-batches.ts b/packages/eve/src/harness/pending-input-batches.ts
index ee7680d11..eb9ed4877 100644
--- a/packages/eve/src/harness/pending-input-batches.ts
+++ b/packages/eve/src/harness/pending-input-batches.ts
@@ -1,5 +1,7 @@
import type { ModelMessage } from "ai";
+import { contextStorage } from "#context/container.js";
+import { ActivityRootTurnIdKey } from "#context/keys.js";
import type { InputRequest } from "#shared/input.js";
import type { HarnessSession, SessionStateMap, StepInput } from "#harness/types.js";
import { coalesceTurnInputs } from "#harness/messages.js";
@@ -27,6 +29,7 @@ export interface PendingInputBatchEvent {
*/
export interface PendingInputBatch {
readonly event?: PendingInputBatchEvent;
+ readonly activityRootTurnId?: string;
readonly requests: readonly InputRequest[];
readonly responseAuthRequiredRequestIds?: readonly string[];
readonly responseMessages: readonly ModelMessage[];
@@ -133,6 +136,7 @@ function setPendingInputBatches(
} else {
state[PENDING_INPUT_BATCHES_KEY] = batches.map((batch) => ({
event: batch.event,
+ activityRootTurnId: batch.activityRootTurnId,
responseAuthRequiredRequestIds: batch.responseAuthRequiredRequestIds,
requests: [...batch.requests],
responseMessages: [...batch.responseMessages],
@@ -148,6 +152,7 @@ function setPendingInputBatches(
*/
export function appendPendingInputBatch(input: {
readonly event?: PendingInputBatchEvent;
+ readonly activityRootTurnId?: string;
readonly requests: readonly InputRequest[];
readonly responseAuthRequiredRequestIds?: readonly string[];
readonly responseMessages: readonly ModelMessage[];
@@ -157,6 +162,8 @@ export function appendPendingInputBatch(input: {
...getPendingInputBatches(input.session.state),
{
event: input.event,
+ activityRootTurnId:
+ input.activityRootTurnId ?? contextStorage.getStore()?.get(ActivityRootTurnIdKey),
responseAuthRequiredRequestIds: input.responseAuthRequiredRequestIds,
requests: input.requests,
responseMessages: input.responseMessages,
@@ -164,6 +171,26 @@ export function appendPendingInputBatch(input: {
]);
}
+export function activityRootTurnIdForInputResponses(
+ state: SessionStateMap | undefined,
+ requestIds: ReadonlySet<string>,
+): string | undefined {
+ return getPendingInputBatches(state).find((batch) =>
+ batch.requests.some((request) => requestIds.has(request.requestId)),
+ )?.activityRootTurnId;
+}
+
+export function activityRequestIdsForRootTurn(
+ state: SessionStateMap | undefined,
+ rootTurnId: string,
+): readonly string[] {
+ return getPendingInputBatches(state).flatMap((batch) =>
+ batch.activityRootTurnId === rootTurnId
+ ? batch.requests.map((request) => request.requestId)
+ : [],
+ );
+}
+
// ---------------------------------------------------------------------------
// Deferred step input
// ---------------------------------------------------------------------------
diff --git a/packages/eve/src/public/channels/slack/activity-progress.test.ts b/packages/eve/src/public/channels/slack/activity-progress.test.ts
index 28272d9e9..c63495ed7 100644
--- a/packages/eve/src/public/channels/slack/activity-progress.test.ts
+++ b/packages/eve/src/public/channels/slack/activity-progress.test.ts
@@ -113,6 +113,30 @@ describe("Slack activity activity", () => {
expect(selectSlackActivityStatus(completed)).toBe("Found Slack docs");
});
+ it("keeps task-reporting activity in the originating tree", () => {
+ const reportingAction = {
+ action: {
+ id: "action:work:root:turn:report",
+ kind: "tool" as const,
+ name: "compose_result",
+ parentWorkId: root.id,
+ rootTurnId: "turn",
+ stepIndex: 0,
+ },
+ eventId: "report",
+ kind: "action.started" as const,
+ startedAt: "4",
+ };
+ const activity = reduceActivityBatch(snapshot(), {
+ events: [reportingAction],
+ version: 1,
+ });
+
+ expect(activityMessages(activity)).toEqual(
+ new Map([["turn", expect.stringContaining("compose_result")]]),
+ );
+ });
+
it("renders inherited child tool activity beneath an existing task row", () => {
const task = {
id: "work:task",
diff --git a/packages/eve/src/tasks/delivery-context.test.ts b/packages/eve/src/tasks/delivery-context.test.ts
index 1f2fab34b..4fc59da5a 100644
--- a/packages/eve/src/tasks/delivery-context.test.ts
+++ b/packages/eve/src/tasks/delivery-context.test.ts
@@ -89,6 +89,7 @@ describe("resolveTaskDeliveryContext", () => {
context:
'[Task state]\n{"tasks":[{"name":"report_probe","status":"completed","taskId":"task_1"},{"name":"report_probe","status":"pending","taskId":"task_2"}]}',
phase: "pending",
+ rootTurnId: "turn_1",
},
);
});
@@ -119,6 +120,7 @@ describe("resolveTaskDeliveryContext", () => {
context:
'[Task state]\n{"tasks":[{"name":"report_probe","output":{"data":{"result":"first"},"type":"result"},"status":"completed","taskId":"task_1"},{"name":"report_probe","output":{"data":{"result":"second"},"type":"result"},"status":"completed","taskId":"task_2"}]}',
phase: "settled",
+ rootTurnId: "turn_1",
});
});
diff --git a/packages/eve/src/tasks/delivery-context.ts b/packages/eve/src/tasks/delivery-context.ts
index efc836c1c..42f16a7b0 100644
--- a/packages/eve/src/tasks/delivery-context.ts
+++ b/packages/eve/src/tasks/delivery-context.ts
@@ -15,13 +15,19 @@ export const TASK_DELIVERY_SETTLED_INSTRUCTION = `Background task reporting\nThi
export function resolveTaskDeliveryContext(input: {
readonly state: SessionStateMap | undefined;
readonly taskDeliveryId: string;
-}): { readonly context: string; readonly phase: "pending" | "settled" } | undefined {
+}):
+ | {
+ readonly context: string;
+ readonly phase: "pending" | "settled";
+ readonly rootTurnId: string;
+ }
+ | undefined {
const entries = getSessionTaskIndex(input.state);
const delivered = entries.find((entry) => input.taskDeliveryId.startsWith(`${entry.taskId}:`));
if (delivered === undefined) return undefined;
const cohort = entries.filter((entry) => entry.createdByTurnId === delivered.createdByTurnId);
- return projectTaskCohort(cohort);
+ return { ...projectTaskCohort(cohort), rootTurnId: delivered.createdByTurnId };
}
/** Returns model context for durable tasks launched by the active parent turn. */