The Open Framework for Building Agents
fix(eve): workflow attributes - seed tags at run creation (#278)
Andrew Barba9d72bb16aabb
diff --git a/.changeset/quick-runs-tag.md b/.changeset/quick-runs-tag.mdnew file mode 100644index 000000000..0e14211f4--- /dev/null+++ b/.changeset/quick-runs-tag.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Seed session, subagent, and turn workflow attributes when their runs are created so Workflow turbo mode cannot race tag writes against run creation.diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex 7556120c1..18633090e 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -1,18 +1,10 @@import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";-import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import {createDurableSessionState,type DurableSessionState,} from "#execution/durable-session-store.js";import { createSession } from "#execution/session.js";-import {- buildSessionAttributes,- buildSubagentRootAttributes,- readParentLineage,- type SessionIdentitySummary,-} from "#execution/eve-workflow-attributes.js";-import { setEveAttributes } from "#runtime/attributes/emit.js";import type { JsonObject } from "#shared/json.js";/**@@ -30,30 +22,13 @@ export interface CreateSessionStepResult {* state before the workflow enters its turn loop.* `nodeId` targets a subagent node in the compiled graph; omitted for* the root agent.- *- * Emits the session/subagent-root `$eve.*` tags from inside this step- * (so the attribute write folds into a step the session already runs)- * and returns the durable state value the driver consumes.*/export async function createSessionStep(input: {readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;readonly continuationToken: string;- /**- * First user message of the run, used to derive `$eve.title` for- * top-level sessions. Threaded in so the session/subagent-root tags- * can be emitted from inside this step (see the tag write below)- * instead of the workflow body, where each `setEveAttributes` call- * spends a standalone `__builtin_set_attributes` step.- */- readonly inputMessage: unknown;readonly outputSchema?: JsonObject;readonly nodeId?: string;readonly rootSessionId?: string;- /**- * Shared serialized context, read for `$eve.trigger` (channel kind)- * and to detect whether this run is a delegated subagent root.- */- readonly serializedContext: Record<string, unknown>;readonly sessionId: string;}): Promise<CreateSessionStepResult> {"use step";@@ -74,42 +49,5 @@ export async function createSessionStep(input: {turnAgent: bundle.turnAgent,});- const state = createDurableSessionState({ session });-- const identity: SessionIdentitySummary = {- nodeId: bundle.nodeId ?? ROOT_RUNTIME_AGENT_NODE_ID,- };-- // Tag the session/subagent run for observability dashboards from- // inside this step. Emitting here (rather than the workflow body)- // folds the attribute write into this already-durable step instead- // of spending a separate `__builtin_set_attributes` step. Best effort- // — `setEveAttributes` swallows runtime failures so a broken tag write- // never breaks the session itself.- const parentLineage = readParentLineage(input.serializedContext);- if (parentLineage.sessionId === undefined) {- await setEveAttributes(- buildSessionAttributes({- inputMessage: input.inputMessage,- serializedContext: input.serializedContext,- }),- );- } else {- await setEveAttributes(- buildSubagentRootAttributes({- identity,- parentCallId: parentLineage.callId,- parentSessionId: parentLineage.sessionId,- parentTurnId: parentLineage.turnId,- // `rootSessionId` is the denormalized chain root, always set at- // dispatch (a first-level subagent's root equals its immediate- // parent). The fallback only satisfies the optional input type- // for the unreachable malformed-context case.- rootSessionId: input.rootSessionId ?? parentLineage.sessionId,- serializedContext: input.serializedContext,- }),- );- }-- return { state };+ return { state: createDurableSessionState({ session }) };}diff --git a/packages/eve/src/execution/eve-workflow-attributes.ts b/packages/eve/src/execution/eve-workflow-attributes.tsindex e34ba00bf..4e76b0e13 100644--- a/packages/eve/src/execution/eve-workflow-attributes.ts+++ b/packages/eve/src/execution/eve-workflow-attributes.ts@@ -26,7 +26,7 @@*/import { ChannelRequestIdKey } from "#context/keys.js";-import type { EveAttributeValue } from "#runtime/attributes/emit.js";+import type { EveAttributeValue } from "#runtime/attributes/normalize.js";import { isNonEmptyString } from "#shared/guards.js";/**diff --git a/packages/eve/src/execution/workflow-entry.integration.test.ts b/packages/eve/src/execution/workflow-entry.integration.test.tsindex f44928265..c580d7995 100644--- a/packages/eve/src/execution/workflow-entry.integration.test.ts+++ b/packages/eve/src/execution/workflow-entry.integration.test.ts@@ -6,8 +6,13 @@ import { createTestRuntime } from "#internal/testing/app-harness.js";import { waitForHook } from "#internal/testing/workflow-test-helpers.js";import { createBundledRuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";import { workflowEntry } from "#execution/workflow-entry.js";+import {+ buildSessionAttributes,+ buildSubagentRootAttributes,+} from "#execution/eve-workflow-attributes.js";import { createToolExecuteWithAuth } from "#execution/tool-auth.js";import { createWorkflowRuntime } from "#execution/workflow-runtime.js";+import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";import { ROOT_COMPILED_AGENT_NODE_ID } from "#compiler/manifest.js";import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";@@ -472,22 +477,32 @@ describe("workflowEntry integration", () => {const continuationToken = "http:workflow-entry-tags";await runtime.run(async () => {- const run = await start(workflowEntry, [+ const serializedContext = buildSerializedContext({+ channelKind: "http",+ continuationToken,+ mode: "conversation",+ });+ const run = await start(+ workflowEntry,+ [+ {+ input: { message: "session tag round-trip" },+ serializedContext,+ },+ ],{- input: { message: "session tag round-trip" },- serializedContext: buildSerializedContext({- channelKind: "http",- continuationToken,- mode: "conversation",- }),+ allowReservedAttributes: true,+ attributes: normalizeEveAttributes(+ buildSessionAttributes({+ inputMessage: "session tag round-trip",+ serializedContext,+ }),+ ),},- ]);+ );const stream = captureTurnEvents(run);try {- // Drain the first turn — by the time it completes `createSessionStep`- // has run and emitted the session-level `$eve.*` keys from inside- // its own step body.await stream.nextTurn();const world = await getWorld();@@ -511,22 +526,39 @@ describe("workflowEntry integration", () => {const runtime = createTestRuntime({ agent: { name: "workflow-entry-subagent-tags" } });await runtime.run(async () => {- const run = await start(workflowEntry, [+ const serializedContext = buildSerializedContext({+ channelKind: "subagent",+ continuationToken: "subagent:parent-session:call-subagent-1",+ mode: "task",+ parent: {+ callId: "call-subagent-1",+ rootSessionId: "root-session",+ sessionId: "parent-session",+ turn: { id: "turn-parent", sequence: 2 },+ },+ });+ const run = await start(+ workflowEntry,+ [+ {+ input: { message: "subagent tag round-trip" },+ serializedContext,+ },+ ],{- input: { message: "subagent tag round-trip" },- serializedContext: buildSerializedContext({- channelKind: "subagent",- continuationToken: "subagent:parent-session:call-subagent-1",- mode: "task",- parent: {- callId: "call-subagent-1",+ allowReservedAttributes: true,+ attributes: normalizeEveAttributes(+ buildSubagentRootAttributes({+ identity: { nodeId: "researcher" },+ parentCallId: "call-subagent-1",+ parentSessionId: "parent-session",+ parentTurnId: "turn-parent",rootSessionId: "root-session",- sessionId: "parent-session",- turn: { id: "turn-parent", sequence: 2 },- },- }),+ serializedContext,+ }),+ ),},- ]);+ );await expect(run.returnValue).resolves.toEqual({output: expect.stringContaining("subagent tag round-trip"),diff --git a/packages/eve/src/execution/workflow-entry.test.ts b/packages/eve/src/execution/workflow-entry.test.tsindex 69a41434c..e62773750 100644--- a/packages/eve/src/execution/workflow-entry.test.ts+++ b/packages/eve/src/execution/workflow-entry.test.ts@@ -136,12 +136,7 @@ describe("workflowEntry", () => {expect(createSessionStep).toHaveBeenCalledWith({compiledArtifactsSource: {},continuationToken: "http:test",- inputMessage: "hello there",nodeId: undefined,- serializedContext: expect.objectContaining({- "eve.continuationToken": "http:test",- "eve.mode": "conversation",- }),sessionId: "wrun_test_123",});expect(dispatchTurnStep).toHaveBeenCalledWith(diff --git a/packages/eve/src/execution/workflow-entry.ts b/packages/eve/src/execution/workflow-entry.tsindex d2796d707..908ba810c 100644--- a/packages/eve/src/execution/workflow-entry.ts+++ b/packages/eve/src/execution/workflow-entry.ts@@ -99,17 +99,12 @@ export async function workflowEntry(input: WorkflowEntryInput): Promise<Workflow// chain-root id can never drift between persisted session and tags.const rootSessionIdFromParent = readRootSessionId(input.serializedContext);- // `createSessionStep` emits the session/subagent-root `$eve.*` tags- // from inside its own step body (see create-session-step.ts), so no- // separate attribute step is spent here in the workflow body.const { state: sessionState } = await createSessionStep({compiledArtifactsSource: serializedBundle.source,continuationToken,- inputMessage: input.input.message,nodeId: serializedBundle.nodeId,outputSchema: input.input.outputSchema,rootSessionId: rootSessionIdFromParent,- serializedContext: input.serializedContext,sessionId,});diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex a46429f99..87c64fea5 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -177,7 +177,15 @@ describe("createWorkflowRuntime#run", () => {}),},],- { deploymentId: "latest" },+ {+ allowReservedAttributes: true,+ attributes: {+ "$eve.title": "hello",+ "$eve.trigger": "http",+ "$eve.type": "session",+ },+ deploymentId: "latest",+ },);});@@ -205,10 +213,58 @@ describe("createWorkflowRuntime#run", () => {}),},],- { deploymentId: "latest" },+ {+ allowReservedAttributes: true,+ attributes: {+ "$eve.channel_request_id": "req_run",+ "$eve.title": "hello",+ "$eve.trigger": "http",+ "$eve.type": "session",+ },+ deploymentId: "latest",+ },);});+ it("seeds subagent lineage attributes when starting a delegated session", async () => {+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;+ vi.mocked(getCompiledRuntimeAgentBundle).mockResolvedValue({+ compiledArtifactsSource,+ nodeId: "researcher",+ } as never);+ startMock.mockResolvedValue({ runId: "subagent-run" });++ await createWorkflowRuntime({+ compiledArtifactsSource,+ nodeId: "researcher",+ }).run({+ adapter: { kind: "subagent" },+ auth: null,+ continuationToken: "subagent:parent-session:call-1",+ input: { message: "research this" },+ mode: "task",+ parent: {+ callId: "call-1",+ rootSessionId: "root-session",+ sessionId: "parent-session",+ turn: { id: "turn-1", sequence: 1 },+ },+ });++ expect(startMock).toHaveBeenCalledWith(workflowEntryReference, expect.any(Array), {+ allowReservedAttributes: true,+ attributes: {+ "$eve.parent": "parent-session",+ "$eve.parent_call": "call-1",+ "$eve.parent_turn": "turn-1",+ "$eve.root": "root-session",+ "$eve.subagent": "researcher",+ "$eve.trigger": "subagent",+ "$eve.type": "subagent",+ },+ });+ });+it("falls back to the current deployment when latest is unsupported", async () => {vi.stubEnv("VERCEL_ENV", "production");const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;@@ -225,9 +281,22 @@ describe("createWorkflowRuntime#run", () => {});expect(startMock).toHaveBeenNthCalledWith(1, workflowEntryReference, expect.any(Array), {+ allowReservedAttributes: true,+ attributes: {+ "$eve.title": "hello",+ "$eve.trigger": "http",+ "$eve.type": "session",+ },deploymentId: "latest",});- expect(startMock).toHaveBeenNthCalledWith(2, workflowEntryReference, expect.any(Array));+ expect(startMock).toHaveBeenNthCalledWith(2, workflowEntryReference, expect.any(Array), {+ allowReservedAttributes: true,+ attributes: {+ "$eve.title": "hello",+ "$eve.trigger": "http",+ "$eve.type": "session",+ },+ });});it.each(["preview", "development", undefined])(@@ -254,7 +323,14 @@ describe("createWorkflowRuntime#run", () => {});expect(startMock).toHaveBeenCalledTimes(1);- expect(startMock).toHaveBeenCalledWith(workflowEntryReference, expect.any(Array));+ expect(startMock).toHaveBeenCalledWith(workflowEntryReference, expect.any(Array), {+ allowReservedAttributes: true,+ attributes: {+ "$eve.title": "hello",+ "$eve.trigger": "http",+ "$eve.type": "session",+ },+ });},);diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex b5cb86fd5..d90e06fea 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -1,5 +1,4 @@import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";-import type { WorkflowFunction, WorkflowMetadata } from "#compiled/@workflow/core/runtime/start.js";import type {DeliverInput,@@ -10,11 +9,18 @@ import type {Runtime,} from "#channel/types.js";import { serializeContext } from "#context/serialize.js";+import {+ buildSessionAttributes,+ buildSubagentRootAttributes,+ readParentLineage,+} from "#execution/eve-workflow-attributes.js";import { resolveInstalledPackageInfo } from "#internal/application/package.js";import { createLogger, logError } from "#internal/logging.js";import { getRun, resumeHook, start, type Run } from "#internal/workflow/runtime.js";import type { HandleMessageStreamEvent } from "#protocol/message.js";import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";+import { ROOT_RUNTIME_AGENT_NODE_ID } from "#runtime/graph.js";+import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import { buildRunContext } from "#execution/runtime-context.js";import { parseNdjsonStream } from "#execution/ndjson-stream.js";@@ -23,6 +29,18 @@ import { RuntimeNoActiveSessionError } from "#execution/runtime-errors.js";const WORKFLOW_ENTRY_NAME = "workflowEntry";const TURN_WORKFLOW_NAME = "turnWorkflow";const EVE_PACKAGE_INFO = resolveInstalledPackageInfo();++type WorkflowFunction<TArgs extends unknown[], TResult> = (...args: TArgs) => Promise<TResult>;++interface WorkflowMetadata {+ readonly workflowId: string;+}++interface WorkflowStartOptions {+ readonly allowReservedAttributes?: boolean;+ readonly attributes?: Record<string, string>;+}+export const LATEST_DEPLOYMENT_UNSUPPORTED_MESSAGE ="deploymentId 'latest' requires a World that implements resolveLatestDeploymentId()";@@ -86,15 +104,37 @@ export function createWorkflowRuntime(config: {});const ctx = buildRunContext({ bundle, run: input });const serializedContext = serializeContext(ctx);+ const parentLineage = readParentLineage(serializedContext);+ const attributes =+ parentLineage.sessionId === undefined+ ? buildSessionAttributes({+ inputMessage: input.input.message,+ serializedContext,+ })+ : buildSubagentRootAttributes({+ identity: { nodeId: bundle.nodeId ?? ROOT_RUNTIME_AGENT_NODE_ID },+ parentCallId: parentLineage.callId,+ parentSessionId: parentLineage.sessionId,+ parentTurnId: parentLineage.turnId,+ rootSessionId: parentLineage.rootSessionId ?? parentLineage.sessionId,+ serializedContext,+ });let run: Awaited<ReturnType<typeof startWorkflowPreferLatest>>;try {- run = await startWorkflowPreferLatest(workflowEntryReference, [+ run = await startWorkflowPreferLatest(+ workflowEntryReference,+ [+ {+ input: input.input,+ serializedContext,+ },+ ],{- input: input.input,- serializedContext,+ allowReservedAttributes: true,+ attributes: normalizeEveAttributes(attributes),},- ]);+ );} catch (error) {logError(log, "failed to start workflow run", error, {continuationToken: input.continuationToken,@@ -160,19 +200,24 @@ export function createWorkflowRuntime(config: {export async function startWorkflowPreferLatest<TArgs extends unknown[], TResult>(workflow: WorkflowFunction<TArgs, TResult> | WorkflowMetadata,args: TArgs,+ options?: WorkflowStartOptions,): Promise<Run<unknown> | Run<TResult>> {if (!shouldRouteToLatestDeployment()) {- return await start(workflow, args);+ return options === undefined+ ? await start(workflow, args)+ : await start(workflow, args, options);}try {- return await start(workflow, args, { deploymentId: "latest" });+ return await start(workflow, args, { ...options, deploymentId: "latest" });} catch (error) {if (!isLatestDeploymentUnsupportedError(error)) {throw error;}- return await start(workflow, args);+ return options === undefined+ ? await start(workflow, args)+ : await start(workflow, args, options);}}diff --git a/packages/eve/src/execution/workflow-steps.test.ts b/packages/eve/src/execution/workflow-steps.test.tsindex 4b78e8769..e31560a4c 100644--- a/packages/eve/src/execution/workflow-steps.test.ts+++ b/packages/eve/src/execution/workflow-steps.test.ts@@ -191,7 +191,11 @@ describe("dispatchTurnStep", () => {return {capabilities: undefined,completionToken: "turn-complete",- delivery: { kind: "deliver", payloads: [{ message: "hello" }] },+ delivery: {+ kind: "deliver",+ payloads: [{ message: "hello" }],+ requestId: "req_turn",+ },mode: "conversation",parentWritable,serializedContext: { state: "driver" },@@ -207,6 +211,13 @@ describe("dispatchTurnStep", () => {await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });expect(startMock).toHaveBeenCalledWith(turnWorkflow, [createTurnWorkflowInput(input)], {+ allowReservedAttributes: true,+ attributes: {+ "$eve.channel_request_id": "req_turn",+ "$eve.parent": "sess-test",+ "$eve.root": "sess-test",+ "$eve.type": "turn",+ },deploymentId: "latest",});});@@ -219,7 +230,15 @@ describe("dispatchTurnStep", () => {await expect(dispatchTurnStep(input)).resolves.toEqual({ runId: "turn-run" });expect(startMock).toHaveBeenCalledTimes(1);- expect(startMock).toHaveBeenCalledWith(turnWorkflow, [createTurnWorkflowInput(input)]);+ expect(startMock).toHaveBeenCalledWith(turnWorkflow, [createTurnWorkflowInput(input)], {+ allowReservedAttributes: true,+ attributes: {+ "$eve.channel_request_id": "req_turn",+ "$eve.parent": "sess-test",+ "$eve.root": "sess-test",+ "$eve.type": "turn",+ },+ });});it("falls back to the current deployment when latest is unsupported", async () => {@@ -233,9 +252,24 @@ describe("dispatchTurnStep", () => {const wireInput = createTurnWorkflowInput(input);expect(startMock).toHaveBeenNthCalledWith(1, turnWorkflow, [wireInput], {+ allowReservedAttributes: true,+ attributes: {+ "$eve.channel_request_id": "req_turn",+ "$eve.parent": "sess-test",+ "$eve.root": "sess-test",+ "$eve.type": "turn",+ },deploymentId: "latest",});- expect(startMock).toHaveBeenNthCalledWith(2, turnWorkflow, [wireInput]);+ expect(startMock).toHaveBeenNthCalledWith(2, turnWorkflow, [wireInput], {+ allowReservedAttributes: true,+ attributes: {+ "$eve.channel_request_id": "req_turn",+ "$eve.parent": "sess-test",+ "$eve.root": "sess-test",+ "$eve.type": "turn",+ },+ });});});@@ -317,7 +351,15 @@ describe("dispatchRuntimeActionsStep", () => {}),}),],- { deploymentId: "latest" },+ {+ allowReservedAttributes: true,+ attributes: expect.objectContaining({+ "$eve.parent": "parent-session",+ "$eve.root": "parent-session",+ "$eve.type": "subagent",+ }),+ deploymentId: "latest",+ },);});diff --git a/packages/eve/src/execution/workflow-steps.ts b/packages/eve/src/execution/workflow-steps.tsindex 891cef670..8810aa882 100644--- a/packages/eve/src/execution/workflow-steps.ts+++ b/packages/eve/src/execution/workflow-steps.ts@@ -59,7 +59,7 @@ import { createExecutionNodeStep } from "#execution/node-step.js";import { emitProxiedInputRequest, routeDeliverPayload } from "#execution/subagent-hitl-proxy.js";import { hydrateDurableSession, refreshSessionFromTurnAgent } from "#execution/session.js";import { buildTurnAttributes, readRootSessionId } from "#execution/eve-workflow-attributes.js";-import { setEveAttributes } from "#runtime/attributes/emit.js";+import { normalizeEveAttributes } from "#runtime/attributes/normalize.js";import { turnWorkflow } from "#execution/turn-workflow.js";import { createWorkflowRuntime, startWorkflowPreferLatest } from "#execution/workflow-runtime.js";import { resumeHook } from "#internal/workflow/runtime.js";@@ -106,22 +106,6 @@ export async function turnStep(rawInput: TurnStepInput): Promise<DurableStepResulet input = rawInput;- // Tag this turn run with the lineage attributes the dashboard uses to- // roll turns up under their parent session. Emitted from inside this- // step — which the turn workflow already pays for — so we never spend- // a standalone `__builtin_set_attributes` step in the workflow body.- // The values are constant for the run, so emitting on every step- // iteration is idempotent (last-write-wins) and avoids guessing which- // iteration is "first". Best effort — `setEveAttributes` swallows- // runtime failures.- await setEveAttributes(- buildTurnAttributes({- parentSessionId: input.sessionState.sessionId,- requestId: input.input?.kind === "deliver" ? input.input.requestId : undefined,- rootSessionId: readRootSessionId(input.serializedContext) ?? input.sessionState.sessionId,- }),- );-let durableSession = await readDurableSession(input.sessionState);const ctx = await deserializeContext(input.serializedContext);const adapter = ctx.require(ChannelKey);@@ -653,7 +637,16 @@ export async function dispatchTurnStep(): Promise<{ readonly runId: string }> {"use step";- const run = await startWorkflowPreferLatest(turnWorkflow, [createTurnWorkflowInput(input)]);+ const run = await startWorkflowPreferLatest(turnWorkflow, [createTurnWorkflowInput(input)], {+ allowReservedAttributes: true,+ attributes: normalizeEveAttributes(+ buildTurnAttributes({+ parentSessionId: input.sessionState.sessionId,+ requestId: input.delivery.kind === "deliver" ? input.delivery.requestId : undefined,+ rootSessionId: readRootSessionId(input.serializedContext) ?? input.sessionState.sessionId,+ }),+ ),+ });return { runId: run.runId };}diff --git a/packages/eve/src/runtime/attributes/emit.ts b/packages/eve/src/runtime/attributes/emit.tsindex b5137a87b..f1eee0192 100644--- a/packages/eve/src/runtime/attributes/emit.ts+++ b/packages/eve/src/runtime/attributes/emit.ts@@ -7,38 +7,13 @@// effect import is the smallest change that keeps the contract intact.import "#internal/workflow/builtins.js";-/**- * Maximum byte size for an attribute value on a workflow run.- *- * Local mirror of `ATTRIBUTE_VALUE_MAX_BYTES` from `@workflow/world`- * (source of truth: `packages/world/src/attributes.ts` in the workflow- * repo). The value is duplicated rather than imported because- * `@workflow/core` — the only workflow surface bundled into the- * workflow body — does not re-export it, and pulling `@workflow/world`- * into the body bundle would drag in the full zod attribute validator- * (the same reason `workflow-core-shim.ts` skips runtime validation in- * its `experimental_setAttributes`).- *- * Strings emitted through {@link setEveAttributes} are truncated to this- * byte count before they reach the runtime so the validator never- * rejects a tag for length alone.- *- * Drift is conservative-by-construction: if workflow LOWERS the limit,- * over-long values are rejected and `setEveAttributes` swallows the- * failure (warn-once-per-process) — dashboards see a missing tag, never- * a broken agent; if workflow RAISES it, titles are merely shorter than- * necessary. `emit.drift.test.ts` asserts equality against the real- * `@workflow/world` export (a devDependency) so CI fails loudly the day- * the constants diverge.- */-export const EVE_ATTRIBUTE_VALUE_MAX_BYTES = 256;+import { normalizeEveAttributes, type EveAttributeValue } from "#runtime/attributes/normalize.js";-/**- * Attribute value the caller wants to write. `undefined` values are- * stripped before the runtime call; numbers are stringified; strings- * are truncated to {@link EVE_ATTRIBUTE_VALUE_MAX_BYTES}.- */-export type EveAttributeValue = string | number | undefined;+export {+ EVE_ATTRIBUTE_VALUE_MAX_BYTES,+ type EveAttributeValue,+ truncateForTag,+} from "#runtime/attributes/normalize.js";/*** Per-process flag: once we've warned about a tag write failure we@@ -49,50 +24,6 @@ export type EveAttributeValue = string | number | undefined;*/let WARNED_ABOUT_TAG_FAILURE = false;-/**- * Truncates a string so its UTF-8 byte length is at most `maxBytes`- * without splitting a multi-byte character.- *- * The workflow runtime measures attribute values in UTF-8 bytes, not- * code units, so `value.slice(0, maxBytes)` is not safe — a JS string- * with two-byte characters (e.g. emoji surrogate pairs) can serialize- * to twice as many bytes as code units. We re-encode the truncated- * candidate after each drop and shrink one code unit at a time when- * the candidate's last character straddles the byte budget.- */-export function truncateForTag(value: string, maxBytes = EVE_ATTRIBUTE_VALUE_MAX_BYTES): string {- if (maxBytes <= 0) {- return "";- }-- const encoder = new TextEncoder();- const fullBytes = encoder.encode(value);- if (fullBytes.length <= maxBytes) {- return value;- }-- // Walk back one code unit at a time, but never stop on a position- // that would leave a lone high surrogate at the tail — `slice` is- // code-unit based, so slicing between the two halves of a surrogate- // pair would otherwise produce a malformed string that TextEncoder- // emits as the 3-byte U+FFFD replacement character.- let end = value.length;- while (end > 0) {- const lastCharCode = value.charCodeAt(end - 1);- const endsOnHighSurrogate = lastCharCode >= 0xd800 && lastCharCode <= 0xdbff;- if (endsOnHighSurrogate) {- end -= 1;- continue;- }- const candidate = value.slice(0, end);- if (encoder.encode(candidate).length <= maxBytes) {- return candidate;- }- end -= 1;- }- return "";-}-/*** Writes a batch of eve-owned attributes to the active workflow run.*@@ -122,14 +53,7 @@ export function truncateForTag(value: string, maxBytes = EVE_ATTRIBUTE_VALUE_MAX* the runtime throws a `FatalError` outside those contexts.*/export async function setEveAttributes(attrs: Record<string, EveAttributeValue>): Promise<void> {- const normalized: Record<string, string> = {};- for (const [key, value] of Object.entries(attrs)) {- if (value === undefined) {- continue;- }- const stringValue = typeof value === "number" ? String(value) : value;- normalized[key] = truncateForTag(stringValue);- }+ const normalized = normalizeEveAttributes(attrs);if (Object.keys(normalized).length === 0) {return;diff --git a/packages/eve/src/runtime/attributes/normalize.ts b/packages/eve/src/runtime/attributes/normalize.tsnew file mode 100644index 000000000..65e6745f6--- /dev/null+++ b/packages/eve/src/runtime/attributes/normalize.ts@@ -0,0 +1,58 @@+/**+ * Maximum UTF-8 byte size for one Workflow run attribute value.+ *+ * Mirrored from `ATTRIBUTE_VALUE_MAX_BYTES` in `@workflow/world` so the+ * normalization helper stays independent of the full world package.+ * `emit.drift.test.ts` guards the mirror against upstream changes.+ */+export const EVE_ATTRIBUTE_VALUE_MAX_BYTES = 256;++/** Attribute value accepted by eve's internal attribute builders. */+export type EveAttributeValue = string | number | undefined;++/**+ * Truncates a string to Workflow's UTF-8 byte budget without splitting+ * a surrogate pair.+ */+export function truncateForTag(value: string, maxBytes = EVE_ATTRIBUTE_VALUE_MAX_BYTES): string {+ if (maxBytes <= 0) {+ return "";+ }++ const encoder = new TextEncoder();+ const fullBytes = encoder.encode(value);+ if (fullBytes.length <= maxBytes) {+ return value;+ }++ let end = value.length;+ while (end > 0) {+ const lastCharCode = value.charCodeAt(end - 1);+ const endsOnHighSurrogate = lastCharCode >= 0xd800 && lastCharCode <= 0xdbff;+ if (endsOnHighSurrogate) {+ end -= 1;+ continue;+ }+ const candidate = value.slice(0, end);+ if (encoder.encode(candidate).length <= maxBytes) {+ return candidate;+ }+ end -= 1;+ }+ return "";+}++/** Normalizes sparse eve attributes into Workflow's string-only shape. */+export function normalizeEveAttributes(+ attrs: Record<string, EveAttributeValue>,+): Record<string, string> {+ const normalized: Record<string, string> = {};+ for (const [key, value] of Object.entries(attrs)) {+ if (value === undefined) {+ continue;+ }+ const stringValue = typeof value === "number" ? String(value) : value;+ normalized[key] = truncateForTag(stringValue);+ }+ return normalized;+}