Skip to content

@aparte/engine — API reference

Defined in: agent/parsers/artifact-xml-state-machine.ts:81

A stateful streaming parser for one turn’s <artifact> blocks. Feed it each text delta; drain the returned events. Call finalize when the stream ends to flush a truncated (unclosed) artifact.

new ArtifactXmlStateMachine(hint, idGen?): ArtifactXmlStateMachine;

Defined in: agent/parsers/artifact-xml-state-machine.ts:95

ParameterType
hintXmlArtifactHint
idGen?() => string

ArtifactXmlStateMachine

get currentState(): XmlArtifactState;

Defined in: agent/parsers/artifact-xml-state-machine.ts:178

Current parser state (for the adapter to decide finalize routing).

XmlArtifactState

feed(delta): XmlArtifactEvent[];

Defined in: agent/parsers/artifact-xml-state-machine.ts:100

Feed one text delta; returns the ordered micro-events it produced.

ParameterType
deltastring

XmlArtifactEvent[]

finalize(): XmlArtifactEvent[];

Defined in: agent/parsers/artifact-xml-state-machine.ts:165

Flush a truncated artifact: if the stream ended mid-body (model cut off before </artifact>), emit a close with whatever was buffered. Mirrors _streamLoop’s finalize block (:1658-1669).

XmlArtifactEvent[]

Defined in: agent/parsers/artifact-xml-state-machine.ts:24

Fallback mime/kind for an artifact whose open tag omits the attribute.

mimeType: string;

Defined in: agent/parsers/artifact-xml-state-machine.ts:25

kind: string;

Defined in: agent/parsers/artifact-xml-state-machine.ts:26


Defined in: agent/stream-events.ts:33

Token usage. Structurally a superset-compatible mirror of AparteUsage: the five common fields plus an index signature that carries the provider-specific rest (ttft/decode/phases/…) opaquely — the loop transports usage, never reads past these five.

[key: string]: unknown
inputTokens: number;

Defined in: agent/stream-events.ts:34

outputTokens: number;

Defined in: agent/stream-events.ts:35

optional totalTokens?: number;

Defined in: agent/stream-events.ts:36

optional cacheReadTokens?: number;

Defined in: agent/stream-events.ts:37

optional durationMs?: number;

Defined in: agent/stream-events.ts:38


Defined in: agent/stream-events.ts:43

One tool call as surfaced by the provider stream (mirrors AparteToolCall).

id: string;

Defined in: agent/stream-events.ts:44

name: string;

Defined in: agent/stream-events.ts:45

input: unknown;

Defined in: agent/stream-events.ts:46


Defined in: agent/stream-events.ts:65

A conversation message (mirrors AparteChatMessage). role is left open (string) so the loop can push the 'tool_call' / 'tool_result' envelope roles _streamLoop uses without importing core’s union.

[key: string]: unknown
role: string;

Defined in: agent/stream-events.ts:66

content: string;

Defined in: agent/stream-events.ts:67

optional toolCalls?: StreamToolCall[];

Defined in: agent/stream-events.ts:69

Present on a 'tool_call' envelope — the whole turn’s calls, grouped.

optional toolCallId?: string;

Defined in: agent/stream-events.ts:71

Present on a 'tool_result' message — which call it answers.

optional precedingText?: string;

Defined in: agent/stream-events.ts:73

Assistant text that preceded the tool call(s) this turn.


Defined in: agent/stream-events.ts:78

The request handed to the transport each turn (mirrors AparteChatRequest).

[key: string]: unknown
messages: StreamAgentMessage[];

Defined in: agent/stream-events.ts:79


Defined in: agent/stream-events.ts:90

Per-tool loop configuration (mirrors the AparteTool subset the loop reads).

optional maxTurns?: number;

Defined in: agent/stream-events.ts:91

optional needsApproval?: boolean;

Defined in: agent/stream-events.ts:92


Defined in: agent/stream-run.ts:46

messageId: string;

Defined in: agent/stream-run.ts:48

Id of the assistant message being streamed (opaque; carried in events).

baseRequest: StreamChatRequest;

Defined in: agent/stream-run.ts:50

Turn-1 request; the loop clones its messages and enriches them per turn.

transportCall: (request) => Promise<
| string
| AsyncIterable<StreamChatEvent, any, any>>;

Defined in: agent/stream-run.ts:57

Calls the transport with the (possibly enriched) request. Returns the structured stream, or a plain string for a non-streaming provider. Mirrors getTransport().chat(provider, request, auth, ctx) with provider/auth/ctx closed over by the adapter.

ParameterType
requestStreamChatRequest

Promise< | string | AsyncIterable<StreamChatEvent, any, any>>

toolLookup: (name) => StreamToolHandler | undefined;

Defined in: agent/stream-run.ts:59

Resolves a tool’s handler by name (mirrors AparteConfig.getToolHandler).

ParameterType
namestring

StreamToolHandler | undefined

optional toolConfigLookup?: (name) => StreamToolConfig | undefined;

Defined in: agent/stream-run.ts:61

Resolves a tool’s loop config by name (maxTurns / needsApproval).

ParameterType
namestring

StreamToolConfig | undefined

optional approvalResolver?: StreamApprovalResolver;

Defined in: agent/stream-run.ts:63

HITL approval resolver for needsApproval tools (default: never called).

emitter: StreamRunEmitter;

Defined in: agent/stream-run.ts:65

Synchronous, ordered event sink consumed by the adapter.

signal: AbortSignal;

Defined in: agent/stream-run.ts:67

Single abort signal composing _isAborted + the stream controller.

optional maxTurns?: number;

Defined in: agent/stream-run.ts:69

Global turn cap.

10
optional toolTimeoutMs?: number;

Defined in: agent/stream-run.ts:71

Per-tool-call handler timeout in ms.

300000
optional idGen?: (prefix) => string;

Defined in: agent/stream-run.ts:78

Generates artifact segment ids (prefix is e.g. 'artifact-raw'). The default is a deterministic per-run counter; the adapter injects a crypto-based one to match _streamLoop’s artifact-*-<uuid>. (Tool ids still flow from the stream; only artifacts need generated ids.)

ParameterType
prefixstring

string


Defined in: conversation/compactor.ts:27

conversation/compactor.ts — adaptive budgeting + context-window assembly.

Conversation history budgeting and sliding-window assembly — framework-free and tokenizer-free (char-count heuristic).

Pattern (cf. Claude Code /context, OpenAI Agents SDK TrimmingSession): Budget = CONTEXT_WINDOW − systemPrompt − tools − reservedThinking − reservedGeneration − autocompactBuffer − safetyMargin

The history budget is then split into:

  • summary (global summary, LLM-generated, ~10%)
  • ragHist (older turns retrieved by cosine similarity, ~25%)
  • window (verbatim sliding window, the rest)

Drop priority on overflow:

  1. summary (async-regenerable)
  2. ragHist (retrievable on the next turn)
  3. window oldest turns X. NEVER dropped: currentUser + lastAssistant (absolute working memory)

Browser-portable: zero deps, just an estimateTokens heuristic.

role: "tool" | "system" | "assistant" | "user";

Defined in: conversation/compactor.ts:28

content: string;

Defined in: conversation/compactor.ts:29


Defined in: conversation/compactor.ts:32

role: "assistant" | "user";

Defined in: conversation/compactor.ts:33

content: string;

Defined in: conversation/compactor.ts:34

optional score?: number;

Defined in: conversation/compactor.ts:35


Defined in: conversation/compactor.ts:38

contextWindow: number;

Defined in: conversation/compactor.ts:40

Total context window of the active model, in tokens.

reservedThinking: number;

Defined in: conversation/compactor.ts:42

Reserved budget for the model’s thinking/reasoning block, in tokens.

reservedGeneration: number;

Defined in: conversation/compactor.ts:44

Reserved budget for the assistant response (max_new_tokens cap).

autocompactBufferPct: number;

Defined in: conversation/compactor.ts:46

Fraction of context_window kept as autocompact buffer (0..1).

safetyMargin: number;

Defined in: conversation/compactor.ts:48

Hard safety margin in tokens.

minHistoryBudget: number;

Defined in: conversation/compactor.ts:50

Floor for history budget — never compact below this.

summaryRatio: number;

Defined in: conversation/compactor.ts:52

Ratio of history budget allocated to the summary block.

summaryMaxTokens: number;

Defined in: conversation/compactor.ts:54

Hard cap for summary tokens.

ragHistRatio: number;

Defined in: conversation/compactor.ts:56

Ratio of history budget allocated to the RAG-retrieved old turns.

ragHistMaxTokens: number;

Defined in: conversation/compactor.ts:58

Hard cap for ragHist tokens.

triggerSummaryThresholdPct: number;

Defined in: conversation/compactor.ts:60

Trigger summarization once history usage reaches this % of the budget.

summarizeEveryNTurns: number;

Defined in: conversation/compactor.ts:62

Re-run summarization every N user turns.

summaryLabel: string;

Defined in: conversation/compactor.ts:65

Header prepended to the summary block injected into the model context. English by default — override to localise (the compactor ships no locale system).

ragIntroLabel: string;

Defined in: conversation/compactor.ts:67

Header prepended to the RAG-retrieved old turns injected into the context.


Defined in: conversation/compactor.ts:70

contextWindow: number;

Defined in: conversation/compactor.ts:71

systemPrompt: number;

Defined in: conversation/compactor.ts:72

tools: number;

Defined in: conversation/compactor.ts:73

reservedThinking: number;

Defined in: conversation/compactor.ts:74

reservedGeneration: number;

Defined in: conversation/compactor.ts:75

autocompactBuffer: number;

Defined in: conversation/compactor.ts:76

safetyMargin: number;

Defined in: conversation/compactor.ts:77

historyAvailable: number;

Defined in: conversation/compactor.ts:78


Defined in: conversation/compactor.ts:81

historyBudget: number;

Defined in: conversation/compactor.ts:82

breakdown: BudgetBreakdown;

Defined in: conversation/compactor.ts:83

config: CompactionConfig;

Defined in: conversation/compactor.ts:84


Defined in: conversation/compactor.ts:87

summary: number;

Defined in: conversation/compactor.ts:88

ragHist: number;

Defined in: conversation/compactor.ts:89

window: number;

Defined in: conversation/compactor.ts:90


Defined in: conversation/compactor.ts:93

system: number;

Defined in: conversation/compactor.ts:94

summary: number;

Defined in: conversation/compactor.ts:95

ragHist: number;

Defined in: conversation/compactor.ts:96

window: number;

Defined in: conversation/compactor.ts:97


Defined in: conversation/compactor.ts:100

ragHits: number;

Defined in: conversation/compactor.ts:101

oldTurns: number;

Defined in: conversation/compactor.ts:102

summary: boolean;

Defined in: conversation/compactor.ts:103


Defined in: conversation/compactor.ts:106

contextWindow: number;

Defined in: conversation/compactor.ts:71

BudgetBreakdown.contextWindow

systemPrompt: number;

Defined in: conversation/compactor.ts:72

BudgetBreakdown.systemPrompt

tools: number;

Defined in: conversation/compactor.ts:73

BudgetBreakdown.tools

reservedThinking: number;

Defined in: conversation/compactor.ts:74

BudgetBreakdown.reservedThinking

reservedGeneration: number;

Defined in: conversation/compactor.ts:75

BudgetBreakdown.reservedGeneration

autocompactBuffer: number;

Defined in: conversation/compactor.ts:76

BudgetBreakdown.autocompactBuffer

safetyMargin: number;

Defined in: conversation/compactor.ts:77

BudgetBreakdown.safetyMargin

historyAvailable: number;

Defined in: conversation/compactor.ts:78

BudgetBreakdown.historyAvailable

historyAllocated: SplitBudget;

Defined in: conversation/compactor.ts:107

historyUsed: UsageBreakdown;

Defined in: conversation/compactor.ts:108

totalUsed: number;

Defined in: conversation/compactor.ts:109

free: number;

Defined in: conversation/compactor.ts:111

Free tokens left in the context window after all reservations + actual use.

dropped: DroppedBreakdown;

Defined in: conversation/compactor.ts:112


Defined in: conversation/compactor.ts:115

messages: CompactionMessage[];

Defined in: conversation/compactor.ts:116

systemPrompt: string;

Defined in: conversation/compactor.ts:117

optional toolsArray?: unknown;

Defined in: conversation/compactor.ts:119

Tools array passed to apply_chat_template (or null/undefined when no tools).

optional summary?: string;

Defined in: conversation/compactor.ts:121

Running summary text (regenerable).

optional retrievedTurns?: RetrievedTurn[];

Defined in: conversation/compactor.ts:123

RAG-retrieved old turns (older than the sliding window).

optional config?: Partial<CompactionConfig>;

Defined in: conversation/compactor.ts:125

Partial override of the default config.


Defined in: conversation/compactor.ts:128

compactedMessages: CompactionMessage[];

Defined in: conversation/compactor.ts:129

breakdown: FullBreakdown;

Defined in: conversation/compactor.ts:130

type XmlArtifactState = "normal" | "scanning" | "in-artifact";

Defined in: agent/parsers/artifact-xml-state-machine.ts:21

Where the streaming parser is between artifacts.


type XmlArtifactEvent =
| {
type: "chat-text";
text: string;
reduced?: boolean;
}
| {
type: "artifact-open";
id: string;
mimeType: string;
kind: string;
title: string;
}
| {
type: "artifact-chunk";
id: string;
content: string;
}
| {
type: "artifact-close";
id: string;
content: string;
inline: boolean;
};

Defined in: agent/parsers/artifact-xml-state-machine.ts:30

DOM-free micro-events the machine emits; the adapter renders them.


type StreamChatEvent =
| {
type: "text";
delta: string;
}
| {
type: "thinking";
delta: string;
}
| {
type: "tool_use";
id: string;
name: string;
input: unknown;
}
| {
type: "error";
message: string;
}
| {
type: "done";
usage?: StreamUsage;
};

Defined in: agent/stream-events.ts:53

A structured stream event from the transport (mirrors AparteStreamEvent). The tool_use variant spreads StreamToolCall exactly like core’s does.


type StreamToolHandler = (call, signal) => Promise<{
content: string;
}>;

Defined in: agent/stream-events.ts:84

A tool handler (mirrors the resolved AparteToolHandler).

ParameterType
callStreamToolCall
signalAbortSignal

Promise<{ content: string; }>


type StreamApprovalResolver = (toolCallId, signal) => Promise<{
approved: boolean;
payload?: unknown;
}>;

Defined in: agent/stream-events.ts:99

Resolves a human-in-the-loop approval (mirrors core’s AparteToolApprovalResolver). Injected so the loop stays headless.

ParameterType
toolCallIdstring
signalAbortSignal

Promise<{ approved: boolean; payload?: unknown; }>


type StreamRunEvent =
| {
type: "run-start";
}
| {
type: "turn-start";
}
| {
type: "text-delta";
delta: string;
reduced?: boolean;
}
| {
type: "text-flush";
}
| {
type: "thinking-delta";
delta: string;
}
| {
type: "artifact-open";
id: string;
mimeType: string;
kind: string;
title: string;
}
| {
type: "artifact-chunk";
id: string;
content: string;
}
| {
type: "artifact-close";
id: string;
content: string;
inline: boolean;
}
| {
type: "artifact-ready";
id: string;
mimeType: string;
kind: string;
title: string;
content: string;
}
| {
type: "tool-start";
toolCallId: string;
name: string;
input: unknown;
}
| {
type: "tool-awaiting-approval";
toolCallId: string;
name: string;
input: unknown;
}
| {
type: "tool-approved";
toolCallId: string;
}
| {
type: "tool-rejected";
toolCallId: string;
reason: string;
}
| {
type: "tool-resolved";
toolCallId: string;
result: string;
}
| {
type: "tool-aborted";
toolCallId: string;
}
| {
type: "turn-limit-exceeded";
scope: "global" | "tool";
limit: number;
toolCallId?: string;
}
| {
type: "phase-advance";
index: number;
}
| {
type: "run-aborted";
}
| {
type: "run-done";
usage?: StreamUsage;
};

Defined in: agent/stream-events.ts:132

High-level, DOM-free events isomorphic to _streamLoop’s targetElement.* call sequence. Emitted synchronously and in order (see StreamRunEmitter) so the adapter reproduces the exact streaming update order.

Mapping to _streamLoop (aparte-client.ts) for the adapter:

  • run-start → updateMessage(status:‘streaming’) once at loop entry (the leading write before turn 1)
  • turn-start → reset the per-turn parser / thinking / streaming-segment state (no DOM); one per turn
  • text-delta → parser-driven addSegment/updateSegment, else typeName/updateLastMessage
  • text-flush → textParser.finalize() then addSegment/updateSegment the finalized segments; one per turn, after the inner SSE loop ends (surfaced by the spike — a turn-boundary flush)
  • thinking-delta → addSegment(‘thinking’) then updateSegment(content); first text-delta after thinking collapses it (updateSegment collapsed:true)
  • tool-start → renderer lookup + per-tool-name CSS inject into document.head + addSegment
  • tool-awaiting-approval → updateSegment(‘awaiting-approval’) + dispatch aparte-tool-approval-request
  • tool-approved → updateSegment(‘pending’)
  • tool-rejected → updateSegment(‘rejected’, result)
  • tool-resolved → updateSegment(‘resolved’, result)
  • tool-aborted → updateSegment(‘aborted’) (no-handler path, timeout/abort path, or per-tool maxTurns path)
  • turn-limit-exceeded scope:‘global’ → addSegment(error ‘MAX_TURNS_EXCEEDED’); scope:‘tool’ → updateSegment(‘aborted’)
  • phase-advance → addSegment({type:‘pipeline-waiting’}); the loop has already pushed the phase’s reply into history and bumped the phase index
  • run-aborted → dispatch aparte-message-aborted (from the inner-loop abort check or the outer turn-boundary abort check)
  • run-done → updateMessage(status:‘completed’) always + setUsage if usage

type StreamRunEmitter = (event) => void;

Defined in: agent/stream-events.ts:174

Synchronous event sink — mirrors AGUIEmitter. Synchronous by contract: the loop must never yield between emitting an event and its ordered successor, or the adapter’s streaming updates would interleave out of order.

ParameterType
eventStreamRunEvent

void

const DEFAULT_COMPACTION_CONFIG: CompactionConfig;

Defined in: conversation/compactor.ts:135

function deriveArtifactKind(mimeType, fallback?): string;

Defined in: agent/parsers/artifact-xml-state-machine.ts:53

Map an artifact mimeType to a renderer kind. Byte-identical copy of core’s canonical deriveArtifactKind (parsers/aparte-stream-parser.ts) — the duplicate stays because @aparte/core is an OPTIONAL peer of the engine, so no runtime import is possible. Kept in sync mechanically by __tests__/derive-artifact-kind-parity.test.ts.

ParameterTypeDefault value
mimeTypestringundefined
fallbackstring'unknown'

string


function runStreamAgent(opts): Promise<StreamUsage | undefined>;

Defined in: agent/stream-run.ts:88

Run the structured-stream agent loop. Resolves the last turn’s usage (the done{usage} last-write-wins, mirroring _streamLoop’s return), or undefined. Throws on a stream error event or a non-abort tool failure — the caller (adapter) routes that to its lifecycle-error handler, exactly as _handleSend/_handleRetry/_handleEdit catch _streamLoop.

ParameterType
optsStreamRunOptions

Promise<StreamUsage | undefined>


function estimateTokens(text): number;

Defined in: conversation/compactor.ts:164

Token heuristic (FR ~3.5 chars/tok, EN ~4 chars/tok). Accurate to ±10% — enough for budgeting, and it avoids tokenizer.encode(), which costs ~5ms per message × N (too slow to run on every turn).

ParameterType
textstring | null | undefined

number


function estimateTokensJson(obj): number;

Defined in: conversation/compactor.ts:172

Estimate tokens for a JSON-serializable structure (e.g. tools array).

ParameterType
objunknown

number


function computeHistoryBudget(input): BudgetResult;

Defined in: conversation/compactor.ts:186

Compute the available history budget after subtracting fixed costs.

ParameterType
input{ systemPrompt: string; toolsArray?: unknown; config?: Partial<CompactionConfig>; }
input.systemPromptstring
input.toolsArray?unknown
input.config?Partial<CompactionConfig>

BudgetResult


function splitHistoryBudget(historyBudget, cfg?): SplitBudget;

Defined in: conversation/compactor.ts:222

Split history budget into summary / ragHist / window slots.

ParameterTypeDefault value
historyBudgetnumberundefined
cfgCompactionConfigDEFAULT_COMPACTION_CONFIG

SplitBudget


function assembleCompacted(params): AssembleResult;

Defined in: conversation/compactor.ts:262

Assemble compacted message list given a budget and conversation state.

Output order: [system?] → [summary system msg?] → [ragHist system msg?] → window verbatim

Always keeps the last 2 non-system messages verbatim (working memory), regardless of windowBudget — these are the floor that can never be dropped.

ParameterType
paramsAssembleParams

AssembleResult


function compactConversation(input): CompactionResult;

Defined in: conversation/compactor.ts:369

Compute budget + assemble in one call. The primary entry point for consumers (a browser request interceptor, mobile, Node tests).

ParameterType
inputCompactionInput

CompactionResult