Complete API index
Grouped by responsibility and usage. Includes 46 public modules, 649 standalone symbols and 547 callable members. Aggregating entry points that share one implementation reuse the same page.
Each page covers declarations, parameters, results, fields, members and related examples. Core accepts contract implementations, Support provides recommended implementations, and Kits are chosen by the App.
Browse by import module · Scenario examples · Policy source
Core · Interfaces & runtime guarantees
Transport & streaming
| Symbol | Kind | Purpose |
|---|---|---|
abortableStream | function | Re-yield an async iterable, but reject as soon as signal aborts. The abort reason is propagated unchanged, so callers can tell user cancellation from a provider failure without inspecting messages. |
readSse | function | Decode an SSE response body into events. Framing contract: - A network chunk is not an event. Bytes are buffered until a blank line, because UTF-8 sequences, CRLF pairs and data: lines may all straddle chunk boundaries. - \r\n, \r and \n all terminate a line; a trailing \r at the end of a chunk is held back until the next chunk shows whether an \n follows. - Comment lines (leading :) are discarded; they are used as heartbeats. - The size limit applies per line and per event (1 MiB), not per network read, so many complete events coalesced into one chunk after backpressure remain valid. - Cancellation is checked between lines, so aborting while the consumer is paused stops emitting the remaining buffered events of the same chunk. |
SseEvent | interface | One dispatched SSE event, assembled from all lines up to a blank line. |
SseIdleTimeoutError | class | Raised when no bytes arrive within the configured idle window. A distinct type lets callers treat a silent connection as retryable instead of mixing it with transport or decoding failures. |
SseReadOptions | type | Per-read configuration; snapshotted when readSse starts. |
Execution & workflows
| Symbol | Kind | Purpose |
|---|---|---|
AgentBranch | interface | Immutable identity of one branch of an agent. The three required ids are generated per engine unless the host restores a branch; the optional ids are only present on a fork and record the exact origin, so a forked run can be attributed without consulting external storage. |
AgentCacheAddress | interface | Exact immutable address passed to the App port, including cancellation for this visit. |
AgentCacheOptions | interface | Persistent and volatile storage are independent; there is no implicit fallback or mirroring. |
AgentCachePort | interface | App-owned storage. Capacity, expiry, serialization and user isolation belong to the App. |
AgentCheckpoint | interface | In-memory checkpoint with a copy-on-read accessor. The stored data is already a clone, and read clones again, so a caller cannot mutate the checkpoint by mutating what it read. |
AgentCheckpointRecord | interface | Host-owned serializable data, never a saved credential, model budget or executable handler. |
AgentCoreEngine | class | Bounded execution shared by applications; business rules are registered by each host. Configuration is bound before a run and may be bound only once per model, tool runtime and workflow. A run resolves its signal from the engine, the request runtime and the caller, then executes either the bound workflow or a supplied step function until the round budget, cancellation or a completion stops it. |
AgentCoreEngineOptions | interface | Engine construction options. |
AgentCoreEngineSetup | type | Engine construction options. Combines round budget and error factories with exactly one model shape (a single bound model or a named catalog), an optional tool runtime, an optional branch identity, and an optional workflow together with its App dependencies. |
AgentModelBinding | type | Model binding accepted by the engine. Execution scope belongs to the engine, so a bound model may not carry its own signal or execution options. |
AgentModelRuntime | type | The subset of a runner an engine may drive; kept small so the App can supply it. |
AgentWorkflow | class | Executable catalog: validate references and bounded cycles before any handler runs. Validation happens once, at construction, so traversal can assume every target exists and every cycle is budget-bounded. |
AgentWorkflowDefinition | type | The graph an engine executes. |
AttemptBudget | class | Successful acquisitions consume attempts; a refused acquisition never grants another. available is a snapshot of the counter, not a reservation: a caller must still call take and honor its boolean result before acting. |
CacheContext | interface | Cache access shared by workflow visits and the low-level $step loop. |
CacheReadOptions | interface | Only reads may name another node. Partition names are not authorization boundaries. |
CoreStep | type | One loop iteration. Must be re-entrant: the same step object runs every round. |
defineWorkflow | function | Build a validated workflow from a definition. |
EngineCacheOptions | interface | Optional Engine memory bounds; TTL is measured from the latest write. |
ExecutionEventDescriptor | interface | Event name, content class and the producing execution identity. |
ExecutionObserver | interface | Live consumer of Core facts. |
LoopEvent | interface | Progress fact for one loop round, correlated with the enclosing diagnostics span. |
NodeAgentCache | interface | Async node view. Writes and clear can only address the current partition. |
NodeCache | interface | Synchronous view of the current node's Engine-owned memory. Values retain identity. |
requireWorkflowValue | function | Read a state field that must already be present. Used by requires declarations and terminal deliveries, so a node cannot observe a field as undefined and silently produce a wrong result. |
route | function | |
StepOutcome | type | Decision a step returns to the engine. |
WorkflowChain | interface | Observed visits, never merged by static node id or synthesized from adjacency. |
WorkflowChainCoverage | interface | Capture completeness is independent of whether diagnostic content was included. |
WorkflowChainNode | interface | A single node visit, with flat ordered subflow records including every independent fix. |
WorkflowChainNodeEvent | interface | Node-local lifecycle facts; payload remains subject to the source's content policy. |
WorkflowChainSource | type | App resolves authorization, retention, pagination and storage paths before returning. |
WorkflowChainTransition | interface | Actual handoff evidence; a target span does not prove its enter event was captured. |
WorkflowContext | interface | Execution facts available to every node of a running workflow. |
WorkflowEvent | interface | Metadata only: never includes state, prompt, parameters, results or raw errors. |
WorkflowExtension | interface | Additional nodes and routes merged into an existing definition. |
WorkflowFailure | interface | Error retained only while entering a registered failure phase. |
WorkflowGraph | interface | Pure registered topology; routes sharing a target share an edge within one kind. |
WorkflowGraphEdge | interface | Completion has no target node; recovery edges remain distinct from normal edges. |
WorkflowGraphNode | interface | Node metadata and derived incident edges, without executable callbacks. |
WorkflowGraphRoute | interface | Declaration order is retained even when multiple routes share a topology edge. |
WorkflowModel | interface | Model and tool access for one workflow invocation. Every call is charged to the workflow's shared budget. Overloads select the transport: a prepared call, the default plain-text transport, or one registered transport with its typed result. |
WorkflowNode | type | One node of the graph. |
WorkflowNodeReport | interface | Detail an App node reports about its current visit. |
WorkflowRoute | type | One route out of a node. Routes are evaluated in array order and the first match wins. A route either continues at targetNodeId or completes the workflow through complete; declaring both is invalid. |
WorkflowSubflowRecord | type | Historical subflow snapshots may omit recorder fields or descriptive content. |
Shared contracts & helpers
| Symbol | Kind | Purpose |
|---|---|---|
AgentErrorInfo | interface | Stable error metadata for App diagnostics. Unknown retryability is deliberately omitted. |
AsyncSink | type | Awaitable sink for an ordered stream. A rejection propagates to the emitter. |
BudgetError | class | A configured allowance (rounds, model calls, attempts) is exhausted. The optional message states which allowance ran out; code is the stable marker. |
CheckResult | interface | Verdict of one registered check. unavailable and not-run are not verdicts on the value: they state that the check could not produce an answer, so callers must not treat them as failures. |
commonPrefixLength | function | Length of the longest common prefix of two strings. Implemented as a binary search over slice comparisons so long prompts stay on the native string comparison path instead of running a JavaScript character loop. |
configureBreakWhile | function | Install the host-owned break observer. No logging or persistence is enabled by default; passing no argument (or an empty config) removes any previously installed observer. |
DurationMs | type | Elapsed time in milliseconds; never an absolute instant. |
ErrorContext | interface | Boundary metadata is recorded internally, without replacing the original thrown value. |
ExecutionContext | interface | Required execution facts available inside a running call. |
ExecutionOptions | interface | Optional controls accepted by any public Core call. |
getErrorInfo | function | Produce a frozen diagnostic view of any thrown value. Inspection is guarded: an exotic error (revoked proxy, throwing getter, null prototype) degrades to UNKNOWN_ERROR instead of raising a second failure while handling the first. |
Id | type | Opaque identifier. Format and meaning belong to the App or to the registering module. |
InvocationMetadata | interface | Identity and timing shared by every invocation receipt. |
InvocationResult | interface | A produced value together with the receipt of the invocation that produced it. |
InvocationStatus | type | Terminal state of one invocation; cancelled is distinct from a failure. |
Issue | interface | One validation problem, locatable by code and, when available, by field path. |
JsonSchema | type | JSON Schema as consumed by the App's validator; Core never interprets its contents. |
MaybePromise | type | A value that may already be resolved or still pending. |
ModelCallRecord | interface | Receipt of a model call that returned successfully. |
ModelResult | type | Model call result with its model-call receipt. |
Observer | type | Notification callback. A rejected promise propagates to the emitter. |
OperationContext | interface | Execution context plus the App-owned host object. app carries services, identity and per-request dependencies supplied by the host; Core treats it as opaque and must not depend on application-specific fields. |
ProtocolRegistry | class | Append-only protocol registry. Extending Map keeps lookup semantics familiar while set rejects every invalid registration, which makes the instance effectively immutable after wiring. |
ReadonlyCatalog | interface | Read-only projection of a definition set; the implementation owns ordering and validation. |
Registry | interface | Mutable catalog. Registrations append; seal freezes the set against later writes. |
retrievalQueryKey | function | Serialize a query into a stable structural key. Object keys are sorted recursively while array positions are preserved. Values that JSON cannot represent, such as functions or undefined, make JSON.stringify return undefined and therefore produce an error instead of a colliding key. |
SchemaAdapter | interface | Compiled schema pair: the JSON form shown to the model and the runtime parser. |
SearchHit | interface | One search result. score semantics stay algorithm-specific (direction and scale are not part of this contract), and document may be a projection that only exposes stored fields rather than the full record. |
TimestampMs | type | Wall-clock instant in milliseconds since the Unix epoch. |
ToolCallRecord | interface | Receipt of a tool call that returned successfully. |
ToolResult | type | Tool call result with its tool-call receipt. |
ValidationError | class | Rejected input or output that failed one or more registered checks. The message is fixed; consumers should read issues for the actual reasons. |
WorkflowContractError | class | The workflow definition violates Core's execution contract, as opposed to failing business logic. Examples: unknown model binding, asynchronous predicate, unmatched route, missing state field. It is a programming error, so callers should not treat it as retryable. |
Models & interaction
| Symbol | Kind | Purpose |
|---|---|---|
AggregatedToolCall | interface | One completed native tool call in provider index order. |
AsIntent | type | Demand-discovery metadata; it has no identity independent of its tool. |
ChatProvider | class | Streaming model provider. Implementations must stop producing when context.signal aborts and should surface transport failures by rejecting the iteration rather than ending it silently. |
createModelTransport | function | Compose a registered selection transport. The capability source may be a static catalog or a function of the stage id; the resulting definitions are captured when prepare runs and are used both to build the instruction and to reject unknown capability ids at finish time. requireStrictArguments is a registration-time assertion: a transport cannot demand strict arguments from an adapter that does not support them. |
createToolCallCollector | function | Create a collector for one response. |
FunctionCallDelta | interface | One streamed fragment of a function call; fragments with the same index must be joined. |
IntentOptions | interface | Demand-facing hints attached to one Tool; no independent identity is created. |
jsonObjectInteraction | constant | |
ModelAssistantToolMessage | type | Assistant turn that may declare tool calls and may carry an empty text body. |
ModelCallRequest | type | One model call request. The input shape selects prompt mode or message mode. |
ModelCallTrace | interface | Accumulated facts of one model call, reported on success and on failure. |
ModelChildOptions | interface | Request-bound isolated runner settings; provider and ancestor budgets cannot be replaced. |
ModelChildPolicy | interface | Request-wide limits, shared by every descendant. They cannot be enlarged by a child. |
ModelFunction | interface | Provider-neutral function definition. Execution and authorization stay with the host. |
ModelImage | interface | Model message primitives shared by every provider adapter. These shapes are deliberately provider-neutral: they describe text, optional images, streamed parts and the options a call may carry. Provider-specific wire formats stay in support/model. Exports: ModelImage, ModelMessage, ModelToolCall, ModelAssistantToolMessage, ModelToolResultMessage, ModelUsage, ModelFunction, FunctionCallDelta, ModelPart, ModelOptions. |
ModelInputMeasurement | interface | Exact prepared-request accounting; token values exist only with an explicit model counter. |
ModelInteractionAdapter | interface | Pluggable implementations all consume the same business registry. No automatic fallback. |
ModelMessage | interface | One provider-neutral turn; images are user visual input and are not part of the text budget. |
ModelOptions | interface | Per-call provider options; Core passes them through and does not normalize provider ranges. |
ModelOutputEvent | type | Delivery sink, awaited in order. Parts are unvalidated proposals, never execution receipts. |
ModelPart | type | One streamed response part: assistant text or a function-call fragment. |
ModelPrepareRequest | interface | Transport selection for prepare; omitted fields take the runner defaults. |
modelProtocolError | function | Throw a model protocol validation error. |
ModelProviderContext | interface | Per-call facts a provider receives besides the messages themselves. |
ModelResponseCollector | interface | Accumulates streamed parts for one call and resolves them into the transport's result. |
ModelRunner | class | Execute registered model stages under one request's budgets and lifetime. Invariants: at most one call is in flight per runner; callCount and journal are local to the runner while totalCallCount includes descendants; every call is charged to the shared budget before I/O and every failure is annotated with its stage before it propagates. No business prompts, domain stages or provider SDKs are built into this runner. |
modelRunnerDefaults | constant | |
ModelRunnerOptions | type | Full runner construction options: provider, transports, sinks and named limits. |
ModelRunnerPorts | interface | Host ports a model runner needs in addition to its provider and transports. |
ModelRunnerSettings | interface | Named settings keep all model limits together; output token reservation stays per call. |
ModelRuntimeConfig | interface | Per-request model runtime limits. |
ModelSelection | type | A model's chosen capability together with its parsed arguments. |
ModelSessionCall | interface | One completed tool call in a session response. |
ModelSessionResult | interface | Complete result of one session response. |
ModelTokenBudget | interface | Provider-injected token accounting. Core never guesses a character-to-token conversion, so token budgets exist only when a host supplies a real counter. |
ModelTool | interface | Common selectable model interface; resolution proposes a value without business execution. |
ModelToolCall | interface | One tool call the assistant declared, in provider order. |
ModelToolCatalog | type | A compiled entity catalog also supports the minimal stage source contract. |
ModelToolRegistration | type | Registration form: input typing is erased, output typing is preserved. |
ModelToolRegistry | class | A request/stage projection is a sealed registry. Hosts filter availability before projection. |
ModelToolResultMessage | type | Tool result turn; toolCallId is required and images/tool declarations are rejected. |
ModelToolSource | interface | Minimal source a stage needs: enumerate tools and resolve one selection. |
ModelTransportDefinition | interface | One registered transport: a wire format prepared for a stage. |
ModelTransportRegistration | interface | Binds an adapter to the tools one transport serves. |
ModelUsage | interface | Provider-reported token counts for one call; used for accounting, never for admission. |
NativeFunctionCall | interface | Request-local native call buffer; never an execution receipt. |
nativeFunctionInteraction | constant | |
PreparedModelCall | interface | Request-bound, single-use transport snapshot. Repeated measurements do not prepare or spend calls. |
PreparedModelInteraction | interface | Adapter output for one stage, before the caller binds capability resolution. |
PreparedModelTransport | interface | Prepared transport handed to the runner, including sampling defaults. |
RegisteredModelTool | type | Frozen snapshot stored by a registry after schema validation. |
RegisteredTransportOutput | type | Result type of a transport selected by id. core:plain-text yields string, a registered id yields its declared result, and an id the runner does not know yields unknown rather than a guessed type. |
retryMultipleModelCalls | function | Retry once when the failure is a rejected multi-call proposal. Only the MODEL_MULTIPLE_CALLS code is retried; every other failure is rethrown unchanged. The caller owns the fallback prompt and the budget it consumes. |
ToolCallCollector | interface | Aggregation entry point for streamed function-call deltas. |
ToolCallFailure | type | Report a protocol violation and stop; callers decide how the failure is classified. |
ToolCondition | type | Activation is independent of participation in demand discovery. |
ToolContext | type | Read-only host data without changing explicit any/unknown erasure into an object constraint. |
ToolProposal | interface | A model proposal, not an authorization or execution receipt. |
Context & journals
| Symbol | Kind | Purpose |
|---|---|---|
assembleContextPlan | function | Build the model input for a context plan. |
assembleFragments | function | Build the model input from fragments. Metadata remains program-side: data never becomes a system instruction. |
BuiltContext | interface | Assembled context plus the accounting needed to explain the budget decision. |
ContextFragment | interface | One piece of model-visible input before assembly. |
ContextFragmentUsage | interface | Accounting entry reported for one fragment that actually entered the context. |
ContextJournal | class | Request-local context projection of execution receipts; not a separate persistent log store. |
ContextLifetime | type | Declared validity window of a fragment's content. |
ContextPlan | interface | Unassembled input; App-side nodes may process it before the Core budget boundary. |
ContextRecord | type | One journal entry: a model call, a tool request or a tool result. The three variants are distinguished by type; value/input stay unknown because their domain meaning belongs to the App. |
ContextTrust | type | Who produced the content, and therefore how much it may influence the model. |
validateContextBudget | function | Enforce the character budget of the whole model input. |
validateContextFragment | function | Validate one fragment and return the text it contributes to the model input. |
Configuration, catalogs & policies
| Symbol | Kind | Purpose |
|---|---|---|
BreakCheck | interface | Each rule owns a semantic/readability group and its tags, independently of shared errors. |
BreakEvent | interface | Diagnostic metadata only; rule inputs and request data are not included. |
BreakPredicate | type | Each predicate is evaluated only after the preceding predicates passed. |
BreakReason | type | Lazy reasons preserve error construction and message evaluation on the rejection path only. |
breakWhile | function | Reject as soon as one of several conditions holds. Ordinary processing stays an ordinary if; this helper is for validation tables whose entries are evaluated in order and stop at the first failure. Behaviour that depends on earlier entries is expressed with a callback form. Reject when any predicate holds, reporting the given observer tags. Reject when any structured check holds. Each check may carry its own reason and tags; the first match stops the evaluation. Reject when a single value is truthy. Ordinary truthiness applies, so a function passed as a value counts as a failure; use the predicate form to evaluate it instead. Reject when a single value is truthy, reporting the given observer tags. |
BreakWhileConfig | interface | Global rejection observer installed once per process. |
matchRule | function | Dispatch to the first matching rule. A rule without a pattern matches unconditionally, so the table's order decides precedence. The first match owns the result even when its handler returns undefined, and later rules are not consulted. |
MatchRule | interface | Order is priority. Patterns may inspect values, types, state or regular expressions. |
WalkRule | interface | Synchronous traversal; local rules may omit catalog metadata. |
walkRules | function | Walk every rule in order, mutating the shared input. Later rules observe the mutations of earlier ones, which is why traversal is strictly sequential and every participant must be synchronous. Throwing stops the walk immediately; remaining rules are skipped. Walk every rule in order, mutating the shared input. |
Observation & diagnostics
| Symbol | Kind | Purpose |
|---|---|---|
CoreDiagnosticRecord | interface | Persisted data is untrusted: normalization checks the current envelope, not arbitrary payloads. |
CoreEvent | type | A recorded Core fact. Every variant carries the same envelope: a version marker, unique event id, producing span's identity, a per-producer monotonic sequence, the occurrence instant and optional reported sub-steps. subStepsDropped/subStepsTruncated state that reported detail was bounded. |
coreEventCatalog | constant | |
CoreEventDescriptor | interface | Event classification used when deciding whether a sink accepts an event. metadata events carry identity, timing and status only; content events may carry user, model or tool content and therefore require an explicit acceptance decision. |
CoreEventName | type | Union of every Core event name; the key set of CoreEventPayloads. |
CoreEventPayloads | interface | Payload of every Core event, keyed by event name. Fields are the event's own facts only. |
CoreLogOutput | interface | Destination for recorded facts; implementations decide filtering and durability. |
createDiagnostics | function | Configure the optional log consumer of the shared execution fact source. |
CreateDiagnosticsOptions | interface | Options for creating a root diagnostic scope. |
DebugStepsOutput | interface | Debug material a handler contributes to a diagnostic event. |
DiagnosticContext | interface | Recording scope bound to one execution identity. A child scope inherits the sink and observer of its parent; only identity changes. |
diagnosticError | function | Convert a thrown value into a plain record suitable as a log payload. |
DiagnosticIdentity | interface | Execution identity only: never message, account or HTTP identity. |
DiagnosticSpanFields | type | Identity fields a child span may override; the parent supplies run, span and parent span. |
NodeReportingContext | interface | Reporting surface handed to a node or tool for the duration of one visit. |
normalizeDiagnosticEvent | function | Validate a persisted diagnostic record and return a detached copy. Persisted data is untrusted, so the envelope version, event type, identity, ordering and the bounded sub-step shape are checked; the payload itself is not interpreted. The copy is deep cloned, so a store cannot hand back a record that later shares structure with the caller. |
RecordedSubStep | interface | A step already accepted by a logger, carrying recorder-assigned bookkeeping fields. |
ReportedStep | interface | One step as reported by a node; fields beyond identity are optional detail. |
ReportedStepStatus | type | A status a node may report; derived from the catalog, never declared separately. |
reportedStepStatusCatalog | constant | |
reportedStepStatuses | constant | |
ScopedSubFlowLogger | class | Non-inheriting delegate. Stores only the original logger and its bound subnode identity. |
ScopedSubFlowStepInput | type | Scoped writes cannot supply or override the identity bound by their delegate. |
SubFlowLog | interface | Common read/write surface for both independently implemented logger classes. |
SubFlowLogger | class | Full execution-owned recorder. Owns its store and may issue restricted delegates. |
SubFlowStepFix | interface | Explicit revision whitelist: identity, grouping and business type are never patchable. |
SubFlowStepInput | interface | Input accepted by write; the logger assigns the step id and sequence. |
SubFlowValue | type | JSON-like value accepted in reported payloads; depth and size are bounded by the recorder. |
SubStepProgress | interface | Compact progress notification emitted for each accepted sub-step write or fix. |
Tools & capabilities
| Symbol | Kind | Purpose |
|---|---|---|
ErasedTool | interface | Type-erased tool shape the registry executes after parsing at the boundary. |
ExecutableTool | interface | One registered tool, typed by its input, output, host context and id literal. |
executeInvocation | function | Run one synchronous invocation and record its effects. |
InvocationHandler | interface | A named handler invoked by a tool lifecycle step. |
RegisteredTool | type | Registered snapshot: public data is retained, implementation helpers are not a contract. |
ToolDefinition | type | Configuration form; Support supplies the identity resolver when omitted. |
ToolExecutionContext | interface | Execution facts handed to a tool for one invocation. |
ToolExecutionEvent | interface | Fact emitted when one tool call settles, correlated by invocationId. |
ToolInvocationPorts | interface | Optional tools the lifecycle resolves from the host context for one invocation. |
ToolInvocationRequest | interface | One invocation request; the registry supplies signal and diagnostics when omitted. |
ToolJournal | interface | Request-local execution receipts; the host decides their domain content. |
ToolJournalFinish | interface | Closing record for one tool call, written once with the terminal outcome. |
ToolJournalStart | interface | Opening record for one tool call, written before the handler runs. |
ToolRegistry | class | Registry mechanism only: visibility, authorization policy, schemas and semantic metadata are host registrations. A registry is mutable until sealed and keeps its own call log. |
ToolRegistryOptions | interface | Registry construction options. |
ToolRegistryPorts | interface | Host ports a tool registry needs in addition to the tool definitions. |
Support · Recommended implementations & strategies
Shared contracts & helpers
| Symbol | Kind | Purpose |
|---|---|---|
agent | function | Instantiate an Engine configuration class without creating an Engine, budget or request. |
Agent | type | Original Engine configuration; union branches retain their required App/model relationships. |
AgentOptions | type | Agent id is an external pool identity, not an override of Core branch or request identity. |
agentPool | constant | |
AssociatedRegistration | interface | Owners retain their business fields; Support only reads model interface associations. |
AssociationOptions | interface | Shared independent tools and a default projection from existing contracts. |
AssociationSource | interface | Local provenance, never an extra model input requirement. |
ClassDecoration | type | |
DecorationOptions | interface | Namespaces group external registration without changing Core options. |
defineAssociatedCatalog | function | Compile independent and owner-derived Tool declarations, validating all references eagerly. |
DefinitionReader | interface | Read-only roots. A typed read describes the expected contract, not a static id/type lookup. |
fragment | function | Instantiate a self-describing fragment class; the original builder owns formatting checks. Bind a host's formatter method into an original fragment configuration. |
Fragment | type | A formatter and its original provenance, trust and budget configuration. |
fragmentPool | constant | |
IdentifiedDefinition | interface | Registration identity; ids are unique within one kind and namespace. |
Intent | function | Mark a WorkflowTool for demand discovery; alone this decorator registers nothing. |
MethodDecoration | type | |
model | function | Instantiate and validate model options without creating a Runner or consuming calls. |
Model | type | Original Runner configuration; the decorator's pool id is not a model identity override. |
ModelOptions | type | Model id is only a pool key; Core still owns the configured model/transport identities. |
modelPool | constant | |
node | function | Instantiate a node definition class once, injecting its id; graph validation stays in Workflow. Bind a named host method as run without renaming or manually binding the original object. |
Node | type | A node implementation; its public id is supplied by |
nodePool | constant | |
Support | namespace | |
tool | function | Instantiate a tool definition class; schema and authorization stay with existing defineTool. Bind an existing host method as the tool's execute callback. A model-only tool method provides its synchronous resolver. |
Tool | type | A tool implementation with the original schema, authorization and execution contracts. |
ToolAssociation | type | Explicit tool references or inline overrides of the owner's default model interface. |
toolPool | constant | |
workflow | function | Instantiate and validate workflow options, leaving actual execution with the original Engine. |
Workflow | type | A complete graph definition whose workflow id is supplied by |
workflowPool | constant |
Tools & capabilities
| Symbol | Kind | Purpose |
|---|---|---|
CapabilityCatalogOptions | interface | Catalog construction options. |
CapabilityModule | interface | Minimal composition contract; lifecycle and domain fields remain application-owned. |
CapabilityToolReferences | interface | Tool references declared by one owner module. |
CompiledTool | type | Tool definition type derived from a declaration literal, preserving input/output/id. |
defineCapabilityCatalog | function | Build a frozen capability catalog from application module declarations. Each module must carry a non-empty description, and every contributed tool ID must be unique across modules. Reference projections run during construction and must be synchronous. |
defineTool | function | Validate one tool declaration and freeze a detached copy of it. authorize must settle with void; a rejection has to be thrown, so a returned false cannot silently pass. Handlers are bound to the declaration object, and the input schema is re-snapshotted so later mutation cannot widen the accepted input. |
defineToolCatalog | function | Infer the host context from existing executable definitions, without widening it to unknown. Explicit host typing remains available for contextually typed declaration lists. |
SelectedTools | type | Catalog narrowed to the given ids: each kept tool's id literal is intersected with Id. |
ToolCatalog | interface | Frozen tool catalog with model tools and per-request binding. |
ToolCatalogEntry | type | Public declaration surface of one tool, without registry internals. |
ToolModelView | interface | Model capability view of a tool catalog, retaining the host context type. |
ToolOutput | type | Output type of the tool whose id matches Id; never for any other id. |
ToolRuntime | interface | Catalog bound to one App request. |
validateToolReferences | function | Validate tool references against the complete registered set. Checking against every registered tool (not only the ones available in the current request) keeps the declaration honest: a module may reference a tool that this request filters out, but never one that does not exist. |
Models & interaction
| Symbol | Kind | Purpose |
|---|---|---|
chatCompletionFunctionOptions | function | Build the tool-selection request fields for a function-calling stage. The adapter expects exactly one function call per response, so tool use is required and parallel calls are disabled. |
chatCompletionMessages | function | Map Core and provider messages to chat-completions message payloads. Only declared message fields are sent. Assistant tool declarations become nested tool_calls, and tool results become tool_call_id; both are rewritten explicitly rather than forwarded as-is. Messages with images become a content-block array; images are accepted only on user messages and only as http(s) or data:image URLs. |
chatCompletionParts | function | Convert one streamed choice.delta into Core model parts. Text is emitted only when non-empty; each tool-call fragment carries its index so Core can reassemble arguments that arrive across chunks. |
CompatibleModelConfig | interface | Configuration of one OpenAI-compatible endpoint. |
CompatibleModelPorts | interface | Adapter ports the App may override without replacing the provider. |
CompatibleModelProvider | class | HTTP/SSE lifecycle shared by hosts. Apps supply config and user-visible error mapping only. A static configuration is validated and frozen in the constructor. A configuration function is called once per request instead, so credentials and models may rotate between calls. |
CompatibleModelProviderOptions | interface | Construction options for a compatible provider. |
CompletionFailure | type | Build the classified failure a policy throws; the provider records it like its own failures. |
CompletionPolicy | interface | Decision whether a finished stream satisfies the request. |
completionPolicyCatalog | constant | |
CompletionRequestFacts | interface | Facts the provider reads from the request it actually sends. functions reports the Core call options and keeps the default policy equivalent to the behavior that existed before policies were configurable. toolChoice is the effective field of the serialized body, so a host override, or a field dropped for being undefined, is visible exactly as the upstream receives it. |
CompletionSession | interface | Per-request completion state observed by one policy. |
createJsonTransport | function | Create a typed JSON transport without a capability-selection envelope. The transport embeds the JSON Schema in the instruction and requires the response to be one complete JSON value. The returned response parser rejects native call events and invalid JSON, then validates the value through the supplied schema. |
createModelStrategy | function | Compose runner options in precedence order: budget preset, selected model, declared reasoning, exact budget, then explicit Core fields. The result is validated through the same Core binding rules but creates no runner and spends no calls. |
createProviderObservationScope | function | Bind provider observations to a caller-owned destination across diagnostic child spans. attach returns a scoped diagnostic context; contexts that were not attached through this scope produce no observations. Child contexts inherit the owner and a parent/child span path. |
createReplyPreview | function | Create a model-output event handler that publishes preview bubbles. The handler resets on model.start, ignores other invocations, disables itself on unexpected output, and clears the preview when a call ends unsuccessfully. Rules are snapshotted at creation, and only explicitly registered prose fields are projected. |
createReplyPreviewRules | function | Generate frozen preview rules from capability and stage declarations. Capabilities without preview metadata are skipped even when their stage opts in. Default paths are text and bubbles[*], each kept only when the capability schema declares it. |
createSessionModelTransport | function | Create a session transport. |
createStageModelTransport | function | Build a transport that projects a capability source through declared stage references. |
createTextTransport | function | Create a plain-text transport that trims the assembled response. |
defaultCompletionPolicy | constant | |
defineModelTools | function | Build a sealed capability catalog from typed declarations. |
modelBudgetStrategies | constant | |
ModelBudgetStrategy | type | Preset name, or an explicit partial set of Core runner settings. |
ModelChildrenOptions | interface | Group options: worker count, extra cancellation and accept/commit hooks. |
ModelChildTask | interface | One child call in a group: its own limits plus the work to run with the child runner. |
ModelChoiceIndex | interface | Minimal selector shape used while filtering the provider response choices. |
modelInteractionCatalog | constant | |
ModelProviderErrorCode | type | Stable failure classification reported by the compatible provider adapter. |
ModelProviderFailure | interface | Failure detail passed to the App's error factory. |
ModelStageTransportRegistration | interface | Stage IDs and capability references are App-owned; this adapter only compiles their relation. |
ModelStrategyOptions | type | Input of createModelStrategy: model selection, optional reasoning and budget plus explicit Core overrides. Explicit Core fields win over every generated value. |
PreparedSessionTransport | interface | Prepared session transport handed to the runner. |
prepareSessionFunctions | function | Build the session policy for one stage. |
PreviewTool | interface | A model tool with an explicit, presentation-only streaming preview contract. |
ProviderAssistantMessage | interface | Assistant turn; content may be empty when the turn is only a tool declaration. |
ProviderErrorCapture | interface | Captured upstream error body and whether it had to be truncated. |
ProviderEventDescriptor | interface | Provider event name plus its content class. |
ProviderEventName | type | Union of provider event names. |
ProviderEventPayloads | interface | Payload of each provider event. Content-bearing events are accepted explicitly. |
ProviderMessage | type | Message list a host may pass to the compatible provider directly. |
ProviderObservation | type | One observation: event name with its payload. |
ProviderObserver | interface | The caller can correlate each observation using the original, request-local model options. |
ProviderReasoningLevel | type | Supplier wire shape is explicit; levels express requested effort, not measured quality. |
ProviderReasoningStrategy | type | How a reasoning level is translated into request fields. requestBody entries override generated fields, so a host can correct a provider that expects a different shape. |
ProviderSystemMessage | interface | System instruction turn; text only, so the union rejects images and tool fields here. |
ProviderToolCall | type | One tool call the assistant declared, in wire order; aliases the Core shape. |
ProviderToolMessage | interface | Tool result answering one declared call. |
ProviderUserMessage | interface | User turn; the only message type that may carry images, and never tool calls. |
ReplyPreviewOptions | interface | Settings for createReplyPreview; sink receives every bubble list and is required. |
ReplyPreviewRule | interface | One projection rule: which stage/capability it matches and which prose fields may be shown. A rule without toolId may only match a registered plain-text stage. |
ReplyPreviewStage | interface | Stage declaration: which tools it exposes and whether it previews text or arguments. |
ReplyPreviewTool | interface | Capability declaration used to derive preview rules. Omitted preview means the capability never previews, so previewing is an explicit opt-in. |
ResolvedSessionCall | interface | One completed call with host-facing resolution; unknown tools and bad JSON stay non-fatal. |
ResolvedSessionResult | interface | Complete result of one session response after host-facing resolution. |
runChildren | function | Run child tasks concurrently and return their values in declaration order. The first failure aborts the remaining group, but an already in-flight commit is still awaited because cancellation does not mean the write was rolled back. |
sessionCompletionPolicy | constant | |
SessionFunctionOptions | interface | Options a session transport may pass through to provider options. |
SessionModelTransportRegistration | interface | Registration for one session transport. |
Context & journals
| Symbol | Kind | Purpose |
|---|---|---|
ContextAssemblyOptions | interface | Assembly options for placement-based projections. |
ContextBuilder | interface | Compiled builder. It holds no request state and may be shared across invocations. |
ContextBuilderOptions | interface | Shared builder options. |
ContextCompressionCall | interface | One compression request. |
ContextCompressor | interface | Registered compressor handler. |
ContextFragmentConfig | interface | Self-describing fragment declaration: metadata plus a formatter. |
contextHandlerCalls | function | |
ContextHandlerReference | interface | Reference to a registered compressor or selector handler. |
ContextHistoryGrouping | type | How a message history is split into groups for trimming. |
contextHistoryStrategies | constant | |
ContextModelCall | interface | Same runner and same fixed invocation result as public model calls. |
ContextModelRequest | interface | One model call made on behalf of a selector or compressor. |
ContextNodeResult | interface | Outcome of one context node: the built input, its prepared model call and the change report. |
ContextPolicy | type | Declared context policy for one stage. |
contextPolicyCatalog | constant | |
ContextProcessingNodeDefinition | type | Definition accepted by createContextProcessingNode. It is a normal Core WorkflowNode except that the node body is declared here: plan builds the context, update decides the committed state, and policy/handlers/timeout are validated when the node is created. |
ContextProcessingOptions | interface | Runtime inputs for one processing run. |
ContextProcessingReport | interface | Facts recorded for one processing run. |
ContextProjection | type | One declared projection: a single fragment or a placement expanded into fragments. |
ContextRecentHistory | interface | Recent history that compression must keep verbatim. |
ContextReduction | type | One declared reduction step. |
contextReductionCatalog | constant | |
ContextReductionNodeDefinition | type | Definition of a reduction node: one registered step is applied per node run. stepId may be fixed or derived from state, which lets a graph route over several steps. |
ContextSelection | type | Selection is independent of ownership; omitted selection preserves ordered execution. |
ContextSelectionCall | interface | Everything a selector may inspect for one decision. |
ContextSelectionCandidate | interface | Candidate step considered by selection, with its measured cost. |
contextSelectionCatalog | constant | |
ContextSelectionNodeDefinition | type | Definition of a selection node: like a processing node, but update receives chosen step IDs. |
ContextSelectionResult | interface | Selection stage result: the chosen step IDs plus the unchanged stage snapshot. |
ContextSelector | interface | Model or local selector that chooses which reductions to apply. |
ContextStageResult | interface | Result of a selection or reduction stage, before the node's update commits chosen fields. |
ContextStrategy | interface | Validated inputs ready to pass to a context processing node. |
ContextStrategyOptions | type | One history declaration that generates a step, or an explicit step list with optional history fields (fragment, field, preset, targetChars, keepGroups, grouping). |
ContextStrategySettings | type | Shared reduce-policy settings applied to the whole strategy. Trigger and target fields follow the Core policy contract; omitted values fall back to the plan budget or to the trigger. Supplying steps disables generation and uses the explicit list. |
ContextTokenMeasurement | interface | Injected token measurement for token-triggered policies. |
createContextCompressor | function | Build a compressor that asks a model to rewrite one fragment. The request pairs a system instruction with a user message carrying the fragment ID, its current value and the target character count. Only the model's parsed value is returned; the caller decides whether the result fits the reduction contract. |
createContextProcessingNode | function | Create one node that runs the complete context policy and returns the built context. Use this when the graph does not need to route between selection and reduction phases. |
createContextReductionNode | function | Create a node that applies exactly one registered reduction step. Partial plans keep the full budget until final assembly, so intermediate nodes do not shrink the allowance reserved for the reply. |
createContextSelectionNode | function | Create an ordinary node that selects reduction steps without executing them. The node reports the registered step IDs so the graph can route to reduction nodes itself. |
createContextSelector | function | Build a selector that asks a model to pick reduction steps. Without a custom parser the model must answer with a JSON object containing a stepIds array; with a custom parser the application owns that contract but must still return step IDs. |
createContextStrategy | function | Build a reduction policy from one or more history declarations. recent keeps a window of recent groups; continuity summarizes older groups while preserving the most recent originals. Neither preset claims semantic quality, only bounded input size. |
defineContextAssembly | function | Compile ordered context projections into a builder. A projection is either a single fragment (with its own formatter) or a placement whose contribution handler expands to any number of fragments at request time. |
defineContextFragments | function | Compile self-describing fragment declarations into a builder. Each definition carries its own trust, lifetime and size metadata, so no separate metadata catalog is needed. The budget may be a constant or a function of the request input. |
processContext | function | Run a complete context policy in one call: snapshot, execute and finalize. |
reservedContextCalls | function | |
selectContextSteps | function | Choose steps that fit the remaining call budget. Feasibility uses exact trim previews and declared call ceilings; the reply reserve and the selector's own allowance are subtracted before candidates are considered, so neither can be spent on reductions. |
transformContextText | function | Apply a text transform to a fragment value, including strings nested inside objects. Structured values are walked through a JSON round trip, which is what the budget measurement serializes later; values that JSON cannot represent are therefore not preserved. |
validateContextPolicy | function | Validate a complete context policy and every handler it can reference. Handler IDs must be unique and each handler must declare a non-negative integer call ceiling. Reduction targets and selection modes are checked by their own catalog entries. |
validateContextSelection | function | Validate selector declarations and the selection mode they serve. |
Configuration, catalogs & policies
| Symbol | Kind | Purpose |
|---|---|---|
defineRegistrationCatalog | function | Compile an ordered installation plan. Predicates observe the effects of preceding installations at request time; a predicate that throws rejects the install instead of being treated as false. Callbacks are bound to their declaring definition so implementations may rely on this. |
defineSchema | function | Re-snapshot an existing adapter without changing its behavior. Used to detach a caller-owned adapter from later mutation before it is exposed or reused. |
fromJsonSchema | function | Build an adapter from a caller-owned typed JSON Schema compiler. The schema is cloned and frozen before it reaches the compiler, so later mutation of the input cannot change validation. Compilation and validation must both be synchronous. |
fromParserSchema | function | Wrap a library schema that already parses values (for example Zod or Valibot style). parse is delegated unchanged, so the library keeps ownership of coercion and error reporting; only the JSON Schema projection is produced here. |
JsonSchemaOptions | interface | Options for building an adapter from a JSON Schema compiler. |
JsonSchemaValidator | interface | App-owned JSON Schema compilers provide synchronous validation. |
RegistrationDefinition | interface | One install step. |
Transport & streaming
| Symbol | Kind | Purpose |
|---|---|---|
encodeSseEvent | function | Encode one event in the server-sent events wire format. Every line of data gets its own data: field, because a raw newline would start a new field. |
JsonFrameLimits | interface | Bounds applied while scanning a streamed text. |
JsonTransportPart | type | One scanned span: a complete object frame or a character outside any frame. |
parseJsonFrames | function | Parse complete object frames under explicit count and size limits. Only whitespace may appear outside frames; a stray closing brace is tolerated only up to maxExtraClosings, which covers transports that repeat the delimiter after the payload. |
scanJsonObjectFrames | function | Extract complete object-shaped spans from surrounding text, without parsing or selecting them. |
SseOutputEvent | interface | One outbound event before wire encoding. |
SseWriter | interface | Destination that reports backpressure instead of buffering without bound. |
writeSseFrame | function | Write one encoded frame and wait for drain when the writer reports backpressure. The signal is re-checked around the write and the drain wait, so cancellation does not leave a pending write considered successful. |
Observation & diagnostics
| Symbol | Kind | Purpose |
|---|---|---|
streamEvents | function | Bridge a push-style producer to a pull-style async iterable with a one-slot rendezvous. The producer must await every emit call before emitting again; concurrent emissions are rejected rather than buffered. The slot is released only after the consumer receives the event, so backpressure is exact. |
Kit · Optional business libraries
Configuration, catalogs & policies
| Symbol | Kind | Purpose |
|---|---|---|
AgentCatalogPorts | interface | Ports the catalog reads from the App's registries. |
CatalogGoal | interface | Goal as the catalog sees it: an id plus its declared delegates. |
CatalogScope | interface | Scope as the catalog sees it: an id plus the tools it may use. |
CatalogTask | interface | The goal currently accepted for the request, used to narrow the catalog. |
CatalogTool | interface | Tool facts the catalog needs, independent of lifecycle details. |
defineAgentCatalog | function | Compile a catalog projection over the App's live registries. The actual registries determine availability and relationships. No parallel capability list exists: goalIds filters by tool support, modelCatalog narrows to the currently accepted task when restrictToTask is enabled, and scope tool ids are filtered to tools that exist. |
definePolicySet | function | Compile a policy set that reports every matching reason. Collect every matching reason; a configured mode cannot silently override a mandatory policy. assess returns the matched ids and deduplicated kinds rather than a single verdict, so callers keep the ordering information they need for messages and diagnostics. |
defineRecoveryChain | function | Compile an ordered recovery chain. A handler reports whether it handled the input; handled undefined values remain explicit. The first handler that reports handled ends the walk, so declaration order is the precedence, and { handled: false } is the only way to fall through. |
DescribedTool | interface | Model- or host-facing description of one tool. |
Policies | constant | |
PolicyAssessment | interface | Result of assessing every registered policy against one input. |
PolicyDefinition | interface | One declarative policy. |
RecoveryDefinition | interface | One recovery handler in an ordered chain. |
RecoveryResult | type | Outcome of one recovery handler, or of the whole chain. |
Branches & versioning
| Symbol | Kind | Purpose |
|---|---|---|
AgentFamily | interface | Compiled family API. Every mutation returns the record after the write. |
defineAgentFamily | function | Compile a versioned family backed by an App-owned compare-and-swap store. Every mutation reads the record, verifies the caller's expected revision, then commits with a compare-and-swap, so concurrent writers fail with a revision conflict rather than overwriting each other. Reads are also treated as policy checks because the App binds its read rules into the store it supplies. |
Family | constant | |
FamilyDefinition | interface | App-owned hooks and limits for one family. |
FamilyOperation | type | One of the four family mutations. |
familyOperations | constant | |
FamilyRecord | interface | A whole family: its versions and which version is currently active. |
FamilyStore | interface | CAS must cover every writer and the active pointer in one real storage commit. |
FamilyVersion | interface | Immutable snapshot of App state at one point on a branch. |
Observation & diagnostics
| Symbol | Kind | Purpose |
|---|---|---|
AgentOutputEvent | type | One output event of a delivered reply. |
publishReplyEvents | function | Stream one reply as paced text chunks and bubble separators. Publish a validated reply without exposing its internal boundary to consumers. The pacing options are upper bounds, not exact timings: the pause and interval are clamped against maxDurationMs, so added delay never exceeds the budget while every chunk is still emitted. |
REPLY_BUBBLE_BOUNDARY | constant | |
ReplyBubbleInput | interface | Reply pieces accepted by the bubble helpers; non-string entries are ignored. |
replyBubbleTexts | function | Collect the non-empty-text parts of a reply. |
ReplyDeliveryOptions | interface | Host-controlled delivery of already validated text; not upstream model generation. |
serializeOutputEvents | function | Serialize the event protocol for callers using a text stream. preview events are dropped because they are not final text; bubbles become the boundary character again, so a consumer can re-split the stream. |
textOutputEvents | function | Wrap already-chunked text as text events. |
Shared contracts & helpers
| Symbol | Kind | Purpose |
|---|---|---|
Aggregation | constant | |
Candidates | constant | |
CandidateSelectionDefinition | interface | Declares the alternative-proposal envelope. A value without the declared field is treated as a single implicit candidate. |
ContentProjection | interface | Projection output. |
ContentProjectionOptions | interface | Candidate strategy for content projection. |
createIntentRegistry | function | Create and seal a complete catalog; use the constructor for incremental installation. |
defineCandidateSelection | function | Compile an alternative-proposal envelope contract. Alternative proposals are bounded and shallow; accepting a task closes this capability. A value that is not an object, or that does not carry the candidate field, is treated as a single implicit candidate and returned as-is. Once the envelope is present it must contain only that field, and its array must hold between minCandidates (default 1) and maxCandidates distinct candidate objects that do not themselves repeat the field. |
defineContentProjection | function | Compile a JSON-preserving projector. Keep valid JSON while reducing prose before dropping records; budgets are caller policy. The candidate list is tried in order (outer counts, inner lengths), so callers control whether trimming text or dropping items is preferred, and the configured fallback is used only when no candidate fits. |
defineDelivery | function | Compile a delivery pipeline from its declared stages. Stages are registered once, in declaration order, and must have unique non-blank ids. A stage without a handle is a named hook only, so beforeStage can observe it. |
defineNormalization | function | Compile an ordered normalization pipeline. Steps run in declaration order. Each step may be skipped by its when predicate, receives the value produced by the previous step, and isComplete can stop the walk early, so the usual contract is "first completion wins" rather than "always run everything". |
defineQueryAggregation | function | Compile one ordered read plan over a list of inputs. Ordered synchronous queries with optional stable-key merging; each real read stays host-owned. Inputs run sequentially in the given order, so a host can rely on a deterministic visit sequence. Without key every item is kept; with key the last write wins per key but the position of the first occurrence is retained. |
defineTextSkillLoader | function | Compile a loader that validates registrations and reads their documents. The default contract is narrow by design: ids are lower-case words joined by hyphens (up to maxIdChars, default 64), each entry lives at <id>/SKILL.md, the kind is text-workflow, and the document starts with name/description front matter. |
defineTreeProjection | function | Compile a depth-limited tree transform. Traverse synchronously in property/array order; only undefined omits a result. Because a visitor returns a new value instead of mutating, an omitted branch disappears from arrays and objects the same way, and maxDepth bounds both cycles and cost. |
Delivery | constant | |
DeliveryOptions | interface | Pipeline construction options. |
DeliveryStage | interface | One pipeline stage, identified for reporting and optional observation. |
IntentDescription | type | Registered domain Tool with its delegates widened to the definition's delegate literals. |
IntentId | type | Union of the ids of a definition set, or string when it cannot be narrowed. |
IntentPolicy | interface | Registration rules for one intent registry. |
IntentRegistry | class | Goal semantics and allowed values are configuration; the registry owns their common lifecycle. Registration order is preserved by ids, definitions, values and entries; once seal() is called the set is final and further registration is rejected. |
IntentTool | interface | One domain Tool. |
IntentToolRegistration | type | Configuration form; object arguments and a Tool proposal are the registration defaults. |
mergeByKey | function | Merge duplicates without moving their first position; selection policy remains host-owned. The first occurrence of a key fixes the output position; select decides which item that position finally holds, so callers can prefer the newest or the most complete duplicate. |
ModelBinding | interface | App-defined I/O. Registered literal IDs determine input and output types. |
ModelCalls | class | Frozen catalog of model bindings plus a checked invocation entry point. Registration happens once in the constructor; the catalog is never mutated afterwards, so a caller cannot swap a provider in the middle of a run. |
ModelInvocationContext | interface | One take consumes one binding invocation attempt, independent of batch size or chat tokens. |
ModelInvocationRequest | interface | One model call: registered binding id, the input to hand over and its timeout. |
Normalization | constant | |
NormalizationOptions | interface | Pipeline options. |
NormalizationStep | interface | One ordered transformation. |
projectContinuousExcerpt | function | Project a continuous excerpt of a body by binary-searching the longest prefix that fits. Binary-search a continuous prefix and keep an existing surrogate pair intact. render receives the prefix length, not the text, so the caller decides how the excerpt is framed. |
Projection | constant | |
QueryAggregationOptions | interface | Query aggregation contract: several ordered reads collapsed into one item list. Place in the package: an optional App-side helper for merging results of the same query shape run against several inputs. The Kit owns ordering and optional stable-key merging; every real read, the merge policy and the meaning of an item stay with the App. Exports: QueryAggregationOptions. |
RegisteredIntent | type | Frozen registration view: list fields are frozen copies, helper methods are dropped. |
splitTextBlocks | function | Split long plain text on structural boundaries. Headings and horizontal rules start a new block, blank lines end the current one, and all other lines break only when the target size would be exceeded. A single line longer than the target becomes its own block so that paging can cut it into fragments later without splitting the line into unrelated sections. Concatenating every block reproduces the input exactly: no truncation, padding or dropped whitespace. The input must be plain text; binaries and rich documents are read elsewhere. |
TextBlock | interface | One structure-aware block of a long text. |
TextBlockOptions | interface | Splitting options. |
TextBlocks | constant | |
TextSkill | interface | Loaded skill: registration plus the parsed document text. |
TextSkillHeader | interface | Header every skill document must carry. |
TextSkillLoader | interface | Compiled loader. |
TextSkillLoaderDefinition | interface | Loader limits, parsing hooks and rejection wording. |
TextSkillReadPorts | interface | Host port that reads one skill document by path. |
TextSkillRegistration | interface | Catalog entry of one text skill, before its document is read. |
TextSkills | constant | |
TreeProjectionOptions | interface | Depth- and record-level traversal options for tree projection. |
uniqueBy | function | Stable deduplication preserves the original values; the host chooses equivalence. The first occurrence of each key wins and the input order is kept, so callers can rely on deduplication never reordering their list. |
Knowledge, answering & presentation
| Symbol | Kind | Purpose |
|---|---|---|
AnswerCheck | interface | Result of one local or review check over a generated answer. |
AnswerChecker | interface | One named check applied to a generated answer value. |
AnswerFlowDefinition | interface | Static handlers and limits; signal, diagnostics and App dependencies arrive at run. |
Answering | constant | |
AnswerIssue | interface | Validation problem produced while checking a generated answer. |
AnswerItem | interface | One unit an answer batch must produce. |
AnswerReader | interface | App-owned reader that gathers evidence for one task. |
AnswerResult | interface | Final outcome for one item. |
AnswerTaskDefinition | interface | Static binding of one answerable task. |
AnswerTaskPorts | interface | Registries a task catalog validates its references against. |
CompiledReplyFormat | interface | A resolved format with its checks bound; callers only inspect replies using it. |
defineAnswerCheckCatalog | function | Compile a checker catalog. A checker may return a replacement value; it is threaded into the next checker, so the selected ids behave like an ordered chain rather than independent assertions. |
defineAnswerFlow | function | Compile a reusable answer workflow. Reusable answer workflow. Requests own cells and repair budgets; models remain caller-owned. The flow runs at most maxRepairs + 1 rounds: one generation pass, then one repair round per failing item set, and finally an explicit accepted/fallback/blocked result per item. |
defineAnswerReaderCatalog | function | Compile a reader catalog. |
defineAnswerTaskCatalog | function | Compile the answer task catalog from its declarations and shared ports. Task ids, schemas, readers, outputs and checks have one compiled authority: a task can only reference a reader or check that the ports actually registered, and metadata is cloned and frozen so later mutation by the caller cannot change a registered task. |
defineKnowledgeCatalog | function | Compile a knowledge catalog from document declarations. Reads are declarative: document returns the whole text, self returns exactly the named sections and subtree includes their nested sections. Section ids are validated up front, so a typo fails at read time instead of silently returning partial content. |
defineKnowledgePublication | function | Compile a publication lifecycle over one App-owned atomic record. Candidate preparation and publication share the same compiler and an App-owned atomic revision. propose compiles and validates a candidate but leaves published documents alone; publish re-verifies sources and the base revision before swapping, so a stale candidate can never overwrite newer content. |
defineOutputCatalog | function | Compile output definitions into one catalog. Compilation is where most mistakes surface: group membership is checked for cycles, master templates must have exactly one slot per field, and every bound/semantic field must name a registered provider. Composition then trusts the compiled catalog. |
defineReplyFormats | function | Compile reply formats so that checks run only for templates the current turn uses. |
defineSemanticSlots | function | Models select public semantic keys; hosts retain private values and selection policy. A text is valid when it uses at most maxOccurrences namespaced slots, every name is a declared key, and no malformed {{namespace remnant is left behind — the last check stops partial or misspelled placeholders from reaching the template engine. |
defineTextTemplate | function | The program owns the master; inserted model text is a value and is substituted once only. Substitution is single-pass String.replace: a value that itself contains {{slot}} is left as literal text, so a slot value cannot inject further substitutions. |
Knowledge | constant | |
KnowledgeCandidate | interface | A proposed document awaiting publish or reject. |
KnowledgeCatalog | interface | Compiled catalog of knowledge documents. |
KnowledgeCatalogOptions | interface | Catalog construction options. |
KnowledgeDocument | interface | One versioned document as supplied by the App. |
KnowledgePart | type | Document content: a text leaf or a nested section. |
KnowledgePublication | interface | Compiled publication workflow. |
knowledgePublicationOperations | constant | |
KnowledgePublicationOptions | interface | App-owned guards, store and limits for a publication workflow. |
KnowledgePublicationRecord | interface | Stored publication state: one published revision plus pending candidates. |
KnowledgePublicationStore | interface | Single-writer store for the publication record. |
KnowledgeRead | interface | A request for one document selection. |
KnowledgeSection | interface | A named section that may contain text and further sections. |
KnowledgeSnapshot | interface | Materialized read result. |
KnowledgeSourceReference | interface | Citation of the material a candidate was derived from. |
mergeReplyBubbles | function | Normalize a reply that has no declared format: drop blank bubbles and merge overflow into the last allowed one. Text content is preserved. |
OutputCatalogOptions | interface | Catalog construction options. |
OutputComposeInput | interface | Input for composing one output: model values plus program-assigned group members. |
OutputDefinition | interface | One output shape. |
OutputField | interface | One field of an output definition. |
OutputIssue | interface | Output problem with a guaranteed field path. |
OutputProvider | interface | App-owned value provider for bound and semantic fields. |
OutputResult | interface | Composed output value. |
parseKnowledgeDocument | function | Paired, nestable anchors are one text adapter. Other sources supply the same document contract directly. |
Presentation | constant | |
ReplyFormatCheck | interface | One check a template declares, evaluated against the rendered bubbles. |
replyFormatChecks | constant | |
ReplyFormatDefinition | interface | A template-bound reply format, matched against per-turn facts. |
ReplyFormatOptions | interface | Declaration input for defineReplyFormats. |
resolvePreference | function | Resolve the preferred candidate. Highest priority wins; order breaks ties with the later entry first, so recency can be encoded without touching priority. The input array is copied before sorting. |
SectionSelection | type | Which part of a document a read returns. |
selectVariant | function | Pick one variant, avoiding an immediate repeat when alternatives exist. When every candidate equals previous, the full list is used again, so a single-value set still yields a result instead of failing. |
SemanticSlotDefinition | interface | Declares the {{namespace:key}} slots a model may use, and how often. |
TextTemplateOptions | interface | Text template construction options. |
validateAnswerBatch | function | Validate that one batch is well formed and fully covered. |
Artifacts & recovery
| Symbol | Kind | Purpose |
|---|---|---|
ArtifactReference | interface | References locate artifacts; only the App resolver establishes access and current validity. |
ArtifactResolver | interface | App-registered resolver that turns a reference into an App value. |
Artifacts | constant | |
defineArtifactCatalog | function | Compile a catalog of artifact resolvers plus a checked resolve entry point. |
defineDurableTask | function | Compile a durable task definition into a resumable runner. Each run call locks the task id in the store, loads the checkpoint and resumes at nextStepIndex. A checkpoint from another definition id or revision, or one that fails the predicates below, is rejected instead of being repaired, because silently accepting it would replay App side effects under a different contract. |
Durable | constant | |
DurableCheckpoint | interface | Persisted task progress; the only state a resume reads back. |
durableReplayPolicies | constant | |
durableStatuses | constant | |
DurableStep | interface | One step of a durable task. |
DurableStepContext | interface | Execution facts handed to a durable step. |
DurableStore | interface | App implements an exclusive lock across every writer and validates/serializes stored state. |
DurableTask | interface | Compiled task: resumes from the store and returns the final state. |
DurableTaskDefinition | interface | Task definition, including the App hooks that guard every resume. |
DurableTaskOptions | interface | Runtime options for a compiled durable task. |
Models & interaction
| Symbol | Kind | Purpose |
|---|---|---|
bindInteraction | function | Bind every registered transfer command to a local handler. Models cannot add handlers. |
Command | interface | Compiled command. |
CommandCatalog | class | Mode and cross-protocol field ownership checks are shared by all receiving hosts. The catalog seals itself as soon as construction finishes, so a run cannot register a new command later; set remains available only for the superclass installation pass. |
CommandCatalogOptions | interface | Envelope-level options for a command catalog. |
CommandDefinition | interface | Declarative command shape before compilation. |
commandSchema | function | Build a JSON schema for one command id. Prefer compiled schemas; retain the existing open-schema contract for dynamic host protocols. A protocol without fieldSchemas falls back to an open object that only pins the discriminator, which keeps legacy hosts working without weakening compiled ones. |
compileCommands | function | Compile a whole catalog with shared envelope fields. Applications declare only their own data and handlers. Defaults are merged in this order: unrelated default keys, then the command's own keys, with fields, checks and tags concatenated so shared envelope checks always run before per-command checks. |
defineCommand | function | Compile declarations once. Parsing is synchronous and never executes a registered tool. Two schemas are produced from one declaration: modelJsonSchema marks only fields the model must fill, while inputJsonSchema marks every required field. A discriminator, when present, is prepended as a required constant field. |
defineCommandCatalog | function | Compile definitions and wrap them in a sealed catalog. |
defineInteractionProtocol | function | Construct a protocol from one definition. |
INTERACTION_CATEGORIES | constant | |
InteractionCategory | type | Interaction purpose, never an authorization level or an assertion of execution success. |
InteractionDescriptor | interface | Catalog metadata for one command, independent of its field shape. |
InteractionHandlers | type | Handler map keyed by command id; each handler receives the parsed value and App context. |
InteractionProtocol | class | Web/AI payload family. HTTP/SSE framing and actual command execution remain separate ports. Every command registered here gets the envelope's discriminator forced to its own id, so a payload cannot claim one command while carrying another command's data. |
InteractionProtocolDefinition | type | Transfer envelope plus its registered command family; no change to HTTP or SSE framing. |
ProtocolCheck | interface | One declarative rejection rule. |
ProtocolField | interface | Field presence, schema and ownership are declared together; schemas describe model input. |
ProtocolPredicate | type | Predicate evaluated during validation; any truthy result counts as a failure. |
ProtocolReason | type | Lazy rejection wording: a fixed message, a pre-built error, or a factory bound to the value. |
ProtocolShape | interface | Custom protocols may derive dynamic keys without supplying a compiled schema. |
RegisteredProtocol | interface | Runtime extension contract; hosts retain their own version values and validation context. |
MockGPT · Mock models & debugging
| Symbol | Kind | Purpose |
|---|---|---|
CallRecord | interface | Detached snapshot of one accepted call, exposed through MockGPT.records. |
createMockHandler | function | Create a bare Node request listener backed by the mock. |
createMockServer | function | Create a self-contained mock HTTP server with explicit listen/close control. No UI or static assets are served: only the model routes answer, everything else is a 404. |
encodeModelResponse | function | Optional app-owned codec; validation and encoding consume the same snapshots. Thin public wrapper over encodeModel: re-validates identity arguments and re-snapshots both the request and the model output, so callers that build replies themselves get identical validation and cannot mutate the mock's state afterwards. |
Generated | type | What a rule may produce: plain data, or a descriptor that changes transport behaviour. |
GenerationContext | interface | Everything a rule or generator may read for one accepted call. The context is frozen; the only mutable side channel is report, and only while the call is still pending. |
GenerationInput | interface | Input of MockGPT.generate. Normalized exactly like an HTTP request body, so a rule matches identically through both entry points; only model and messages are required. |
GenerationOptions | interface | Per-call options of MockGPT.generate. |
Generator | type | A rule's output: either a fixed value (deep-copied and frozen when the instance is built) or a function evaluated per call. A function may be async and is awaited under cancellation. |
generatorNames | constant | |
generators | constant | |
HandlerOptions | interface | Options shared by the standalone server and the bare request handler. |
HttpFault | interface | A simulated HTTP-level failure returned instead of a model reply. |
isPublicAddress | function | Decide whether an address is an acceptable public destination. |
JsonValue | type | Any value accepted by the package's JSON snapshot rules: strings, finite numbers, booleans, null, arrays and plain objects. |
LoadedPage | interface | A fetched page body plus the metadata needed for decoding and diagnostics. |
Message | type | One entry of an OpenAI chat conversation. The runtime validates role against the OpenAI role set and validates the outer shape of content; every other field is retained verbatim so vendor extensions flow through. |
MockGPT | class | Configurable mock model instance. Create one per test or per mock server. |
MockGPTError | class | Error type carrying a stable machine-readable code plus optional HTTP status and details. The HTTP adapter maps status onto the response and serializes code/details into the OpenAI-style error body, so codes are part of the public contract. |
MockGPTOptions | interface | Construction options of a MockGPT instance. |
ModelOutput | interface | The model-authored part of a reply, before it becomes JSON or SSE frames. |
ModelRequest | interface | A normalized /chat/completions request, produced by snapshotRequest. Optional undefined fields have already been dropped and stream is already defaulted, so rules always observe the same shape regardless of whether the caller used generate or the injected fetch. |
OutputOptions | interface | Transport-level knobs of a generated response. All values are simulated: they affect framing and timing of the mock reply, not real model behaviour. |
ResponseDescription | class | Wrapper that distinguishes a transport instruction from ordinary generator data. kind: 'model' carries a ModelOutput, 'http' an HttpFault response, and 'reject' a message used to simulate a network failure. Instances are recognized by brand rather than by instanceof alone, so descriptors survive crossing the ESM/CJS boundary. |
responses | constant | |
routes | constant | |
Rule | interface | One ordered matching rule of a MockGPT instance. |
ServerOptions | interface | Options of createMockServer, adding shutdown behaviour. |
sources | constant | |
TextOptions | interface | Common options of the text generators. |
TextSource | type | Text supplied to a text generator. A function may be async; it receives the per-call context so a source can depend on the prompt or on the call index. |
ToolCall | interface | A tool call the mocked assistant emits instead of executing. |
Usage | interface | Token accounting reported by the OpenAI API; validated for internal consistency. |
WebOptions | interface | Configuration of sources.web. |
WebProfile | type | Name of an entry in webHeaderProfiles. |
Intents & scopes
| Symbol | Kind | Purpose |
|---|---|---|
createScopeRegistry | function | Create and seal a complete catalog; use the constructor for incremental installation. |
RegisteredScope | type | Frozen registration view: every list is a frozen copy, evidence entries are projected. |
RegisteredScopeEvidence | type | Registered evidence entry: public data only, frozen by the registry. |
ScopeDefinition | interface | One declarable scope. Ids and aliases share one namespace and must be unique. |
ScopeDescription | type | Plain description with mutable arrays, for documentation and model-facing catalogs. |
ScopeRegistry | class | Generic scope relationships; categories, intent policy and extra fields belong to the host. A scope is addressable by its id or by any of its aliases; aliases resolve to the declaring scope, and a name may be claimed only once across both namespaces. |
ScopeRegistryPolicy | interface | Registration rules for one scope registry. |
Retrieval & evidence
| Symbol | Kind | Purpose |
|---|---|---|
defineEvidenceChecklist | function | Compile a reusable completion checklist over actual observations. A requirement is satisfied when at least one observation satisfies the provider registered for its kind; isComplete requires every requirement to be satisfied, and missing returns those that are not. Hosts define evidence semantics. |
defineEvidenceProjection | function | Compile a projection that keeps only the sources a caller asked to see. No selection retains the complete evidence; a selection narrows registered source-bearing results. Observations whose tool has no provider pass through untouched, so the projection can only ever remove sources it knows how to name. |
defineRetrieval | function | Compile a retrieval runner from its declared ports and effects. Rejected queries stay in the caller's seen set, so a retry is reported as a duplicate instead of silently repeating the adapter call; only successful results increment the query count. |
Evidence | constant | |
EvidenceProjectionDefinition | interface | Projection configuration, keyed by the tool that produced an observation. |
EvidenceProjectionProvider | interface | Describes which sources an observation can cite, and how to narrow it to cited ones. |
EvidenceProvider | interface | Adjudicates one evidence kind against real observations. |
EvidenceRequirement | interface | Requirements describe evidence that must already exist, never a model's assertion of success. |
FusedRank | interface | One fused result with the per-source ranks that produced its score. |
RankedList | interface | One retriever's ordered result, optionally weighted. |
reciprocalRankFusion | function | Fuse ranked lists with one-based reciprocal rank fusion. Raw retriever scores are intentionally not mixed. Ties break on id, so the output is deterministic for a given input. |
Retrieval | constant | |
RetrievalDefinition | type | Retrieval ports specialized to an App operation context. |
RetrievalEffect | interface | One effect applied after a successful query, in declaration order. |
RetrievalPorts | interface | Host ports and policy for one retrieval kind. |
RetrievalReason | type | Lazy rejection wording: a fixed message, a pre-built error, or a factory bound to the query. |
RetrievalReceipt | interface | Facts of one accepted query. |
RetrievalResult | interface | Adapter output for one accepted query; the Kit renames each source before returning it. |
RetrievalRunner | interface | Compiled retrieval runner. |
RetrievalSource | interface | Request-local citation reference; the App may separately carry its content entity id. |
RetrievalState | interface | Request-owned state. Clearing current evidence must not replenish spent budgets or seen keys. |
TextSearch | class | Optional App-side full-text index. No storage, identity, model calls or Core dependencies. Only declared fields are indexed and only storedFields come back with a hit, so a document never leaks extra properties into search results. |
TextSearchHit | interface | One ranked match; terms are post-tokenization and only stored fields are returned. |
TextSearchOptions | interface | App supplies fields, tokenizer and its own schema/tokenizer revision. |
TextSearchQuery | interface | Search input: a hard result limit and an App-owned filter, both required on every query. |
TextSearchSnapshot | interface | Serialized index; the revision pair proves the snapshot matches the current configuration. |
VectorSearch | class | Exact cosine search for a bounded embedded corpus. Identity and metadata are App-owned. Vectors arrive as plain arrays and are stored normalized in Float32Array form, so query time only needs a dot product per candidate. |
VectorSearchHit | interface | One search hit; the document is a cloned snapshot, not the indexed instance. |
VectorSearchQuery | interface | Search options excluding the query vector, which search takes alongside them. |
VectorSearchSpace | interface | Embedding space identity and width; vectors from another space must never be mixed in. |
Log review & evidence reports
| Symbol | Kind | Purpose |
|---|---|---|
defineReflection | function | Compile a reflection task. Model-driven investigation through ordinary registered tools and the existing Core loop. The task always reports persisted: false: storing a report is the App's decision. Observed findings must cite evidence ids that were actually returned in this run, which is what keeps the report tied to real observations instead of model recall. |
defineReflectionLogSource | function | Build a reflection source over a log reader. Coverage is reported as best-effort: a page is only complete when the reader exhausted the run without capture gaps or omitted issues, and every gap or issue code is surfaced instead of being silently dropped. |
Reflection | constant | |
ReflectionDefinition | interface | Configuration for compiling a reflection task. |
ReflectionEvidence | interface | Explicit metadata projection, not an arbitrary original event/payload. |
ReflectionFinding | interface | One finding, always tied to the evidence it rests on. |
reflectionFindingKinds | constant | |
reflectionIdentityFields | constant | |
ReflectionLogReader | interface | Structural port: the App supplies its own FileLogReader, trusted scope and current authorization. |
ReflectionPage | interface | One page of evidence plus an honest statement of its coverage. |
ReflectionQuery | interface | One evidence query. |
ReflectionReport | interface | Request-local reflection result. |
ReflectionSource | interface | App-owned evidence source, including its own authorization. |
ReflectionTask | interface | Compiled reflection task. |
Tools & capabilities
| Symbol | Kind | Purpose |
|---|---|---|
LifecycleHooks | interface | Everything one tool declares for a request. Declaring id turns the tool into an invocation owner, so protocol and call become required in practice; the registry rejects a partial declaration. Every other hook is optional and returning nothing expresses "no opinion". |
LifecycleProtocol | interface | Output protocol carried by a tool lifecycle. |
Policy | interface | Registration policy shared by every tool in the registry. |
RegisteredToolDefinition | type | Registered snapshot with frozen goal ids and projected hooks. |
Tool | interface | A registered tool: model metadata plus one optional lifecycle block. |
ToolFinalizer | type | Converts an executed decision into the tool result; must be synchronous. |
ToolLifecycleRegistry | class | Registry of tools whose lifecycle, protocols and context contributions the App declares. Registration is only possible before seal(); afterwards the catalog is read-only, so a run cannot change which tools exist. Every hook is optional and is applied in registration order, which is why registerAll preserves iteration order. |
ToolModelField | interface | One model-context field contributed by a tool. |
ToolNormalizer | type | Converts untrusted input into a decision; must be synchronous. |
ToolProtocol | type | Protocol type of a tool's lifecycle invocation. |
ToolRegistration | type | Declaration form; the registry derives the ModelTool projection from existing handlers. |
ToolRuntimeTypes | interface | One schema binds lifecycle handler types without introducing platform fields into core. |
ToolsOptions | interface | Construction options for a tool registry. |