Skip to content

Hosted Streaming API ​

The hosted streaming API is for UI and integration clients that submit messages, work, and active controls, observe canonical thread events, and answer interactive middleware requests.

Every runtime route names the thread, and only the thread:

text
/sessions/{sessionId}/threads/{threadId}/inputs
/sessions/{sessionId}/threads/{threadId}/events

Threads belong to no agent, so any agent can run on any thread. Input that runs work names its agent in the body; input that names none runs the runtime's default agent. Answers, cancels, and client tool results reach the running execution, whichever agent runs it.

Submit Input ​

Submit simple text:

http
POST /sessions/{sessionId}/threads/{threadId}/inputs
Content-Type: application/json

{
  "text": "Explain this thread in one sentence.",
  "agentId": "researcher",
  "runConfig": {}
}

If the JSON body has no type property and has a non-empty text property, hosting treats it as a convenience text request and converts it to a UserMessagesInputEvent. agentId names the agent that runs it; omit it to run the default agent. An event envelope names its agent the same way, in its agentId property.

You can also submit an event envelope:

json
{
  "version": "1.0",
  "type": "USER_MESSAGES_INPUT",
  "messages": [
    {
      "role": "user",
      "contents": [
        {
          "$type": "text",
          "text": "Continue from here."
        }
      ]
    }
  ]
}

messages is optional on USER_MESSAGES_INPUT. Normal user submissions should include at least one message. Omitting it or sending an empty array asks the runtime to resume the scoped thread with the supplied run configuration; the thread must already have history.

The submitted runConfig may include harness settings for one execution:

json
{
  "harnesses": [
    {
      "name": "SearchHarness",
      "config": {
        "maxResults": 5
      }
    }
  ]
}

The agent must already contain the matching registered harness and generated codec. See Configure A Harness Per Run.

Accepted input returns 202 Accepted with the backend-owned run identity:

json
{
  "disposition": "started",
  "threadExecutionId": "execution-123",
  "startedAt": "2026-07-15T10:15:30Z"
}

Observe committed SSE events to render output, completion, errors, and interactive requests. Keep the returned threadExecutionId for lifecycle correlation and interruption.

Only one execution runs per thread. A user message sent while a turn runs joins that turn: the response's disposition is steered and threadExecutionId is the running execution. When the running work cannot take the message, it starts the next turn as soon as that work finishes. A message never names a threadExecutionId; one that does returns 400 ThreadExecutionIdNotAllowed. Other work, such as compaction, on a busy thread returns 409 with the ThreadExecutionActive error.

Estimate Context Usage ​

Hosted clients can ask the runtime how much context the current thread is using for a candidate run configuration:

http
POST /sessions/{sessionId}/threads/{threadId}/context-usage
Content-Type: application/json

{
  "runConfig": {
    "clients": {
      "chat": {
        "provider": {
          "key": "openai"
        },
        "modelName": "gpt-4.1"
      }
    },
    "compaction": null
  }
}

The response is ThreadContextUsage:

json
{
  "sessionId": "session-1",
  "threadId": "main",
  "providerKey": "openai",
  "modelId": "gpt-4.1",
  "contextWindow": 128000,
  "effectiveInputTokens": 64000,
  "usageRatio": 0.5,
  "isEstimate": false,
  "source": "last-observed-provider-usage"
}

This endpoint does not start a run or mutate thread history. Use it for model-switch warnings, context meters, and deciding whether to submit an explicit compaction command.

Explicit Compaction ​

Submit a dedicated compaction input through the normal hosted input route:

json
{
  "version": "1.0",
  "type": "COMPACT_THREAD_INPUT",
  "request": {
    "compaction": {
      "point": { "$type": "currentHead" },
      "preservation": { "$type": "previousTurns", "count": 5 },
      "strategy": { "$type": "summarizing" }
    },
    "continuation": 1
  }
}

continuation: 1 is CompactionContinuation.StopAfterCompaction. The compaction appends a THREAD_HISTORY_COMPACTION_CHECKPOINT to the thread journal. Hosting gives explicit compaction normal run ownership and interruption semantics without creating a user message or entering a model turn.

Read State Then Observe With SSE ​

First load authoritative runtime control state:

http
GET /sessions/{sessionId}/threads/{threadId}/state

It returns observedCursor, the backend-owned activeExecution, and currently answerable pendingRequests. It does not return event history. Restore controls immediately, then connect SSE from the greatest contiguous cursor your client has successfully projected. Use sequence zero when no local projection exists:

http
GET /sessions/{sessionId}/threads/{threadId}/events?after=0
Accept: text/event-stream

The same stream catches up every committed event after the cursor and then remains attached for future commits. Each event includes its journal sequence number as the SSE id:

text
id: 43
event: agent-event
data: {"event":{"version":"1.0","type":"TEXT_DELTA","threadSequenceNumber":43,"text":"hello","messageId":"message-1"},"route":{"origin":{"sessionId":"session-1","threadId":"main"},"path":[{"sessionId":"session-1","threadId":"main"}],"threadExecutionId":"execution-123"}}

Historical catch-up uses agent-event; live deliveries use live-agent-event. In both cases the data is the delivery envelope: read event as the domain event and route as its immutable origin/path attribution.

Process events serially and advance the applied cursor only after the consumer applies event successfully. observedCursor classifies the initial catch-up boundary; it must never overwrite the applied cursor. On EOF or a connection error, reconnect with the last applied sequence number. The server also accepts Last-Event-ID when after is absent. Comment heartbeats can be ignored. If observation fails after SSE headers are committed, the server closes the stream; it never fabricates an uncommitted error AgentEvent.

Semantic inputs use /inputs, interactive responses use /responses, and committed thread observation uses SSE. See Hosted Lifecycle And Recovery for the complete recovery contract.

Render Nested Activity ​

SSE delivers a linear committed stream. A hosted client can project that stream into a transcript, timeline, workflow tree, subagent view, or permission queue by grouping events with fields such as messageId, callId, permissionId, traceId, spanId, parentSpanId, eventFlowId, and agent metadata.

Workflow and subagent events may appear in the same observation stream as parent agent events when child execution is routed through the parent event coordinator. Treat the transport as delivery only; use Render An Event Stream for UI projection guidance.

Fork Threads ​

Hosted clients fork threads with:

http
POST /sessions/{sessionId}/threads/{threadId}/fork
Content-Type: application/json

{
  "newThreadId": "try-short-answer",
  "agentId": "researcher",
  "fromMessageId": "message-id-to-fork-from",
  "name": "Short answer",
  "compaction": {
    "$type": "enabled",
    "compaction": {
      "point": { "$type": "currentHead" },
      "preservation": { "$type": "previousTurns", "count": 3 },
      "strategy": { "$type": "summarizing" }
    }
  }
}

agentId is optional and names the agent whose fork compaction defaults apply; omit it to use the default agent's. Use $type: "inherit" to apply configured fork compaction, $type: "disabled" to skip it, or $type: "enabled" with an explicit specification. Omitting compaction inherits the server-side configuration.

Control An Active Execution ​

Cancel the active thread execution through its exact execution route:

http
POST /sessions/{sessionId}/threads/{threadId}/executions/execution-123/cancel

Read /state immediately before cancellation. The cancellation response reports the execution's terminal status and whether the cancellation applied. When the execution is no longer the thread's active one, the route returns 409 ThreadExecutionNotActive. Do not automatically retry against a mismatched execution; it may be newer work started by another client.

Messages that joined the cancelled turn and that it had not read yet are answered in one follow-up turn, which starts on its own.

Answer Interactive Middleware ​

HTTP clients answer bidirectional requests through one response route:

http
POST /sessions/{sessionId}/threads/{threadId}/responses
Content-Type: application/json

{
  "version": "1.0",
  "type": "PERMISSION_RESPONSE",
  "permissionId": "permission-id-from-request",
  "sourceName": "PermissionMiddleware",
  "choiceId": "allow_once",
  "feedback": null
}

The body must be a serialized AgentEvent envelope whose event implements IResponseEvent, such as PermissionResponseEvent, ContinuationResponseEvent, ClarificationResponseEvent, ClientToolInvokeOutcomeEvent, or an app-owned custom response event.

Middleware responses are not thread executions. Canonical request events are committed only after the request is externally answerable. /state also exposes currently pending requests, allowing a recovering client to restore interaction UI before historical replay completes. The response route requires an existing session/thread scope, an active thread runtime, and a waiter that accepts the response. If the scope does not exist, it returns 404. If no runtime is active, the route returns a thread-runtime-not-active conflict. If the runtime exists but no waiter accepts the response, it returns 409 with the RespondResult status.

Event Bodies ​

Hosted streaming uses the selected application composition's AgentEventCodec. Envelopes contain version, type, and camelCase payload properties, with null values omitted.

This page intentionally shows contract-level examples only. For composition selection and persistence compatibility, see Application Composition. For event families and publication semantics, see Events.

Built for production .NET agent applications.