The Open Framework for Building Agents
[1/5] feat(eve): define activity protocol and reducer (#2293)
Ben Pankowcace2c59b826
diff --git a/.changeset/curly-progress-protocol.md b/.changeset/curly-progress-protocol.mdnew file mode 100644index 000000000..2a5ea57c3--- /dev/null+++ b/.changeset/curly-progress-protocol.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Add the internal versioned protocol and reducer used by channel activity renderers.diff --git a/packages/eve/src/execution/activity-text.ts b/packages/eve/src/execution/activity-text.tsnew file mode 100644index 000000000..b1a8c21e8--- /dev/null+++ b/packages/eve/src/execution/activity-text.ts@@ -0,0 +1,13 @@+export const MAX_ACTIVITY_TEXT_LENGTH = 500;++/** Normalizes bounded untrusted presentation text before it reaches a renderer. */+export function normalizeActivityText(text: string): string {+ return (+ text+ // Control bytes are untrusted presentation data, not meaningful activity text.+ .replace(/\p{Cc}/gu, " ")+ .replace(/\s+/g, " ")+ .trim()+ .slice(0, MAX_ACTIVITY_TEXT_LENGTH)+ );+}diff --git a/packages/eve/src/execution/activity-work-id.ts b/packages/eve/src/execution/activity-work-id.tsnew file mode 100644index 000000000..d32b7b543--- /dev/null+++ b/packages/eve/src/execution/activity-work-id.ts@@ -0,0 +1,22 @@+import { createHash } from "node:crypto";++import { deriveAgentOperationId } from "#harness/handles/operation-id.js";++export function deriveRootTurnActivityWorkId(input: {+ readonly sessionId: string;+ readonly turnId: string;+}): string {+ return `root:${hashTuple([input.sessionId, input.turnId])}`;+}++export function deriveChildActivityWorkId(input: {+ readonly callId: string;+ readonly parentSessionId: string;+ readonly parentTurnId: string;+}): string {+ return `work:${deriveAgentOperationId(input)}`;+}++function hashTuple(values: readonly string[]): string {+ return createHash("sha256").update(JSON.stringify(values)).digest("hex");+}diff --git a/packages/eve/src/execution/activity-work.test.ts b/packages/eve/src/execution/activity-work.test.tsnew file mode 100644index 000000000..e08d22c54--- /dev/null+++ b/packages/eve/src/execution/activity-work.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";++import { deriveChildWorkIdentity, deriveRootTurnWorkIdentity } from "#execution/activity-work.js";++describe("activity work identity", () => {+ it("derives root work from the active root turn", () => {+ expect(+ deriveRootTurnWorkIdentity({+ auth: { current: null, initiator: null },+ sessionId: "root",+ turn: { id: "turn-1", sequence: 0 },+ }),+ ).toEqual({+ id: expect.stringMatching(/^root:[a-f0-9]{64}$/),+ kind: "root-turn",+ rootSessionId: "root",+ rootTurnId: "turn-1",+ sessionId: "root",+ turnId: "turn-1",+ });+ });++ it("preserves immediate parent and root-turn lineage for nested work", () => {+ const root = {+ id: "root:fixture",+ kind: "root-turn" as const,+ rootSessionId: "root",+ rootTurnId: "turn-1",+ sessionId: "root",+ turnId: "turn-1",+ };+ const child = deriveChildWorkIdentity({+ callId: "call-a",+ kind: "subagent",+ name: "research",+ parentSessionId: "root",+ parentTurnId: "turn-1",+ parentWork: root,+ });+ const grandchild = deriveChildWorkIdentity({+ callId: "call-b",+ kind: "subagent",+ name: "tester",+ parentSessionId: "child-a",+ parentTurnId: "child-turn",+ parentWork: child,+ });++ expect(grandchild).toMatchObject({+ id: expect.stringMatching(/^work:[a-f0-9]{64}$/),+ parentId: child.id,+ rootSessionId: "root",+ rootTurnId: "turn-1",+ });+ });++ it("keeps colon-containing root tuples distinct", () => {+ const first = deriveRootTurnWorkIdentity({+ auth: { current: null, initiator: null },+ sessionId: "a:b",+ turn: { id: "c", sequence: 0 },+ });+ const second = deriveRootTurnWorkIdentity({+ auth: { current: null, initiator: null },+ sessionId: "a",+ turn: { id: "b:c", sequence: 0 },+ });++ expect(first.id).not.toBe(second.id);+ });++ it("keeps colon-containing child tuples distinct", () => {+ const parentWork = {+ id: "root:fixture",+ kind: "root-turn" as const,+ rootSessionId: "root",+ rootTurnId: "turn",+ };+ const first = deriveChildWorkIdentity({+ callId: "d",+ kind: "subagent",+ name: "first",+ parentSessionId: "a:b",+ parentTurnId: "c",+ parentWork,+ });+ const second = deriveChildWorkIdentity({+ callId: "d",+ kind: "subagent",+ name: "second",+ parentSessionId: "a",+ parentTurnId: "b:c",+ parentWork,+ });++ expect(first.id).not.toBe(second.id);+ });+});diff --git a/packages/eve/src/execution/activity-work.ts b/packages/eve/src/execution/activity-work.tsnew file mode 100644index 000000000..a7d53dff9--- /dev/null+++ b/packages/eve/src/execution/activity-work.ts@@ -0,0 +1,39 @@+import type { Session } from "#context/keys.js";+import {+ deriveChildActivityWorkId,+ deriveRootTurnActivityWorkId,+} from "#execution/activity-work-id.js";+import type { ActivityWorkIdentityV1, ActivityWorkKind } from "#protocol/activity.js";++export function deriveRootTurnWorkIdentity(session: Session): ActivityWorkIdentityV1 {+ return {+ id: deriveRootTurnActivityWorkId({+ sessionId: session.sessionId,+ turnId: session.turn.id,+ }),+ kind: "root-turn",+ rootSessionId: session.sessionId,+ rootTurnId: session.turn.id,+ sessionId: session.sessionId,+ turnId: session.turn.id,+ };+}++export function deriveChildWorkIdentity(input: {+ readonly callId: string;+ readonly kind: Exclude<ActivityWorkKind, "root-turn">;+ readonly name: string;+ readonly parentSessionId: string;+ readonly parentTurnId: string;+ readonly parentWork: ActivityWorkIdentityV1;+}): ActivityWorkIdentityV1 {+ return {+ callId: input.callId,+ id: deriveChildActivityWorkId(input),+ kind: input.kind,+ name: input.name,+ parentId: input.parentWork.id,+ rootSessionId: input.parentWork.rootSessionId,+ rootTurnId: input.parentWork.rootTurnId,+ };+}diff --git a/packages/eve/src/execution/session-activity.test.ts b/packages/eve/src/execution/session-activity.test.tsnew file mode 100644index 000000000..0a7610981--- /dev/null+++ b/packages/eve/src/execution/session-activity.test.ts@@ -0,0 +1,258 @@+import { describe, expect, it } from "vitest";++import { createActivitySnapshot, reduceActivityBatch } from "#execution/session-activity.js";+import { parseActivityBatchV1, type ActivityEventV1 } from "#protocol/activity.js";++const work = {+ id: "root:session:turn",+ kind: "root-turn" as const,+ rootSessionId: "session",+ rootTurnId: "turn",+};++function reduce(events: readonly ActivityEventV1[]) {+ return reduceActivityBatch(createActivitySnapshot(), { events, version: 1 });+}++describe("activity protocol and reducer", () => {+ it("retains known siblings while ignoring additive unknown events", () => {+ expect(+ parseActivityBatchV1({+ events: [+ { eventId: "future", kind: "detail.updated", message: "working" },+ { eventId: "started", kind: "work.started", startedAt: "2026-01-01", work },+ ],+ version: 1,+ }),+ ).toEqual({+ events: [{ eventId: "started", kind: "work.started", startedAt: "2026-01-01", work }],+ version: 1,+ });+ });++ it("rejects malformed known events", () => {+ expect(+ parseActivityBatchV1({+ events: [{ eventId: "started", kind: "work.started", work }],+ version: 1,+ }),+ ).toBeUndefined();+ });++ it("deduplicates only by event id", () => {+ const event = { eventId: "started", kind: "work.started" as const, startedAt: "now", work };+ const first = reduce([event]);+ const duplicate = reduceActivityBatch(first, { events: [event], version: 1 });+ expect(duplicate).toBe(first);+ });++ it("applies settlement before start and never reopens terminal work", () => {+ const settled = reduce([+ {+ eventId: "settled",+ kind: "work.settled",+ outcome: "completed",+ settledAt: "later",+ workId: work.id,+ },+ ]);+ const started = reduceActivityBatch(settled, {+ events: [{ eventId: "started", kind: "work.started", startedAt: "earlier", work }],+ version: 1,+ });+ const duplicateStart = reduceActivityBatch(started, {+ events: [{ eventId: "started-again", kind: "work.started", startedAt: "latest", work }],+ version: 1,+ });+ expect(started.work[work.id]?.phase).toBe("completed");+ expect(duplicateStart.work[work.id]).toBe(started.work[work.id]);+ });++ it.each([+ ["child before parent", ["child", "root-settled", "root"]],+ ["parent before child", ["root-settled", "root", "child"]],+ ["ordered", ["root", "child", "root-settled"]],+ ] as const)("converges work settlement for %s delivery", (_name, order) => {+ const child = {+ id: "work:child",+ kind: "subagent" as const,+ parentId: work.id,+ rootSessionId: "session",+ rootTurnId: "turn",+ };+ const events: Record<string, ActivityEventV1> = {+ root: { eventId: "root", kind: "work.started", startedAt: "1", work },+ child: { eventId: "child", kind: "work.started", startedAt: "2", work: child },+ "root-settled": {+ eventId: "root-settled",+ kind: "work.settled",+ outcome: "failed",+ settledAt: "3",+ workId: work.id,+ },+ };++ const snapshot = reduce(order.map((key) => events[key]!));++ expect(snapshot.work[work.id]?.phase).toBe("failed");+ expect(snapshot.work[child.id]?.phase).toBe("cancelled");+ expect(snapshot.pendingSettlements).toEqual({});+ });++ it("cancels early actions and blockers when their parent starts terminal", () => {+ const snapshot = reduce([+ {+ action: {+ id: "action",+ kind: "tool",+ name: "search",+ parentWorkId: work.id,+ rootTurnId: "turn",+ stepIndex: 0,+ },+ eventId: "action",+ kind: "action.started",+ startedAt: "1",+ },+ {+ blocker: {+ id: "input",+ kind: "input",+ parentWorkId: work.id,+ rootTurnId: "turn",+ },+ eventId: "input",+ kind: "blocker.started",+ startedAt: "1",+ },+ {+ eventId: "settled",+ kind: "work.settled",+ outcome: "completed",+ settledAt: "2",+ workId: work.id,+ },+ { eventId: "root", kind: "work.started", startedAt: "0", work },+ ]);++ expect(snapshot.work[work.id]?.phase).toBe("completed");+ expect(snapshot.actions.action?.phase).toBe("cancelled");+ expect(snapshot.blockers.input?.phase).toBe("cancelled");+ });++ it("retains unmatched settlement without changing revision", () => {+ const initial = createActivitySnapshot();+ const next = reduceActivityBatch(initial, {+ events: [+ {+ blockerId: "authorization:work:attempt",+ eventId: "settled",+ kind: "blocker.settled",+ outcome: "completed",+ settledAt: "now",+ },+ ],+ version: 1,+ });+ expect(next.revision).toBe(0);+ expect(next.pendingSettlements).toHaveProperty("blocker:authorization:work:attempt");+ });++ it("recursively cancels active descendant work and its owned entities", () => {+ const child = {+ id: "work:child",+ kind: "subagent" as const,+ parentId: work.id,+ rootSessionId: "session",+ rootTurnId: "turn",+ };+ const grandchild = {+ id: "work:grandchild",+ kind: "subagent" as const,+ parentId: child.id,+ rootSessionId: "session",+ rootTurnId: "turn",+ };+ const snapshot = reduce([+ { eventId: "root", kind: "work.started", startedAt: "1", work },+ { eventId: "child", kind: "work.started", startedAt: "2", work: child },+ { eventId: "grandchild", kind: "work.started", startedAt: "3", work: grandchild },+ {+ action: {+ id: "grandchild-action",+ kind: "tool",+ name: "search",+ parentWorkId: grandchild.id,+ rootTurnId: "turn",+ stepIndex: 0,+ },+ eventId: "grandchild-action",+ kind: "action.started",+ startedAt: "4",+ },+ {+ blocker: {+ id: "child-input",+ kind: "input",+ parentWorkId: child.id,+ rootTurnId: "turn",+ },+ eventId: "child-input",+ kind: "blocker.started",+ startedAt: "5",+ },+ {+ eventId: "root-settled",+ kind: "work.settled",+ outcome: "failed",+ settledAt: "6",+ workId: work.id,+ },+ ]);++ expect(snapshot.work[work.id]?.phase).toBe("failed");+ expect(snapshot.work[child.id]?.phase).toBe("cancelled");+ expect(snapshot.work[grandchild.id]?.phase).toBe("cancelled");+ expect(snapshot.actions["grandchild-action"]?.phase).toBe("cancelled");+ expect(snapshot.blockers["child-input"]?.phase).toBe("cancelled");+ });++ it("cancels running owned actions and blockers when work settles", () => {+ const snapshot = reduce([+ { eventId: "work", kind: "work.started", startedAt: "1", work },+ {+ action: {+ id: "action",+ kind: "tool",+ name: "search",+ parentWorkId: work.id,+ rootTurnId: "turn",+ stepIndex: 0,+ },+ eventId: "action",+ kind: "action.started",+ startedAt: "2",+ },+ {+ blocker: {+ id: "input",+ kind: "input",+ parentWorkId: work.id,+ rootTurnId: "turn",+ },+ eventId: "input",+ kind: "blocker.started",+ startedAt: "3",+ },+ {+ eventId: "settled",+ kind: "work.settled",+ outcome: "failed",+ settledAt: "4",+ workId: work.id,+ },+ ]);+ expect(snapshot.actions.action?.phase).toBe("cancelled");+ expect(snapshot.blockers.input?.phase).toBe("cancelled");+ });+});diff --git a/packages/eve/src/execution/session-activity.ts b/packages/eve/src/execution/session-activity.tsnew file mode 100644index 000000000..1b2e0cb61--- /dev/null+++ b/packages/eve/src/execution/session-activity.ts@@ -0,0 +1,321 @@+import { normalizeActivityText } from "#execution/activity-text.js";+import {+ type PendingActivitySettlementV1,+ type ActivityActionPhase,+ type ActivityBatchV1,+ type ActivityBlockerPhase,+ type ActivityEventV1,+ type ActivitySnapshotV1,+ type ActivityWorkPhase,+ type ActivityWorkStateV1,+} from "#protocol/activity.js";++export const MAX_ACTIVITY_EVENT_IDS = 1_000;+export const MAX_ACTIVITY_PENDING_SETTLEMENTS = 500;+export const MAX_ACTIVITY_ENTITIES = 500;++export function createActivitySnapshot(): ActivitySnapshotV1 {+ return {+ actions: {},+ blockers: {},+ pendingSettlements: {},+ revision: 0,+ seenEventIds: [],+ version: 1,+ work: {},+ };+}++export function reduceActivityBatch(+ snapshot: ActivitySnapshotV1,+ batch: ActivityBatchV1,+): ActivitySnapshotV1 {+ let state = snapshot;+ let seenEventIds = snapshot.seenEventIds;+ let presentationChanged = false;+ let accepted = false;++ for (const event of batch.events) {+ if (seenEventIds.includes(event.eventId)) continue;+ const next = reduceEvent(state, event);+ if (next === state) continue;+ accepted = true;+ seenEventIds = appendBounded(seenEventIds, event.eventId, MAX_ACTIVITY_EVENT_IDS);+ presentationChanged ||= presentationDiffers(state, next);+ state = next;+ }++ if (!accepted) return snapshot;+ if (!presentationChanged) return { ...state, revision: snapshot.revision, seenEventIds };+ return { ...state, revision: snapshot.revision + 1, seenEventIds };+}++function presentationDiffers(left: ActivitySnapshotV1, right: ActivitySnapshotV1): boolean {+ return (+ left.actions !== right.actions || left.blockers !== right.blockers || left.work !== right.work+ );+}++function reduceEvent(snapshot: ActivitySnapshotV1, event: ActivityEventV1): ActivitySnapshotV1 {+ switch (event.kind) {+ case "work.started":+ return startWork(snapshot, event);+ case "work.settled":+ return settleWork(snapshot, event);+ case "action.started":+ return startAction(snapshot, event);+ case "action.settled":+ return settleAction(snapshot, event);+ case "blocker.started":+ return startBlocker(snapshot, event);+ case "blocker.settled":+ return settleBlocker(snapshot, event);+ }+}++function startWork(+ snapshot: ActivitySnapshotV1,+ event: Extract<ActivityEventV1, { readonly kind: "work.started" }>,+): ActivitySnapshotV1 {+ const current = snapshot.work[event.work.id];+ if (current !== undefined) return snapshot;+ const pending = pendingFor(snapshot, "work", event.work.id);+ const parent = event.work.parentId === undefined ? undefined : snapshot.work[event.work.parentId];+ const phase =+ pending?.outcome ??+ (parent !== undefined && parent.phase !== "running" ? "cancelled" : "running");+ const work: ActivityWorkStateV1 = {+ ...event.work,+ name: event.work.name === undefined ? undefined : normalizeActivityText(event.work.name),+ phase: phase as ActivityWorkPhase,+ settledAt: pending?.settledAt ?? (phase === "cancelled" ? parent?.settledAt : undefined),+ startedAt: event.startedAt,+ };+ const started = {+ ...snapshot,+ pendingSettlements: removeKey(snapshot.pendingSettlements, pendingKey("work", work.id)),+ work: replaceBounded(snapshot.work, work.id, work),+ };+ return work.phase === "running"+ ? started+ : settleWorkTree(started, {+ outcome: work.phase,+ settledAt: work.settledAt ?? event.startedAt,+ workId: work.id,+ });+}++function settleWork(+ snapshot: ActivitySnapshotV1,+ event: Extract<ActivityEventV1, { readonly kind: "work.settled" }>,+): ActivitySnapshotV1 {+ const current = snapshot.work[event.workId];+ if (current === undefined) return retainPending(snapshot, "work", event.workId, event);+ if (current.phase !== "running") return snapshot;+ return settleWorkTree(snapshot, {+ outcome: event.outcome,+ settledAt: event.settledAt,+ workId: event.workId,+ });+}++function startAction(+ snapshot: ActivitySnapshotV1,+ event: Extract<ActivityEventV1, { readonly kind: "action.started" }>,+): ActivitySnapshotV1 {+ if (snapshot.actions[event.action.id] !== undefined) return snapshot;+ const pending = pendingFor(snapshot, "action", event.action.id);+ const parent = snapshot.work[event.action.parentWorkId];+ const phase =+ pending?.outcome ??+ (parent !== undefined && parent.phase !== "running" ? "cancelled" : "running");+ return {+ ...snapshot,+ actions: replaceBounded(snapshot.actions, event.action.id, {+ ...event.action,+ name: normalizeActivityText(event.action.name),+ phase: phase as ActivityActionPhase,+ settledAt: pending?.settledAt ?? (phase === "cancelled" ? parent?.settledAt : undefined),+ startedAt: event.startedAt,+ }),+ pendingSettlements: removeKey(+ snapshot.pendingSettlements,+ pendingKey("action", event.action.id),+ ),+ };+}++function settleAction(+ snapshot: ActivitySnapshotV1,+ event: Extract<ActivityEventV1, { readonly kind: "action.settled" }>,+): ActivitySnapshotV1 {+ const current = snapshot.actions[event.actionId];+ if (current === undefined) return retainPending(snapshot, "action", event.actionId, event);+ if (current.phase !== "running") return snapshot;+ return {+ ...snapshot,+ actions: replaceBounded(snapshot.actions, event.actionId, {+ ...current,+ phase: event.outcome,+ settledAt: event.settledAt,+ }),+ };+}++function startBlocker(+ snapshot: ActivitySnapshotV1,+ event: Extract<ActivityEventV1, { readonly kind: "blocker.started" }>,+): ActivitySnapshotV1 {+ if (snapshot.blockers[event.blocker.id] !== undefined) return snapshot;+ const pending = pendingFor(snapshot, "blocker", event.blocker.id);+ const parent = snapshot.work[event.blocker.parentWorkId];+ const phase =+ pending?.outcome ??+ (parent !== undefined && parent.phase !== "running" ? "cancelled" : "blocked");+ return {+ ...snapshot,+ blockers: replaceBounded(snapshot.blockers, event.blocker.id, {+ ...event.blocker,+ label:+ event.blocker.label === undefined ? undefined : normalizeActivityText(event.blocker.label),+ phase: phase as ActivityBlockerPhase,+ settledAt: pending?.settledAt ?? (phase === "cancelled" ? parent?.settledAt : undefined),+ startedAt: event.startedAt,+ }),+ pendingSettlements: removeKey(+ snapshot.pendingSettlements,+ pendingKey("blocker", event.blocker.id),+ ),+ };+}++function settleBlocker(+ snapshot: ActivitySnapshotV1,+ event: Extract<ActivityEventV1, { readonly kind: "blocker.settled" }>,+): ActivitySnapshotV1 {+ const current = snapshot.blockers[event.blockerId];+ if (current === undefined) return retainPending(snapshot, "blocker", event.blockerId, event);+ if (current.phase !== "blocked") return snapshot;+ return {+ ...snapshot,+ blockers: replaceBounded(snapshot.blockers, event.blockerId, {+ ...current,+ phase: event.outcome,+ settledAt: event.settledAt,+ }),+ };+}++function retainPending(+ snapshot: ActivitySnapshotV1,+ entityKind: PendingActivitySettlementV1["entityKind"],+ entityId: string,+ event: Extract<ActivityEventV1, { readonly kind: `${string}.settled` }>,+): ActivitySnapshotV1 {+ const key = pendingKey(entityKind, entityId);+ if (snapshot.pendingSettlements[key] !== undefined) return snapshot;+ return {+ ...snapshot,+ pendingSettlements: replaceBounded(+ snapshot.pendingSettlements,+ key,+ { entityKind, eventId: event.eventId, outcome: event.outcome, settledAt: event.settledAt },+ MAX_ACTIVITY_PENDING_SETTLEMENTS,+ ),+ };+}++function pendingFor(+ snapshot: ActivitySnapshotV1,+ kind: PendingActivitySettlementV1["entityKind"],+ id: string,+): PendingActivitySettlementV1 | undefined {+ return snapshot.pendingSettlements[pendingKey(kind, id)];+}++function pendingKey(kind: PendingActivitySettlementV1["entityKind"], id: string): string {+ return `${kind}:${id}`;+}++function settleWorkTree(+ snapshot: ActivitySnapshotV1,+ input: {+ readonly outcome: Exclude<ActivityWorkPhase, "running">;+ readonly settledAt: string;+ readonly workId: string;+ },+): ActivitySnapshotV1 {+ const subtree = new Set([input.workId]);+ let discovered = true;+ while (discovered) {+ discovered = false;+ for (const work of Object.values(snapshot.work)) {+ if (work.parentId === undefined || !subtree.has(work.parentId) || subtree.has(work.id))+ continue;+ subtree.add(work.id);+ discovered = true;+ }+ }++ return {+ ...snapshot,+ actions: mapActivityStates(snapshot.actions, (action) =>+ subtree.has(action.parentWorkId) && action.phase === "running"+ ? { ...action, phase: "cancelled", settledAt: input.settledAt }+ : action,+ ),+ blockers: mapActivityStates(snapshot.blockers, (blocker) =>+ subtree.has(blocker.parentWorkId) && blocker.phase === "blocked"+ ? { ...blocker, phase: "cancelled", settledAt: input.settledAt }+ : blocker,+ ),+ work: mapActivityStates(snapshot.work, (work) => {+ if (work.id === input.workId) {+ return { ...work, phase: input.outcome, settledAt: input.settledAt };+ }+ return subtree.has(work.id) && work.phase === "running"+ ? { ...work, phase: "cancelled", settledAt: input.settledAt }+ : work;+ }),+ };+}++function mapActivityStates<T>(+ values: Readonly<Record<string, T>>,+ transform: (value: T) => T,+): Readonly<Record<string, T>> {+ let next = values;+ for (const [id, value] of Object.entries(values)) {+ const transformed = transform(value);+ if (transformed === value) continue;+ if (next === values) next = { ...values };+ (next as Record<string, T>)[id] = transformed;+ }+ return next;+}++function replaceBounded<T>(+ values: Readonly<Record<string, T>>,+ key: string,+ value: T,+ max = MAX_ACTIVITY_ENTITIES,+): Readonly<Record<string, T>> {+ const next = { ...values, [key]: value };+ const overflow = Object.keys(next).length - max;+ for (const oldKey of Object.keys(next).slice(0, Math.max(0, overflow))) delete next[oldKey];+ return next;+}++function removeKey<T>(+ values: Readonly<Record<string, T>>,+ key: string,+): Readonly<Record<string, T>> {+ if (values[key] === undefined) return values;+ const next = { ...values };+ delete next[key];+ return next;+}++function appendBounded<T>(values: readonly T[], value: T, max: number): readonly T[] {+ return [...values, value].slice(-max);+}diff --git a/packages/eve/src/protocol/activity.ts b/packages/eve/src/protocol/activity.tsnew file mode 100644index 000000000..69f8ef654--- /dev/null+++ b/packages/eve/src/protocol/activity.ts@@ -0,0 +1,343 @@+export const MAX_ACTIVITY_EVENTS_PER_BATCH = 100;++export type ActivityWorkKind = "root-turn" | "subagent" | "remote-agent" | "task";+export type ActivityWorkPhase = "running" | "completed" | "failed" | "cancelled";+export type ActivityActionKind = "tool" | "skill";+export type ActivityActionPhase = "running" | "completed" | "failed" | "rejected" | "cancelled";+export type ActivityBlockerKind = "approval" | "authorization" | "input";+export type ActivityBlockerPhase = "blocked" | "completed" | "cancelled" | "failed";++export interface ActivityWorkIdentityV1 {+ readonly callId?: string;+ readonly id: string;+ readonly kind: ActivityWorkKind;+ readonly name?: string;+ readonly parentId?: string;+ readonly rootSessionId: string;+ readonly rootTurnId: string;+ readonly sessionId?: string;+ readonly turnId?: string;+}++export interface PendingActivitySettlementV1 {+ readonly entityKind: "action" | "blocker" | "work";+ readonly eventId: string;+ readonly outcome: ActivityActionPhase | ActivityBlockerPhase | ActivityWorkPhase;+ readonly settledAt: string;+}++export interface ActivityWorkStateV1 extends ActivityWorkIdentityV1 {+ readonly phase: ActivityWorkPhase;+ readonly settledAt?: string;+ readonly startedAt: string;+}++export interface ActivityActionIdentityV1 {+ readonly id: string;+ readonly kind: ActivityActionKind;+ readonly name: string;+ readonly parentWorkId: string;+ readonly rootTurnId: string;+ readonly stepIndex: number;+}++export interface ActivityActionStateV1 extends ActivityActionIdentityV1 {+ readonly phase: ActivityActionPhase;+ readonly settledAt?: string;+ readonly startedAt: string;+}++export interface ActivityBlockerIdentityV1 {+ readonly id: string;+ readonly kind: ActivityBlockerKind;+ readonly label?: string;+ readonly parentActionId?: string;+ readonly parentWorkId: string;+ readonly rootTurnId: string;+}++export interface ActivityBlockerStateV1 extends ActivityBlockerIdentityV1 {+ readonly phase: ActivityBlockerPhase;+ readonly settledAt?: string;+ readonly startedAt: string;+}++export type ActivityEventV1 =+ | {+ readonly eventId: string;+ readonly kind: "work.started";+ readonly startedAt: string;+ readonly work: ActivityWorkIdentityV1;+ }+ | {+ readonly eventId: string;+ readonly kind: "work.settled";+ readonly outcome: Exclude<ActivityWorkPhase, "running">;+ readonly settledAt: string;+ readonly workId: string;+ }+ | {+ readonly action: ActivityActionIdentityV1;+ readonly eventId: string;+ readonly kind: "action.started";+ readonly startedAt: string;+ }+ | {+ readonly actionId: string;+ readonly eventId: string;+ readonly kind: "action.settled";+ readonly outcome: Exclude<ActivityActionPhase, "running">;+ readonly settledAt: string;+ }+ | {+ readonly blocker: ActivityBlockerIdentityV1;+ readonly eventId: string;+ readonly kind: "blocker.started";+ readonly startedAt: string;+ }+ | {+ readonly blockerId: string;+ readonly eventId: string;+ readonly kind: "blocker.settled";+ readonly outcome: Exclude<ActivityBlockerPhase, "blocked">;+ readonly settledAt: string;+ };++export interface ActivityBatchV1 {+ readonly events: readonly ActivityEventV1[];+ readonly version: 1;+}++export interface ActivitySnapshotV1 {+ readonly actions: Readonly<Record<string, ActivityActionStateV1>>;+ readonly blockers: Readonly<Record<string, ActivityBlockerStateV1>>;+ readonly pendingSettlements: Readonly<Record<string, PendingActivitySettlementV1>>;+ readonly revision: number;+ readonly seenEventIds: readonly string[];+ readonly version: 1;+ readonly work: Readonly<Record<string, ActivityWorkStateV1>>;+}++export function parseActivityWorkIdentityV1(value: unknown): ActivityWorkIdentityV1 | undefined {+ if (+ !isRecord(value) ||+ !hasOnlyKeys(value, [+ "callId",+ "id",+ "kind",+ "name",+ "parentId",+ "rootSessionId",+ "rootTurnId",+ "sessionId",+ "turnId",+ ])+ )+ return undefined;+ const kind = value.kind;+ if (+ !isOneOf(kind, ["root-turn", "subagent", "remote-agent", "task"] as const) ||+ !isIdentity(value.id) ||+ !isIdentity(value.rootSessionId) ||+ !isIdentity(value.rootTurnId) ||+ !isOptionalIdentity(value.callId) ||+ !isOptionalBoundedString(value.name) ||+ !isOptionalIdentity(value.parentId) ||+ !isOptionalIdentity(value.sessionId) ||+ !isOptionalIdentity(value.turnId)+ )+ return undefined;+ return {+ callId: value.callId,+ id: value.id,+ kind,+ name: value.name,+ parentId: value.parentId,+ rootSessionId: value.rootSessionId,+ rootTurnId: value.rootTurnId,+ sessionId: value.sessionId,+ turnId: value.turnId,+ };+}++/** Parses known lifecycle events while ignoring additive unknown event kinds. */+export function parseActivityBatchV1(value: unknown): ActivityBatchV1 | undefined {+ if (+ !isRecord(value) ||+ !hasOnlyKeys(value, ["events", "version"]) ||+ value.version !== 1 ||+ !Array.isArray(value.events) ||+ value.events.length > MAX_ACTIVITY_EVENTS_PER_BATCH+ )+ return undefined;++ const events: ActivityEventV1[] = [];+ for (const candidate of value.events) {+ if (!isRecord(candidate) || !isBoundedString(candidate.kind)) return undefined;+ const event = parseKnownEvent(candidate);+ if (event === null) continue;+ if (event === undefined) return undefined;+ events.push(event);+ }+ return { events, version: 1 };+}++function parseKnownEvent(value: Record<string, unknown>): ActivityEventV1 | null | undefined {+ switch (value.kind) {+ case "work.started": {+ if (!hasOnlyKeys(value, ["eventId", "kind", "startedAt", "work"])) return undefined;+ const work = parseActivityWorkIdentityV1(value.work);+ if (!isIdentity(value.eventId) || !isBoundedString(value.startedAt) || work === undefined)+ return undefined;+ return { eventId: value.eventId, kind: "work.started", startedAt: value.startedAt, work };+ }+ case "work.settled": {+ if (!hasOnlyKeys(value, ["eventId", "kind", "outcome", "settledAt", "workId"]))+ return undefined;+ if (+ !isIdentity(value.eventId) ||+ !isOneOf(value.outcome, ["completed", "failed", "cancelled"] as const) ||+ !isBoundedString(value.settledAt) ||+ !isIdentity(value.workId)+ )+ return undefined;+ return {+ eventId: value.eventId,+ kind: "work.settled",+ outcome: value.outcome,+ settledAt: value.settledAt,+ workId: value.workId,+ };+ }+ case "action.started": {+ if (!hasOnlyKeys(value, ["action", "eventId", "kind", "startedAt"])) return undefined;+ const action = parseActionIdentity(value.action);+ if (!isIdentity(value.eventId) || !isBoundedString(value.startedAt) || action === undefined)+ return undefined;+ return { action, eventId: value.eventId, kind: "action.started", startedAt: value.startedAt };+ }+ case "action.settled": {+ if (!hasOnlyKeys(value, ["actionId", "eventId", "kind", "outcome", "settledAt"]))+ return undefined;+ if (+ !isIdentity(value.actionId) ||+ !isIdentity(value.eventId) ||+ !isOneOf(value.outcome, ["completed", "failed", "rejected", "cancelled"] as const) ||+ !isBoundedString(value.settledAt)+ )+ return undefined;+ return {+ actionId: value.actionId,+ eventId: value.eventId,+ kind: "action.settled",+ outcome: value.outcome,+ settledAt: value.settledAt,+ };+ }+ case "blocker.started": {+ if (!hasOnlyKeys(value, ["blocker", "eventId", "kind", "startedAt"])) return undefined;+ const blocker = parseBlockerIdentity(value.blocker);+ if (!isIdentity(value.eventId) || !isBoundedString(value.startedAt) || blocker === undefined)+ return undefined;+ return {+ blocker,+ eventId: value.eventId,+ kind: "blocker.started",+ startedAt: value.startedAt,+ };+ }+ case "blocker.settled": {+ if (!hasOnlyKeys(value, ["blockerId", "eventId", "kind", "outcome", "settledAt"]))+ return undefined;+ if (+ !isIdentity(value.blockerId) ||+ !isIdentity(value.eventId) ||+ !isOneOf(value.outcome, ["completed", "cancelled", "failed"] as const) ||+ !isBoundedString(value.settledAt)+ )+ return undefined;+ return {+ blockerId: value.blockerId,+ eventId: value.eventId,+ kind: "blocker.settled",+ outcome: value.outcome,+ settledAt: value.settledAt,+ };+ }+ default:+ return null;+ }+}++function parseActionIdentity(value: unknown): ActivityActionIdentityV1 | undefined {+ if (+ !isRecord(value) ||+ !hasOnlyKeys(value, ["id", "kind", "name", "parentWorkId", "rootTurnId", "stepIndex"])+ )+ return undefined;+ if (+ !isIdentity(value.id) ||+ !isOneOf(value.kind, ["tool", "skill"] as const) ||+ !isBoundedString(value.name) ||+ !isIdentity(value.parentWorkId) ||+ !isIdentity(value.rootTurnId) ||+ !Number.isInteger(value.stepIndex) ||+ (value.stepIndex as number) < 0+ )+ return undefined;+ return {+ id: value.id,+ kind: value.kind,+ name: value.name,+ parentWorkId: value.parentWorkId,+ rootTurnId: value.rootTurnId,+ stepIndex: value.stepIndex as number,+ };+}++function parseBlockerIdentity(value: unknown): ActivityBlockerIdentityV1 | undefined {+ if (+ !isRecord(value) ||+ !hasOnlyKeys(value, ["id", "kind", "label", "parentActionId", "parentWorkId", "rootTurnId"])+ )+ return undefined;+ if (+ !isIdentity(value.id) ||+ !isOneOf(value.kind, ["approval", "authorization", "input"] as const) ||+ !isOptionalBoundedString(value.label) ||+ !isOptionalIdentity(value.parentActionId) ||+ !isIdentity(value.parentWorkId) ||+ !isIdentity(value.rootTurnId)+ )+ return undefined;+ return {+ id: value.id,+ kind: value.kind,+ label: value.label,+ parentActionId: value.parentActionId,+ parentWorkId: value.parentWorkId,+ rootTurnId: value.rootTurnId,+ };+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}+function hasOnlyKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {+ return Object.keys(value).every((key) => keys.includes(key));+}+function isBoundedString(value: unknown): value is string {+ return typeof value === "string" && value.length > 0 && value.length <= 500;+}+function isIdentity(value: unknown): value is string {+ return typeof value === "string" && value.length > 0 && value.length <= 1_000;+}+function isOptionalIdentity(value: unknown): value is string | undefined {+ return value === undefined || isIdentity(value);+}+function isOptionalBoundedString(value: unknown): value is string | undefined {+ return value === undefined || isBoundedString(value);+}+function isOneOf<const T extends readonly string[]>(value: unknown, values: T): value is T[number] {+ return typeof value === "string" && values.includes(value);+}