Docs · Reference

Agent ports and the event contract

Updated 2026-10-26 Shirish Kadam, Claude Source: docs/engineering/agent-ports-and-events.md Edit on GitHub

Status: implemented. Source of truth is the code: ports/__init__.py declares the ports; events.py holds the vocabulary and the AG-UI map.

Duct rents an agent framework and does not marry one. This page explains the six seams that keep that true and publishes the event contract the app reads. For anyone adding a runner, changing an event or swapping frameworks.

At a glance

A framework touches Duct through six ports

Inside a port the framework is as framework-shaped as it likes; what crosses it has Duct's shape and follows a multi-vendor standard.

PortWhat crosses itToday
ToolsA plain function plus its descriptionA thin binder per framework
Events outDuct's event vocabulary, via an emitterThe LangChain stream translator
Human in the loopPause, ask, return the answerAn in-process future (audit); a checkpointed interrupt (insights, content)
ArtifactsA streaming tag, a parser, a persisterFramework-neutral by construction
Session and stateA live registry; the conversation id as the threadA LangGraph checkpointer (Postgres, SQLite, memory)
Model transportProvider, model and engine registriesFive native packages; one compatible shape for gateways

A port is earned on the second implementation

Rule: write the adapter on the second implementation, not the first. One implementation is a guess; two are a fact.

The pause port is the example. For a year the only way to park a run was an in-process future that dies with its worker. When insights moved onto LangGraph's interrupt, the protocol was declared from two real implementations, and the tools stopped knowing which one they held.

The checkpointed one survives a redeploy and re-shows the waiting question on resume. Every port now has one adapter; two frameworks have already left through these seams.

Why a seam, not a framework

Agent frameworks are the fastest-churning, least-differentiated layer. The deep-agent library Duct rents is 0.x with no stability policy, so it is pinned exactly and gated by a test.

There is deliberately no shared "harness interface". Frameworks differ in capability, not only in API shape: take the intersection and you lose sub-agents, a filesystem, skills and compaction; take the union and you are writing a framework.

So the question is how small a surface the framework touches. LangChain is layered: the lower the rung, the firmer the promise.

RungRuns
Long-term support (1.x)Audit
Deep-agent library (0.x, pinned)Insights, content

Abandon the top rung tomorrow and one file breaks, the shared session loop; the fallback is one rung down, not a rewrite.

Events are mapped to AG-UI, never renamed

Duct's event names predate AG-UI and mostly agree. Renaming them would break every consumer to buy nothing, so a table maps each event to its AG-UI meaning; domain events no protocol covers map to Custom.

That table is the whole adapter: an AG-UI endpoint is a short translation over it, and the boundary test fails when an event is missing.

Failures travel as a code, never an exception

A failed step or run carries a code, a retryable flag and a one-sentence error. One classifier assigns the code from the exception's class and status, looking through wrappers, and decides retries: a rate limit backs off, a rejected key fails at once.

The app maps the code to copy and an action; the recorder writes run status and error on the conversation, so a thread list badges "Needs you" or "Failed" before anyone opens it.

Why: the raw message has carried request ids, and once a URL with a key in it. It goes to the log, never the browser.

Mid-turn messages are steered or queued, never refused

A session that can steer hands the message to the model at its next call, checkpointed with the thread; one that cannot holds it for the next turn. The app marks the row "queued" until an event names it consumed.

Artifacts, not reports

The streaming tag is named for artifacts, not reports: content streams plans and post drafts through the same tag, and the store versions them all alike.

The mechanism (tag, events, parser, persister) says artifact; the value layer (the kind column, the audit schema) says report, because that artifact really is one. Renaming kind would carry no information and cost a data migration.

Any OpenAI-compatible gateway is a config entry

OpenRouter now runs on its own first-party package, for routing preferences and a reasoning parameter the bare shape cannot carry. The compatible shape is still the port: any other gateway is served as chat completions at its base URL, a config value.

A self-hosted gateway replaces OpenRouter's interface and key management, not its commercial aggregation. One key reaches dozens of providers; a gateway reaches accounts you already hold. They are complements on one code path.

Observability is Duct's job

LangChain's tracing goes to its own vendor, so Duct emits the OpenTelemetry GenAI spans itself: one per model call, one per tool call, at the choke point all binders share. The attribute names are a pinned copy of an experimental convention; a test keeps the copy honest.

Remember: the framework is a tenant. Six ports and one test keep it one.

Reference

Tables only; the linked code is the source of truth.

Ports in code

PortContractAdapters
ToolsA plain callable plus its description; ToolBinder in ports/__init__.pybuild_memory_tools_lc, build_artifact_tools_lc, build_execution_tools_lc, build_mcp_tools_lc, and the connector, web, audit, content and insights binders listed in test_harness_boundaries.py
Events outAgentEvent / EventKind plus Emitterstream_agent in lc.py
Human in the loopPauseFn: await pause(event, payload) returns the answer (session.py)make_future_pause: in-process future, 120 s timeout (audit v1; the slide-render bridge uses its own future). interrupt_pause: LangGraph interrupt(), no timeout (insights v1, content v1)
Artifacts<duct_artifact> tag, DuctArtifactStreamParser, ArtifactPersisterstream.py, artifact_store.py
Session and stateBaseAgentSession registry (in-process); conversation id as the threadcheckpoint.py: Postgres, SQLite or in-memory, chosen from DATABASE_URL, degrading to in-memory. DeepSession loop in deep_session.py
Model transportProvider / ModelName / Engine plus get_api_key_kwargsmodels.py, engines.py; resolve_chat_model in lc.py

LangChain rungs

RungStabilityUsed for
init_chat_model plus with_structured_output1.x, long-term support under semverCompaction summaries (compact_thread), memory consolidation, typed one-shot answers (enrichment research, audit draft inference, content reference diagnosis)
create_agent1.x, long-term supportThe audit runner (build_session_agent), the enrichment research loop (research.py)
deepagents0.x, no stability policy; pinned exactly in pyproject.toml, gated by test_deepagents_harness.pyThe insights and content sessions (build_deep_session_agent): planning, sub-agents, scratch space
First-party surface in useAll on the 1.x tiercreate_agent, init_chat_model, StructuredTool, the middleware classes, the message classes

Standard behind each port

PortStandardMaturity
ToolsMCP, under the Linux Foundation's Agentic AI Foundation since Dec 2025 (OpenAI, Anthropic, Google, Microsoft, AWS, Block)The most durable of the four
Model transportOpenAI-compatible chat completionsDe facto universal
Events outAG-UICredible, younger, single-vendor origin
ObservabilityOpenTelemetry GenAI semantic conventionsgen_ai.client settled, gen_ai.agent experimental

Live SSE events (AgentEvent to AG-UI)

Duct eventAG-UIMeaning and payload
pipeline_startedRunStartedA run began
pipeline_finishedRunFinishedA run completed
pipeline_failedRunErrorA run failed: code, retryable, error
step_startedStepStartedA workflow stage began (step_id, status)
step_finishedStepFinishedA workflow stage completed
step_failedStepFinishedAG-UI has no StepFailed; failure rides in status (error). Carries code, retryable, error
agent_message_chunkTextMessageContentProse token
agent_messageTextMessageChunkA complete message
message_stopTextMessageEndTurn boundary
thinking_chunkReasoningMessageContentExtended-thinking delta
synthesis_chunkTextMessageContentInsights synthesis stream (legacy alias on audit)
todo_updateActivitySnapshotThe full todo list; a snapshot, never a delta
questions_requiredCustomPause: the agent needs an answer. interrupt_id on a checkpointed run; replay: true when re-emitted on resume
connection_requiredCustomPause: a connector the project lacks. connector_id, label, auth_kind, authorize_path, reason
account_selection_requiredCustomPause: which account, property or site. connector_id, label, candidates
tool_approval_requiredCustomPause: a connected MCP tool its server does not mark read-only. Server, tool, reason, argument preview
slide_render_requestedCustomThe agent asks the browser to rasterize a slide
artifact_chunkCustomToken inside <duct_artifact>
artifact_versionCustomNew version of the primary artifact: full payload, version_id, label
artifact_updatedCustomCompact artifact card for the transcript; no payload
project_draftCustomOnboarding: fields learned about the site, each with provenance
plan_generatedCustomContent: a plan
post_draft_updatedCustomContent: a post draft
execution_proposedCustomStaged-execution change set; upsert by change_set_id
tool_activityCustomOne allowlisted tool call, emitted as running then success or error; upsert by activity_id. Fields title, subtitle, source, meta; never the output (activity.py)
memory_writtenCustomEntries this turn stored, with undo
memory_recalledCustomEntry ids this turn was primed with
model_retryingCustomStatus, not failure; the next token clears it. attempt, max_attempts, code, retry_in (seconds; a duration the client anchors to its own clock)
token_usageCustomOne model call's bill: input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens, context_window, model, scope, cost_usd. Scope is thread, subagent or compaction; all three are billed, only thread drives the gauge. Cost comes from PRICING; null for an unpriced model, never a guess
context_compacting, context_compactedCustomThe session is summarising old history, then did. The summariser's tokens never reach the transcript. Also emitted around the one emergency compaction: a request the provider rejects as too long is summarised once and retried from its checkpoint; a second rejection is the ordinary context_window failure
user_input_consumedCustomA message sent mid-turn reached the model; carries its client_message_id

Pause answers

One answer endpoint for every pause. interrupt_id is passed back on a checkpointed run; omitted, the only pending pause is assumed. An empty answer always means "carry on without it".

EventAnswer
questions_requiredAnswers keyed by question
connection_required{"skipped": true} to decline; anything else after the sign-in, and the server re-reads the connector rather than trusting the answer
account_selection_required{"account_id": ...}; empty is a skip
tool_approval_required{"approved": true}; anything else is a skip

Failure code

FieldValue
codeErrorCode in errors.py: rate_limited, overloaded, upstream_error, timeout, network (retryable); auth, permission, context_window, bad_request, model_not_found, connector_expired, connector_forbidden, reference_unavailable, cancelled, unknown
retryableWhether the same request may succeed if sent again shortly
errorOne code-specific sentence; never the exception text
Classifierclassify_error, also the retry decision in ReportedRetryMiddleware (lc.py)
App sideerrorAction in agentSession.js; codes mirrored in agentEvents.js

Run status (RunStatus on agent_conversations)

Written only by ConversationRecorder (persistence.py), derived from the stream; run_error carries {code, retryable, error}. Both ride on the conversation list and the state route.

ValueMeaning
idleWaiting for the user's next message
runningA turn is in flight
pausedParked on a question, a connect offer or an account pick
failedThe last turn ended in a failure (see run_error)
cancelledThe session closed while a turn was running

Persisted conversation kinds (EventKind to AG-UI)

KindAG-UINote
user, assistantMessagesSnapshot
thinkingReasoningMessageContent
tool_useToolCallStartName plus full input
tool_resultToolCallResultPaired by tool_use_id; output plus is_error
question, answerCustom
failureRunError{code, retryable, error} where a turn or run died; code: cancelled for a stop
contextCustomWhat the model was given: composed turn, blocks, model, system-prompt fingerprint
compactedCustomThe thread was summarised in place: {summary}
memory_recalled, memory_writtenCustomWhat memory gave the run and what the run gave memory

Mid-turn input

Harness can steerDeliveryWhere
Yes (steer_queue set)SteerMiddleware, a before_model hook, so the message is checkpointed with the threadlc.py
Nochat_queue; waits for the next turnsession.py
Steer after the last model callBecomes the next turn (_leftover_steers)deep_session.py

Artifact vocabulary by layer

LayerWordWhy
Mechanism: tag, events, parser, persisterartifactShared by every agent; test_no_live_event_uses_report_vocabulary pins it
Value: artifacts.kind, the AuditReport schemareportThis artifact really is a report

Renamed wire values

WasIsMigration
<duct_report><duct_artifact>The parser accepts both tags
report_chunkartifact_chunkThe app accepts both strings (LEGACY_* in agentEvents.js); the backend emits only the new ones, so deploy the app first, then the backend. Python aliases are gone
report_updatedartifact_versionAs above
artifacts.kindunchanged: report, document, ticket, imagemodels/artifact.py

Model transport

ProviderPackageNote
openailangchain-openai
google_genailangchain-google-genai
anthropiclangchain-anthropic
openrouterlangchain-openrouterNative gateway: routing preferences, unified reasoning parameter. Base URL overridable via openrouter_base_url. A vendor/slug not in the curated list passes through verbatim; a bare name resolves by prefix
xailangchain-xaiFirst-party vendor, not a gateway
Any other gatewayOpenAI chat-completions shape at its own base URLGATEWAY_BASE_URL and NATIVE_GATEWAY_PROVIDERS in models.py; what Ollama, vLLM or LiteLLM would get

Self-hosted gateways on the same code path

GatewayLicenceRuntimeNote
LiteLLMMITPython100+ providers, virtual keys, spend control; the default choice
BifrostOpen sourceGoAbout 11 µs routing overhead at 5k requests/s; LiteLLM's Python path climbs sharply past about 500
Portkey GatewayMITNodeAdds guardrails and observability
LLM GatewayAGPLv3DockerClosest to OpenRouter's whole platform (dashboard, caching, analytics); check the licence before embedding
Envoy AI GatewayOpen sourceKubernetesFor a cluster that already runs Envoy
Ollama, vLLM, llama.cppOpen sourceLocalModel servers, not gateways; same compatible path

Enforcement

TestFails when
test_harness_boundaries.pyA framework import appears outside ADAPTERS; an ADAPTERS entry no longer imports one; a FRAMEWORK_FREE module (events, prompts, schemas, registries, the three runners) imports one; an event is missing from the AG-UI maps; an app event mirror names an unknown event, or marks a live one LEGACY_; a live event uses report vocabulary
Boundary debt, named in that allowlistroutes/chat.py and service/memory_consolidation.py import LangChain from the wrong layer
test_deepagents_harness.pyThe deepagents pin changes what interrupt() raised inside a tool does
test_telemetry.pyThe pinned GenAI attribute names drift from the installed package

Telemetry

ItemWhere
model_span, tool_spantelemetry.py; attribute names pinned to SEMCONV_VERSION, not imported from the package's private module
ExporterOTEL_EXPORTER_OTLP_ENDPOINT; unset means tracing off
Dependencyopentelemetry-api declared directly, no longer transitive; import guarded, degrades to a no-op