Skip to content

Self-improving AI Employees for everyone

fix(temporal): carry agent transcript across continue-as-new; one wire standard; simple compaction

trohitg5f2c47e9ab37
diff --git a/server/models/agent_context.py b/server/models/agent_context.py
index eaf1cef2..3d0df25f 100644
--- a/server/models/agent_context.py
+++ b/server/models/agent_context.py
@@ -1,7 +1,7 @@
"""Durable Agent Context V2 contracts and normalized persistence records.
The public models in this module are deliberately payload-reference oriented.
-Only :class:`AgentContextEvent` may expose an exact ``MessageWireV2`` value,
+Only :class:`AgentContextEvent` may expose an exact ``MessageWire`` value,
and only when an authorized caller explicitly loads the journal. Workflow
graphs, node parameters, Temporal commands, status events, and ordinary node
outputs use :class:`AgentContextRef` instead.
@@ -50,7 +50,7 @@ class AgentContextEvent(BaseModel):
sequence: int = PydanticField(ge=1)
event_type: str
- message_wire_v2: Optional[dict[str, Any]] = None
+ message_wire: Optional[dict[str, Any]] = None
payload_ref: Optional[str] = None
operation_id: str
provider: Optional[str] = None
@@ -221,7 +221,7 @@ class AgentContextEventRecord(SQLModel, table=True):
epoch: int = Field(index=True)
sequence: int
event_type: str = Field(max_length=100)
- message_wire_v2: Optional[dict[str, Any]] = Field(
+ message_wire: Optional[dict[str, Any]] = Field(
default=None,
sa_column=Column(JSON, nullable=True),
)
diff --git a/server/nodes/context/_handlers.py b/server/nodes/context/_handlers.py
index 1e16f0f6..5ab1537b 100644
--- a/server/nodes/context/_handlers.py
+++ b/server/nodes/context/_handlers.py
@@ -24,7 +24,7 @@ from models.agent_context import (
from services.agent_context import (
AgentContextStore,
OpaqueCheckpointError,
- reconstruct_message_wire_v2,
+ reconstruct_transcript,
)
from services.agent_context.lifecycle import fence_context_provider_resources
from services.plugin import NodeUserError
@@ -440,7 +440,7 @@ async def _portable_handoff(
active = await store.load_active(thread.ref)
portable = True
try:
- _, messages = await reconstruct_message_wire_v2(
+ _, messages = await reconstruct_transcript(
store,
active.ref,
)
@@ -449,9 +449,9 @@ async def _portable_handoff(
# Historical opaque checkpoints cannot be translated. Preserve the
# exact observable tail and clearly mark the handoff as partial.
messages = [
- event.message_wire_v2
+ event.message_wire
for event in active.tail
- if event.message_wire_v2 is not None
+ if event.message_wire is not None
]
return await store.put_blob(
{
diff --git a/server/services/agent_context/__init__.py b/server/services/agent_context/__init__.py
index 52abc31c..4b4d4a41 100644
--- a/server/services/agent_context/__init__.py
+++ b/server/services/agent_context/__init__.py
@@ -17,7 +17,7 @@ from services.agent_context.store import (
from services.agent_context.runtime import (
AgentContextTransitionWriter,
OpaqueCheckpointError,
- reconstruct_message_wire_v2,
+ reconstruct_transcript,
reconstruct_messages,
)
from services.agent_context.compaction import (
@@ -51,6 +51,6 @@ __all__ = [
"get_provider_context_adapter",
"import_generation_zero_handoff",
"provider_context_request_options",
- "reconstruct_message_wire_v2",
+ "reconstruct_transcript",
"reconstruct_messages",
]
diff --git a/server/services/agent_context/compaction.py b/server/services/agent_context/compaction.py
index 8d6709e4..5857c453 100644
--- a/server/services/agent_context/compaction.py
+++ b/server/services/agent_context/compaction.py
@@ -288,7 +288,7 @@ class NativeOutputContextAdapter(PortableContextAdapter):
committed_prefix: Sequence[AgentContextEvent],
) -> Optional[ContextCompactionCandidate]:
for event in reversed(committed_prefix):
- wire = event.message_wire_v2
+ wire = event.message_wire
if not isinstance(wire, dict):
continue
state = wire.get("provider_state")
@@ -605,10 +605,10 @@ class AgentContextCompactionService:
else _base_messages(base_replay)
)
wires.extend(
- deepcopy(event.message_wire_v2)
+ deepcopy(event.message_wire)
for event in plan.committed_prefix
if event.sequence > snapshot_sequence
- and isinstance(event.message_wire_v2, dict)
+ and isinstance(event.message_wire, dict)
)
return wires
@@ -636,7 +636,7 @@ def _is_complete_transaction(
event = events[index]
if event.event_type in {"response.final", "response.truncated"}:
return True
- wire = event.message_wire_v2
+ wire = event.message_wire
if event.event_type == "message.assistant" and isinstance(wire, dict):
calls = wire.get("tool_calls")
return not isinstance(calls, list) or not calls
@@ -650,7 +650,7 @@ def _is_complete_transaction(
break
if assistant_index is None:
return False
- assistant_wire = events[assistant_index].message_wire_v2 or {}
+ assistant_wire = events[assistant_index].message_wire or {}
calls = assistant_wire.get("tool_calls")
if not isinstance(calls, list) or not calls:
return False
@@ -665,7 +665,7 @@ def _is_complete_transaction(
return False
if result.event_type != "message.tool_result":
continue
- result_wire = result.message_wire_v2 or {}
+ result_wire = result.message_wire or {}
completed.add(str(result_wire.get("tool_call_id") or ""))
return bool(requested) and requested.issubset(completed)
@@ -674,9 +674,9 @@ def _message_wires(
events: Sequence[AgentContextEvent],
) -> list[dict[str, Any]]:
return [
- deepcopy(event.message_wire_v2)
+ deepcopy(event.message_wire)
for event in events
- if isinstance(event.message_wire_v2, dict)
+ if isinstance(event.message_wire, dict)
]
diff --git a/server/services/agent_context/legacy.py b/server/services/agent_context/legacy.py
index eeeb268a..01fc0de0 100644
--- a/server/services/agent_context/legacy.py
+++ b/server/services/agent_context/legacy.py
@@ -96,7 +96,7 @@ async def _import_legacy_events(
f"{source.ref.thread_id}:{event.payload_hash}"
),
),
- message_wire_v2=dict(message_to_wire(message)),
+ message_wire=dict(message_to_wire(message)),
payload_ref=event.payload_ref,
provider="legacy",
)
diff --git a/server/services/agent_context/runtime.py b/server/services/agent_context/runtime.py
index 55244d5d..1ee89b6e 100644
--- a/server/services/agent_context/runtime.py
+++ b/server/services/agent_context/runtime.py
@@ -43,7 +43,7 @@ class AgentContextTransitionWriter:
event_type: str,
operation_id: str,
provider: str,
- message_wire_v2: Optional[dict[str, Any]] = None,
+ message_wire: Optional[dict[str, Any]] = None,
payload: Optional[dict[str, Any]] = None,
) -> AgentContextAppendResult:
payload_ref = (
@@ -57,14 +57,14 @@ class AgentContextTransitionWriter:
event_type=event_type,
operation_id=operation_id,
provider=provider,
- message_wire_v2=message_wire_v2,
+ message_wire=message_wire,
payload_ref=payload_ref,
)
self.ref = result.ref
return result
-async def reconstruct_message_wire_v2(
+async def reconstruct_transcript(
store: AgentContextStore,
ref: AgentContextRef,
) -> tuple[AgentContextRef, list[dict[str, Any]]]:
@@ -72,7 +72,7 @@ async def reconstruct_message_wire_v2(
Provider-native checkpoints are intentionally opaque and must be replayed
by that provider's context adapter. Portable checkpoints use a JSON
- object containing ``messages`` (or ``message_wire_v2`` /
+ object containing ``messages`` (or ``message_wire`` /
``replay_messages``) and can be reconstructed here.
"""
@@ -86,7 +86,7 @@ async def reconstruct_message_wire_v2(
elif isinstance(payload, dict):
candidates = (
payload.get("messages")
- or payload.get("message_wire_v2")
+ or payload.get("message_wire")
or payload.get("replay_messages")
)
else:
@@ -166,10 +166,10 @@ async def reconstruct_message_wire_v2(
)
)
wires.extend(
- dict(event.message_wire_v2)
+ dict(event.message_wire)
for event in state.tail
if event.sequence > snapshot_sequence
- and event.message_wire_v2 is not None
+ and event.message_wire is not None
)
return state.ref, wires
@@ -178,15 +178,15 @@ async def reconstruct_messages(
store: AgentContextStore,
ref: AgentContextRef,
) -> tuple[AgentContextRef, list[Message]]:
- """Typed convenience wrapper over :func:`reconstruct_message_wire_v2`."""
+ """Typed convenience wrapper over :func:`reconstruct_transcript`."""
- current_ref, wires = await reconstruct_message_wire_v2(store, ref)
+ current_ref, wires = await reconstruct_transcript(store, ref)
return current_ref, [message_from_wire(wire) for wire in wires]
__all__ = [
"AgentContextTransitionWriter",
"OpaqueCheckpointError",
- "reconstruct_message_wire_v2",
+ "reconstruct_transcript",
"reconstruct_messages",
]
diff --git a/server/services/agent_context/store.py b/server/services/agent_context/store.py
index 6154fed1..bce11823 100644
--- a/server/services/agent_context/store.py
+++ b/server/services/agent_context/store.py
@@ -35,7 +35,6 @@ from models.agent_context import (
from models.database import RuntimeMutation
from services.agent_context.listeners import notify_context_commit
from services.llm.protocol import (
- MESSAGE_WIRE_VERSION,
message_from_wire,
message_to_wire,
)
@@ -386,7 +385,7 @@ class AgentContextStore:
*,
event_type: str,
operation_id: str,
- message_wire_v2: Optional[dict[str, Any]] = None,
+ message_wire: Optional[dict[str, Any]] = None,
payload_ref: Optional[str] = None,
provider: Optional[str] = None,
expected_revision: Optional[int] = None,
@@ -399,7 +398,7 @@ class AgentContextStore:
_validate_identity("payload_ref", payload_ref, 512)
if provider is not None:
_validate_identity("provider", provider, 100)
- wire = _validate_message_wire(message_wire_v2)
+ wire = _validate_message_wire(message_wire)
for _ in range(_MAX_CAS_ATTEMPTS):
async with self._session() as session:
@@ -418,7 +417,7 @@ class AgentContextStore:
_assert_idempotent_event_reuse(
existing,
event_type=event_type,
- message_wire_v2=wire,
+ message_wire=wire,
payload_ref=payload_ref,
provider=provider,
)
@@ -443,7 +442,7 @@ class AgentContextStore:
sequence=sequence,
epoch=thread.epoch,
event_type=event_type,
- message_wire_v2=wire,
+ message_wire=wire,
payload_ref=payload_ref,
operation_id=operation_id,
provider=provider,
@@ -455,7 +454,7 @@ class AgentContextStore:
epoch=thread.epoch,
sequence=sequence,
event_type=event_type,
- message_wire_v2=deepcopy(wire),
+ message_wire=deepcopy(wire),
payload_ref=payload_ref,
operation_id=operation_id,
provider=provider,
@@ -968,7 +967,7 @@ class AgentContextStore:
sequence=next_sequence,
epoch=next_epoch,
event_type="provider_handoff",
- message_wire_v2=None,
+ message_wire=None,
payload_ref=handoff_payload_ref,
operation_id=handoff_operation,
provider=provider,
@@ -1521,7 +1520,7 @@ def _assert_idempotent_event_reuse(
existing: AgentContextEventRecord,
*,
event_type: str,
- message_wire_v2: Optional[dict[str, Any]],
+ message_wire: Optional[dict[str, Any]],
payload_ref: Optional[str],
provider: Optional[str],
) -> None:
@@ -1532,7 +1531,7 @@ def _assert_idempotent_event_reuse(
sequence=existing.sequence,
epoch=existing.epoch,
event_type=event_type,
- message_wire_v2=message_wire_v2,
+ message_wire=message_wire,
payload_ref=payload_ref,
operation_id=existing.operation_id,
provider=provider,
@@ -1540,7 +1539,7 @@ def _assert_idempotent_event_reuse(
)
if (
existing.event_type != event_type
- or existing.message_wire_v2 != message_wire_v2
+ or existing.message_wire != message_wire
or existing.payload_ref != payload_ref
or existing.provider != provider
or stored_hash != existing.payload_hash
@@ -1617,13 +1616,9 @@ def _validate_message_wire(
if value is None:
return None
if not isinstance(value, dict):
- raise TypeError("message_wire_v2 must be a JSON object")
- if value.get("version") != MESSAGE_WIRE_VERSION:
- raise ValueError(
- f"Context requires MessageWireV2 version {MESSAGE_WIRE_VERSION}"
- )
- # Round-tripping through the existing native codec enforces JSON-safe
- # provider state and preserves ordered blocks/tool calls.
+ raise TypeError("message_wire must be a JSON object")
+ # Round-tripping through the codec enforces JSON-safe provider state,
+ # preserves ordered blocks/tool calls, and rejects shapes with no role.
return dict(message_to_wire(message_from_wire(value)))
@@ -1632,7 +1627,7 @@ def _event_hash(
sequence: int,
epoch: int,
event_type: str,
- message_wire_v2: Optional[dict[str, Any]],
+ message_wire: Optional[dict[str, Any]],
payload_ref: Optional[str],
operation_id: str,
provider: Optional[str],
@@ -1642,7 +1637,7 @@ def _event_hash(
"sequence": sequence,
"epoch": epoch,
"event_type": event_type,
- "message_wire_v2": message_wire_v2,
+ "message_wire": message_wire,
"payload_ref": payload_ref,
"operation_id": operation_id,
"provider": provider,
@@ -1656,7 +1651,7 @@ def _event_record_hash(row: AgentContextEventRecord) -> str:
sequence=row.sequence,
epoch=row.epoch,
event_type=row.event_type,
- message_wire_v2=row.message_wire_v2,
+ message_wire=row.message_wire,
payload_ref=row.payload_ref,
operation_id=row.operation_id,
provider=row.provider,
@@ -1828,7 +1823,7 @@ def _to_event(row: AgentContextEventRecord) -> AgentContextEvent:
return AgentContextEvent(
sequence=row.sequence,
event_type=row.event_type,
- message_wire_v2=deepcopy(row.message_wire_v2),
+ message_wire=deepcopy(row.message_wire),
payload_ref=row.payload_ref,
operation_id=row.operation_id,
provider=row.provider,
diff --git a/server/services/agent_runtime.py b/server/services/agent_runtime.py
index b407bde3..3eff1d44 100644
--- a/server/services/agent_runtime.py
+++ b/server/services/agent_runtime.py
@@ -59,7 +59,7 @@ class AgentContextTransitionSink(Protocol):
event_type: str,
operation_id: str,
provider: str,
- message_wire_v2: Optional[Dict[str, Any]] = None,
+ message_wire: Optional[Dict[str, Any]] = None,
payload: Optional[Dict[str, Any]] = None,
) -> Any: ...
@@ -265,7 +265,7 @@ async def run_native_agent_loop(
event_type=event_type,
operation_id=f"{context_operation_id}:{operation_id}",
provider=provider,
- message_wire_v2=message_to_wire(message) if message else None,
+ message_wire=message_to_wire(message) if message else None,
payload=payload,
)
diff --git a/server/services/ai.py b/server/services/ai.py
index c9c9ae12..cc69e856 100644
--- a/server/services/ai.py
+++ b/server/services/ai.py
@@ -360,7 +360,7 @@ class AIService:
ContextCompactionPolicy,
import_generation_zero_handoff,
provider_context_request_options,
- reconstruct_message_wire_v2,
+ reconstruct_transcript,
)
from services.llm.protocol import (
Message,
@@ -439,13 +439,13 @@ class AIService:
ref = await import_generation_zero_handoff(store, ref)
# A provider transition is an epoch boundary. Opaque state remains
- # archived while the observable MessageWireV2 replay is handed off.
+ # archived while the observable MessageWire replay is handed off.
summary = await store.load_thread_summary(ref)
if (
summary.provider
and summary.provider != provider
):
- _, handoff_wires = await reconstruct_message_wire_v2(store, ref)
+ _, handoff_wires = await reconstruct_transcript(store, ref)
portable_handoff_wires: list[dict[str, Any]] = []
for handoff_wire in handoff_wires:
source_message = message_from_wire(handoff_wire)
@@ -510,7 +510,7 @@ class AIService:
exc,
)
- ref, history_wires = await reconstruct_message_wire_v2(store, ref)
+ ref, history_wires = await reconstruct_transcript(store, ref)
history = [message_from_wire(wire) for wire in history_wires]
policy = ContextCompactionPolicy.from_mapping(
context_data.get("policy")
diff --git a/server/services/cli_agent/context_bridge.py b/server/services/cli_agent/context_bridge.py
index f73d2dac..0d568ae4 100644
--- a/server/services/cli_agent/context_bridge.py
+++ b/server/services/cli_agent/context_bridge.py
@@ -29,7 +29,7 @@ from services.agent_context import (
AgentContextTransitionWriter,
OpaqueCheckpointError,
import_generation_zero_handoff,
- reconstruct_message_wire_v2,
+ reconstruct_transcript,
)
from services.llm.protocol import Message, message_from_wire, message_to_wire
@@ -96,9 +96,9 @@ async def _observable_handoff_messages(
"request.snapshot",
}:
continue
- if event.message_wire_v2 is not None:
+ if event.message_wire is not None:
if include_message_wires:
- messages.append(_portable_wire(event.message_wire_v2))
+ messages.append(_portable_wire(event.message_wire))
continue
payload = (
@@ -148,7 +148,7 @@ async def _build_portable_handoff(
fidelity = "portable"
reconstructed: list[dict[str, Any]] = []
try:
- _, reconstructed = await reconstruct_message_wire_v2(
+ _, reconstructed = await reconstruct_transcript(
store,
state.ref,
)
@@ -373,7 +373,7 @@ class SpecializedAgentContextBridge:
separators=(",", ":"),
)
return (
- "## Prior agent context (portable MessageWireV2 replay)\n"
+ "## Prior agent context (portable MessageWire replay)\n"
"The backend reconstructed the following committed context "
"from the previous provider. Treat it as prior conversation "
"state and continue from it.\n"
diff --git a/server/services/llm/__init__.py b/server/services/llm/__init__.py
index 694a8041..149d2368 100644
--- a/server/services/llm/__init__.py
+++ b/server/services/llm/__init__.py
@@ -12,10 +12,7 @@ from services.llm.config import (
build_headers,
)
from services.llm.protocol import (
- MESSAGE_WIRE_VERSION,
- NATIVE_MESSAGE_WIRE_VERSIONS,
- SUPPORTED_MESSAGE_WIRE_VERSIONS,
- MessageWireV2,
+ MessageWire,
ThinkingConfig,
ToolDef,
ToolCall,
@@ -60,10 +57,7 @@ __all__ = [
"resolve_temperature",
"build_headers",
# Protocol types
- "MESSAGE_WIRE_VERSION",
- "NATIVE_MESSAGE_WIRE_VERSIONS",
- "SUPPORTED_MESSAGE_WIRE_VERSIONS",
- "MessageWireV2",
+ "MessageWire",
"ThinkingConfig",
"ToolDef",
"ToolCall",
diff --git a/server/services/llm/protocol.py b/server/services/llm/protocol.py
index f703adfb..c03aad50 100644
--- a/server/services/llm/protocol.py
+++ b/server/services/llm/protocol.py
@@ -2,7 +2,7 @@
The dataclasses in this module deliberately contain only JSON-safe data. SDK
objects are useful while normalising a response, but must never leak into the
-agent/Temporal message history. ``MessageWireV2`` is represented as a plain
+agent/Temporal message history. ``MessageWire`` is represented as a plain
dictionary so it can be recorded by Temporal without a custom payload codec.
All providers implement :class:`LLMProvider` (structural typing via Protocol).
@@ -28,15 +28,6 @@ from typing import (
)
-MESSAGE_WIRE_VERSION = 2
-"""Current durable message representation version."""
-
-SUPPORTED_MESSAGE_WIRE_VERSIONS = frozenset({1, 2})
-"""Every durable version this worker can decode; never derive from current."""
-
-NATIVE_MESSAGE_WIRE_VERSIONS = frozenset({2})
-"""Versioned native-agent formats accepted by the Temporal activity."""
-
MAX_PROVIDER_STATE_DEPTH = 20
BINARY_STATE_MARKER = "__opencompany_bytes_base64__"
"""Marker used to persist SDK byte strings in ordinary JSON state."""
@@ -73,10 +64,9 @@ def decode_binary_state(value: Any) -> Any:
raise ValueError("Invalid durable binary-state base64") from exc
-class MessageWireV2(TypedDict):
- """Versioned JSON object recorded in memory and Temporal histories."""
+class MessageWire(TypedDict):
+ """The one JSON message shape recorded in memory and Temporal histories."""
- version: int
role: str
content: str
blocks: List[Dict[str, Any]]
@@ -473,15 +463,14 @@ class LLMError(Exception):
# ---------------------------------------------------------------------------
-# Durable MessageWireV2 codec
+# Durable MessageWire codec
# ---------------------------------------------------------------------------
-def message_to_wire(message: Message) -> MessageWireV2:
- """Serialize a message to the versioned, JSON-safe wire contract."""
+def message_to_wire(message: Message) -> MessageWire:
+ """Serialize a message to the JSON-safe wire contract."""
return {
- "version": MESSAGE_WIRE_VERSION,
"role": message.role,
"content": message.content,
"blocks": [_block_to_wire(block) for block in message.blocks],
@@ -493,26 +482,23 @@ def message_to_wire(message: Message) -> MessageWireV2:
def message_from_wire(value: Mapping[str, Any]) -> Message:
- """Decode MessageWireV2 (and the pre-version flat native shape)."""
+ """Decode the wire shape produced by :func:`message_to_wire`."""
- version = value.get("version", value.get("wire_version", 1))
- if version not in SUPPORTED_MESSAGE_WIRE_VERSIONS:
- raise ValueError(f"Unsupported message wire version: {version!r}")
+ if not isinstance(value, Mapping) or not (
+ value.get("role") or value.get("type")
+ ):
+ raise ValueError("Invalid message wire object: missing role")
calls = [
_tool_call_from_wire(call)
for call in value.get("tool_calls", ())
if isinstance(call, Mapping)
]
- blocks = (
- [
- _block_from_wire(block)
- for block in value.get("blocks", ())
- if isinstance(block, Mapping)
- ]
- if version in NATIVE_MESSAGE_WIRE_VERSIONS
- else []
- )
+ blocks = [
+ _block_from_wire(block)
+ for block in value.get("blocks", ())
+ if isinstance(block, Mapping)
+ ]
return Message(
role=str(value.get("role") or value.get("type") or "user"),
content=str(value.get("content") or ""),
@@ -524,7 +510,7 @@ def message_from_wire(value: Mapping[str, Any]) -> Message:
)
-def messages_to_wire(messages: Iterable[Message]) -> List[MessageWireV2]:
+def messages_to_wire(messages: Iterable[Message]) -> List[MessageWire]:
return [message_to_wire(message) for message in messages]
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 996e0d4c..0a64b276 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -935,43 +935,6 @@ class BaseNode:
from core.container import container
from services.status_broadcaster import get_status_broadcaster
- if context.get("protocol") == "agent-context-tool-v2":
- from services.temporal.agent_activities import (
- execute_tool_activity,
- )
-
- pending = dict(context.get("pending_tool") or {})
- tool_node_id = str(pending.get("node_id") or "")
- activity.heartbeat(
- f"Executing Context V2 tool {cls.type}: {tool_node_id}"
- )
- beat_task: Optional[asyncio.Task] = None
- if cls.start_to_close_timeout > cls.heartbeat_timeout:
-
- async def _tool_beat_loop() -> None:
- while True:
- await asyncio.sleep(30)
- activity.heartbeat(
- f"Still executing Context V2 tool "
- f"{cls.type}: {tool_node_id}"
- )
-
- beat_task = asyncio.create_task(_tool_beat_loop())
- try:
- result = await execute_tool_activity(
- context,
- expected_node_type=cls.type,
- expected_version=cls.version,
- )
- activity.heartbeat(
- f"Context V2 tool {cls.type} completed: "
- f"{tool_node_id}"
- )
- return result
- finally:
- if beat_task is not None:
- beat_task.cancel()
-
node_id = context["node_id"]
workflow_id = context.get("workflow_id")
execution_id = context.get("execution_id")
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index ab6528a6..374f12be 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -16,9 +16,10 @@ RFC §6.3 plus the F4 deferred follow-up). Activities defined here:
``services.ai`` uses today. Per user decision (plan §15) memory
appends per turn, not on completion, so workflow failures don't lose
progress.
-- :func:`compact_agent_memory` — invoke ``CompactionService.compact_context``
- when token thresholds trip. Returns the compacted summary message
- list. Token accounting stays in the workflow state.
+- :func:`compact_context` — summarize the live conversation via
+ ``CompactionService`` when token thresholds trip. The workflow swaps
+ its ``messages`` for the summary; token accounting stays in the
+ workflow state.
Determinism: every activity is a leaf computation (LLM ainvoke, DB
write, summarisation). The workflow that calls them is sandboxed=False
@@ -40,7 +41,7 @@ import hashlib
import json
import logging
import re
-from typing import Any, Dict, Iterable, List, Mapping, Optional
+from typing import Any, Dict, List, Mapping, Optional
from temporalio import activity
from temporalio.exceptions import ApplicationError
@@ -49,12 +50,6 @@ from models.agent_context import AgentContextRef
logger = logging.getLogger(__name__)
-# The only engine there is. Kept as a named constant rather than inlined
-# because it is written into Temporal history by ``prepare_agent_payload``
-# and read back by ``execute_llm_step`` to detect pre-cutover runs.
-_NATIVE_LLM_ENGINE = "native"
-
-
# Activity result shapes — keep these in sync with AgentWorkflow's
# expectations. Pydantic was considered but plain dicts keep the
# payload-serialisation cost flat (Temporal serialises via JSON anyway)
@@ -234,8 +229,6 @@ async def _execute_native_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
from services.llm.messages import filter_empty_messages
from services.llm.protocol import (
LLMError,
- MESSAGE_WIRE_VERSION,
- NATIVE_MESSAGE_WIRE_VERSIONS,
Message,
ThinkingConfig,
ToolDef,
@@ -243,18 +236,6 @@ async def _execute_native_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
messages_from_wire,
)
- wire_version = int(
- payload.get("message_wire_version") or MESSAGE_WIRE_VERSION
- )
- if wire_version not in NATIVE_MESSAGE_WIRE_VERSIONS:
- from temporalio.exceptions import ApplicationError
-
- raise ApplicationError(
- f"Unsupported native message wire version {wire_version}",
- type="InvalidAgentMessageWireVersion",
- non_retryable=True,
- )
-
messages = filter_empty_messages(
messages_from_wire(payload.get("messages") or [])
)
@@ -372,7 +353,7 @@ async def _journal_llm_turn(
Observation only: it never influences the request. ``request.snapshot``
carries the exact list sent, which is what
- :func:`services.agent_context.runtime.reconstruct_message_wire_v2`
+ :func:`services.agent_context.runtime.reconstruct_transcript`
documents that event to be — the render boundary that later assistant and
tool transitions are applied on top of.
"""
@@ -398,7 +379,7 @@ async def _journal_llm_turn(
event_type="message.assistant",
operation_id=f"{operation_id}:assistant",
provider=provider,
- message_wire_v2=assistant_wire,
+ message_wire=assistant_wire,
)
except Exception:
# Observation must never fail the run. The provider has already been
@@ -454,28 +435,6 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
)
activity.heartbeat(f"LLM step starting: {payload.get('model')}")
- # ``agent.prepare_payload.v1`` records the engine marker. Its absence
- # means the run predates the native cutover, when conversation state was
- # serialised in a retired wire format the native reader cannot
- # interpret. Failing loudly is the honest outcome: reinterpreting those
- # messages would silently corrupt the conversation.
- engine = str(payload.get("llm_engine") or "").strip().lower()
- if engine != _NATIVE_LLM_ENGINE:
- from temporalio.exceptions import ApplicationError
-
- detail = (
- "was started before the native LLM cutover, so its conversation "
- "state is in a retired wire format"
- if not engine
- else f"records an unsupported LLM engine {engine!r}"
- )
- raise ApplicationError(
- f"This agent run {detail} and cannot continue. Reset the workflow "
- "to start a new generation.",
- type="InvalidAgentLLMEngine",
- non_retryable=True,
- )
-
result = await _execute_native_llm_step(payload)
activity.heartbeat("LLM step: model returned")
return result
@@ -560,61 +519,6 @@ async def persist_agent_turn(payload: Dict[str, Any]) -> Dict[str, Any]:
}
[email protected](name="agent.compact_memory")
-async def compact_agent_memory(payload: Dict[str, Any]) -> Dict[str, Any]:
- """Compact the running conversation when token budget exceeded.
-
- Wraps ``CompactionService.compact_context`` (existing, in
- ``services/compaction.py``) so the workflow can replace its
- ``messages`` list with the summary message when needed.
-
- ``payload``::
-
- {
- "session_id": str,
- "node_id": str,
- "memory_content": str,
- "provider": str,
- "node_id": str,
- "model": str,
- }
-
- Returns ``{"success": bool, "summary": str, "tokens_before": int,
- "tokens_after": int, "usage": dict}``. Caller replaces its ``messages``
- with a single summary, resets only the context-threshold counter, and
- retains both pre-compaction and summarizer usage for final billing.
- """
- from services.compaction import get_compaction_service
-
- activity.heartbeat("Compacting agent memory")
- svc = get_compaction_service()
- if svc is None:
- # CompactionService is a Singleton wired by the FastAPI lifespan
- # (main.py). If the worker activity runs before lifespan init,
- # the singleton is None and compaction must no-op so the agent
- # loop keeps running — the workflow checks ``success`` and
- # keeps the existing messages list on False.
- return {
- "success": False,
- "error": "CompactionService not initialized (worker bootstrap race)",
- "summary": "",
- "tokens_before": 0,
- "tokens_after": 0,
- "usage": {},
- }
- return await svc.compact_context(
- session_id=payload["session_id"],
- node_id=payload["node_id"],
- memory_content=payload.get("memory_content", ""),
- provider=payload["provider"],
- api_key=await _resolve_activity_api_key(payload),
- model=payload["model"],
- # Temporal owns activity retries; never repeat an ambiguous provider
- # request inside the activity or SDK.
- explicit_max_retries=0,
- )
-
-
@activity.defn(name="agent.broadcast_progress")
async def broadcast_agent_progress(payload: Dict[str, Any]) -> Dict[str, Any]:
"""Emit a CloudEvents-shaped ``agent_progress`` broadcast per turn.
@@ -1181,7 +1085,10 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
svc = get_compaction_service()
if svc is not None:
cfg = await svc.anthropic_config(model=model, provider=provider)
- compaction_threshold = int(cfg.get("context_token_threshold") or 0) or None
+ # A disabled service must actually disable compaction — the
+ # workflow treats a falsy threshold as "never compact".
+ if cfg.get("enabled"):
+ compaction_threshold = int(cfg.get("context_token_threshold") or 0) or None
except Exception: # noqa: BLE001 — defensive, optional feature
compaction_threshold = None
@@ -1246,10 +1153,6 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
except Exception: # noqa: BLE001 — last-resort fallback
effective_recursion_limit = 200
- from services.llm.protocol import MESSAGE_WIRE_VERSION
-
- message_wire_version = MESSAGE_WIRE_VERSION
-
return {
"node_id": node_id,
"node_type": node_type,
@@ -1280,11 +1183,6 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
or context.get("execution_id")
or ""
),
- # The marker `execute_llm_step` checks: a history without it
- # predates the native cutover and carries messages in a retired wire
- # format that can no longer be read.
- "llm_engine": _NATIVE_LLM_ENGINE,
- "message_wire_version": message_wire_version,
}
@@ -1904,7 +1802,6 @@ def collect_agent_activities() -> List[Any]:
return [
execute_llm_step,
persist_agent_turn,
- compact_agent_memory,
prepare_agent_payload,
broadcast_agent_progress,
store_agent_output,
@@ -1925,28 +1822,20 @@ def collect_agent_activities() -> List[Any]:
register_task_execution,
finish_agent_delegation,
finalize_agent_team,
- # Context journal surface (formerly collect_agent_v2_activities).
- # NOTE: execute_tool_activity is deliberately absent — it is a
- # plain coroutine invoked by each plugin's own activity wrapper in
- # services/plugin/base.py, not a Temporal activity of its own.
+ # Context journal surface: thread resolution for the view-only
+ # journal, plus the conversation summarizer.
prepare_context,
- reconstruct_context_messages,
- append_context,
compact_context,
]
# ---------------------------------------------------------------------------
-# Agent Context journal surface.
-#
-# Moved here from the retired ``agent_activities_v2`` module so there is a
-# single agent-activity module. These five activities own the backend
-# execution journal: the request snapshot, the LLM step, tool-result and
-# assistant appends, and compaction.
+# Agent Context journal surface (view-only).
#
-# ``execute_tool_activity`` is NOT Temporal-only -- ``services/plugin/base.py``
-# calls it from every plugin's ``as_activity()`` when the node context carries
-# ``protocol == "agent-context-tool-v2"``, so it must stay importable from here.
+# The journal observes the agent; it never feeds the request and is never
+# read back on rollover — continue_as_new carries the live transcript.
+# ``_journal_llm_turn`` records each turn, ``prepare_context`` resolves the
+# thread, and ``compact_context`` summarizes the live conversation.
# ---------------------------------------------------------------------------
_SENSITIVE_GRAPH_KEYS = frozenset(
@@ -2072,55 +1961,6 @@ def _tool_identity(tool: Mapping[str, Any]) -> Dict[str, Any]:
"version": int(tool.get("version") or 1),
"task_queue": str(tool.get("dispatch_task_queue") or ""),
}
-def _validate_unique_tool_names(
- tools: Iterable[Mapping[str, Any]],
- *,
- phase: str,
-) -> None:
- """Reject an ambiguous provider-visible tool surface.
-
- A dict comprehension would otherwise silently select the last connected
- node. Validation belongs in this backend preparation/rebind boundary,
- before another provider request can be billed.
- """
-
- seen: Dict[str, str] = {}
- conflicts: Dict[str, set[str]] = {}
- for tool in tools:
- if tool.get("llm_hidden"):
- continue
- name = str(tool.get("name") or "").strip()
- if not name:
- continue
- node_id = str(tool.get("tool_node_id") or "")
- previous = seen.get(name)
- if previous is None:
- seen[name] = node_id
- continue
- conflicts.setdefault(name, {previous}).add(node_id)
- if conflicts:
- details = ", ".join(
- f"{name!r} ({', '.join(sorted(node_ids))})"
- for name, node_ids in sorted(conflicts.items())
- )
- raise _non_retryable(
- (
- f"Context V2 {phase} rejected duplicate canonical tool "
- f"name(s): {details}"
- ),
- "DuplicateAgentToolName",
- )
-async def _runtime_config(
- store: Any,
- payload_ref: str,
-) -> Dict[str, Any]:
- value = await store.get_blob(payload_ref)
- if not isinstance(value, dict) or value.get("protocol") != "agent-context-v2":
- raise _non_retryable(
- "The Context V2 runtime snapshot is missing or invalid.",
- "InvalidAgentContextRuntimeSnapshot",
- )
- return value
async def _append_event(
store: Any,
ref: AgentContextRef,
@@ -2128,7 +1968,7 @@ async def _append_event(
event_type: str,
operation_id: str,
provider: Optional[str] = None,
- message_wire_v2: Optional[Dict[str, Any]] = None,
+ message_wire: Optional[Dict[str, Any]] = None,
payload_ref: Optional[str] = None,
) -> AgentContextRef:
result = await store.append_transition(
@@ -2136,7 +1976,7 @@ async def _append_event(
event_type=event_type,
operation_id=operation_id,
provider=provider,
- message_wire_v2=message_wire_v2,
+ message_wire=message_wire,
payload_ref=payload_ref,
)
return result.ref
@@ -2187,839 +2027,83 @@ async def prepare_context(payload: Dict[str, Any]) -> Dict[str, Any]:
return {"context_ref": _ref_dict(thread)}
[email protected](name="agent.reconstruct_context_messages")
-async def reconstruct_context_messages(payload: Dict[str, Any]) -> Dict[str, Any]:
- """Replay a Context thread's active transcript. Read-only.
-
- Used only by ``AgentWorkflow`` after ``continue_as_new``. A rollover
- carries references, not the conversation, so without this the resumed run
- rebuilds ``messages`` from system + memory + prompt alone and the agent
- silently forgets everything it had said — but only when a Context node is
- attached, since the rollover itself is gated on ``context_ref``.
-
- Returns ``{"messages": [...], "restored": bool, "reason": str}``. A thread
- that cannot be replayed reports ``restored: False`` rather than raising, so
- the workflow falls back to the freshly built list instead of failing a run
- over a rehydration miss.
- """
-
- ref_data = payload.get("context_ref") or {}
- if not ref_data:
- return {"messages": [], "restored": False, "reason": "no_context_ref"}
-
- from services.agent_context import (
- OpaqueCheckpointError,
- reconstruct_message_wire_v2,
- )
-
- store = _context_store()
- try:
- _ref, wires = await reconstruct_message_wire_v2(
- store, _context_ref(ref_data)
- )
- except OpaqueCheckpointError:
- # A provider-native checkpoint holds opaque continuation state, not a
- # message list. The provider itself carries that context, so the
- # rebuilt prompt is the correct fallback.
- return {"messages": [], "restored": False, "reason": "opaque_checkpoint"}
- except Exception as exc: # noqa: BLE001 -- never fail a run over replay
- activity.logger.warning(
- "Context transcript replay failed; resuming from the rebuilt "
- f"prompt instead: {exc!r}"
- )
- return {"messages": [], "restored": False, "reason": "replay_failed"}
-
- messages = [dict(wire) for wire in wires]
- return {
- "messages": messages,
- "restored": bool(messages),
- "reason": "ok" if messages else "empty_thread",
- }
-
-
-def _pending_tool_identities(
- calls: Iterable[Mapping[str, Any]],
- configured_tools: Iterable[Mapping[str, Any]],
-) -> List[Dict[str, Any]]:
- index = {
- str(tool.get("name") or ""): tool
- for tool in configured_tools
- if not tool.get("llm_hidden")
- }
- pending: List[Dict[str, Any]] = []
- for call_index, call in enumerate(calls, start=1):
- name = str(call.get("name") or "")
- tool = index.get(name) or {}
- pending.append(
- {
- "call_index": call_index,
- "call_id": str(
- call.get("id") or f"call-{call_index}"
- ),
- "name": name,
- "node_id": str(tool.get("tool_node_id") or ""),
- "node_type": str(tool.get("node_type") or ""),
- "version": int(tool.get("version") or 1),
- "task_queue": str(
- tool.get("dispatch_task_queue") or ""
- ),
- "known": bool(tool),
- }
- )
- return pending
-def _find_call(
- response: Mapping[str, Any],
- pending: Mapping[str, Any],
-) -> Dict[str, Any]:
- call_index = int(pending.get("call_index") or 0)
- calls = list(response.get("calls") or [])
- if call_index < 1 or call_index > len(calls):
- raise _non_retryable(
- "Pending Context V2 tool identity does not match its response.",
- "InvalidPendingAgentTool",
- )
- call = dict(calls[call_index - 1])
- if (
- str(call.get("name") or "") != str(pending.get("name") or "")
- or str(call.get("id") or f"call-{call_index}")
- != str(pending.get("call_id") or "")
- ):
- raise _non_retryable(
- "Pending Context V2 tool identity hash boundary was violated.",
- "InvalidPendingAgentTool",
- )
- return call
-async def _validate_tool_args(
- tool: Mapping[str, Any],
- call: Mapping[str, Any],
-) -> tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
- if call.get("parse_error"):
- return None, {
- "error": "Tool arguments were invalid JSON",
- "detail": str(call.get("parse_error") or ""),
- "raw_arguments": str(call.get("raw_arguments") or ""),
- }
- args = call.get("args") or {}
- if not isinstance(args, dict):
- return None, {
- "error": "Tool arguments must be an object",
- }
-
- definition = dict(tool.get("definition") or {})
- schema = dict(
- definition.get("parameters")
- or {"type": "object", "properties": {}}
- )
- try:
- from jsonschema import Draft202012Validator
-
- Draft202012Validator(schema).validate(args)
- except Exception as exc:
- return None, {
- "error": "Invalid tool arguments",
- "details": str(exc),
- }
-
- # Security-sensitive ToolInput models also validate through the plugin
- # boundary so model arguments cannot replace persisted configuration.
- from services.node_registry import get_node_class
-
- node_cls = get_node_class(str(tool.get("node_type") or ""))
- if node_cls is not None:
- model_factory = getattr(node_cls, "tool_input_model", None)
- if callable(model_factory):
- try:
- model = model_factory()
- value = model.model_validate(args)
- return (
- value.model_dump(mode="json", exclude_unset=True),
- None,
- )
- except Exception as exc:
- return None, {
- "error": "Invalid tool arguments",
- "details": str(exc),
- }
- return dict(args), None
-async def _execute_tool_and_append(
- *,
- store: Any,
- ref: AgentContextRef,
- runtime_config: Dict[str, Any],
- runtime_config_ref: str,
- response_ref: str,
- pending: Dict[str, Any],
- operation_id: str,
- iteration: int,
-) -> Dict[str, Any]:
- from core.container import container
- from services.handlers.tools import execute_tool
- from services.llm.protocol import Message, message_to_wire
- from services.node_registry import get_node_class
[email protected](name="agent.compact_context")
+async def compact_context(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Summarize the live conversation into a compact replacement.
- prepared = dict(runtime_config["prepared"])
- provider = str(prepared.get("provider") or "")
- response = await store.get_blob(response_ref)
- if not isinstance(response, dict):
- raise _non_retryable(
- "Context V2 response reference is invalid.",
- "InvalidAgentContextResponse",
- )
- call = _find_call(response, pending)
- tool = next(
- (
- item
- for item in prepared.get("tools") or []
- if str(item.get("name") or "") == str(call.get("name") or "")
- and not item.get("llm_hidden")
- ),
- None,
- )
+ Simple by design: render the wire messages to text, ask
+ ``CompactionService`` for its five-section summary, return it. The
+ workflow swaps its ``messages`` for the summary. No journal side
+ effects and no checkpoints — the next LLM turn journals a fresh
+ ``request.snapshot`` containing the compacted messages, so the
+ Context panel and any later rollover see the compacted state
+ naturally.
- if tool is None:
- tool_result: Any = {
- "error": (
- f"Tool {call.get('name')!r} is not connected to this agent."
- )
- }
- else:
- args, validation_error = await _validate_tool_args(tool, call)
- if validation_error is not None:
- tool_result = validation_error
- else:
- source_context = dict(runtime_config.get("source_context") or {})
- node_cls = get_node_class(str(tool.get("node_type") or ""))
- needs_canvas = bool(
- node_cls is not None
- and getattr(node_cls, "needs_canvas", False)
- )
- tool_info = dict(tool.get("tool_info") or {})
- execution = {
- "node_type": str(tool.get("node_type") or ""),
- "node_id": str(tool.get("tool_node_id") or ""),
- "parameters": dict(tool_info.get("parameters") or {}),
- "label": str(
- tool_info.get("label")
- or tool.get("node_type")
- or call.get("name")
- or "tool"
- ),
- "connected_services": list(
- tool_info.get("connected_services") or []
- ),
- "workflow_id": runtime_config.get("workflow_id"),
- "ai_service": container.ai_service(),
- "database": container.database(),
- "parent_node_id": runtime_config.get("agent_node_id"),
- "provider": provider,
- "nodes": source_context.get("nodes") if needs_canvas else [],
- "edges": source_context.get("edges") if needs_canvas else [],
- "workspace_dir": source_context.get("workspace_dir") or "",
- "session_id": source_context.get("session_id") or "default",
- "user_id": source_context.get("user_id") or "owner",
- "execution_id": source_context.get("execution_id"),
- "root_execution_id": source_context.get("root_execution_id"),
- "tool_call_id": str(call.get("id") or ""),
- "operation_id": operation_id,
- "delegation_depth": source_context.get("delegation_depth", 0),
- "team_id": source_context.get("team_id"),
- "max_concurrent_subagents": prepared.get(
- "max_concurrent_subagents", 3
- ),
- "max_delegation_depth": prepared.get(
- "max_delegation_depth", 2
- ),
- "auto_rebind_tools": bool(
- prepared.get("auto_rebind_tools", True)
- ),
- }
- try:
- tool_result = await execute_tool(
- str(call.get("name") or ""),
- args or {},
- execution,
- )
- except Exception as exc:
- # Tool failures are exact observable outcomes and are returned
- # to the model rather than failing the whole agent loop.
- tool_result = {
- "error": str(exc),
- "error_type": type(exc).__name__,
- }
+ ``payload``::
- try:
- tool_content = json.dumps(
- tool_result,
- ensure_ascii=False,
- default=str,
- )
- except Exception:
- tool_content = str(tool_result)
- result_ref = await store.put_blob(
{
- "tool_call_id": str(call.get("id") or pending.get("call_id") or ""),
- "tool_name": str(call.get("name") or ""),
- "result": tool_result,
- "iteration": iteration,
+ "session_id": str,
+ "node_id": str,
+ "messages": [<message wire>], # the live transcript
+ "provider": str,
+ "model": str,
}
- )
- tool_message = Message(
- role="tool",
- content=tool_content,
- tool_call_id=str(call.get("id") or pending.get("call_id") or ""),
- name=str(call.get("name") or ""),
- )
- from services.llm.media import image_blocks_from_tool_result
-
- # Tools opt into vision via `llm_media`; blocks journal as ~450 B refs.
- tool_message.blocks.extend(image_blocks_from_tool_result(tool_result))
- ref = await _append_event(
- store,
- ref,
- event_type="message.tool_result",
- operation_id=f"{operation_id}:result",
- provider=provider,
- message_wire_v2=message_to_wire(tool_message),
- payload_ref=result_ref,
- )
-
- # Canvas-mutating tools can rebind newly-created tool identities without
- # placing their schemas or operation results in Event History.
- next_runtime_ref = runtime_config_ref
- operations = (
- tool_result.get("operations") or []
- if isinstance(tool_result, dict)
- else []
- )
- if operations and prepared.get("auto_rebind_tools", True):
- from services.temporal.agent_activities import refresh_agent_tools
-
- refreshed = await refresh_agent_tools(
- {
- "operations": operations,
- "agent_node_type": prepared.get("node_type"),
- }
- )
- additions = list(refreshed.get("tools") or [])
- _validate_unique_tool_names(
- [*(prepared.get("tools") or []), *additions],
- phase="hot rebind",
- )
- if additions:
- prepared["tools"] = [
- *(prepared.get("tools") or []),
- *additions,
- ]
- runtime_config = {
- **runtime_config,
- "prepared": prepared,
- }
- next_runtime_ref = await store.put_blob(runtime_config)
- ref = await _append_event(
- store,
- ref,
- event_type="request.tools_rebound",
- operation_id=f"{operation_id}:rebind",
- provider=provider,
- payload_ref=next_runtime_ref,
- )
- return {
- "context_ref": _ref_dict(ref),
- "runtime_config_ref": next_runtime_ref,
- "result_ref": result_ref,
- "result_hash": _hash_from_ref(result_ref),
- }
-async def execute_tool_activity(
- payload: Dict[str, Any],
- *,
- expected_node_type: str,
- expected_version: int,
-) -> Dict[str, Any]:
- """Execute one Context V2 tool from its plugin-owned activity.
-
- The Temporal payload contains only hashes, Context references, and the
- pending tool identity. Tool arguments and persisted configuration remain
- in ``AgentContextStore`` and are loaded inside the activity.
+ Returns ``{"success": bool, "summary": str, "usage": dict}``.
"""
- if payload.get("protocol") != "agent-context-tool-v2":
- raise _non_retryable(
- "The plugin activity received an invalid Context V2 tool payload.",
- "InvalidAgentToolActivityPayload",
- )
- pending = dict(payload.get("pending_tool") or {})
- if (
- not pending.get("known")
- or str(pending.get("node_type") or "") != expected_node_type
- or int(pending.get("version") or 0) != int(expected_version)
- ):
- raise _non_retryable(
- "The pending tool identity does not match the dispatched plugin.",
- "InvalidPendingAgentTool",
- )
-
- store = _context_store()
- ref = _context_ref(payload["context_ref"])
- runtime_config_ref = str(payload["runtime_config_ref"])
- config = await _runtime_config(store, runtime_config_ref)
- configured = next(
- (
- item
- for item in config["prepared"].get("tools") or []
- if str(item.get("name") or "") == str(pending.get("name") or "")
- ),
- None,
- )
- if (
- not isinstance(configured, dict)
- or str(configured.get("tool_node_id") or "")
- != str(pending.get("node_id") or "")
- or str(configured.get("node_type") or "") != expected_node_type
- or int(configured.get("version") or 1) != int(expected_version)
- ):
- raise _non_retryable(
- "The persisted tool binding no longer matches the pending identity.",
- "InvalidPendingAgentTool",
- )
-
- return await _execute_tool_and_append(
- store=store,
- ref=ref,
- runtime_config=config,
- runtime_config_ref=runtime_config_ref,
- response_ref=str(payload["response_ref"]),
- pending=pending,
- operation_id=str(payload["operation_id"]),
- iteration=int(payload.get("iteration") or 0),
- )
-async def _lifetime_usage(
- store: Any,
- ref: AgentContextRef,
- operation_prefix: str,
-) -> Dict[str, int]:
- totals: Dict[str, int] = {}
- after = 0
- while True:
- page, next_after = await store.load_journal_page(
- ref,
- after_sequence=after,
- limit=200,
- epoch=ref.epoch,
- )
- for event in page:
- if (
- event.event_type
- not in {"message.assistant", "context.compacted"}
- or not event.payload_ref
- or not event.operation_id.startswith(operation_prefix)
- ):
- continue
- value = await store.get_blob(event.payload_ref)
- if not isinstance(value, dict):
- continue
- for key, amount in (value.get("usage") or {}).items():
- if isinstance(amount, int):
- totals[key] = totals.get(key, 0) + amount
- if next_after is None:
- break
- after = next_after
- return totals
-async def _finalize(
- *,
- store: Any,
- ref: AgentContextRef,
- runtime_config: Dict[str, Any],
- response_ref: str,
- operation_id: str,
- truncated: bool,
-) -> Dict[str, Any]:
- from core.container import container
-
- response = await store.get_blob(response_ref)
- if not isinstance(response, dict):
- raise _non_retryable(
- "Context V2 final response reference is invalid.",
- "InvalidAgentContextResponse",
- )
- prepared = dict(runtime_config["prepared"])
- operation_prefix = str(runtime_config.get("operation_prefix") or "")
- usage = await _lifetime_usage(store, ref, operation_prefix)
- result = {
- "response": str(response.get("content") or ""),
- "thinking": response.get("thinking"),
- "model": prepared.get("model"),
- "provider": prepared.get("provider"),
- "usage": usage,
- "execution_id": (
- runtime_config.get("source_context") or {}
- ).get("execution_id"),
- "root_execution_id": (
- runtime_config.get("source_context") or {}
- ).get("root_execution_id"),
- "truncated": truncated,
- }
- output_ref = await store.put_blob(result)
- ref = await _append_event(
- store,
- ref,
- event_type=(
- "response.truncated" if truncated else "response.final"
- ),
- operation_id=f"{operation_id}:response",
- provider=str(prepared.get("provider") or ""),
- payload_ref=output_ref,
- )
-
- workflow_service = container.workflow_service()
- session_id = str(
- (runtime_config.get("source_context") or {}).get("session_id")
- or "default"
- )
- node_id = str(runtime_config.get("agent_node_id") or "")
- for output_name in ("output_main", "output_top", "output_0"):
- await workflow_service.store_node_output(
- session_id,
- node_id,
- output_name,
- result,
- )
-
- try:
- from services.skill_runtime import clear_skill_turn
+ from services.compaction import get_compaction_service
+ from services.llm.protocol import message_from_wire
- await clear_skill_turn(
- str(runtime_config.get("workflow_id") or ""),
- str(
- (runtime_config.get("source_context") or {}).get(
- "execution_id"
- )
- or ""
+ activity.heartbeat("Compacting agent context")
+ svc = get_compaction_service()
+ if svc is None:
+ # Singleton wired by the FastAPI lifespan (main.py). A worker
+ # bootstrap race must not kill the run — the workflow checks
+ # ``success`` and keeps its existing messages on False.
+ return {
+ "success": False,
+ "error": (
+ "CompactionService not initialized (worker bootstrap race)"
),
- node_id,
- )
- except Exception:
- activity.logger.exception(
- "Context V2 finalization could not clear active skills"
- )
-
- return {
- "context_ref": _ref_dict(ref),
- "output_ref": output_ref,
- "response_hash": _hash_from_ref(response_ref),
- }
[email protected](name="agent.append_context")
-async def append_context(payload: Dict[str, Any]) -> Dict[str, Any]:
- """Record an unknown tool outcome or finalize a persisted response."""
-
- from services.llm.protocol import Message, message_to_wire
+ "summary": "",
+ "usage": {},
+ }
- store = _context_store()
- ref = _context_ref(payload["context_ref"])
- runtime_config_ref = str(payload["runtime_config_ref"])
- config = await _runtime_config(store, runtime_config_ref)
- action = str(payload.get("action") or "")
- operation_id = str(payload["operation_id"])
- iteration = int(payload.get("iteration") or 0)
-
- if action == "record_unknown_tool":
- pending = dict(payload["pending_tool"])
- if pending.get("known"):
- raise _non_retryable(
- "Known tools must execute on their plugin-owned activity.",
- "InvalidAgentToolActivityPayload",
+ lines: List[str] = []
+ for wire in payload.get("messages") or []:
+ if not isinstance(wire, dict):
+ continue
+ try:
+ message = message_from_wire(wire)
+ except Exception:
+ continue
+ line = f"{message.role.upper()}: {message.content}"
+ if message.tool_calls:
+ line += "\nTOOL_CALLS: " + json.dumps(
+ [
+ {"name": call.name, "args": call.args}
+ for call in message.tool_calls
+ ],
+ ensure_ascii=False,
+ default=str,
)
- return await _execute_tool_and_append(
- store=store,
- ref=ref,
- runtime_config=config,
- runtime_config_ref=runtime_config_ref,
- response_ref=str(payload["response_ref"]),
- pending=pending,
- operation_id=operation_id,
- iteration=iteration,
- )
- if action == "append_messages":
- # Journal turns that were produced outside a journaling activity.
- # The agent loop executes tools through its own per-type and
- # delegation paths, so their results never pass through
- # ``_execute_tool_and_append``; without this the journal loses every
- # tool result and the next reconstruction replays an assistant turn
- # whose tool calls have no answers.
- wires = list(payload.get("messages") or [])
- current = ref
- for offset, wire in enumerate(wires):
- if not isinstance(wire, dict):
- continue
- current = await _append_event(
- store,
- current,
- event_type=str(payload.get("event_type") or "message.tool"),
- operation_id=f"{operation_id}:{offset}",
- provider=str(config.get("prepared", {}).get("provider") or ""),
- message_wire_v2=wire,
+ if message.tool_call_id:
+ line += (
+ f"\nTOOL_RESULT_FOR: {message.name or message.tool_call_id}"
)
- return {"context_ref": _ref_dict(current), "appended": len(wires)}
-
- if action == "finalize":
- return await _finalize(
- store=store,
- ref=ref,
- runtime_config=config,
- response_ref=str(payload["response_ref"]),
- operation_id=operation_id,
- truncated=False,
- )
- if action == "truncate":
- prepared = dict(config["prepared"])
- content = (
- "[Recursion limit reached. Simplify the task or increase the "
- "agent recursion limit.]"
- )
- message = Message(role="assistant", content=content)
- response_ref = await store.put_blob(
- {
- "kind": "final",
- "assistant_message": message_to_wire(message),
- "content": content,
- "thinking": None,
- "usage": {},
- "iteration": iteration,
- "truncated": True,
- }
- )
- ref = await _append_event(
- store,
- ref,
- event_type="message.assistant",
- operation_id=f"{operation_id}:assistant",
- provider=str(prepared.get("provider") or ""),
- message_wire_v2=message_to_wire(message),
- payload_ref=response_ref,
- )
- return await _finalize(
- store=store,
- ref=ref,
- runtime_config=config,
- response_ref=response_ref,
- operation_id=operation_id,
- truncated=True,
- )
- raise _non_retryable(
- f"Unknown Context V2 append action {action!r}.",
- "InvalidAgentContextAppendAction",
- )
-def _estimate_tokens(value: Any) -> int:
- encoded = json.dumps(
- value,
- ensure_ascii=False,
- separators=(",", ":"),
- default=str,
- )
- return max(1, (len(encoded) + 3) // 4)
[email protected](name="agent.compact_context")
-async def compact_context(
- payload: Dict[str, Any],
-) -> Dict[str, Any]:
- """Run Temporal compaction through the shared provider adapter service."""
+ lines.append(line)
- from core.container import container
- from services.agent_context import (
- AgentContextCompactionService,
- CompactionConflictError,
- ContextCompactionCandidate,
- ContextCompactionPolicy,
- reconstruct_message_wire_v2,
- )
- from services.agent_runtime import run_native_llm_step
- from services.llm.protocol import (
- Message,
- message_from_wire,
- message_to_wire,
- )
- from services.temporal.agent_activities import (
- _await_with_llm_heartbeats,
- _resolve_activity_api_key,
- )
-
- store = _context_store()
- ref = _context_ref(payload["context_ref"])
- config = await _runtime_config(
- store,
- str(payload["runtime_config_ref"]),
- )
- prepared = dict(config["prepared"])
- provider = str(prepared.get("provider") or "")
- model = str(prepared.get("model") or "")
- policy = ContextCompactionPolicy.from_mapping(
- dict(config.get("context_policy") or {})
- )
- response = await store.get_blob(str(payload["response_ref"]))
- usage = (
- dict(response.get("usage") or {})
- if isinstance(response, dict)
- else {}
- )
- active_input_tokens = int(usage.get("input_tokens") or 0) + int(
- usage.get("output_tokens") or 0
+ return await svc.compact_context(
+ session_id=str(payload.get("session_id") or "default"),
+ node_id=payload["node_id"],
+ memory_content="\n\n".join(lines),
+ provider=payload["provider"],
+ api_key=await _resolve_activity_api_key(payload),
+ model=payload["model"],
+ # Temporal owns activity retries; never repeat an ambiguous provider
+ # request inside the activity or SDK.
+ explicit_max_retries=0,
)
- output_headroom = max(0, int(prepared.get("max_tokens") or 0))
- rendered_request: Optional[List[Dict[str, Any]]] = None
- try:
- ref, rendered_request = await reconstruct_message_wire_v2(store, ref)
- except Exception:
- # Provider-native checkpoints may be intentionally opaque. Exact
- # provider usage still drives pressure in that case.
- rendered_request = None
-
- async def _portable_compactor(
- wires: list[dict[str, Any]],
- _policy: ContextCompactionPolicy,
- ) -> ContextCompactionCandidate:
- transcript: list[str] = []
- for wire in wires:
- message = message_from_wire(wire)
- line = f"{message.role.upper()}: {message.content}"
- if message.tool_calls:
- line += "\nTOOL_CALLS: " + json.dumps(
- [
- {
- "id": call.id,
- "name": call.name,
- "args": call.args,
- "raw_arguments": call.raw_arguments,
- "parse_error": call.parse_error,
- }
- for call in message.tool_calls
- ],
- ensure_ascii=False,
- default=str,
- )
- if message.tool_call_id:
- line += (
- f"\nTOOL_RESULT_FOR: {message.tool_call_id} "
- f"({message.name or 'tool'})"
- )
- transcript.append(line)
- prompt = (
- "Create a compact, provider-portable continuation checkpoint "
- "for the exact agent transcript below. Preserve instructions, "
- "decisions, constraints, identifiers, completed and pending "
- "tool work, errors, open questions, and the next action. Never "
- "claim a tool ran unless its result appears. Return only the "
- "checkpoint.\n\n"
- + "\n\n".join(transcript)
- )
- api_key = await _resolve_activity_api_key(prepared)
- compacted = await _await_with_llm_heartbeats(
- run_native_llm_step(
- container.chat_unifier(),
- provider=provider,
- api_key=api_key,
- messages=[Message(role="user", content=prompt)],
- model=model,
- temperature=0.2,
- max_tokens=min(4096, output_headroom or 4096),
- sdk_max_retries=0,
- explicit_max_retries=0,
- translate_errors=False,
- ),
- detail=f"Context V2 compaction waiting: {model}",
- )
- summary = str(compacted.content or "").strip()
- if not summary:
- raise ValueError("empty_compaction_candidate")
- summary_wire = dict(
- message_to_wire(
- Message(
- role="user",
- content=(
- "<agent_context_checkpoint>\n"
- f"{summary}\n"
- "</agent_context_checkpoint>"
- ),
- )
- )
- )
- message_from_wire(summary_wire)
- billing_usage = compacted.billing_usage or compacted.usage
- return ContextCompactionCandidate(
- strategy="portable_structured",
- replay_payload={
- "format": "agent-context-portable-v1",
- "messages": [summary_wire],
- },
- active_token_count=_estimate_tokens([summary_wire]),
- lifetime_usage=asdict(billing_usage),
- )
- operation_id = str(payload["operation_id"])
- try:
- result = await AgentContextCompactionService(
- store
- ).update_pressure_and_compact(
- ref,
- operation_id=operation_id,
- provider=provider,
- model=model,
- policy=policy,
- active_input_tokens=active_input_tokens,
- output_headroom=output_headroom,
- rendered_request=rendered_request,
- portable_compactor=_portable_compactor,
- )
- except CompactionConflictError:
- latest = await store.load_active(ref)
- return {
- "context_ref": _ref_dict(latest.ref),
- "status": "cas_conflict",
- }
- except Exception as exc:
- activity.logger.warning(
- "Context V2 compaction failed; prior checkpoint retained: %s",
- type(exc).__name__,
- )
- latest = await store.load_active(ref)
- return {
- "context_ref": _ref_dict(latest.ref),
- "status": "failed",
- "error_code": type(exc).__name__,
- }
- latest_ref = result.ref
- response_payload: Dict[str, Any] = {
- "context_ref": _ref_dict(latest_ref),
- "status": result.reason,
- "active_pressure": result.pressure_tokens,
- "context_window": result.context_window,
- }
- if result.compacted and result.checkpoint is not None:
- usage_ref = await store.put_blob(
- {
- "usage": result.lifetime_usage,
- "active_tokens_before": active_input_tokens + output_headroom,
- "active_tokens_after": result.pressure_tokens,
- "checkpoint_ref": result.checkpoint.replay_payload_ref,
- "strategy": result.checkpoint.strategy,
- }
- )
- latest_ref = await _append_event(
- store,
- latest_ref,
- event_type="context.compacted",
- operation_id=f"{operation_id}:event",
- provider=provider,
- payload_ref=usage_ref,
- )
- response_payload.update(
- {
- "context_ref": _ref_dict(latest_ref),
- "status": "compacted",
- "strategy": result.checkpoint.strategy,
- "checkpoint_hash": _hash_from_ref(
- result.checkpoint.replay_payload_ref
- ),
- "active_tokens_after": result.pressure_tokens,
- }
- )
- return response_payload
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index cf911f9f..44aab368 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -15,9 +15,9 @@ Architecture (matches Temporal's AI Cookbook canonical pattern):
│ → returns "final" OR "tool_calls"
├─> if tool_calls:
│ execute_activity(node.{tool_type}.v1) for each
- ├─> execute_activity(agent.persist_turn.v1)
+ ├─> execute_activity(agent.persist_turn)
├─> token check; if over threshold:
- │ execute_activity(agent.compact_memory.v1)
+ │ execute_activity(agent.compact_context)
└─> repeat until "final" or max_iterations
User decisions baked in (plan §15):
@@ -47,6 +47,7 @@ References:
from __future__ import annotations
import asyncio
+import json
from datetime import timedelta
from typing import Any, Dict, List, Optional
@@ -80,9 +81,6 @@ TOOL_STEP_TIMEOUT = timedelta(minutes=10)
TOOL_HEARTBEAT_TIMEOUT = timedelta(minutes=2)
LLM_STEP_HEARTBEAT_TIMEOUT = timedelta(minutes=1)
-NATIVE_LLM_ENGINE = "native"
-LEGACY_LLM_ENGINE = "langchain"
-
# Bounded loop count to defend against a runaway LLM. Plugin classes
# override via ``payload["max_iterations"]`` (set by
# ``prepare_agent_payload`` from Settings.agent_recursion_limit). This
@@ -127,7 +125,7 @@ def _native_message(
tool_call_id: Optional[str] = None,
name: Optional[str] = None,
) -> Dict[str, Any]:
- """Build the canonical v2 wire representation without SDK objects."""
+ """Build the canonical wire representation without SDK objects."""
from services.llm.protocol import Message, message_to_wire
@@ -144,40 +142,24 @@ def _native_message(
def _append_tool_result_message(
messages: List[Dict[str, Any]],
*,
- llm_engine: str,
content: str,
tool_call_id: str,
name: str,
) -> None:
- """Append a tool result in the history-pinned engine's wire format."""
-
- if llm_engine == NATIVE_LLM_ENGINE:
- messages.append(
- _native_message(
- role="tool",
- content=content,
- tool_call_id=tool_call_id,
- name=name,
- )
- )
- return
+ """Append a tool result message in the canonical wire shape."""
- # Do not change this legacy shape: histories created before the cutover
- # pass it through the legacy message reader on replay.
messages.append(
- {
- "type": "tool",
- "data": {
- "content": content,
- "tool_call_id": tool_call_id,
- "name": name,
- },
- }
+ _native_message(
+ role="tool",
+ content=content,
+ tool_call_id=tool_call_id,
+ name=name,
+ )
)
def _native_assistant_thinking(message: Any) -> Optional[str]:
- """Read reasoning text from a MessageWireV2 assistant turn.
+ """Read reasoning text from a MessageWire assistant turn.
``agent.execute_llm_step.v1`` keeps its historical tool-call result keys,
so native tool turns carry their reasoning only inside the canonical
@@ -240,11 +222,19 @@ _INHERITED_SCOPE_KEYS = (
# signal and this soft cap is the deterministic backstop.
_AGENT_HISTORY_SOFT_CAP = 10_000
-# State carried across a rollover. Deliberately all O(1) or bounded: the
-# transcript is NOT carried -- a journal-backed run reconstructs it from
-# the Context store, which is the whole point of holding refs.
+# State carried across a rollover: refs, counters, usage totals, and the
+# live transcript itself. Carrying the transcript keeps the resumed run's
+# conversation exact with no replay machinery; compaction keeps it
+# token-bounded and the byte guard below keeps it under Temporal's 2 MiB
+# payload error limit.
_RESUME_MARKER = "_agent_resume"
+# Byte ceiling for the carried transcript (Temporal's payload error limit is
+# 2 MiB for the WHOLE continue_as_new argument, which also carries the
+# original context). Past this the rollover restarts from the opening
+# prompt with a warning instead of failing the rollover itself.
+_CAN_TRANSCRIPT_MAX_BYTES = 1_000_000
+
def _inherited_scope(context: Dict[str, Any]) -> Dict[str, Any]:
"""Return the scope keys a delegated child must inherit from its parent."""
@@ -625,18 +615,6 @@ class AgentWorkflow:
start_to_close_timeout=PERSIST_TURN_TIMEOUT * 2, # 60s default
retry_policy=AGENT_ACTIVITY_RETRY,
)
- # The prepare result is recorded in history. Absence of the marker is
- # the deterministic migration sentinel for pre-cutover executions.
- has_recorded_engine = "llm_engine" in payload
- llm_engine = str(
- payload.get("llm_engine") or LEGACY_LLM_ENGINE
- ).strip().lower()
- if llm_engine not in {NATIVE_LLM_ENGINE, LEGACY_LLM_ENGINE}:
- raise ValueError(f"Unsupported agent LLM engine {llm_engine!r}")
- message_wire_version = int(
- payload.get("message_wire_version")
- or (2 if llm_engine == NATIVE_LLM_ENGINE else 1)
- )
# Stable per-run execution id, forwarded into every tool-call
# activity so session-keyed nodes (browser) reuse one instance
# across iterations instead of minting a fresh uuid per call
@@ -716,20 +694,13 @@ class AgentWorkflow:
"result": {"iterations": 0, "usage": {}},
}
- # ---- Build initial message list ---------------------------------
- # Native executions use the SDK-neutral v2 wire codec. Legacy
- # histories keep the legacy canonical {type, data} shape exactly.
- # ---- Context journal -------------------------------------------
- # A Context node makes the backend journal every turn the agent sends.
- # It never steers the request: the LLM activity always builds from
- # ``messages``, and ``context_ref`` only says where to record. The
- # workflow itself holds references, never transcript content.
- #
- # The one place the journal is read back is the continue-as-new
- # rollover below, which carries references rather than the
- # conversation.
+ # ---- Context journal (view-only) --------------------------------
+ # A Context node makes the backend journal every turn the agent sends,
+ # for the Context panel. It never steers the request: the LLM activity
+ # always builds from ``messages``, and ``context_ref`` only says where
+ # to record. The rollover does NOT read the journal back — the live
+ # transcript itself crosses the continue-as-new boundary.
context_ref: Optional[Dict[str, Any]] = None
- runtime_config_ref = ""
if payload.get("context_descriptor"):
await self._wait_until_resumed()
prepared_context = await workflow.execute_activity(
@@ -745,79 +716,37 @@ class AgentWorkflow:
retry_policy=AGENT_ACTIVITY_RETRY,
)
context_ref = prepared_context.get("context_ref")
- runtime_config_ref = str(
- prepared_context.get("runtime_config_ref") or ""
- )
if resume:
- # Only references and counters cross the rollover boundary; the
- # transcript is replayed from the journal further down.
context_ref = resume.get("context_ref") or context_ref
- runtime_config_ref = (
- str(resume.get("runtime_config_ref") or "") or runtime_config_ref
- )
+ # ---- Build the message list -------------------------------------
+ # A resumed run continues from the exact transcript the previous run
+ # carried across continue_as_new. Only a fresh run builds the
+ # system + memory + prompt opening.
+ carried_transcript = list(resume.get("transcript") or [])
messages: List[Dict[str, Any]] = []
+ user_prompt = payload.get("user_prompt") or ""
+ memory_markdown = payload.get("memory_content") or ""
system = payload.get("system_message") or ""
- if system:
- if llm_engine == NATIVE_LLM_ENGINE:
+ if carried_transcript:
+ messages = [dict(message) for message in carried_transcript]
+ else:
+ if system:
messages.append(_native_message(role="system", content=system))
- else:
- messages.append(
- {"type": "system", "data": {"content": system}}
- )
- # Pre-loaded memory becomes an additional system note. The actual
- # parse / append happens in the persist_turn activity, but the
- # current markdown content seeds the conversation here.
- memory_markdown = payload.get("memory_content") or ""
- if memory_markdown:
- memory_content = f"## Prior conversation:\n{memory_markdown}"
- if llm_engine == NATIVE_LLM_ENGINE:
+ # Pre-loaded memory becomes an additional system note. The actual
+ # parse / append happens in the persist_turn activity, but the
+ # current markdown content seeds the conversation here.
+ if memory_markdown:
+ memory_content = f"## Prior conversation:\n{memory_markdown}"
messages.append(
_native_message(role="system", content=memory_content)
)
- else:
- messages.append(
- {"type": "system", "data": {"content": memory_content}}
- )
- user_prompt = payload.get("user_prompt") or ""
- if user_prompt:
- if llm_engine == NATIVE_LLM_ENGINE:
- messages.append(_native_message(role="user", content=user_prompt))
- else:
+ if user_prompt:
messages.append(
- {"type": "human", "data": {"content": user_prompt}}
- )
-
- # ---- Resume: replay the transcript from the journal --------------
- # continue_as_new carries references, not the conversation, so the
- # list built above is just system + memory + prompt. Without this the
- # agent forgets everything it had said mid-run — and only when a
- # Context node is attached, since the rollover is gated on
- # ``context_ref``. The journal is authoritative here because it holds
- # the exact message list each turn was sent with.
- if resume and context_ref:
- await self._wait_until_resumed()
- replayed = await workflow.execute_activity(
- "agent.reconstruct_context_messages",
- args=[{"context_ref": context_ref}],
- activity_id="reconstruct-context-messages",
- start_to_close_timeout=PERSIST_TURN_TIMEOUT * 2,
- retry_policy=AGENT_ACTIVITY_RETRY,
- )
- restored = replayed.get("messages") or []
- if restored:
- messages = [dict(message) for message in restored]
- else:
- # An opaque provider checkpoint or an unreadable thread. The
- # rebuilt prompt is the honest fallback; log which, so a
- # forgetful agent is diagnosable rather than mysterious.
- workflow.logger.warning(
- "AgentWorkflow resumed without a replayed transcript "
- f"({replayed.get('reason') or 'unknown'}); continuing from "
- "the rebuilt prompt"
+ _native_message(role="user", content=user_prompt)
)
# Map LLM tool name -> {node_type, version, task_queue, node_id,
@@ -828,11 +757,21 @@ class AgentWorkflow:
compaction_threshold = payload.get("compaction_threshold")
thinking_accumulated = ""
final_content: Optional[str] = None
- # Billing/observability is cumulative for the entire execution.
+ # Billing/observability is cumulative for the entire execution and
+ # survives continue_as_new via the resume marker — the final result
+ # must report every generation's tokens, not just the last one.
# Context usage is reset only after a summary replaces the active
# message history and exists solely to decide when to compact again.
- usage_total: Dict[str, int] = {}
- context_usage_total: Dict[str, int] = {}
+ usage_total: Dict[str, int] = {
+ k: int(v)
+ for k, v in dict(resume.get("usage") or {}).items()
+ if isinstance(v, int)
+ }
+ context_usage_total: Dict[str, int] = {
+ k: int(v)
+ for k, v in dict(resume.get("context_usage") or {}).items()
+ if isinstance(v, int)
+ }
# Emit "executing" + phase="starting" via the existing
# broadcast_agent_progress activity (CloudEvents
@@ -867,93 +806,50 @@ class AgentWorkflow:
)
await self._wait_until_resumed()
- # Strip per-turn fields the activity doesn't need. Native turns
- # receive only provider-neutral JSON tool definitions. Legacy
- # histories retain raw tool_info so their activity rebuilds the
- # exact StructuredTool surface it used before the cutover.
+ # Strip per-turn fields the activity doesn't need. Turns receive
+ # only provider-neutral JSON tool definitions.
visible_tools = [t for t in tools if not t.get("llm_hidden")]
- if llm_engine == NATIVE_LLM_ENGINE:
- llm_payload = {
- "node_id": payload["node_id"],
- "provider": payload["provider"],
- "model": payload["model"],
- "messages": messages,
- "tools": [
- t["definition"]
- for t in visible_tools
- if t.get("definition")
- ],
- "system_message": system,
- "temperature": payload.get("temperature", 0.7),
- "max_tokens": payload.get("max_tokens", 4096),
- "thinking_config": payload.get("thinking_config"),
- "llm_engine": NATIVE_LLM_ENGINE,
- "message_wire_version": message_wire_version,
- # Journalling only. The activity always builds its request
- # from ``messages`` above; these just tell it where to
- # record the turn it actually sent. A Context node observes
- # the agent, it never steers it.
- **(
- {
- "context_ref": context_ref,
- # Scoped by agent node as well as firing: two
- # agents wired to one Context node resolve to the
- # same thread, so a firing-only id made them mint
- # identical operation ids, collide on
- # (thread, operation_id), and have their turns
- # discarded by the store's idempotency guard.
- "journal_operation_id": (
- f"{journal_operation_id}:{agent_node_id}"
- f":iter:{iteration}"
- ),
- }
- if context_ref
- else {}
- ),
- # A provider may stop a turn to compact rather than to
- # answer. Without the finish reason that response is
- # indistinguishable from a normal completion and gets
- # returned to the user as a truncated final answer.
- "include_finish_reason": True,
- }
- else:
- if not has_recorded_engine:
- # Preserve both values and insertion order of the
- # pre-cutover JSON payload so replay emits the same
- # encoded activity command bytes for histories that
- # already scheduled a turn.
- llm_payload = {
- "provider": payload["provider"],
- "model": payload["model"],
- "api_key": payload["api_key"],
- "messages": messages,
- "tool_data": [
- t["tool_info"] for t in visible_tools
- ],
- "system_message": system,
- "temperature": payload.get("temperature", 0.7),
- "max_tokens": payload.get("max_tokens", 4096),
- "thinking_config": payload.get("thinking_config"),
- }
- else:
- # Newly prepared emergency-switch executions still use
- # the legacy adapter but resolve credentials inside the
- # activity, just like native runs.
- llm_payload = {
- "node_id": payload["node_id"],
- "provider": payload["provider"],
- "model": payload["model"],
- "messages": messages,
- "tool_data": [
- t["tool_info"] for t in visible_tools
- ],
- "system_message": system,
- "temperature": payload.get("temperature", 0.7),
- "max_tokens": payload.get("max_tokens", 4096),
- "thinking_config": payload.get("thinking_config"),
- "llm_engine": LEGACY_LLM_ENGINE,
- "message_wire_version": 1,
+ llm_payload = {
+ "node_id": payload["node_id"],
+ "provider": payload["provider"],
+ "model": payload["model"],
+ "messages": messages,
+ "tools": [
+ t["definition"]
+ for t in visible_tools
+ if t.get("definition")
+ ],
+ "system_message": system,
+ "temperature": payload.get("temperature", 0.7),
+ "max_tokens": payload.get("max_tokens", 4096),
+ "thinking_config": payload.get("thinking_config"),
+ # Journalling only. The activity always builds its request
+ # from ``messages`` above; these just tell it where to
+ # record the turn it actually sent. A Context node observes
+ # the agent, it never steers it.
+ **(
+ {
+ "context_ref": context_ref,
+ # Scoped by agent node as well as firing: two
+ # agents wired to one Context node resolve to the
+ # same thread, so a firing-only id made them mint
+ # identical operation ids, collide on
+ # (thread, operation_id), and have their turns
+ # discarded by the store's idempotency guard.
+ "journal_operation_id": (
+ f"{journal_operation_id}:{agent_node_id}"
+ f":iter:{iteration}"
+ ),
}
+ if context_ref
+ else {}
+ ),
+ # A provider may stop a turn to compact rather than to
+ # answer. Without the finish reason that response is
+ # indistinguishable from a normal completion and gets
+ # returned to the user as a truncated final answer.
+ "include_finish_reason": True,
+ }
# Wave 17.2: one-shot retry. The LLM call is not idempotent —
# a worker crash mid-call must not silently re-bill the full
@@ -962,56 +858,40 @@ class AgentWorkflow:
# future enhancement can re-ask with context; today we
# surface the error to the canvas and stop the loop.
try:
- if has_recorded_engine:
- step_result = await workflow.execute_activity(
- "agent.execute_llm_step",
- args=[llm_payload],
- activity_id=f"llm-step-{iteration + 1}",
- start_to_close_timeout=LLM_STEP_TIMEOUT,
- heartbeat_timeout=LLM_STEP_HEARTBEAT_TIMEOUT,
- retry_policy=LLM_STEP_RETRY,
- )
- else:
- step_result = await workflow.execute_activity(
- "agent.execute_llm_step",
- args=[llm_payload],
- activity_id=f"llm-step-{iteration + 1}",
- start_to_close_timeout=LLM_STEP_TIMEOUT,
- retry_policy=LLM_STEP_RETRY,
- )
+ step_result = await workflow.execute_activity(
+ "agent.execute_llm_step",
+ args=[llm_payload],
+ activity_id=f"llm-step-{iteration + 1}",
+ start_to_close_timeout=LLM_STEP_TIMEOUT,
+ heartbeat_timeout=LLM_STEP_HEARTBEAT_TIMEOUT,
+ retry_policy=LLM_STEP_RETRY,
+ )
except Exception as e:
cause = getattr(e, "cause", None)
raw_detail = str(cause) if cause is not None else str(e)
- if not has_recorded_engine:
- # Exact pre-cutover result behavior: replayed histories
- # exposed the activity cause text in their terminal
- # workflow result. Changing it would alter completion.
- detail = raw_detail
+ cause_type = str(getattr(cause, "type", "") or "")
+ cause_message = str(
+ getattr(cause, "message", "") or ""
+ ).strip()
+ safe_activity_types = {
+ "MissingAgentProviderCredential",
+ "EmptyAgentPrompt",
+ }
+ if cause_type.startswith("LLMError."):
+ detail = (
+ cause_message
+ or "The language model request failed."
+ )
+ elif cause_type in safe_activity_types:
+ detail = (
+ cause_message
+ or "The language model request failed."
+ )
else:
- cause_type = str(getattr(cause, "type", "") or "")
- cause_message = str(
- getattr(cause, "message", "") or ""
- ).strip()
- safe_activity_types = {
- "MissingAgentProviderCredential",
- "InvalidAgentMessageWireVersion",
- "EmptyAgentPrompt",
- }
- if cause_type.startswith("LLMError."):
- detail = (
- cause_message
- or "The language model request failed."
- )
- elif cause_type in safe_activity_types:
- detail = (
- cause_message
- or "The language model request failed."
- )
- else:
- detail = (
- "The language model step failed unexpectedly. "
- "Retry the run or check server logs."
- )
+ detail = (
+ "The language model step failed unexpectedly. "
+ "Retry the run or check server logs."
+ )
workflow.logger.error(
f"AgentWorkflow LLM step failed (iteration {iteration + 1}, "
f"no auto-retry): {raw_detail}"
@@ -1054,12 +934,11 @@ class AgentWorkflow:
for k, v in (step_result.get("usage") or {}).items():
if isinstance(v, int):
usage_total[k] = usage_total.get(k, 0) + v
- if has_recorded_engine:
- context_usage_total[k] = (
- context_usage_total.get(k, 0) + v
- )
+ context_usage_total[k] = (
+ context_usage_total.get(k, 0) + v
+ )
step_thinking = step_result.get("thinking")
- if not step_thinking and llm_engine == NATIVE_LLM_ENGINE:
+ if not step_thinking:
step_thinking = _native_assistant_thinking(
step_result.get("assistant_message")
)
@@ -1677,14 +1556,13 @@ class AgentWorkflow:
raise
for call_index, call in enumerate(calls):
- if llm_engine == NATIVE_LLM_ENGINE and call.get("parse_error"):
+ if call.get("parse_error"):
# Native adapters retain malformed arguments rather than
# throwing during normalization. Return a deterministic
# tool result and let the model repair its invocation on
# the next turn; never execute partially parsed args.
_append_tool_result_message(
messages,
- llm_engine=llm_engine,
content=_serialise_tool_result(
{
"error": "Tool arguments were invalid JSON",
@@ -1703,7 +1581,6 @@ class AgentWorkflow:
workflow.logger.warning(f"AgentWorkflow: LLM called unknown tool {call.get('name')!r}; " "returning error to model")
_append_tool_result_message(
messages,
- llm_engine=llm_engine,
content=(
f"Error: tool {call.get('name')!r} is not "
"connected to this agent."
@@ -1750,7 +1627,6 @@ class AgentWorkflow:
# instead of spawning a child that cannot run.
_append_tool_result_message(
messages,
- llm_engine=llm_engine,
content=(
'{"error": "delegate_to_* requires a '
"non-empty 'task' argument describing "
@@ -1763,7 +1639,6 @@ class AgentWorkflow:
if delegation_depth >= max_delegation_depth:
_append_tool_result_message(
messages,
- llm_engine=llm_engine,
content=(
'{"error": "Maximum delegation depth '
f'{max_delegation_depth} exceeded."}}'
@@ -1874,6 +1749,12 @@ class AgentWorkflow:
raise
else:
await _release_delegation_permit(call_index)
+ # The child is done — drop its handle so a completed
+ # delegation no longer blocks the rollover guard.
+ # (An agent that delegates every turn previously
+ # could never continue_as_new and grew until
+ # Temporal's hard history terminate.)
+ delegation_handles.pop(call_index, None)
child_succeeded = (
bool(tool_result.get("success", True))
if isinstance(tool_result, dict) else True
@@ -1962,7 +1843,9 @@ class AgentWorkflow:
# Await in original tool-call order; every
# child was already started above, so slow
# earlier siblings do not prevent later work.
- delegated = await task_manager_delegation_tasks[call_index]
+ # pop: a finished task must not block the
+ # rollover guard for the rest of the turn.
+ delegated = await task_manager_delegation_tasks.pop(call_index)
else:
delegated = await _run_task_manager_delegation(
tool_result["delegation_request"], call_index, call
@@ -2148,7 +2031,6 @@ class AgentWorkflow:
_append_tool_result_message(
messages,
- llm_engine=llm_engine,
content=tool_content,
tool_call_id=call.get("id", ""),
name=call.get("name", ""),
@@ -2180,71 +2062,51 @@ class AgentWorkflow:
)
# ---- Compaction check --------------------------------------
- if has_recorded_engine:
- token_total = int(
- context_usage_total.get("total_tokens") or 0
- )
- if not token_total:
- token_total = sum(
- int(context_usage_total.get(key) or 0)
- for key in (
- "input_tokens",
- "cache_creation_tokens",
- "cache_read_tokens",
- "output_tokens",
- )
- )
- else:
- # Exact pre-cutover schedule predicate. Captured histories
- # ignored total/cache/reasoning fields here.
+ # Simple by design: token threshold -> summarize the live
+ # conversation -> swap messages. No memory-node gate, no
+ # checkpoint machinery. A later rollover resumes from the
+ # compacted state for free, because the next LLM turn journals
+ # a fresh request.snapshot containing the compacted messages.
+ token_total = int(
+ context_usage_total.get("total_tokens") or 0
+ )
+ if not token_total:
token_total = sum(
- int(usage_total.get(key) or 0)
- for key in ("input_tokens", "output_tokens")
+ int(context_usage_total.get(key) or 0)
+ for key in (
+ "input_tokens",
+ "cache_creation_tokens",
+ "cache_read_tokens",
+ "output_tokens",
+ )
)
- if compaction_threshold and token_total >= compaction_threshold and memory_markdown:
+ if compaction_threshold and token_total >= compaction_threshold:
workflow.logger.info(f"AgentWorkflow compaction triggered: {token_total} tokens")
- if has_recorded_engine:
- compact_payload = {
- "session_id": payload.get(
- "session_id", "default"
- ),
- "node_id": payload["node_id"],
- "memory_content": memory_markdown,
- "provider": payload["provider"],
- "model": payload["model"],
- }
- else:
- # Preserve values and insertion order of the historical
- # activity command, including its recorded credential.
- compact_payload = {
- "session_id": payload.get(
- "session_id", "default"
- ),
- "node_id": payload["node_id"],
- "memory_content": memory_markdown,
- "provider": payload["provider"],
- "api_key": payload["api_key"],
- "model": payload["model"],
- }
+ compact_payload = {
+ "session_id": payload.get("session_id", "default"),
+ "node_id": payload["node_id"],
+ "messages": messages,
+ "provider": payload["provider"],
+ "model": payload["model"],
+ }
await self._wait_until_resumed()
compact_result = await workflow.execute_activity(
- "agent.compact_memory",
+ "agent.compact_context",
args=[compact_payload],
- activity_id=f"compact-memory-{iteration + 1}",
+ activity_id=f"compact-context-{iteration + 1}",
start_to_close_timeout=COMPACT_MEMORY_TIMEOUT,
retry_policy=AGENT_ACTIVITY_RETRY,
)
# The summarizer is another billed model call. Include it in
# execution-wide usage whether persistence after the call
# succeeds or fails, but never in the active-context counter.
- if has_recorded_engine:
- for key, value in (
- compact_result.get("usage") or {}
- ).items():
- if isinstance(value, int):
- usage_total[key] = (
- usage_total.get(key, 0) + value
- )
+ for key, value in (
+ compact_result.get("usage") or {}
+ ).items():
+ if isinstance(value, int):
+ usage_total[key] = (
+ usage_total.get(key, 0) + value
+ )
# Compaction is best-effort. When the service errors or
# was not initialized (worker bootstrap race), keep the
# existing messages and let the loop continue — masking
@@ -2262,42 +2124,21 @@ class AgentWorkflow:
# plus the last user prompt — same pattern
# ``CompactionService`` uses today in services/ai.py.
compacted_content = f"## Compacted summary:\n{summary}"
- if llm_engine == NATIVE_LLM_ENGINE:
- messages = [
- _native_message(
- role="system",
- content=system,
- ),
- _native_message(
- role="system",
- content=compacted_content,
- ),
- _native_message(
- role="user",
- content=user_prompt,
- ),
- ]
- else:
- messages = [
- {
- "type": "system",
- "data": {"content": system},
- },
- {
- "type": "system",
- "data": {"content": compacted_content},
- },
- {
- "type": "human",
- "data": {"content": user_prompt},
- },
- ]
- memory_markdown = summary
- if has_recorded_engine:
- context_usage_total = {}
- else:
- # Exact pre-cutover completion shape.
- usage_total = {}
+ messages = [
+ _native_message(
+ role="system",
+ content=system,
+ ),
+ _native_message(
+ role="system",
+ content=compacted_content,
+ ),
+ _native_message(
+ role="user",
+ content=user_prompt,
+ ),
+ ]
+ context_usage_total = {}
# ---- Continue-as-new -------------------------------------
# Only at a clean turn boundary, and never while a delegation
@@ -2309,11 +2150,30 @@ class AgentWorkflow:
_history_pressure,
)
- if context_ref and _history_pressure(_AGENT_HISTORY_SOFT_CAP):
+ if _history_pressure(_AGENT_HISTORY_SOFT_CAP):
delegations_live = bool(
delegation_handles or task_manager_delegation_tasks
)
if not delegations_live:
+ # The live transcript crosses the boundary directly.
+ # Compaction keeps it token-bounded; the byte guard
+ # below keeps a pathological transcript away from
+ # Temporal's 2 MiB payload error (which would fail the
+ # rollover itself). Oversized and uncompactable means
+ # restarting from the opening prompt with a warning —
+ # visible, and strictly better than a dead run.
+ carried = messages
+ transcript_bytes = len(
+ json.dumps(carried, default=str).encode("utf-8")
+ )
+ if transcript_bytes > _CAN_TRANSCRIPT_MAX_BYTES:
+ workflow.logger.warning(
+ f"AgentWorkflow rollover transcript is "
+ f"{transcript_bytes} bytes (> "
+ f"{_CAN_TRANSCRIPT_MAX_BYTES}); dropping to the "
+ "opening prompt"
+ )
+ carried = []
workflow.logger.info(
f"AgentWorkflow continue_as_new at iteration "
f"{iteration + 1} (history pressure)"
@@ -2324,9 +2184,11 @@ class AgentWorkflow:
**context,
_RESUME_MARKER: {
"context_ref": context_ref,
- "runtime_config_ref": runtime_config_ref,
"iteration": iteration + 1,
"execution_id": execution_id,
+ "transcript": carried,
+ "usage": usage_total,
+ "context_usage": context_usage_total,
},
}
]
diff --git a/server/services/temporal/trigger_listener_workflow.py b/server/services/temporal/trigger_listener_workflow.py
index beba5da6..8d4e3913 100644
--- a/server/services/temporal/trigger_listener_workflow.py
+++ b/server/services/temporal/trigger_listener_workflow.py
@@ -87,16 +87,17 @@ _FILTER_ACTIVITY_TIMEOUT = timedelta(seconds=10)
def _history_pressure(soft_cap: int) -> bool:
"""True when the server suggests continue-as-new or the current
history length crossed ``soft_cap``. False outside a real workflow
- runtime (direct unit invocation), where history cannot grow. Shared
- by the listener, polling, and controller rollover checks."""
+ runtime (direct unit invocation, or a stubbed ``workflow.info()``),
+ where history cannot grow. Shared by the listener, polling, agent,
+ and controller rollover checks."""
try:
info = workflow.info()
+ return bool(
+ info.is_continue_as_new_suggested()
+ or info.get_current_history_length() > soft_cap
+ )
except Exception: # direct unit invocation outside Temporal runtime
return False
- return bool(
- info.is_continue_as_new_suggested()
- or info.get_current_history_length() > soft_cap
- )
def event_workflow_search_attributes(
diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.py
index c8969394..21937b93 100644
--- a/server/services/temporal/worker.py
+++ b/server/services/temporal/worker.py
@@ -210,8 +210,8 @@ class TemporalWorkerManager:
# zero runtime cost when the flag is off (orchestrator routes to
# execute_node_activity, per-type entries sit idle).
#
- # F4.B: register AgentWorkflow + its three activities
- # (execute_llm_step / persist_turn / compact_memory). The
+ # F4.B: register AgentWorkflow + its agent activities
+ # (execute_llm_step / persist_turn / compact_context / ...). The
# orchestrator schedules AgentWorkflow as a child workflow
# for the 15 migrating agent types when
# ``temporal_agent_workflow_enabled`` is on.
diff --git a/server/tests/llm/test_protocol_codec.py b/server/tests/llm/test_protocol_codec.py
index 8f763f27..2c0ff698 100644
--- a/server/tests/llm/test_protocol_codec.py
+++ b/server/tests/llm/test_protocol_codec.py
@@ -5,7 +5,6 @@ import json
import pytest
from services.llm.protocol import (
- MESSAGE_WIRE_VERSION,
ContentBlock,
LLMError,
LLMErrorCategory,
@@ -20,7 +19,7 @@ from services.llm.protocol import (
)
-def test_message_wire_v2_round_trips_ordered_blocks_and_provider_state():
+def test_message_wire_round_trips_ordered_blocks_and_provider_state():
good_call = ToolCall(id="call-1", name="lookup", args={"q": "weather"})
malformed_call = ToolCall.from_raw(
id="call-2",
@@ -56,7 +55,8 @@ def test_message_wire_v2_round_trips_ordered_blocks_and_provider_state():
)
wire = message_to_wire(original)
- assert wire["version"] == MESSAGE_WIRE_VERSION
+ # One unversioned wire shape — no version discriminator.
+ assert "version" not in wire
# The payload must be safe for Temporal's ordinary JSON payload codec.
json.dumps(wire)
@@ -75,7 +75,7 @@ def test_message_wire_v2_round_trips_ordered_blocks_and_provider_state():
)
-def test_messages_helpers_accept_generators_and_pre_version_flat_shape():
+def test_messages_helpers_accept_generators_and_flat_shape():
encoded = messages_to_wire(
Message(role="user", content=str(index)) for index in range(2)
)
diff --git a/server/tests/llm/test_single_wire_standard.py b/server/tests/llm/test_single_wire_standard.py
new file mode 100644
index 00000000..be405c1b
--- /dev/null
+++ b/server/tests/llm/test_single_wire_standard.py
@@ -0,0 +1,53 @@
+"""Locks the single-standard end state of the agent wire/engine layer.
+
+The v1/v2 duality (legacy ``llm_engine`` branches, ``message_wire_v2``
+naming, wire ``version`` discriminator) was purged deliberately. This test
+keeps it from creeping back — same pattern as ``test_langchain_removed.py``.
+"""
+
+from pathlib import Path
+
+SERVER_ROOT = Path(__file__).resolve().parents[2]
+
+# Retired identifiers that must not reappear in production source.
+_FORBIDDEN = (
+ "LEGACY_LLM_ENGINE",
+ "NATIVE_LLM_ENGINE",
+ "has_recorded_engine",
+ "message_wire_v2",
+ "MessageWireV2",
+ "MESSAGE_WIRE_VERSION",
+ "message_wire_version",
+ "reconstruct_message_wire_v2",
+)
+
+_PRODUCTION_DIRS = ("services", "nodes", "models", "routers", "core")
+
+
+def _production_files():
+ for directory in _PRODUCTION_DIRS:
+ root = SERVER_ROOT / directory
+ if not root.is_dir():
+ continue
+ yield from root.rglob("*.py")
+
+
+def test_no_versioned_wire_or_engine_identifiers_in_production_source():
+ offenders: list[str] = []
+ for path in _production_files():
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ for name in _FORBIDDEN:
+ if name in text:
+ offenders.append(f"{path.relative_to(SERVER_ROOT)}: {name}")
+ assert not offenders, (
+ "retired v1/v2 identifiers found in production source:\n"
+ + "\n".join(offenders)
+ )
+
+
+def test_message_wire_has_no_version_key():
+ from services.llm.protocol import Message, message_to_wire
+
+ wire = message_to_wire(Message(role="user", content="hi"))
+ assert "version" not in wire
+ assert "wire_version" not in wire
diff --git a/server/tests/services/agent_context/test_commit_listeners.py b/server/tests/services/agent_context/test_commit_listeners.py
index 40a8c40e..2111a79f 100644
--- a/server/tests/services/agent_context/test_commit_listeners.py
+++ b/server/tests/services/agent_context/test_commit_listeners.py
@@ -114,7 +114,7 @@ async def test_append_notifies_with_post_commit_state(
ref,
event_type="message.assistant",
operation_id="op-1",
- message_wire_v2=_wire("hello"),
+ message_wire=_wire("hello"),
provider="anthropic",
)
@@ -143,13 +143,13 @@ async def test_idempotent_replay_emits_nothing(
ref,
event_type="message.assistant",
operation_id="op-replay",
- message_wire_v2=wire,
+ message_wire=wire,
)
replay = await store.append_transition(
ref,
event_type="message.assistant",
operation_id="op-replay",
- message_wire_v2=wire,
+ message_wire=wire,
)
assert first.applied is True
@@ -177,7 +177,7 @@ async def test_listener_failure_cannot_fail_the_commit(
ref,
event_type="message.assistant",
operation_id="op-boom",
- message_wire_v2=_wire("hello"),
+ message_wire=_wire("hello"),
)
# The commit stands, and one broken listener does not starve the others.
@@ -225,7 +225,7 @@ async def test_no_listeners_registered_is_a_no_op(
ref,
event_type="message.assistant",
operation_id="op-quiet",
- message_wire_v2=_wire("hello"),
+ message_wire=_wire("hello"),
)
assert result.applied is True
diff --git a/server/tests/services/agent_context/test_compaction.py b/server/tests/services/agent_context/test_compaction.py
index 8d0f2953..cf6de4b7 100644
--- a/server/tests/services/agent_context/test_compaction.py
+++ b/server/tests/services/agent_context/test_compaction.py
@@ -30,7 +30,7 @@ def _event(
return AgentContextEvent(
sequence=sequence,
event_type=event_type,
- message_wire_v2=wire,
+ message_wire=wire,
operation_id=f"operation-{sequence}",
provider="openai",
previous_hash=f"{sequence - 1:064x}",
@@ -131,7 +131,7 @@ async def test_pressure_is_idempotent_and_portable_checkpoint_keeps_tail(
ref,
event_type=event_type,
operation_id=f"transition-{index}",
- message_wire_v2=wire,
+ message_wire=wire,
provider="gemini",
)
).ref
@@ -286,7 +286,7 @@ async def test_native_checkpoint_stops_at_marker_and_keeps_later_events_exact(
ref,
event_type=event_type,
operation_id=f"native-boundary-{index}",
- message_wire_v2=wire,
+ message_wire=wire,
provider="openai",
)
).ref
@@ -314,7 +314,7 @@ async def test_native_checkpoint_stops_at_marker_and_keeps_later_events_exact(
state = await store.load_active(result.ref)
assert state.ref == result.ref
assert [event.sequence for event in state.tail] == [2, 3, 4]
- assert [event.message_wire_v2 for event in state.tail] == [
+ assert [event.message_wire for event in state.tail] == [
tool_wire,
_wire("final after tool"),
None,
@@ -335,7 +335,7 @@ async def test_compaction_returns_authoritative_ref_after_concurrent_append(
ref,
event_type="message.assistant",
operation_id=f"authoritative-ref-{index}",
- message_wire_v2=_wire(f"message-{index}"),
+ message_wire=_wire(f"message-{index}"),
provider="gemini",
)
).ref
@@ -345,7 +345,7 @@ async def test_compaction_returns_authoritative_ref_after_concurrent_append(
ref,
event_type="message.assistant",
operation_id="authoritative-ref-concurrent",
- message_wire_v2=_wire("concurrent tail"),
+ message_wire=_wire("concurrent tail"),
provider="gemini",
)
return ContextCompactionCandidate(
diff --git a/server/tests/services/agent_context/test_store.py b/server/tests/services/agent_context/test_store.py
index 291cf6c7..675cc20e 100644
--- a/server/tests/services/agent_context/test_store.py
+++ b/server/tests/services/agent_context/test_store.py
@@ -27,7 +27,7 @@ from services.agent_context import (
ContextArchivedError,
StaleEpochError,
import_generation_zero_handoff,
- reconstruct_message_wire_v2,
+ reconstruct_transcript,
)
from services.llm.protocol import (
ContentBlock,
@@ -193,7 +193,7 @@ async def test_generation_zero_legacy_artifact_handoff_is_idempotent(
first = await import_generation_zero_handoff(store, target)
second = await import_generation_zero_handoff(store, first)
- _, replay = await reconstruct_message_wire_v2(store, second)
+ _, replay = await reconstruct_transcript(store, second)
bindings = await store.load_provider_bindings(
second,
provider="claude_code",
@@ -227,7 +227,7 @@ async def test_generation_zero_legacy_artifact_handoff_is_idempotent(
execution_id=None,
)
later = await import_generation_zero_handoff(store, later_target)
- _, later_replay = await reconstruct_message_wire_v2(store, later)
+ _, later_replay = await reconstruct_transcript(store, later)
assert len(later_replay) == 1
@@ -358,14 +358,14 @@ async def test_append_is_exact_ordered_hash_chained_and_idempotent(
ref,
event_type="assistant",
operation_id="provider-response-1",
- message_wire_v2=_wire("first", with_tool=True),
+ message_wire=_wire("first", with_tool=True),
provider="openai",
)
duplicate = await store.append_transition(
ref,
event_type="assistant",
operation_id="provider-response-1",
- message_wire_v2=_wire("first", with_tool=True),
+ message_wire=_wire("first", with_tool=True),
provider="openai",
)
with pytest.raises(
@@ -376,7 +376,7 @@ async def test_append_is_exact_ordered_hash_chained_and_idempotent(
ref,
event_type="assistant",
operation_id="provider-response-1",
- message_wire_v2=_wire(
+ message_wire=_wire(
"this must not replace the committed event"
),
provider="openai",
@@ -385,7 +385,7 @@ async def test_append_is_exact_ordered_hash_chained_and_idempotent(
first.ref,
event_type="tool_result",
operation_id="tool-result-1",
- message_wire_v2=dict(
+ message_wire=dict(
message_to_wire(
Message(
role="tool",
@@ -402,7 +402,7 @@ async def test_append_is_exact_ordered_hash_chained_and_idempotent(
assert [event.sequence for event in state.tail] == [1, 2]
assert duplicate.applied is False
assert duplicate.event.payload_hash == first.event.payload_hash
- assert state.tail[0].message_wire_v2 == _wire("first", with_tool=True)
+ assert state.tail[0].message_wire == _wire("first", with_tool=True)
assert state.tail[1].previous_hash == state.tail[0].payload_hash
assert state.ref.revision == 2
@@ -440,14 +440,14 @@ async def test_load_active_rejects_corrupt_event_chain(
ref,
event_type="message.assistant",
operation_id="integrity-event-1",
- message_wire_v2=_wire("first"),
+ message_wire=_wire("first"),
provider="openai",
)
second = await store.append_transition(
first.ref,
event_type="message.assistant",
operation_id="integrity-event-2",
- message_wire_v2=_wire("second"),
+ message_wire=_wire("second"),
provider="openai",
)
@@ -496,7 +496,7 @@ async def test_load_active_rejects_corrupt_checkpoint_source(
ref,
event_type="message.assistant",
operation_id=f"checkpoint-integrity-{index}",
- message_wire_v2=_wire(f"message-{index}"),
+ message_wire=_wire(f"message-{index}"),
provider="openai",
)
).ref
@@ -541,14 +541,14 @@ async def test_blob_digest_is_verified_for_direct_and_checkpoint_replay(
ref,
event_type="message.assistant",
operation_id="blob-integrity-event-1",
- message_wire_v2=_wire("first"),
+ message_wire=_wire("first"),
provider="openai",
)
second = await store.append_transition(
first.ref,
event_type="message.assistant",
operation_id="blob-integrity-event-2",
- message_wire_v2=_wire("second"),
+ message_wire=_wire("second"),
provider="openai",
)
plan = await store.prepare_compaction(
@@ -599,7 +599,7 @@ async def test_parallel_appends_serialize_without_losing_events(
ref,
event_type="message.assistant",
operation_id=f"parallel-{index}",
- message_wire_v2=_wire(f"parallel-message-{index}"),
+ message_wire=_wire(f"parallel-message-{index}"),
)
for index in range(8)
)
@@ -625,7 +625,7 @@ async def test_epoch_rotation_fences_late_writes_and_keeps_handoff(
old_ref,
event_type="message.assistant",
operation_id="before-provider-fork",
- message_wire_v2=_wire("old epoch exact message"),
+ message_wire=_wire("old epoch exact message"),
provider="openai",
)
).ref
@@ -656,7 +656,7 @@ async def test_epoch_rotation_fences_late_writes_and_keeps_handoff(
old_ref,
event_type="assistant",
operation_id="late-provider-response",
- message_wire_v2=_wire("late"),
+ message_wire=_wire("late"),
)
# Retrying the already-committed rotation is idempotent even with the old
# reference that it deliberately fenced.
@@ -720,7 +720,7 @@ async def test_compaction_cas_keeps_concurrent_tail(context_database):
ref,
event_type="assistant",
operation_id=f"response-{index}",
- message_wire_v2=_wire(f"message-{index}"),
+ message_wire=_wire(f"message-{index}"),
provider="openai",
)
ref = result.ref
@@ -736,7 +736,7 @@ async def test_compaction_cas_keeps_concurrent_tail(context_database):
ref,
event_type="assistant",
operation_id="response-4",
- message_wire_v2=_wire("message-4"),
+ message_wire=_wire("message-4"),
provider="openai",
)
replay_ref = await store.put_blob(
@@ -772,7 +772,7 @@ async def test_failed_compaction_preserves_prior_active_state(
ref,
event_type="assistant",
operation_id=f"failure-response-{index}",
- message_wire_v2=_wire(f"failure-{index}"),
+ message_wire=_wire(f"failure-{index}"),
)
).ref
before = await store.load_active(ref)
@@ -803,14 +803,14 @@ async def test_runtime_writer_blobs_payloads_and_reconstructs_portable_replay(
event_type="message.assistant",
operation_id="writer-1",
provider="openai",
- message_wire_v2=first_wire,
+ message_wire=first_wire,
payload={"usage": {"input_tokens": 10}},
)
second = await writer.append_transition(
event_type="message.assistant",
operation_id="writer-2",
provider="openai",
- message_wire_v2=second_wire,
+ message_wire=second_wire,
)
assert writer.ref == second.ref
assert first.event.payload_ref is not None
@@ -834,7 +834,7 @@ async def test_runtime_writer_blobs_payloads_and_reconstructs_portable_replay(
active_token_count=20,
)
latest = writer.ref.model_copy(update={"revision": writer.ref.revision + 1})
- reconstructed_ref, wires = await reconstruct_message_wire_v2(
+ reconstructed_ref, wires = await reconstruct_transcript(
store,
latest,
)
@@ -865,7 +865,7 @@ async def test_reconstruction_uses_latest_exact_request_snapshot(
event_type="message.assistant",
operation_id="assistant-after-snapshot",
provider="openai",
- message_wire_v2=assistant,
+ message_wire=assistant,
)
# Metadata-only final events must not appear in provider replay.
await writer.append_transition(
@@ -875,7 +875,7 @@ async def test_reconstruction_uses_latest_exact_request_snapshot(
payload={"finish_reason": "stop"},
)
- _, wires = await reconstruct_message_wire_v2(store, writer.ref)
+ _, wires = await reconstruct_transcript(store, writer.ref)
assert wires == [system, user, assistant]
@@ -968,7 +968,7 @@ async def test_archive_fences_writes_and_purge_removes_state(context_database):
ref,
event_type="assistant",
operation_id="before-archive",
- message_wire_v2=_wire("preserved until purge"),
+ message_wire=_wire("preserved until purge"),
)
).ref
archived = await store.archive(ref, operation_id="archive-1")
@@ -977,7 +977,7 @@ async def test_archive_fences_writes_and_purge_removes_state(context_database):
ref,
event_type="assistant",
operation_id="after-archive",
- message_wire_v2=_wire("must not commit"),
+ message_wire=_wire("must not commit"),
)
# Archive is recoverable and idempotent; purge is the separate,
@@ -1071,7 +1071,7 @@ async def test_authorized_handlers_paginate_raw_data_but_redact_exports(
event_type="message.assistant",
operation_id="handler-event-2",
provider="openai",
- message_wire_v2=_wire("classified response"),
+ message_wire=_wire("classified response"),
)
page = await context_handlers.handle_get_agent_context(
@@ -1111,7 +1111,7 @@ async def test_authorized_handlers_paginate_raw_data_but_redact_exports(
assert '"redacted": true' in exported["content"]
assert "classified prompt" not in exported["content"]
assert "classified response" not in exported["content"]
- assert "message_wire_v2" not in exported["content"]
+ assert "message_wire" not in exported["content"]
assert "payload_ref" not in exported["content"]
unauthorized = await context_handlers.handle_get_agent_context(
@@ -1183,7 +1183,7 @@ async def test_clear_and_fork_handlers_rotate_epoch_with_metadata_events(
event_type="message.assistant",
operation_id="lifecycle-event",
provider="openai",
- message_wire_v2=_wire("before clear"),
+ message_wire=_wire("before clear"),
)
).ref
diff --git a/server/tests/services/cli_agent/test_context_v2_bridge.py b/server/tests/services/cli_agent/test_context_v2_bridge.py
index 335cd9af..8e90d92f 100644
--- a/server/tests/services/cli_agent/test_context_v2_bridge.py
+++ b/server/tests/services/cli_agent/test_context_v2_bridge.py
@@ -18,7 +18,7 @@ from nodes.agent.claude_code_agent._pool import (
ClaudeSessionPool,
PooledClaudeSession,
)
-from services.agent_context import reconstruct_message_wire_v2
+from services.agent_context import reconstruct_transcript
from services.cli_agent.context_bridge import SpecializedAgentContextBridge
from services.cli_agent.protocol import CanonicalUsage
from services.cli_agent.service import AICliService
@@ -190,7 +190,7 @@ async def test_provider_change_forks_epoch_with_portable_handoff(monkeypatch):
tail=[handoff_event],
)
store.get_blob.return_value = handoff
- _, reconstructed = await reconstruct_message_wire_v2(
+ _, reconstructed = await reconstruct_transcript(
store,
new_ref,
)
diff --git a/server/tests/services/test_native_agent_runtime.py b/server/tests/services/test_native_agent_runtime.py
index 6d18d100..08571904 100644
--- a/server/tests/services/test_native_agent_runtime.py
+++ b/server/tests/services/test_native_agent_runtime.py
@@ -289,8 +289,9 @@ async def test_native_loop_persists_context_transitions_before_tool_execution():
class _Sink:
async def append_transition(self, **kwargs):
observed.append(("context", kwargs["event_type"]))
- if kwargs.get("message_wire_v2"):
- assert kwargs["message_wire_v2"]["version"] == 2
+ if kwargs.get("message_wire"):
+ assert "version" not in kwargs["message_wire"]
+ assert kwargs["message_wire"].get("role")
assert kwargs["operation_id"].startswith("execution-9:")
async def execute(_name, args):
diff --git a/server/tests/temporal/test_agent_llm_contract.py b/server/tests/temporal/test_agent_llm_contract.py
new file mode 100644
index 00000000..04bf41e1
--- /dev/null
+++ b/server/tests/temporal/test_agent_llm_contract.py
@@ -0,0 +1,404 @@
+"""Contract tests for the agent workflow loop and LLM step activity.
+
+There is exactly one message standard (the unversioned wire from
+``services.llm.protocol``) and one engine. These tests lock the payload
+shapes the workflow schedules and the activity's result envelope.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import timedelta
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+
+def _tool() -> dict:
+ definition = {
+ "name": "write_todos",
+ "description": "Write a todo list",
+ "parameters": {
+ "type": "object",
+ "properties": {"todos": {"type": "array"}},
+ },
+ }
+ return {
+ "name": "write_todos",
+ "definition": definition,
+ "node_type": "writeTodos",
+ "version": 1,
+ "task_queue": "write-todos",
+ "tool_node_id": "todo-1",
+ "parameters": {},
+ "tool_info": {
+ "node_id": "todo-1",
+ "node_type": "writeTodos",
+ "label": "Todos",
+ "parameters": {},
+ },
+ }
+
+
+def _payload() -> dict:
+ return {
+ "node_id": "agent-1",
+ "node_type": "aiAgent",
+ "workflow_id": "graph-1",
+ "session_id": "session-1",
+ "provider": "openai",
+ "model": "test-model",
+ "max_tokens": 100,
+ "temperature": 0,
+ "system_message": "Be useful",
+ "user_prompt": "do the work",
+ "tools": [_tool()],
+ "memory_node_id": "",
+ "memory_content": "",
+ "memory_window_size": 10,
+ "max_iterations": 2,
+ "thinking_config": None,
+ "compaction_threshold": None,
+ }
+
+
+def patched_workflow(monkeypatch):
+ import services.temporal.agent_workflow as workflow_module
+
+ temporal_workflow = workflow_module.workflow
+ monkeypatch.setattr(temporal_workflow, "logger", MagicMock())
+ monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: True)
+ monkeypatch.setattr(
+ temporal_workflow,
+ "info",
+ lambda: SimpleNamespace(
+ workflow_id="agent-run-1",
+ run_id="run-id-12345678",
+ ),
+ )
+ monkeypatch.setattr(
+ workflow_module,
+ "get_node_class",
+ lambda _node_type: SimpleNamespace(needs_canvas=False),
+ )
+ return temporal_workflow
+
+
+class TestWorkflowLoopContract:
+ @pytest.mark.asyncio
+ async def test_llm_step_payload_shape_and_heartbeat(
+ self,
+ monkeypatch,
+ patched_workflow,
+ ):
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ llm_calls: list[tuple[dict, dict]] = []
+
+ async def fake_execute_activity(name, *, args, **kwargs):
+ if name == "agent.prepare_payload":
+ return _payload()
+ if name == "agent.broadcast_progress":
+ return {"emitted": True}
+ if name == "agent.execute_llm_step":
+ llm_calls.append((args[0], kwargs))
+ return {
+ "kind": "final",
+ "content": "done",
+ "thinking": None,
+ "usage": {"input_tokens": 3, "output_tokens": 1},
+ }
+ if name == "agent.store_output":
+ return {"stored": True}
+ if name == "agent.skill.clear":
+ return {"cleared": True}
+ raise AssertionError(f"Unexpected activity {name}")
+
+ monkeypatch.setattr(
+ patched_workflow,
+ "execute_activity",
+ fake_execute_activity,
+ )
+
+ result = await AgentWorkflow().run(
+ {"node_id": "agent-1", "execution_id": "root-run-1"}
+ )
+
+ assert result["success"] is True
+ assert len(llm_calls) == 1
+ llm_payload, options = llm_calls[0]
+ # One standard: no engine marker, no wire version, no credential.
+ assert "llm_engine" not in llm_payload
+ assert "message_wire_version" not in llm_payload
+ assert "api_key" not in llm_payload
+ assert "tool_data" not in llm_payload
+ assert llm_payload["tools"] == [_tool()["definition"]]
+ assert [m["role"] for m in llm_payload["messages"]] == [
+ "system",
+ "user",
+ ]
+ assert all("version" not in m for m in llm_payload["messages"])
+ assert options["heartbeat_timeout"] == timedelta(minutes=1)
+ assert options["retry_policy"].maximum_attempts == 1
+
+ @pytest.mark.asyncio
+ async def test_compaction_summarizes_live_messages_without_memory(
+ self,
+ monkeypatch,
+ patched_workflow,
+ ):
+ """Compaction is gated on the token threshold alone.
+
+ The retired design additionally required a memory node's markdown,
+ so context-only agents could never compact. The activity now
+ receives the live transcript, not memory content.
+ """
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ prepared = _payload()
+ prepared["compaction_threshold"] = 5
+ assert prepared["memory_content"] == "" # no memory node
+ llm_turn = 0
+ compact_payloads: list[dict] = []
+
+ async def fake_execute_activity(name, *, args, **_kwargs):
+ nonlocal llm_turn
+ if name == "agent.prepare_payload":
+ return prepared
+ if name == "agent.broadcast_progress":
+ return {"emitted": True}
+ if name == "agent.execute_llm_step":
+ llm_turn += 1
+ if llm_turn == 1:
+ return {
+ "kind": "tool_calls",
+ "calls": [
+ {
+ "id": "missing-1",
+ "name": "not_connected",
+ "args": {},
+ }
+ ],
+ "usage": {
+ "input_tokens": 7,
+ "output_tokens": 3,
+ "total_tokens": 10,
+ },
+ }
+ return {
+ "kind": "final",
+ "content": "done",
+ "thinking": None,
+ "usage": {
+ "input_tokens": 5,
+ "output_tokens": 1,
+ "total_tokens": 6,
+ },
+ }
+ if name == "agent.compact_context":
+ compact_payloads.append(args[0])
+ return {
+ "success": True,
+ "summary": "compacted history",
+ "usage": {
+ "input_tokens": 4,
+ "output_tokens": 2,
+ "total_tokens": 6,
+ },
+ }
+ if name == "agent.store_output":
+ return {"stored": True}
+ if name == "agent.skill.clear":
+ return {"cleared": True}
+ raise AssertionError(f"Unexpected activity {name}")
+
+ monkeypatch.setattr(
+ patched_workflow,
+ "execute_activity",
+ fake_execute_activity,
+ )
+
+ result = await AgentWorkflow().run(
+ {"node_id": "agent-1", "execution_id": "root-run-1"}
+ )
+
+ assert result["success"] is True
+ assert len(compact_payloads) == 1
+ compact_payload = compact_payloads[0]
+ # The live transcript is summarized — not memory markdown.
+ assert "messages" in compact_payload
+ assert "memory_content" not in compact_payload
+ assert compact_payload["provider"] == "openai"
+ assert compact_payload["model"] == "test-model"
+ # Lifetime usage: turn1 + turn2 + summarizer.
+ assert result["result"]["usage"] == {
+ "input_tokens": 16,
+ "output_tokens": 6,
+ "total_tokens": 22,
+ }
+
+ def test_tool_result_message_shape(self):
+ from services.temporal.agent_workflow import (
+ _append_tool_result_message,
+ )
+
+ messages: list[dict] = []
+ _append_tool_result_message(
+ messages,
+ content='{"ok": true}',
+ tool_call_id="call-1",
+ name="write_todos",
+ )
+ assert "version" not in messages[0]
+ assert messages[0]["role"] == "tool"
+ assert messages[0]["tool_call_id"] == "call-1"
+ assert messages[0]["blocks"][0]["type"] == "tool_result"
+
+ def test_tool_turn_reasoning_is_read_from_canonical_message(self):
+ from services.llm.protocol import (
+ ContentBlock,
+ Message,
+ message_to_wire,
+ )
+ from services.temporal.agent_workflow import (
+ _native_assistant_thinking,
+ )
+
+ wire = message_to_wire(
+ Message(
+ role="assistant",
+ blocks=[
+ ContentBlock(type="reasoning", text="first"),
+ ContentBlock(type="reasoning", text="second"),
+ ],
+ )
+ )
+ assert _native_assistant_thinking(wire) == "first\n\nsecond"
+
+
+class TestLlmStepActivity:
+ def test_structured_llm_error_becomes_safe_temporal_failure(self):
+ from services.llm.protocol import LLMError, LLMErrorCategory
+ from services.temporal.agent_activities import (
+ _as_temporal_llm_error,
+ )
+
+ provider_error = LLMError(
+ message="raw body included secret request details",
+ provider="openai",
+ category=LLMErrorCategory.RATE_LIMIT,
+ retryable=True,
+ status_code=429,
+ provider_code="capacity",
+ request_id="req-123",
+ retry_after=1.5,
+ )
+ temporal_error = _as_temporal_llm_error(provider_error)
+
+ assert "raw body" not in str(temporal_error)
+ assert temporal_error.type == "LLMError.rate_limit"
+ assert temporal_error.non_retryable is False
+ assert temporal_error.details == (
+ {
+ "provider": "openai",
+ "category": "rate_limit",
+ "retryable": True,
+ "status_code": 429,
+ "provider_code": "capacity",
+ "request_id": "req-123",
+ "retry_after": 1.5,
+ "retry_after_raw": None,
+ },
+ )
+
+ @pytest.mark.asyncio
+ async def test_buffered_call_heartbeats_while_waiting(
+ self,
+ monkeypatch,
+ ):
+ import services.temporal.agent_activities as activity_module
+
+ heartbeat = MagicMock()
+ monkeypatch.setattr(activity_module.activity, "heartbeat", heartbeat)
+
+ async def delayed_result():
+ await asyncio.sleep(0.02)
+ return "done"
+
+ result = await activity_module._await_with_llm_heartbeats(
+ delayed_result(),
+ detail="waiting",
+ interval_seconds=0.001,
+ )
+
+ assert result == "done"
+ heartbeat.assert_called_with("waiting")
+
+ @pytest.mark.asyncio
+ async def test_step_disables_sdk_retries_and_keeps_result_keys(
+ self,
+ monkeypatch,
+ ):
+ import core.container as container_module
+ import services.agent_runtime as runtime_module
+ from services.llm.protocol import (
+ LLMResponse,
+ Message,
+ ToolCall,
+ Usage,
+ message_to_wire,
+ )
+ from services.temporal.agent_activities import _execute_native_llm_step
+
+ unifier = object()
+ monkeypatch.setattr(
+ container_module.container,
+ "chat_unifier",
+ lambda: unifier,
+ )
+ call = ToolCall.from_raw(
+ id="call-1",
+ name="write_todos",
+ arguments="{not-json",
+ )
+ run_step = AsyncMock(
+ return_value=LLMResponse(
+ tool_calls=[call],
+ usage=Usage(input_tokens=5, output_tokens=2),
+ )
+ )
+ monkeypatch.setattr(runtime_module, "run_native_llm_step", run_step)
+
+ result = await _execute_native_llm_step(
+ {
+ "provider": "openai",
+ "model": "test-model",
+ "api_key": "secret",
+ "messages": [
+ message_to_wire(Message(role="user", content="go"))
+ ],
+ "tools": [_tool()["definition"]],
+ "temperature": 0,
+ "max_tokens": 100,
+ }
+ )
+
+ assert set(result) == {
+ "kind",
+ "assistant_message",
+ "calls",
+ "usage",
+ }
+ assert result["kind"] == "tool_calls"
+ assert "version" not in result["assistant_message"]
+ assert result["calls"][0]["raw_arguments"] == "{not-json"
+ assert result["calls"][0]["parse_error"]
+ assert result["usage"]["total_tokens"] == 7
+
+ assert run_step.await_args.args == (unifier,)
+ kwargs = run_step.await_args.kwargs
+ assert kwargs["sdk_max_retries"] == 0
+ assert kwargs["translate_errors"] is False
+ assert kwargs["tools"][0].name == "write_todos"
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index 9890d4f0..795ba633 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -20,17 +20,6 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
-# Bounded reference shape carried across a continue_as_new rollover.
-_CONTEXT_REF = {
- "workflow_id": "workflow-1",
- "context_node_id": "workflow-1:context:1",
- "generation": 2,
- "thread_id": "session:abc",
- "epoch": 1,
- "revision": 7,
-}
-
-
class TestAgentWorkflowDefinition:
"""``AgentWorkflow`` must be a valid Temporal workflow definition
so workers can register it."""
@@ -145,28 +134,53 @@ class TestContextJournalIdentity:
"sibling agents sharing a Context node overwrite each other"
)
- def test_resumed_run_replays_the_transcript_from_the_journal(self):
- """continue_as_new carries references, not the conversation.
+ def test_resumed_run_continues_from_the_carried_transcript(self):
+ """continue_as_new carries the live transcript itself.
- The rollover is gated on ``context_ref``, so without a replay step
- attaching a Context node is what makes a long run forget everything it
- had said -- the same class of bug as the original ``context_ref``
- regression, one boundary later.
+ The journal-replay design reconstructed the conversation from the
+ Context store on resume, and its journal was missing every tool
+ result — so the replayed transcript ended on an assistant tool-call
+ turn with no answers, which every provider rejects (Gemini 400:
+ "Requests ending with a model turn are not supported"). Carrying
+ the messages directly makes that bug unrepresentable.
"""
import inspect
from services.temporal.agent_workflow import AgentWorkflow
source = inspect.getsource(AgentWorkflow.run)
- assert "agent.reconstruct_context_messages" in source, (
- "a resumed AgentWorkflow must replay its transcript from the "
- "journal before continuing"
+ assert 'resume.get("transcript")' in source, (
+ "a resumed AgentWorkflow must continue from the transcript "
+ "carried across continue_as_new"
+ )
+ assert "agent.reconstruct_context_messages" not in source, (
+ "journal replay on resume was retired; the transcript crosses "
+ "the boundary directly"
)
- replay_at = source.index("agent.reconstruct_context_messages")
+ carried_at = source.index('resume.get("transcript")')
loop_at = source.index("agent.execute_llm_step")
- assert replay_at < loop_at, (
- "the transcript must be restored before the first LLM step of "
- "the resumed run"
+ assert carried_at < loop_at, (
+ "the carried transcript must be adopted before the first LLM "
+ "step of the resumed run"
+ )
+
+ def test_rollover_guards_transcript_size(self):
+ """The CAN argument shares Temporal's 2 MiB payload error limit.
+
+ An oversized transcript must degrade to the opening prompt with a
+ warning instead of failing the rollover itself (which would kill
+ the run at exactly the moment it tried to survive).
+ """
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ assert "_CAN_TRANSCRIPT_MAX_BYTES" in source
+ guard_at = source.index("_CAN_TRANSCRIPT_MAX_BYTES")
+ can_at = source.index("workflow.continue_as_new(")
+ assert guard_at < can_at, (
+ "the size guard must run before continue_as_new is issued"
)
def test_workflow_never_claims_the_activity_rebuilds_the_request(self):
@@ -192,80 +206,6 @@ class TestContextJournalIdentity:
f"always builds its request from `messages`"
)
- @pytest.mark.asyncio
- async def test_replay_returns_the_journalled_transcript(self, monkeypatch):
- import services.agent_context as agent_context
- from services.temporal import agent_activities
-
- wires = [
- {"version": 2, "role": "system", "content": "you are helpful"},
- {"version": 2, "role": "user", "content": "hello"},
- ]
-
- async def _replay(_store, ref):
- return ref, wires
-
- monkeypatch.setattr(agent_activities, "_context_store", lambda: object())
- monkeypatch.setattr(agent_context, "reconstruct_message_wire_v2", _replay)
-
- result = await agent_activities.reconstruct_context_messages(
- {"context_ref": _CONTEXT_REF}
- )
-
- assert result["restored"] is True
- assert result["messages"] == wires
-
- @pytest.mark.asyncio
- @pytest.mark.parametrize(
- "failure, reason",
- [
- ("opaque", "opaque_checkpoint"),
- ("boom", "replay_failed"),
- ],
- )
- async def test_replay_degrades_instead_of_failing_the_run(
- self, monkeypatch, failure, reason
- ):
- """A rehydration miss must never kill a resumed run.
-
- The rebuilt system + memory + prompt is a worse starting point than
- the journal, but it is a working one; raising here would turn an
- unreadable thread into a dead agent.
- """
- import services.agent_context as agent_context
- from services.agent_context import OpaqueCheckpointError
- from services.temporal import agent_activities
-
- async def _replay(_store, _ref):
- raise (
- OpaqueCheckpointError("provider-native checkpoint")
- if failure == "opaque"
- else RuntimeError("blob missing")
- )
-
- monkeypatch.setattr(agent_activities, "_context_store", lambda: object())
- monkeypatch.setattr(agent_context, "reconstruct_message_wire_v2", _replay)
-
- result = await agent_activities.reconstruct_context_messages(
- {"context_ref": _CONTEXT_REF}
- )
-
- assert result["restored"] is False
- assert result["reason"] == reason
- assert result["messages"] == []
-
- @pytest.mark.asyncio
- async def test_replay_without_a_context_ref_is_a_no_op(self):
- from services.temporal import agent_activities
-
- result = await agent_activities.reconstruct_context_messages({})
-
- assert result == {
- "messages": [],
- "restored": False,
- "reason": "no_context_ref",
- }
-
def test_llm_step_has_a_single_implementation(self):
"""A Context node observes execution; it must not steer it.
@@ -476,7 +416,7 @@ class TestContextJournalIdentity:
create_children = source.index("asyncio.create_task(", gather)
ordered_loop = source.index("for call_index, call in enumerate(calls):", create_children)
ordered_await = source.index(
- "await task_manager_delegation_tasks[call_index]", ordered_loop
+ "await task_manager_delegation_tasks.pop(call_index)", ordered_loop
)
assert start_activity < gather < create_children < ordered_loop < ordered_await
assert "task_manager_preflight_results[call_index]" in source
@@ -501,30 +441,28 @@ class TestAgentActivities:
defn = getattr(persist_agent_turn, "__temporal_activity_definition")
assert defn.name == "agent.persist_turn"
- def test_compact_agent_memory_registered(self):
- from services.temporal.agent_activities import compact_agent_memory
+ def test_compact_context_registered(self):
+ from services.temporal.agent_activities import compact_context
- defn = getattr(compact_agent_memory, "__temporal_activity_definition")
- assert defn.name == "agent.compact_memory"
+ defn = getattr(compact_context, "__temporal_activity_definition")
+ assert defn.name == "agent.compact_context"
def test_collect_returns_all_agent_activities(self):
- """Each successive sprint added one F4.B agent activity:
- infra (3) → per-agent-wiring +prepare_payload (4) → CloudEvents
- cleanup +broadcast_progress (5) → +store_output (6) →
- +refresh_tools (7) + durable delegation lifecycle/coordinator (13). All must register so the AgentWorkflow loop
- can schedule them by name."""
+ """Every activity the AgentWorkflow loop schedules by name must
+ register here. The single-standard cleanup retired the journal
+ replay surface (reconstruct_context_messages / append_context /
+ compact_memory) — the transcript now crosses continue_as_new
+ directly and compaction summarizes the live conversation."""
from services.temporal.agent_activities import collect_agent_activities
activities = collect_agent_activities()
names = sorted(getattr(a, "__temporal_activity_definition").name for a in activities)
assert names == [
"agent.acquire_subagent_permit",
- "agent.append_context",
"agent.begin_delegation",
"agent.broadcast_progress",
"agent.cancel_delegation",
"agent.compact_context",
- "agent.compact_memory",
"agent.execute_llm_step",
"agent.finalize_team",
"agent.finish_delegation",
@@ -532,7 +470,6 @@ class TestAgentActivities:
"agent.prepare_context",
"agent.prepare_payload",
"agent.queue_delegation",
- "agent.reconstruct_context_messages",
"agent.refresh_tools",
"agent.register_task_execution",
"agent.release_subagent_permit",
@@ -1234,18 +1171,43 @@ class TestAgentContinueAsNew:
"""The agent loop carries a transcript and a growing tool list, so it
must roll over before Temporal's ~51,200-event hard terminate."""
- def test_rollover_exists_and_is_bounded(self):
+ def test_rollover_exists_and_carries_the_essentials(self):
import inspect
from services.temporal.agent_workflow import AgentWorkflow
source = inspect.getsource(AgentWorkflow.run)
assert "workflow.continue_as_new(" in source
- # Only references and counters cross the boundary. Carrying the
- # transcript would defeat the rollover it is meant to enable.
- carried = source[source.index("_RESUME_MARKER:") :][:600]
- for forbidden in ('"messages"', '"tools"', '"assistant_message"'):
- assert forbidden not in carried, f"{forbidden} must not cross a rollover"
+ # The transcript, usage totals, refs and counters cross the
+ # boundary. The transcript is size-guarded (see
+ # test_rollover_guards_transcript_size) so the CAN argument stays
+ # under Temporal's payload error limit.
+ carried = source[source.index("_RESUME_MARKER:") :][:700]
+ for required in (
+ '"transcript"',
+ '"usage"',
+ '"context_usage"',
+ '"iteration"',
+ '"execution_id"',
+ '"context_ref"',
+ ):
+ assert required in carried, f"{required} must cross the rollover"
+
+ def test_rollover_is_not_gated_on_a_context_node(self):
+ """Every agent must roll over under history pressure.
+
+ The journal-replay design gated the rollover on ``context_ref``,
+ so an agent without a Context node grew until Temporal's hard
+ history terminate. With the transcript carried directly there is
+ no reason to require a Context node.
+ """
+ import inspect
+
+ from services.temporal.agent_workflow import AgentWorkflow
+
+ source = inspect.getsource(AgentWorkflow.run)
+ assert "if _history_pressure(_AGENT_HISTORY_SOFT_CAP):" in source
+ assert "if context_ref and _history_pressure" not in source
def test_execution_id_survives_the_rollover(self):
"""run_id changes on continue-as-new.
diff --git a/server/tests/temporal/test_agent_workflow_replay.py b/server/tests/temporal/test_agent_workflow_replay.py
index 848bacfa..4e19b215 100644
--- a/server/tests/temporal/test_agent_workflow_replay.py
+++ b/server/tests/temporal/test_agent_workflow_replay.py
@@ -1,18 +1,22 @@
-"""SDK-level replay gates for the native agent-engine cutover.
-
-Unlike the fast unit tests in ``test_native_llm_cutover.py``, these tests run
-the real workflow worker against Temporal's time-skipping test server and feed
-the recorded event history through ``Replayer``. Provider calls remain fully
-stubbed activities, so the gate needs no credentials or network API access.
+"""SDK-level replay gate for the agent workflow.
+
+Runs the real workflow worker against Temporal's time-skipping test server
+and feeds the recorded event history through ``Replayer``. Provider calls
+remain fully stubbed activities, so the gate needs no credentials or
+network API access.
+
+There is exactly one message standard: the unversioned wire shape from
+``services.llm.protocol.message_to_wire``. Histories recorded before the
+single-standard cleanup are deliberately non-replayable (dev decision —
+deployments are Reset), so this gate covers every history the current
+code can produce.
"""
from __future__ import annotations
import asyncio
-import base64
import subprocess
import sys
-import zlib
from datetime import timedelta
from pathlib import Path
from typing import Any
@@ -29,11 +33,10 @@ from services.temporal.agent_workflow import AgentWorkflow
TASK_QUEUE = "agent-native-replay-gate"
-FIXTURES_DIR = Path(__file__).with_name("fixtures")
-def _prepared_payload(*, engine: str) -> dict[str, Any]:
- payload: dict[str, Any] = {
+def _prepared_payload() -> dict[str, Any]:
+ return {
"node_id": "agent-replay",
"node_type": "aiAgent",
"workflow_id": "graph-replay",
@@ -52,33 +55,11 @@ def _prepared_payload(*, engine: str) -> dict[str, Any]:
"thinking_config": None,
"compaction_threshold": None,
}
- if engine == "native":
- payload.update(
- {
- "llm_engine": "native",
- "message_wire_version": 2,
- }
- )
- elif engine == "langchain":
- payload.update(
- {
- "llm_engine": "langchain",
- "message_wire_version": 1,
- }
- )
- elif engine == "legacy":
- # Pre-cutover histories included the resolved secret in prepare
- # output. The compatibility branch must continue accepting that
- # recorded shape, while native histories must never persist it.
- payload["api_key"] = "legacy-recorded-test-key"
- else:
- raise AssertionError(f"Unexpected test engine {engine!r}")
- return payload
@activity.defn(name="agent.prepare_payload")
async def _prepare_payload(context: dict[str, Any]) -> dict[str, Any]:
- return _prepared_payload(engine=str(context["test_engine"]))
+ return _prepared_payload()
@activity.defn(name="agent.broadcast_progress")
@@ -88,41 +69,22 @@ async def _broadcast_progress(_payload: dict[str, Any]) -> dict[str, Any]:
@activity.defn(name="agent.execute_llm_step")
async def _execute_llm_step(payload: dict[str, Any]) -> dict[str, Any]:
- if payload.get("llm_engine") == "native":
- assert payload["message_wire_version"] == 2
- assert "api_key" not in payload
- assert "tool_data" not in payload
- assert all(message["version"] == 2 for message in payload["messages"])
- assert activity.info().heartbeat_timeout == timedelta(minutes=1)
- assistant = message_to_wire(
- Message(role="assistant", content="done")
- )
- elif payload.get("llm_engine") == "langchain":
- # New runs under the emergency switch use the legacy adapter without
- # persisting a credential in either activity result or input.
- assert payload["message_wire_version"] == 1
- assert payload["node_id"] == "agent-replay"
- assert "api_key" not in payload
- assert "tools" not in payload
- assert "tool_data" in payload
- assert all("type" in message for message in payload["messages"])
- assert activity.info().heartbeat_timeout == timedelta(minutes=1)
- assistant = {"type": "ai", "data": {"content": "done"}}
- else:
- # This is the pre-cutover contract: no engine marker, LangChain's
- # canonical message dictionaries, and no heartbeat timeout.
- assert "llm_engine" not in payload
- assert "message_wire_version" not in payload
- assert payload["api_key"] == "legacy-recorded-test-key"
- assert "tools" not in payload
- assert "tool_data" in payload
- assert all("type" in message for message in payload["messages"])
- assert activity.info().heartbeat_timeout is None
- assistant = {"type": "ai", "data": {"content": "done"}}
+ # One standard: no engine marker, no wire version, no credential in
+ # the activity input, provider-neutral tool definitions only.
+ assert "llm_engine" not in payload
+ assert "message_wire_version" not in payload
+ assert "api_key" not in payload
+ assert "tool_data" not in payload
+ for message in payload["messages"]:
+ assert "version" not in message
+ assert message.get("role")
+ assert activity.info().heartbeat_timeout == timedelta(minutes=1)
return {
"kind": "final",
- "assistant_message": assistant,
+ "assistant_message": message_to_wire(
+ Message(role="assistant", content="done")
+ ),
"content": "done",
"thinking": None,
"usage": {"input_tokens": 2, "output_tokens": 1},
@@ -148,22 +110,6 @@ _TEST_ACTIVITIES = [
]
-async def _run_and_capture(
- environment: WorkflowEnvironment,
- *,
- engine: str,
-) -> tuple[dict[str, Any], WorkflowHistory]:
- workflow_id = f"agent-{engine}-replay-{uuid4()}"
- handle = await environment.client.start_workflow(
- "AgentWorkflow",
- {"node_id": "agent-replay", "test_engine": engine},
- id=workflow_id,
- task_queue=TASK_QUEUE,
- )
- result = await handle.result()
- return result, await handle.fetch_history()
-
-
def _scheduled_activities(history: WorkflowHistory) -> list[Any]:
return [
event.activity_task_scheduled_event_attributes
@@ -172,16 +118,8 @@ def _scheduled_activities(history: WorkflowHistory) -> list[Any]:
]
-def _load_captured_history(name: str, workflow_id: str) -> WorkflowHistory:
- """Load a frozen Temporal JSON history stored as compressed base64."""
-
- encoded = (FIXTURES_DIR / name).read_bytes()
- history_json = zlib.decompress(base64.b64decode(encoded)).decode("utf-8")
- return WorkflowHistory.from_json(workflow_id, history_json)
-
-
async def _run_replay_gate() -> None:
- """Execute all engine branches and replay their serialized histories."""
+ """Execute a run and replay its serialized history."""
async with await WorkflowEnvironment.start_time_skipping() as environment:
async with Worker(
@@ -190,27 +128,20 @@ async def _run_replay_gate() -> None:
workflows=[AgentWorkflow],
activities=_TEST_ACTIVITIES,
):
- native_result, native_history = await _run_and_capture(
- environment,
- engine="native",
- )
- emergency_result, emergency_history = await _run_and_capture(
- environment,
- engine="langchain",
- )
- legacy_result, legacy_history = await _run_and_capture(
- environment,
- engine="legacy",
+ handle = await environment.client.start_workflow(
+ "AgentWorkflow",
+ {"node_id": "agent-replay"},
+ id=f"agent-replay-{uuid4()}",
+ task_queue=TASK_QUEUE,
)
+ result = await handle.result()
+ history = await handle.fetch_history()
- assert native_result["success"] is True
- assert native_result["result"]["response"] == "done"
- assert emergency_result["success"] is True
- assert emergency_result["result"]["response"] == "done"
- assert legacy_result["success"] is True
- assert legacy_result["result"]["response"] == "done"
+ assert result["success"] is True
+ assert result["result"]["response"] == "done"
- expected_order = [
+ scheduled = _scheduled_activities(history)
+ assert [item.activity_type.name for item in scheduled] == [
"agent.prepare_payload",
"agent.broadcast_progress",
"agent.broadcast_progress",
@@ -219,101 +150,40 @@ async def _run_replay_gate() -> None:
"agent.skill.clear",
"agent.broadcast_progress",
]
- native_scheduled = _scheduled_activities(native_history)
- emergency_scheduled = _scheduled_activities(emergency_history)
- legacy_scheduled = _scheduled_activities(legacy_history)
- assert [
- item.activity_type.name for item in native_scheduled
- ] == expected_order
- assert [
- item.activity_type.name for item in emergency_scheduled
- ] == expected_order
- assert [
- item.activity_type.name for item in legacy_scheduled
- ] == expected_order
-
- native_llm = native_scheduled[3]
- emergency_llm = emergency_scheduled[3]
- legacy_llm = legacy_scheduled[3]
- assert (
- native_llm.heartbeat_timeout.ToTimedelta()
- == timedelta(minutes=1)
- )
- # Temporal records the omitted optional duration as an explicit zero
- # value in history; activity.info() still correctly exposes None.
- assert emergency_llm.heartbeat_timeout.ToTimedelta() == timedelta(
- minutes=1
- )
- assert legacy_llm.heartbeat_timeout.ToTimedelta() == timedelta(0)
- [native_input] = await environment.client.data_converter.decode(
- native_llm.input.payloads
+ llm = scheduled[3]
+ assert llm.heartbeat_timeout.ToTimedelta() == timedelta(minutes=1)
+ [llm_input] = await environment.client.data_converter.decode(
+ llm.input.payloads
)
- [emergency_input] = await environment.client.data_converter.decode(
- emergency_llm.input.payloads
+ assert "llm_engine" not in llm_input
+ assert "message_wire_version" not in llm_input
+ assert "api_key" not in llm_input
+ assert "tool_data" not in llm_input
+
+ completed = next(
+ event.activity_task_completed_event_attributes
+ for event in history.events
+ if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED
)
- [legacy_input] = await environment.client.data_converter.decode(
- legacy_llm.input.payloads
+ [prepared] = await environment.client.data_converter.decode(
+ completed.result.payloads
)
- assert native_input["llm_engine"] == "native"
- assert native_input["message_wire_version"] == 2
- assert "api_key" not in native_input
- assert "tool_data" not in native_input
- assert emergency_input["llm_engine"] == "langchain"
- assert emergency_input["message_wire_version"] == 1
- assert "api_key" not in emergency_input
- assert "tool_data" in emergency_input
- assert "llm_engine" not in legacy_input
- assert "message_wire_version" not in legacy_input
- assert "tool_data" in legacy_input
- assert legacy_input["api_key"] == "legacy-recorded-test-key"
-
- prepare_results = []
- for history in (native_history, emergency_history, legacy_history):
- completed = next(
- event.activity_task_completed_event_attributes
- for event in history.events
- if event.event_type
- == EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED
- )
- [prepared] = await environment.client.data_converter.decode(
- completed.result.payloads
- )
- prepare_results.append(prepared)
-
- native_prepared, emergency_prepared, legacy_prepared = prepare_results
- assert native_prepared["llm_engine"] == "native"
- assert "api_key" not in native_prepared
- assert emergency_prepared["llm_engine"] == "langchain"
- assert "api_key" not in emergency_prepared
- assert "llm_engine" not in legacy_prepared
- assert legacy_prepared["api_key"] == "legacy-recorded-test-key"
+ assert "llm_engine" not in prepared
+ assert "api_key" not in prepared
+ # JSON round-trip makes this a captured-history gate rather than
+ # replaying the live protobuf object in memory.
replayer = Replayer(workflows=[AgentWorkflow])
- live_histories = (
- native_history,
- emergency_history,
- legacy_history,
+ captured = WorkflowHistory.from_json(
+ history.workflow_id,
+ history.to_json(),
)
- for history in live_histories:
- # JSON round-trip makes this a captured-history gate rather
- # than replaying the live protobuf object in memory.
- captured = WorkflowHistory.from_json(
- history.workflow_id,
- history.to_json(),
- )
- replay = await replayer.replay_workflow(captured)
- assert replay.replay_failure is None
-
- # The frozen pre-native fixture was removed with the replay patches.
- # It asserted that a history recorded BEFORE `agent-tool-call-identity-v2`
- # still replayed; with the patch markers deleted that history is
- # deliberately non-replayable, and Temporal history back-compat is
- # explicitly out of scope. The generated-shape replays above still
- # gate determinism for every history this code can now produce.
+ replay = await replayer.replay_workflow(captured)
+ assert replay.replay_failure is None
-def test_all_cutover_history_shapes_execute_and_replay() -> None:
+def test_generated_history_executes_and_replays() -> None:
"""Run the SDK gate in a clean process with valid Windows I/O handles."""
completed = subprocess.run(
diff --git a/server/tests/temporal/test_agent_workflow_v2.py b/server/tests/temporal/test_agent_workflow_v2.py
index ad607a81..11586b1b 100644
--- a/server/tests/temporal/test_agent_workflow_v2.py
+++ b/server/tests/temporal/test_agent_workflow_v2.py
@@ -3,29 +3,7 @@
from __future__ import annotations
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
-
-from pydantic import BaseModel
-import pytest
-
-
-def _ref(revision: int = 1) -> dict:
- return {
- "workflow_id": "workflow-1",
- "context_node_id": "context-1",
- "generation": 3,
- "thread_id": "execution:run-1",
- "epoch": 1,
- "revision": revision,
- }
-
-
-
-
-
-
-
-
+from unittest.mock import patch
def _settings(*, enabled: bool = True):
@@ -119,200 +97,3 @@ def test_explicit_event_session_beats_execution_thread():
"delegated_task_id": None,
"execution_id": "firing-42",
}
-
-
-def test_prepare_and_rebind_reject_duplicate_canonical_tool_names():
- from temporalio.exceptions import ApplicationError
-
- from services.temporal.agent_activities import (
- _validate_unique_tool_names,
- )
-
- tools = [
- {
- "name": "memory",
- "tool_node_id": "memory-a",
- "node_type": "simpleMemory",
- },
- {
- "name": "memory",
- "tool_node_id": "memory-b",
- "node_type": "simpleMemory",
- },
- ]
- with pytest.raises(ApplicationError) as exc_info:
- _validate_unique_tool_names(tools, phase="hot rebind")
-
- assert exc_info.value.type == "DuplicateAgentToolName"
- assert "memory-a" in str(exc_info.value)
- assert "memory-b" in str(exc_info.value)
-
-
-async def test_tool_input_preserves_supplied_only_semantics(monkeypatch):
- import services.node_registry as registry
- from services.temporal.agent_activities import _validate_tool_args
-
- class MemoryInput(BaseModel):
- operation: str
- limit: int = 20
-
- class MemoryNode:
- @classmethod
- def tool_input_model(cls):
- return MemoryInput
-
- monkeypatch.setattr(
- registry,
- "get_node_class",
- lambda node_type: MemoryNode if node_type == "simpleMemory" else None,
- )
-
- validated, error = await _validate_tool_args(
- {
- "node_type": "simpleMemory",
- "definition": {
- "parameters": MemoryInput.model_json_schema(),
- },
- },
- {
- "args": {"operation": "list"},
- },
- )
-
- assert error is None
- assert validated == {"operation": "list"}
-
-
-async def test_plugin_tool_activity_loads_arguments_by_reference(monkeypatch):
- import services.temporal.agent_activities as module
-
- store = object()
- monkeypatch.setattr(module, "_context_store", lambda: store)
- monkeypatch.setattr(
- module,
- "_runtime_config",
- AsyncMock(
- return_value={
- "protocol": "agent-context-v2",
- "prepared": {
- "tools": [
- {
- "name": "memory",
- "tool_node_id": "memory-1",
- "node_type": "simpleMemory",
- "version": 2,
- }
- ]
- },
- }
- ),
- )
- execute = AsyncMock(return_value={"result_ref": "sha256:result"})
- monkeypatch.setattr(module, "_execute_tool_and_append", execute)
- pending = {
- "call_index": 1,
- "call_id": "call-1",
- "name": "memory",
- "node_id": "memory-1",
- "node_type": "simpleMemory",
- "version": 2,
- "task_queue": "memory-heavy",
- "known": True,
- }
-
- result = await module.execute_tool_activity(
- {
- "protocol": "agent-context-tool-v2",
- "context_ref": _ref(2),
- "runtime_config_ref": "sha256:runtime",
- "response_ref": "sha256:response",
- "pending_tool": pending,
- "operation_id": "tool-operation",
- "iteration": 1,
- },
- expected_node_type="simpleMemory",
- expected_version=2,
- )
-
- assert result == {"result_ref": "sha256:result"}
- kwargs = execute.await_args.kwargs
- assert kwargs["store"] is store
- assert kwargs["response_ref"] == "sha256:response"
- assert kwargs["pending"] == pending
- assert "args" not in kwargs
-
-
-def _event(sequence, event_type, *, wire=None, payload_ref=None):
- from models.agent_context import AgentContextEvent
-
- return AgentContextEvent(
- sequence=sequence,
- event_type=event_type,
- message_wire_v2=wire,
- payload_ref=payload_ref,
- operation_id=f"operation:{sequence}",
- provider="openai",
- previous_hash="0" * 64,
- payload_hash=str(sequence) * 64,
- )
-
-
-
-
-
-
-async def test_lifetime_usage_includes_compaction_calls():
- from services.temporal.agent_activities import (
- _context_ref,
- _lifetime_usage,
- )
-
- class Store:
- async def load_journal_page(self, *args, **kwargs):
- return (
- [
- SimpleNamespace(
- event_type="message.assistant",
- payload_ref="sha256:assistant",
- operation_id="temporal:run:iteration:1:assistant",
- ),
- SimpleNamespace(
- event_type="context.compacted",
- payload_ref="sha256:compaction",
- operation_id="temporal:run:iteration:1:compact:event",
- ),
- ],
- None,
- )
-
- async def get_blob(self, payload_ref):
- return {
- "usage": (
- {
- "input_tokens": 10,
- "output_tokens": 2,
- "total_tokens": 12,
- }
- if payload_ref == "sha256:assistant"
- else {
- "input_tokens": 4,
- "output_tokens": 1,
- "total_tokens": 5,
- }
- )
- }
-
- usage = await _lifetime_usage(
- Store(),
- _context_ref(_ref()),
- "temporal:run",
- )
-
- assert usage == {
- "input_tokens": 14,
- "output_tokens": 3,
- "total_tokens": 17,
- }
diff --git a/server/tests/temporal/test_cooperative_pause.py b/server/tests/temporal/test_cooperative_pause.py
index 1f90ef49..4091be58 100644
--- a/server/tests/temporal/test_cooperative_pause.py
+++ b/server/tests/temporal/test_cooperative_pause.py
@@ -350,8 +350,6 @@ def _agent_payload() -> dict:
"max_iterations": 2,
"thinking_config": None,
"compaction_threshold": None,
- "llm_engine": "native",
- "message_wire_version": 2,
}
diff --git a/server/tests/temporal/test_native_llm_cutover.py b/server/tests/temporal/test_native_llm_cutover.py
deleted file mode 100644
index 6a54eda2..00000000
--- a/server/tests/temporal/test_native_llm_cutover.py
+++ /dev/null
@@ -1,804 +0,0 @@
-"""Temporal compatibility tests for the native agent LLM cutover."""
-
-from __future__ import annotations
-
-import asyncio
-from datetime import timedelta
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-
-def _tool() -> dict:
- definition = {
- "name": "write_todos",
- "description": "Write a todo list",
- "parameters": {
- "type": "object",
- "properties": {"todos": {"type": "array"}},
- },
- }
- return {
- "name": "write_todos",
- "definition": definition,
- "node_type": "writeTodos",
- "version": 1,
- "task_queue": "write-todos",
- "tool_node_id": "todo-1",
- "parameters": {},
- "tool_info": {
- "node_id": "todo-1",
- "node_type": "writeTodos",
- "label": "Todos",
- "parameters": {},
- },
- }
-
-
-def _payload(*, native: bool) -> dict:
- value = {
- "node_id": "agent-1",
- "node_type": "aiAgent",
- "workflow_id": "graph-1",
- "session_id": "session-1",
- "provider": "openai",
- "model": "test-model",
- "max_tokens": 100,
- "temperature": 0,
- "system_message": "Be useful",
- "user_prompt": "do the work",
- "tools": [_tool()],
- "memory_node_id": "",
- "memory_content": "",
- "memory_window_size": 10,
- "max_iterations": 2,
- "thinking_config": None,
- "compaction_threshold": None,
- }
- if native:
- value.update({"llm_engine": "native", "message_wire_version": 2})
- else:
- value["api_key"] = "test-key"
- return value
-
-
-def _emergency_langchain_payload() -> dict:
- value = _payload(native=False)
- value.pop("api_key")
- value.update({"llm_engine": "langchain", "message_wire_version": 1})
- return value
-
-
-def patched_workflow(monkeypatch):
- import services.temporal.agent_workflow as workflow_module
-
- temporal_workflow = workflow_module.workflow
- monkeypatch.setattr(temporal_workflow, "logger", MagicMock())
- monkeypatch.setattr(temporal_workflow, "patched", lambda _patch_id: True)
- monkeypatch.setattr(
- temporal_workflow,
- "info",
- lambda: SimpleNamespace(
- workflow_id="agent-run-1",
- run_id="run-id-12345678",
- ),
- )
- monkeypatch.setattr(
- workflow_module,
- "get_node_class",
- lambda _node_type: SimpleNamespace(needs_canvas=False),
- )
- return temporal_workflow
-
-
-class TestEngineSelection:
- """After the LangChain removal there is exactly one engine.
-
- The marker survives because it is the discriminator: a history recorded
- before the cutover carries LangChain-serialised messages and no
- ``llm_engine`` key, and those messages can no longer be read.
- """
-
- @pytest.fixture
- def outside_activity_context(self, monkeypatch):
- """The guard runs after logging/heartbeat, which need a live activity."""
- from services.temporal import agent_activities
-
- monkeypatch.setattr(
- agent_activities.activity, "logger", MagicMock(), raising=False
- )
- monkeypatch.setattr(
- agent_activities.activity, "heartbeat", lambda *a, **k: None
- )
-
- @pytest.mark.asyncio
- async def test_execute_llm_step_refuses_a_pre_cutover_history(
- self, outside_activity_context
- ):
- from temporalio.exceptions import ApplicationError
-
- from services.temporal.agent_activities import execute_llm_step
-
- payload = _payload(native=True)
- payload.pop("llm_engine") # the pre-cutover shape
-
- with pytest.raises(ApplicationError) as excinfo:
- await execute_llm_step(payload)
-
- assert excinfo.value.type == "InvalidAgentLLMEngine"
- assert excinfo.value.non_retryable is True
- assert "before the native LLM cutover" in str(excinfo.value)
-
- @pytest.mark.asyncio
- async def test_execute_llm_step_refuses_the_retired_langchain_engine(
- self, outside_activity_context
- ):
- from temporalio.exceptions import ApplicationError
-
- from services.temporal.agent_activities import execute_llm_step
-
- with pytest.raises(ApplicationError) as excinfo:
- await execute_llm_step(_emergency_langchain_payload())
-
- assert excinfo.value.type == "InvalidAgentLLMEngine"
- assert excinfo.value.non_retryable is True
-
- @pytest.mark.asyncio
- async def test_prepare_payload_always_records_native(self, monkeypatch):
- """No env switch remains; the marker is a constant now."""
- import services.temporal.agent_activities as activities
-
- assert activities._NATIVE_LLM_ENGINE == "native"
- assert not hasattr(activities, "_configured_llm_engine")
- assert not hasattr(activities, "_LEGACY_LLM_ENGINE")
-
-
-class TestWorkflowBranchContract:
- @pytest.mark.asyncio
- async def test_native_history_uses_v2_messages_and_heartbeat(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- llm_calls: list[tuple[dict, dict]] = []
-
- async def fake_execute_activity(name, *, args, **kwargs):
- if name == "agent.prepare_payload":
- return _payload(native=True)
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- llm_calls.append((args[0], kwargs))
- return {
- "kind": "final",
- "content": "done",
- "thinking": None,
- "usage": {"input_tokens": 3, "output_tokens": 1},
- }
- if name == "agent.store_output":
- return {"stored": True}
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
-
- assert result["success"] is True
- assert len(llm_calls) == 1
- llm_payload, options = llm_calls[0]
- assert llm_payload["llm_engine"] == "native"
- assert llm_payload["message_wire_version"] == 2
- assert "api_key" not in llm_payload
- assert "tool_data" not in llm_payload
- assert llm_payload["tools"] == [_tool()["definition"]]
- assert [(m["version"], m["role"]) for m in llm_payload["messages"]] == [
- (2, "system"),
- (2, "user"),
- ]
- assert options["heartbeat_timeout"] == timedelta(minutes=1)
- assert options["retry_policy"].maximum_attempts == 1
-
- @pytest.mark.asyncio
- async def test_compaction_preserves_cumulative_and_summarizer_usage(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- prepared = _payload(native=True)
- prepared.update(
- {
- "memory_content": "prior history",
- "compaction_threshold": 5,
- }
- )
- llm_turn = 0
- compaction_calls = 0
-
- async def fake_execute_activity(name, *, args, **_kwargs):
- nonlocal llm_turn, compaction_calls
- if name == "agent.prepare_payload":
- return prepared
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- llm_turn += 1
- if llm_turn == 1:
- return {
- "kind": "tool_calls",
- "calls": [
- {
- "id": "missing-1",
- "name": "not_connected",
- "args": {},
- }
- ],
- "usage": {
- "input_tokens": 7,
- "output_tokens": 3,
- "total_tokens": 10,
- },
- }
- return {
- "kind": "final",
- "content": "done",
- "thinking": None,
- "usage": {
- "input_tokens": 5,
- "output_tokens": 1,
- "total_tokens": 6,
- },
- }
- if name == "agent.compact_memory":
- compaction_calls += 1
- return {
- "success": True,
- "summary": "compacted history",
- "tokens_before": 10,
- "tokens_after": 0,
- "usage": {
- "input_tokens": 4,
- "output_tokens": 2,
- "total_tokens": 6,
- },
- }
- if name == "agent.store_output":
- return {"stored": True}
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
-
- assert result["success"] is True
- assert compaction_calls == 1
- assert result["result"]["usage"] == {
- "input_tokens": 16,
- "output_tokens": 6,
- "total_tokens": 22,
- }
-
- @pytest.mark.asyncio
- async def test_markerless_compaction_preserves_legacy_payload_and_usage(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- prepared = _payload(native=False)
- prepared.update(
- {
- "memory_content": "prior history",
- "compaction_threshold": 5,
- }
- )
- llm_turn = 0
- compact_payloads = []
-
- async def fake_execute_activity(name, *, args, **_kwargs):
- nonlocal llm_turn
- if name == "agent.prepare_payload":
- return prepared
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- llm_turn += 1
- if llm_turn == 1:
- return {
- "kind": "tool_calls",
- "calls": [
- {
- "id": "missing-1",
- "name": "not_connected",
- "args": {},
- }
- ],
- "usage": {
- "input_tokens": 3,
- "output_tokens": 3,
- "total_tokens": 100,
- "cache_read_tokens": 50,
- },
- }
- return {
- "kind": "final",
- "content": "done",
- "thinking": None,
- "usage": {
- "input_tokens": 2,
- "output_tokens": 1,
- "total_tokens": 3,
- },
- }
- if name == "agent.compact_memory":
- compact_payloads.append(args[0])
- return {
- "success": True,
- "summary": "legacy compacted history",
- "tokens_before": 6,
- "tokens_after": 0,
- "usage": {
- "input_tokens": 400,
- "output_tokens": 100,
- "total_tokens": 500,
- },
- }
- if name == "agent.store_output":
- return {"stored": True}
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
-
- assert list(compact_payloads[0]) == [
- "session_id",
- "node_id",
- "memory_content",
- "provider",
- "api_key",
- "model",
- ]
- assert compact_payloads[0]["api_key"] == "test-key"
- # Historical semantics reset pre-compaction usage and did not include
- # the summarizer call in the final workflow result.
- assert result["result"]["usage"] == {
- "input_tokens": 2,
- "output_tokens": 1,
- "total_tokens": 3,
- }
-
- @pytest.mark.asyncio
- async def test_markerless_compaction_threshold_ignores_total_and_cache(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- prepared = _payload(native=False)
- prepared.update(
- {
- "memory_content": "prior history",
- "compaction_threshold": 7,
- "max_iterations": 1,
- }
- )
-
- async def fake_execute_activity(name, *, args, **_kwargs):
- if name == "agent.prepare_payload":
- return prepared
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- return {
- "kind": "tool_calls",
- "calls": [
- {
- "id": "missing-1",
- "name": "not_connected",
- "args": {},
- }
- ],
- "usage": {
- "input_tokens": 3,
- "output_tokens": 3,
- "total_tokens": 100,
- "cache_read_tokens": 50,
- },
- }
- if name == "agent.compact_memory":
- raise AssertionError(
- "markerless threshold must use input + output only"
- )
- if name == "agent.store_output":
- return {"stored": True}
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
- assert result["success"] is True
- assert result["result"]["usage"]["total_tokens"] == 100
-
- @pytest.mark.asyncio
- async def test_markerless_error_result_keeps_historical_raw_detail(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- async def fake_execute_activity(name, *, args, **_kwargs):
- if name == "agent.prepare_payload":
- return _payload(native=False)
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- failure = RuntimeError("outer activity failure")
- failure.cause = RuntimeError("legacy raw provider detail")
- raise failure
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
-
- assert result["success"] is False
- assert result["error"] == (
- "LLM step failed: legacy raw provider detail"
- )
-
- @pytest.mark.asyncio
- async def test_missing_engine_preserves_legacy_activity_input(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- llm_calls: list[tuple[dict, dict]] = []
-
- async def fake_execute_activity(name, *, args, **kwargs):
- if name == "agent.prepare_payload":
- return _payload(native=False)
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- llm_calls.append((args[0], kwargs))
- return {
- "kind": "final",
- "content": "done",
- "thinking": None,
- "usage": {},
- }
- if name == "agent.store_output":
- return {"stored": True}
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
-
- assert result["success"] is True
- llm_payload, options = llm_calls[0]
- assert "llm_engine" not in llm_payload
- assert "message_wire_version" not in llm_payload
- assert "tools" not in llm_payload
- assert llm_payload["tool_data"] == [_tool()["tool_info"]]
- assert list(llm_payload) == [
- "provider",
- "model",
- "api_key",
- "messages",
- "tool_data",
- "system_message",
- "temperature",
- "max_tokens",
- "thinking_config",
- ]
- assert llm_payload["messages"] == [
- {"type": "system", "data": {"content": "Be useful"}},
- {"type": "human", "data": {"content": "do the work"}},
- ]
- assert "heartbeat_timeout" not in options
-
- @pytest.mark.asyncio
- async def test_explicit_langchain_marker_keeps_credentials_out_of_history(
- self,
- monkeypatch,
- patched_workflow,
- ):
- from services.temporal.agent_workflow import AgentWorkflow
-
- prepared_payload = _emergency_langchain_payload()
- llm_calls: list[tuple[dict, dict]] = []
-
- async def fake_execute_activity(name, *, args, **kwargs):
- if name == "agent.prepare_payload":
- assert "api_key" not in prepared_payload
- return prepared_payload
- if name == "agent.broadcast_progress":
- return {"emitted": True}
- if name == "agent.execute_llm_step":
- llm_calls.append((args[0], kwargs))
- return {
- "kind": "final",
- "content": "done",
- "thinking": None,
- "usage": {},
- }
- if name == "agent.store_output":
- return {"stored": True}
- if name == "agent.skill.clear":
- return {"cleared": True}
- raise AssertionError(f"Unexpected activity {name}")
-
- monkeypatch.setattr(
- patched_workflow,
- "execute_activity",
- fake_execute_activity,
- )
-
- result = await AgentWorkflow().run(
- {"node_id": "agent-1", "execution_id": "root-run-1"}
- )
-
- assert result["success"] is True
- llm_payload, options = llm_calls[0]
- assert list(llm_payload) == [
- "node_id",
- "provider",
- "model",
- "messages",
- "tool_data",
- "system_message",
- "temperature",
- "max_tokens",
- "thinking_config",
- "llm_engine",
- "message_wire_version",
- ]
- assert llm_payload["llm_engine"] == "langchain"
- assert llm_payload["message_wire_version"] == 1
- assert "api_key" not in llm_payload
- assert llm_payload["tool_data"] == [_tool()["tool_info"]]
- assert options["heartbeat_timeout"] == timedelta(minutes=1)
-
- def test_tool_results_follow_the_history_pinned_wire_format(self):
- from services.temporal.agent_workflow import (
- _append_tool_result_message,
- )
-
- native_messages: list[dict] = []
- _append_tool_result_message(
- native_messages,
- llm_engine="native",
- content='{"ok": true}',
- tool_call_id="call-1",
- name="write_todos",
- )
- assert native_messages[0]["version"] == 2
- assert native_messages[0]["role"] == "tool"
- assert native_messages[0]["tool_call_id"] == "call-1"
- assert native_messages[0]["blocks"][0]["type"] == "tool_result"
-
- legacy_messages: list[dict] = []
- _append_tool_result_message(
- legacy_messages,
- llm_engine="langchain",
- content='{"ok": true}',
- tool_call_id="call-1",
- name="write_todos",
- )
- assert legacy_messages == [
- {
- "type": "tool",
- "data": {
- "content": '{"ok": true}',
- "tool_call_id": "call-1",
- "name": "write_todos",
- },
- }
- ]
-
- def test_native_tool_turn_reasoning_is_read_from_canonical_message(self):
- from services.llm.protocol import (
- ContentBlock,
- Message,
- message_to_wire,
- )
- from services.temporal.agent_workflow import (
- _native_assistant_thinking,
- )
-
- wire = message_to_wire(
- Message(
- role="assistant",
- blocks=[
- ContentBlock(type="reasoning", text="first"),
- ContentBlock(type="reasoning", text="second"),
- ],
- )
- )
- assert _native_assistant_thinking(wire) == "first\n\nsecond"
-
-
-class TestNativeActivityBranch:
- def test_structured_llm_error_becomes_safe_temporal_failure(self):
- from services.llm.protocol import LLMError, LLMErrorCategory
- from services.temporal.agent_activities import (
- _as_temporal_llm_error,
- )
-
- provider_error = LLMError(
- message="raw body included secret request details",
- provider="openai",
- category=LLMErrorCategory.RATE_LIMIT,
- retryable=True,
- status_code=429,
- provider_code="capacity",
- request_id="req-123",
- retry_after=1.5,
- )
- temporal_error = _as_temporal_llm_error(provider_error)
-
- assert "raw body" not in str(temporal_error)
- assert temporal_error.type == "LLMError.rate_limit"
- assert temporal_error.non_retryable is False
- assert temporal_error.details == (
- {
- "provider": "openai",
- "category": "rate_limit",
- "retryable": True,
- "status_code": 429,
- "provider_code": "capacity",
- "request_id": "req-123",
- "retry_after": 1.5,
- "retry_after_raw": None,
- },
- )
-
- @pytest.mark.asyncio
- async def test_buffered_native_call_heartbeats_while_waiting(
- self,
- monkeypatch,
- ):
- import services.temporal.agent_activities as activity_module
-
- heartbeat = MagicMock()
- monkeypatch.setattr(activity_module.activity, "heartbeat", heartbeat)
-
- async def delayed_result():
- await asyncio.sleep(0.02)
- return "done"
-
- result = await activity_module._await_with_llm_heartbeats(
- delayed_result(),
- detail="waiting",
- interval_seconds=0.001,
- )
-
- assert result == "done"
- heartbeat.assert_called_with("waiting")
-
- @pytest.mark.asyncio
- async def test_native_step_disables_sdk_retries_and_keeps_v1_result_keys(
- self,
- monkeypatch,
- ):
- import core.container as container_module
- import services.agent_runtime as runtime_module
- from services.llm.protocol import (
- LLMResponse,
- Message,
- ToolCall,
- Usage,
- message_to_wire,
- )
- from services.temporal.agent_activities import _execute_native_llm_step
-
- unifier = object()
- monkeypatch.setattr(
- container_module.container,
- "chat_unifier",
- lambda: unifier,
- )
- call = ToolCall.from_raw(
- id="call-1",
- name="write_todos",
- arguments="{not-json",
- )
- run_step = AsyncMock(
- return_value=LLMResponse(
- tool_calls=[call],
- usage=Usage(input_tokens=5, output_tokens=2),
- )
- )
- monkeypatch.setattr(runtime_module, "run_native_llm_step", run_step)
-
- result = await _execute_native_llm_step(
- {
- "provider": "openai",
- "model": "test-model",
- "api_key": "secret",
- "messages": [
- message_to_wire(Message(role="user", content="go"))
- ],
- "tools": [_tool()["definition"]],
- "temperature": 0,
- "max_tokens": 100,
- }
- )
-
- assert set(result) == {
- "kind",
- "assistant_message",
- "calls",
- "usage",
- }
- assert result["kind"] == "tool_calls"
- assert result["assistant_message"]["version"] == 2
- assert result["calls"][0]["raw_arguments"] == "{not-json"
- assert result["calls"][0]["parse_error"]
- assert result["usage"]["total_tokens"] == 7
-
- assert run_step.await_args.args == (unifier,)
- kwargs = run_step.await_args.kwargs
- assert kwargs["sdk_max_retries"] == 0
- assert kwargs["translate_errors"] is False
- assert kwargs["tools"][0].name == "write_todos"
diff --git a/server/tests/temporal/test_temporal_identity.py b/server/tests/temporal/test_temporal_identity.py
index e51a261a..fe6a97ae 100644
--- a/server/tests/temporal/test_temporal_identity.py
+++ b/server/tests/temporal/test_temporal_identity.py
@@ -14,6 +14,11 @@ import pytest
def _tool(node_id: str, *, name: str = "write_todos", label: str = "Todos") -> dict:
return {
"name": name,
+ "definition": {
+ "name": name,
+ "description": "Write a todo list",
+ "parameters": {"type": "object", "properties": {}},
+ },
"node_type": "writeTodos",
"version": 1,
"task_queue": "write-todos",
@@ -293,10 +298,10 @@ class TestAgentCallIdentity:
)
]
# The conflicting tool never enters the next LLM binding surface.
- assert len(llm_payloads[1]["tool_data"]) == 1
- tool_messages = [m for m in llm_payloads[1]["messages"] if m.get("type") == "tool"]
+ assert len(llm_payloads[1]["tools"]) == 1
+ tool_messages = [m for m in llm_payloads[1]["messages"] if m.get("role") == "tool"]
assert len(tool_messages) == 1
- assert "DuplicateToolNameError" in tool_messages[0]["data"]["content"]
+ assert "DuplicateToolNameError" in tool_messages[0]["content"]
assert any(phase.get("phase") == "tool_error" for phase in phases)