TypeScript Client Events
Use the TypeScript client when a browser, Node app, editor extension, or custom UI needs to render HPD Agent runs.
The TypeScript client opens sessions and threads, observes canonical hosted events, submits inputs, and answers interactive requests.
Install The Client Surface
The main entry point is AgentClient:
import { AgentClient, type EventHandlers } from '@hpd-research/hpd-agent-client';
const client = new AgentClient({
baseUrl: 'http://localhost:5135',
timeoutMs: 60_000,
abortSignal: applicationSignal,
});The client uses HTTP for commands and control state, plus resumable SSE for canonical thread observation.
Every network operation also accepts per-request options:
const controller = new AbortController();
await thread.send('Investigate this case', {
signal: controller.signal,
timeoutMs: 120_000,
headers: { 'x-request-id': requestId },
});The client-wide signal and per-call signal compose. Client-wide and per-call request timeouts cover JSON, multipart, binary, and SSE connection work.
Open a session and observe its thread
const { session, thread } = await client.sessions.create(
{ metadata: { title: 'Support case' } },
{ agentId: 'assistant' },
);
const observation = await thread.observe({
handlers: {
TEXT_DELTA: ({ event, route }) => {
transcript.append(route.origin, event.messageId, event.text);
},
},
});
try {
const submission = await thread.send('Summarize this thread.');
console.log(await submission.execution.wait());
} finally {
await observation.close();
}Session creation returns the initial main thread. Reopen a saved thread with (await client.sessions.get(sessionId)).threads.get(threadId). Threads are not bound to an agent. A call's agentId option picks the agent for that call; otherwise the handle's agent runs it. Set the handle's agent with the agentId option on sessions.create or with thread.withAgent(agentId). A handle without an agent sends no agent, and the runtime runs its default agent: the definition that client.agents.list() reports with isDefault: true.
Observation resolves when the stream opens. Pass an AbortSignal to stop observation when the UI disconnects, and monitor observation.done for terminal stream or handler failures.
Agents, sessions, threads, and content
The session-first handles cover the common application lifecycle:
const agents = await client.agents.list();
const agent = await client.agents.get('assistant');
const { session, thread } = await client.sessions.create({}, { agentId: agent.id });
await session.update({ metadata: { title: 'Billing issue' } });
await thread.update({
name: 'Billing investigation',
description: null,
tags: ['billing'],
});
const content = await thread.content.upload(file, file.name);
const attachment = content.toMessageContent(file.name);
const files = await thread.content.list();
const bytes = await thread.content.download(content.contentId);
await thread.content.delete(content.contentId);An agent's executions across sessions, newest first, show where it has run:
const runs = await client.agents.executions('planner', { limit: 50 });
const inSession = await client.agents.executions('planner', { sessionId });Thread-owned execution methods are available through thread.executions:
const executions = await thread.executions.list();
const graph = await thread.graph();
const children = graph.threads.filter(child => child.parentThreadId === thread.id);
const usage = await thread.contextUsage();Each execution carries models, the distinct { providerKey, modelId } pairs the run called, so a run list can label each run with the models it used.
client.api retains every generated endpoint for administrative or newly generated operations.
Agent definitions
client.agents reads and manages the runtime's agents. list() and get(agentId) return AgentDefinitionDto values for code and stored agents together, code agents first:
for (const agent of await client.agents.list()) {
const label = agent.config.name ?? agent.id;
console.log(`${label} (${agent.source})${agent.isDefault ? ' default' : ''}`);
for (const part of agent.processLocal) {
console.log(` code-only ${part.kind} at ${part.path}: ${part.description}`);
}
}source is Code or Stored. A code agent is read-only (isEditable: false), and its processLocal list describes what its portable config leaves out, such as a chat client instance or a native function. A stored agent has an empty processLocal list.
create, update, and delete change stored agents:
import { HpdApiError } from '@hpd-research/hpd-agent-client';
try {
await client.agents.create({
agentId: 'researcher',
config: {
name: 'Researcher',
clients: { chat: { provider: { key: 'openai' }, modelName: 'gpt-5-mini' } },
},
});
} catch (error) {
if (error instanceof HpdApiError && error.status === 400) {
// Validation errors keyed by code, each naming its definition path.
const errors = (error.problem as { errors?: Record<string, string[]> }).errors ?? {};
showErrors(errors['agent_provider_unknown'] ?? [], errors['config'] ?? []);
} else if (error instanceof HpdApiError && error.code === 'agent_definition_read_only') {
// The id belongs to a code agent.
} else {
throw error;
}
}A refused definition rejects with a 400 HpdApiError whose problem errors are keyed by code: agent_provider_unknown, agent_provider_family_unsupported, agent_harness_unknown, agent_harness_function_unknown, agent_middleware_unknown, and config for errors without a code. A conflict rejects with a 409 whose code is agent_definition_read_only (a code agent's id), agent_definition_exists (a taken stored id), or agent_definition_changed (a stale update). HpdApiError.code reads the problem's code extension.
client.agents.capabilities(agentId) reads what one agent exposes to its model; the server builds the agent on first use.
Composition
client.composition reads what the runtime can run agents with, fixed when it was built. Reading it builds no agent:
const providers = await client.composition.providers();
const harnesses = await client.composition.harnesses();
const middleware = await client.composition.middleware();
const chatProviders = providers.filter(provider => provider.families.includes('Chat'));
const harnessIdentities = harnesses.map(harness => harness.identity);| Method | Route | Returns |
|---|---|---|
providers() | GET /composition/providers | ProviderDescriptorDto[]: key, display name, aliases, families, documentation link, secret names, and models |
harnesses() | GET /composition/harnesses | ToolHarnessDescriptorDto[]: the exact activation identity a definition names in toolHarnesses[].name, and the functions each declares |
middleware() | GET /composition/middleware | MiddlewareDescriptorDto[]: the identity a definition names in middlewares[].name |
events() | GET /composition/events | EventCatalogDto |
inputs() | GET /composition/inputs | InputCatalogDto |
A definition that names anything outside these lists is refused when it is saved. A provider's models is empty unless the server was built with a model catalog.
Event and input catalogs
The runtime's event and input catalogs describe the contracts its agents use:
const events = await client.composition.events();
const inputs = await client.composition.inputs();
if (events.digest !== expectedEventDigest) {
throw new Error(`Server event catalog ${events.digest} does not match this build.`);
}
const durable = events.events.filter(entry => entry.durability === 'Durable');events() reads GET /composition/events and inputs() reads GET /composition/inputs. Each catalog carries a structural digest; compare it with the digest your client was generated against before decoding events from an unfamiliar server. Each event entry carries its discriminator, contractName, moduleId, contractDigest, and durability as the enum name (Durable or LiveOnly).
Client Setup Failures
Hosted MESSAGE_TURN_ERROR events can include clientSetup when provider or client resolution fails before a model call:
const handlers = {
MESSAGE_TURN_ERROR: ({ event }) => {
if (event.clientSetup) {
showSetupFailure({
code: event.clientSetup.code,
message: event.clientSetup.message,
guidance: event.clientSetup.guidance,
provider: event.clientSetup.providerKey,
model: event.clientSetup.modelName,
});
return;
}
showRunFailure(event.errorMessage);
},
} satisfies EventHandlers;Use clientSetup.code for stable behavior and clientSetup.guidance for safe display text. Do not parse the provider's error message to decide which setup action to offer.
Finite history
thread.history() replays the canonical journal through the runtime's current observed head and returns a finite protocol-level message projection:
const history = await thread.history({ signal });
for (const message of history.messages) {
renderMessage({
id: message.id,
role: message.role,
text: message.text,
reasoning: message.reasoning,
toolCalls: message.toolCalls,
visibility: message.visibility,
});
}The returned appliedCursor can be passed to thread.observe({ after }) for live continuation. The richer timeline, work-group, and interaction projection remains in the headless UI package.
Evaluations
Common evaluation reads have a curated facade:
const catalog = await client.evaluations.catalog();
const summary = await client.evaluations.summary({ from, to });
const scores = await client.evaluations.scores('relevance', { from, to });
const runs = await client.evaluations.runs({ executionName });Dataset administration and specialist red-team operations remain available under client.api.evaluations.
Message Policy And Transcript Visibility
Message roles are provider-facing model roles. They are not enough to decide whether something belongs in a human transcript.
Message and text-start events can include HPD-owned policy fields:
const handlers = {
TEXT_MESSAGE_START: ({ event }) => {
// Hosted message policy values follow the C# enums.
if (event.visibility === 1) {
transcript.hide(event.messageId);
} else if (event.visibility === 2) {
transcript.startDiagnosticMessage(event.messageId, event.source);
} else if (event.source === 1) {
transcript.startUserMessage(event.messageId);
} else if (event.source === 2) {
transcript.startAssistantMessage(event.messageId);
}
},
} satisfies EventHandlers;Use source, visibility, and persistence for HPD behavior:
| Field | Meaning |
|---|---|
role | Provider/model role such as user, assistant, system, or tool |
source | HPD reason the message exists, such as UserInput, AssistantOutput, BackgroundNotification, or Steering |
visibility | Transcript policy: Transcript, Hidden, or Diagnostic |
persistence | Durable message policy when present on message-start events |
For example, background task notifications are sent to the model as role: "system" context, but use source: "BackgroundNotification" and visibility: "Hidden". A chat UI should not render their XML payload as assistant text.
Agent Operation Projections
Long-running work from providers, tools, subagents, workflows, MCP servers, and connected clients uses the unified AgentOperation events:
AGENT_OPERATION_REGISTEREDAGENT_OPERATION_TRANSITIONEDAGENT_OPERATION_NOTIFICATION_QUEUEDAGENT_OPERATION_NOTIFICATION_DELIVEREDAGENT_OPERATION_NOTIFICATION_SUPPRESSEDAGENT_OPERATION_TOMBSTONED
Registered and transitioned events carry an operation snapshot with operationId, source kind, name, provider status, observation status, control capabilities, timestamps, completion or failure, and metadata. Group all operation activity by operationId.
Notification queued events carry the bounded model notification payload. Delivered and suppressed events expose the notification ID or suppression reason, respectively. A delivered operation notification uses hidden BackgroundNotification model context and must not become a visible assistant transcript row.
Runtime state also exposes operations on the active thread execution:
const state = await chat.getState();
for (const operation of state?.activeExecution?.operations ?? []) {
operationsPanel.upsert({
id: operation.operationId,
name: operation.name,
status: operation.providerStatus,
observation: operation.observationStatus,
controlHandle: operation.controlHandleId,
summary: operation.completionSummary,
failure: operation.failureMessage,
});
}Execution projections are useful for active-run status, cancellation capabilities, completion summaries, and artifacts. Use the operation events when the client needs a durable timeline.
Typed handlers and routed events
Pass keyed handlers to thread.observe() to infer each event payload. Use onEvent to process all known event types in one callback. The keyed handler runs before onEvent. The SDK awaits both before acknowledging a committed cursor.
For delegated work, set hierarchy: 'threadAndDescendants'. Use route.origin to identify which thread emitted each delivery. Correlate parent-thread delegation events by invocationId and use the child agent, session, and thread IDs from SUBAGENT_INVOCATION_STARTED when opening the child. Use onUnknownEvent for application events that the SDK does not recognize. The callback receives the raw event and its route.
Respond to interactive requests
Use thread.state() to restore actionable pending requests. Historical requests may appear in replay after they have been answered. Send a reply through the thread that owns the request.
await thread.respond({
type: 'PERMISSION_RESPONSE',
permissionId: request.permissionId,
sourceName: request.sourceName,
choiceId: choice.id,
});Select choice.id from the choices in the pending request. Inspect the response to determine whether the server accepted it.
For client tools, provide a registered ClientToolRegistry in the clientTools observation option. Matching live invocations and replayed invocations that are still pending trigger the registered handler and a response to the owning runtime. Send tool harness definitions in runConfig.tools.clientInput when submitting a message.
Recover a thread and control an execution
Use thread.observe({ after: appliedCursor }) to resume a saved projection. When the app has no projection, omit after to replay from { sequence: 0 }. Keep state.observedCursor distinct from the projection's applied cursor. The SDK reconnects after the last applied event and suppresses duplicates.
send() is never refused because the thread is busy. Its status is steered when the message joined the running turn and started when it started a turn; either way execution is the turn that answers it. Call execution.cancel() to target that exact execution. Closing observation and aborting a wait leave the server execution running.
What Does Not Reach TypeScript
AgentStructEvent values do not flow through the TypeScript client. Struct events are process-local samples on the .NET StructEventHub; they are not AgentEvent values, are not encoded by the application composition's AgentEventCodec, and are not sent over hosted SSE.
AgentStructEventSerializer can serialize selected struct events for explicit export or diagnostics, but that is not the hosted agent event stream.
If a process-local sample needs to appear in a hosted UI, summarize or convert it into an intentional AgentEvent.
Lifecycle Transport
The live observer connects to:
/sessions/{sessionId}/threads/{threadId}/events?after={sequence}Inputs are posted separately. Response events are posted to the hosted /sessions/{sessionId}/threads/{threadId}/responses route of the current thread.