Skip to content
English

全量 API 目录 ​

按职责和使用场景分组,包含 46 个公开模块、649 个独立符号、547 个可调用成员。同源聚合入口复用同一页。

每页包含声明、参数、结果、字段、成员及关联示例;Core 接收的是合同实现,Support 提供推荐实现,Kit 由 App 自选。

按导入模块查找 · 场景示例 · 策略源码

Core · 接口与运行保证 ​

传输与流 ​

进入分组

符号类别用途
abortableStreamfunctionRe-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.
readSsefunctionDecode 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.
SseEventinterfaceOne dispatched SSE event, assembled from all lines up to a blank line.
SseIdleTimeoutErrorclassRaised 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.
SseReadOptionstypePer-read configuration; snapshotted when readSse starts.

执行与工作流 ​

进入分组

符号类别用途
AgentBranchinterfaceImmutable 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.
AgentCacheAddressinterfaceExact immutable address passed to the App port, including cancellation for this visit.
AgentCacheOptionsinterfacePersistent and volatile storage are independent; there is no implicit fallback or mirroring.
AgentCachePortinterfaceApp-owned storage. Capacity, expiry, serialization and user isolation belong to the App.
AgentCheckpointinterfaceIn-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.
AgentCheckpointRecordinterfaceHost-owned serializable data, never a saved credential, model budget or executable handler.
AgentCoreEngineclassBounded 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.
AgentCoreEngineOptionsinterfaceEngine construction options.
AgentCoreEngineSetuptypeEngine 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.
AgentModelBindingtypeModel binding accepted by the engine. Execution scope belongs to the engine, so a bound model may not carry its own signal or execution options.
AgentModelRuntimetypeThe subset of a runner an engine may drive; kept small so the App can supply it.
AgentWorkflowclassExecutable 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.
AgentWorkflowDefinitiontypeThe graph an engine executes.
AttemptBudgetclassSuccessful 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.
CacheContextinterfaceCache access shared by workflow visits and the low-level $step loop.
CacheReadOptionsinterfaceOnly reads may name another node. Partition names are not authorization boundaries.
CoreSteptypeOne loop iteration. Must be re-entrant: the same step object runs every round.
defineWorkflowfunctionBuild a validated workflow from a definition.
EngineCacheOptionsinterfaceOptional Engine memory bounds; TTL is measured from the latest write.
ExecutionEventDescriptorinterfaceEvent name, content class and the producing execution identity.
ExecutionObserverinterfaceLive consumer of Core facts.
LoopEventinterfaceProgress fact for one loop round, correlated with the enclosing diagnostics span.
NodeAgentCacheinterfaceAsync node view. Writes and clear can only address the current partition.
NodeCacheinterfaceSynchronous view of the current node's Engine-owned memory. Values retain identity.
requireWorkflowValuefunctionRead 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.
routefunction
StepOutcometypeDecision a step returns to the engine.
WorkflowChaininterfaceObserved visits, never merged by static node id or synthesized from adjacency.
WorkflowChainCoverageinterfaceCapture completeness is independent of whether diagnostic content was included.
WorkflowChainNodeinterfaceA single node visit, with flat ordered subflow records including every independent fix.
WorkflowChainNodeEventinterfaceNode-local lifecycle facts; payload remains subject to the source's content policy.
WorkflowChainSourcetypeApp resolves authorization, retention, pagination and storage paths before returning.
WorkflowChainTransitioninterfaceActual handoff evidence; a target span does not prove its enter event was captured.
WorkflowContextinterfaceExecution facts available to every node of a running workflow.
WorkflowEventinterfaceMetadata only: never includes state, prompt, parameters, results or raw errors.
WorkflowExtensioninterfaceAdditional nodes and routes merged into an existing definition.
WorkflowFailureinterfaceError retained only while entering a registered failure phase.
WorkflowGraphinterfacePure registered topology; routes sharing a target share an edge within one kind.
WorkflowGraphEdgeinterfaceCompletion has no target node; recovery edges remain distinct from normal edges.
WorkflowGraphNodeinterfaceNode metadata and derived incident edges, without executable callbacks.
WorkflowGraphRouteinterfaceDeclaration order is retained even when multiple routes share a topology edge.
WorkflowModelinterfaceModel 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.
WorkflowNodetypeOne node of the graph.
WorkflowNodeReportinterfaceDetail an App node reports about its current visit.
WorkflowRoutetypeOne 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.
WorkflowSubflowRecordtypeHistorical subflow snapshots may omit recorder fields or descriptive content.

共同合同与辅助入口 ​

进入分组

符号类别用途
AgentErrorInfointerfaceStable error metadata for App diagnostics. Unknown retryability is deliberately omitted.
AsyncSinktypeAwaitable sink for an ordered stream. A rejection propagates to the emitter.
BudgetErrorclassA configured allowance (rounds, model calls, attempts) is exhausted. The optional message states which allowance ran out; code is the stable marker.
CheckResultinterfaceVerdict 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.
commonPrefixLengthfunctionLength 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.
configureBreakWhilefunctionInstall 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.
DurationMstypeElapsed time in milliseconds; never an absolute instant.
ErrorContextinterfaceBoundary metadata is recorded internally, without replacing the original thrown value.
ExecutionContextinterfaceRequired execution facts available inside a running call.
ExecutionOptionsinterfaceOptional controls accepted by any public Core call.
getErrorInfofunctionProduce 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.
IdtypeOpaque identifier. Format and meaning belong to the App or to the registering module.
InvocationMetadatainterfaceIdentity and timing shared by every invocation receipt.
InvocationResultinterfaceA produced value together with the receipt of the invocation that produced it.
InvocationStatustypeTerminal state of one invocation; cancelled is distinct from a failure.
IssueinterfaceOne validation problem, locatable by code and, when available, by field path.
JsonSchematypeJSON Schema as consumed by the App's validator; Core never interprets its contents.
MaybePromisetypeA value that may already be resolved or still pending.
ModelCallRecordinterfaceReceipt of a model call that returned successfully.
ModelResulttypeModel call result with its model-call receipt.
ObservertypeNotification callback. A rejected promise propagates to the emitter.
OperationContextinterfaceExecution 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.
ProtocolRegistryclassAppend-only protocol registry. Extending Map keeps lookup semantics familiar while set rejects every invalid registration, which makes the instance effectively immutable after wiring.
ReadonlyCataloginterfaceRead-only projection of a definition set; the implementation owns ordering and validation.
RegistryinterfaceMutable catalog. Registrations append; seal freezes the set against later writes.
retrievalQueryKeyfunctionSerialize 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.
SchemaAdapterinterfaceCompiled schema pair: the JSON form shown to the model and the runtime parser.
SearchHitinterfaceOne 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.
TimestampMstypeWall-clock instant in milliseconds since the Unix epoch.
ToolCallRecordinterfaceReceipt of a tool call that returned successfully.
ToolResulttypeTool call result with its tool-call receipt.
ValidationErrorclassRejected input or output that failed one or more registered checks. The message is fixed; consumers should read issues for the actual reasons.
WorkflowContractErrorclassThe 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.

模型与交互 ​

进入分组

符号类别用途
AggregatedToolCallinterfaceOne completed native tool call in provider index order.
AsIntenttypeDemand-discovery metadata; it has no identity independent of its tool.
ChatProviderclassStreaming model provider. Implementations must stop producing when context.signal aborts and should surface transport failures by rejecting the iteration rather than ending it silently.
createModelTransportfunctionCompose 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.
createToolCallCollectorfunctionCreate a collector for one response.
FunctionCallDeltainterfaceOne streamed fragment of a function call; fragments with the same index must be joined.
IntentOptionsinterfaceDemand-facing hints attached to one Tool; no independent identity is created.
jsonObjectInteractionconstant
ModelAssistantToolMessagetypeAssistant turn that may declare tool calls and may carry an empty text body.
ModelCallRequesttypeOne model call request. The input shape selects prompt mode or message mode.
ModelCallTraceinterfaceAccumulated facts of one model call, reported on success and on failure.
ModelChildOptionsinterfaceRequest-bound isolated runner settings; provider and ancestor budgets cannot be replaced.
ModelChildPolicyinterfaceRequest-wide limits, shared by every descendant. They cannot be enlarged by a child.
ModelFunctioninterfaceProvider-neutral function definition. Execution and authorization stay with the host.
ModelImageinterfaceModel 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.
ModelInputMeasurementinterfaceExact prepared-request accounting; token values exist only with an explicit model counter.
ModelInteractionAdapterinterfacePluggable implementations all consume the same business registry. No automatic fallback.
ModelMessageinterfaceOne provider-neutral turn; images are user visual input and are not part of the text budget.
ModelOptionsinterfacePer-call provider options; Core passes them through and does not normalize provider ranges.
ModelOutputEventtypeDelivery sink, awaited in order. Parts are unvalidated proposals, never execution receipts.
ModelParttypeOne streamed response part: assistant text or a function-call fragment.
ModelPrepareRequestinterfaceTransport selection for prepare; omitted fields take the runner defaults.
modelProtocolErrorfunctionThrow a model protocol validation error.
ModelProviderContextinterfacePer-call facts a provider receives besides the messages themselves.
ModelResponseCollectorinterfaceAccumulates streamed parts for one call and resolves them into the transport's result.
ModelRunnerclassExecute 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.
modelRunnerDefaultsconstant
ModelRunnerOptionstypeFull runner construction options: provider, transports, sinks and named limits.
ModelRunnerPortsinterfaceHost ports a model runner needs in addition to its provider and transports.
ModelRunnerSettingsinterfaceNamed settings keep all model limits together; output token reservation stays per call.
ModelRuntimeConfiginterfacePer-request model runtime limits.
ModelSelectiontypeA model's chosen capability together with its parsed arguments.
ModelSessionCallinterfaceOne completed tool call in a session response.
ModelSessionResultinterfaceComplete result of one session response.
ModelTokenBudgetinterfaceProvider-injected token accounting. Core never guesses a character-to-token conversion, so token budgets exist only when a host supplies a real counter.
ModelToolinterfaceCommon selectable model interface; resolution proposes a value without business execution.
ModelToolCallinterfaceOne tool call the assistant declared, in provider order.
ModelToolCatalogtypeA compiled entity catalog also supports the minimal stage source contract.
ModelToolRegistrationtypeRegistration form: input typing is erased, output typing is preserved.
ModelToolRegistryclassA request/stage projection is a sealed registry. Hosts filter availability before projection.
ModelToolResultMessagetypeTool result turn; toolCallId is required and images/tool declarations are rejected.
ModelToolSourceinterfaceMinimal source a stage needs: enumerate tools and resolve one selection.
ModelTransportDefinitioninterfaceOne registered transport: a wire format prepared for a stage.
ModelTransportRegistrationinterfaceBinds an adapter to the tools one transport serves.
ModelUsageinterfaceProvider-reported token counts for one call; used for accounting, never for admission.
NativeFunctionCallinterfaceRequest-local native call buffer; never an execution receipt.
nativeFunctionInteractionconstant
PreparedModelCallinterfaceRequest-bound, single-use transport snapshot. Repeated measurements do not prepare or spend calls.
PreparedModelInteractioninterfaceAdapter output for one stage, before the caller binds capability resolution.
PreparedModelTransportinterfacePrepared transport handed to the runner, including sampling defaults.
RegisteredModelTooltypeFrozen snapshot stored by a registry after schema validation.
RegisteredTransportOutputtypeResult 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.
retryMultipleModelCallsfunctionRetry 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.
ToolCallCollectorinterfaceAggregation entry point for streamed function-call deltas.
ToolCallFailuretypeReport a protocol violation and stop; callers decide how the failure is classified.
ToolConditiontypeActivation is independent of participation in demand discovery.
ToolContexttypeRead-only host data without changing explicit any/unknown erasure into an object constraint.
ToolProposalinterfaceA model proposal, not an authorization or execution receipt.

上下文与日志 ​

进入分组

符号类别用途
assembleContextPlanfunctionBuild the model input for a context plan.
assembleFragmentsfunctionBuild the model input from fragments. Metadata remains program-side: data never becomes a system instruction.
BuiltContextinterfaceAssembled context plus the accounting needed to explain the budget decision.
ContextFragmentinterfaceOne piece of model-visible input before assembly.
ContextFragmentUsageinterfaceAccounting entry reported for one fragment that actually entered the context.
ContextJournalclassRequest-local context projection of execution receipts; not a separate persistent log store.
ContextLifetimetypeDeclared validity window of a fragment's content.
ContextPlaninterfaceUnassembled input; App-side nodes may process it before the Core budget boundary.
ContextRecordtypeOne 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.
ContextTrusttypeWho produced the content, and therefore how much it may influence the model.
validateContextBudgetfunctionEnforce the character budget of the whole model input.
validateContextFragmentfunctionValidate one fragment and return the text it contributes to the model input.

配置、清单与策略 ​

进入分组

符号类别用途
BreakCheckinterfaceEach rule owns a semantic/readability group and its tags, independently of shared errors.
BreakEventinterfaceDiagnostic metadata only; rule inputs and request data are not included.
BreakPredicatetypeEach predicate is evaluated only after the preceding predicates passed.
BreakReasontypeLazy reasons preserve error construction and message evaluation on the rejection path only.
breakWhilefunctionReject 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.
BreakWhileConfiginterfaceGlobal rejection observer installed once per process.
matchRulefunctionDispatch 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.
MatchRuleinterfaceOrder is priority. Patterns may inspect values, types, state or regular expressions.
WalkRuleinterfaceSynchronous traversal; local rules may omit catalog metadata.
walkRulesfunctionWalk 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.

过程观察与诊断 ​

进入分组

符号类别用途
CoreDiagnosticRecordinterfacePersisted data is untrusted: normalization checks the current envelope, not arbitrary payloads.
CoreEventtypeA 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.
coreEventCatalogconstant
CoreEventDescriptorinterfaceEvent 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.
CoreEventNametypeUnion of every Core event name; the key set of CoreEventPayloads.
CoreEventPayloadsinterfacePayload of every Core event, keyed by event name. Fields are the event's own facts only.
CoreLogOutputinterfaceDestination for recorded facts; implementations decide filtering and durability.
createDiagnosticsfunctionConfigure the optional log consumer of the shared execution fact source.
CreateDiagnosticsOptionsinterfaceOptions for creating a root diagnostic scope.
DebugStepsOutputinterfaceDebug material a handler contributes to a diagnostic event.
DiagnosticContextinterfaceRecording scope bound to one execution identity. A child scope inherits the sink and observer of its parent; only identity changes.
diagnosticErrorfunctionConvert a thrown value into a plain record suitable as a log payload.
DiagnosticIdentityinterfaceExecution identity only: never message, account or HTTP identity.
DiagnosticSpanFieldstypeIdentity fields a child span may override; the parent supplies run, span and parent span.
NodeReportingContextinterfaceReporting surface handed to a node or tool for the duration of one visit.
normalizeDiagnosticEventfunctionValidate 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.
RecordedSubStepinterfaceA step already accepted by a logger, carrying recorder-assigned bookkeeping fields.
ReportedStepinterfaceOne step as reported by a node; fields beyond identity are optional detail.
ReportedStepStatustypeA status a node may report; derived from the catalog, never declared separately.
reportedStepStatusCatalogconstant
reportedStepStatusesconstant
ScopedSubFlowLoggerclassNon-inheriting delegate. Stores only the original logger and its bound subnode identity.
ScopedSubFlowStepInputtypeScoped writes cannot supply or override the identity bound by their delegate.
SubFlowLoginterfaceCommon read/write surface for both independently implemented logger classes.
SubFlowLoggerclassFull execution-owned recorder. Owns its store and may issue restricted delegates.
SubFlowStepFixinterfaceExplicit revision whitelist: identity, grouping and business type are never patchable.
SubFlowStepInputinterfaceInput accepted by write; the logger assigns the step id and sequence.
SubFlowValuetypeJSON-like value accepted in reported payloads; depth and size are bounded by the recorder.
SubStepProgressinterfaceCompact progress notification emitted for each accepted sub-step write or fix.

工具与能力 ​

进入分组

符号类别用途
ErasedToolinterfaceType-erased tool shape the registry executes after parsing at the boundary.
ExecutableToolinterfaceOne registered tool, typed by its input, output, host context and id literal.
executeInvocationfunctionRun one synchronous invocation and record its effects.
InvocationHandlerinterfaceA named handler invoked by a tool lifecycle step.
RegisteredTooltypeRegistered snapshot: public data is retained, implementation helpers are not a contract.
ToolDefinitiontypeConfiguration form; Support supplies the identity resolver when omitted.
ToolExecutionContextinterfaceExecution facts handed to a tool for one invocation.
ToolExecutionEventinterfaceFact emitted when one tool call settles, correlated by invocationId.
ToolInvocationPortsinterfaceOptional tools the lifecycle resolves from the host context for one invocation.
ToolInvocationRequestinterfaceOne invocation request; the registry supplies signal and diagnostics when omitted.
ToolJournalinterfaceRequest-local execution receipts; the host decides their domain content.
ToolJournalFinishinterfaceClosing record for one tool call, written once with the terminal outcome.
ToolJournalStartinterfaceOpening record for one tool call, written before the handler runs.
ToolRegistryclassRegistry mechanism only: visibility, authorization policy, schemas and semantic metadata are host registrations. A registry is mutable until sealed and keeps its own call log.
ToolRegistryOptionsinterfaceRegistry construction options.
ToolRegistryPortsinterfaceHost ports a tool registry needs in addition to the tool definitions.

Support · 推荐实现与策略 ​

共同合同与辅助入口 ​

进入分组

符号类别用途
agentfunctionInstantiate an Engine configuration class without creating an Engine, budget or request.
AgenttypeOriginal Engine configuration; union branches retain their required App/model relationships.
AgentOptionstypeAgent id is an external pool identity, not an override of Core branch or request identity.
agentPoolconstant
AssociatedRegistrationinterfaceOwners retain their business fields; Support only reads model interface associations.
AssociationOptionsinterfaceShared independent tools and a default projection from existing contracts.
AssociationSourceinterfaceLocal provenance, never an extra model input requirement.
ClassDecorationtype
DecorationOptionsinterfaceNamespaces group external registration without changing Core options.
defineAssociatedCatalogfunctionCompile independent and owner-derived Tool declarations, validating all references eagerly.
DefinitionReaderinterfaceRead-only roots. A typed read describes the expected contract, not a static id/type lookup.
fragmentfunctionInstantiate a self-describing fragment class; the original builder owns formatting checks. Bind a host's formatter method into an original fragment configuration.
FragmenttypeA formatter and its original provenance, trust and budget configuration.
fragmentPoolconstant
IdentifiedDefinitioninterfaceRegistration identity; ids are unique within one kind and namespace.
IntentfunctionMark a WorkflowTool for demand discovery; alone this decorator registers nothing.
MethodDecorationtype
modelfunctionInstantiate and validate model options without creating a Runner or consuming calls.
ModeltypeOriginal Runner configuration; the decorator's pool id is not a model identity override.
ModelOptionstypeModel id is only a pool key; Core still owns the configured model/transport identities.
modelPoolconstant
nodefunctionInstantiate 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.
NodetypeA node implementation; its public id is supplied by
nodePoolconstant
Supportnamespace
toolfunctionInstantiate 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.
TooltypeA tool implementation with the original schema, authorization and execution contracts.
ToolAssociationtypeExplicit tool references or inline overrides of the owner's default model interface.
toolPoolconstant
workflowfunctionInstantiate and validate workflow options, leaving actual execution with the original Engine.
WorkflowtypeA complete graph definition whose workflow id is supplied by
workflowPoolconstant

工具与能力 ​

进入分组

符号类别用途
CapabilityCatalogOptionsinterfaceCatalog construction options.
CapabilityModuleinterfaceMinimal composition contract; lifecycle and domain fields remain application-owned.
CapabilityToolReferencesinterfaceTool references declared by one owner module.
CompiledTooltypeTool definition type derived from a declaration literal, preserving input/output/id.
defineCapabilityCatalogfunctionBuild 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.
defineToolfunctionValidate 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.
defineToolCatalogfunctionInfer the host context from existing executable definitions, without widening it to unknown. Explicit host typing remains available for contextually typed declaration lists.
SelectedToolstypeCatalog narrowed to the given ids: each kept tool's id literal is intersected with Id.
ToolCataloginterfaceFrozen tool catalog with model tools and per-request binding.
ToolCatalogEntrytypePublic declaration surface of one tool, without registry internals.
ToolModelViewinterfaceModel capability view of a tool catalog, retaining the host context type.
ToolOutputtypeOutput type of the tool whose id matches Id; never for any other id.
ToolRuntimeinterfaceCatalog bound to one App request.
validateToolReferencesfunctionValidate 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.

模型与交互 ​

进入分组

符号类别用途
chatCompletionFunctionOptionsfunctionBuild 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.
chatCompletionMessagesfunctionMap 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.
chatCompletionPartsfunctionConvert 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.
CompatibleModelConfiginterfaceConfiguration of one OpenAI-compatible endpoint.
CompatibleModelPortsinterfaceAdapter ports the App may override without replacing the provider.
CompatibleModelProviderclassHTTP/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.
CompatibleModelProviderOptionsinterfaceConstruction options for a compatible provider.
CompletionFailuretypeBuild the classified failure a policy throws; the provider records it like its own failures.
CompletionPolicyinterfaceDecision whether a finished stream satisfies the request.
completionPolicyCatalogconstant
CompletionRequestFactsinterfaceFacts 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.
CompletionSessioninterfacePer-request completion state observed by one policy.
createJsonTransportfunctionCreate 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.
createModelStrategyfunctionCompose 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.
createProviderObservationScopefunctionBind 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.
createReplyPreviewfunctionCreate 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.
createReplyPreviewRulesfunctionGenerate 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.
createSessionModelTransportfunctionCreate a session transport.
createStageModelTransportfunctionBuild a transport that projects a capability source through declared stage references.
createTextTransportfunctionCreate a plain-text transport that trims the assembled response.
defaultCompletionPolicyconstant
defineModelToolsfunctionBuild a sealed capability catalog from typed declarations.
modelBudgetStrategiesconstant
ModelBudgetStrategytypePreset name, or an explicit partial set of Core runner settings.
ModelChildrenOptionsinterfaceGroup options: worker count, extra cancellation and accept/commit hooks.
ModelChildTaskinterfaceOne child call in a group: its own limits plus the work to run with the child runner.
ModelChoiceIndexinterfaceMinimal selector shape used while filtering the provider response choices.
modelInteractionCatalogconstant
ModelProviderErrorCodetypeStable failure classification reported by the compatible provider adapter.
ModelProviderFailureinterfaceFailure detail passed to the App's error factory.
ModelStageTransportRegistrationinterfaceStage IDs and capability references are App-owned; this adapter only compiles their relation.
ModelStrategyOptionstypeInput of createModelStrategy: model selection, optional reasoning and budget plus explicit Core overrides. Explicit Core fields win over every generated value.
PreparedSessionTransportinterfacePrepared session transport handed to the runner.
prepareSessionFunctionsfunctionBuild the session policy for one stage.
PreviewToolinterfaceA model tool with an explicit, presentation-only streaming preview contract.
ProviderAssistantMessageinterfaceAssistant turn; content may be empty when the turn is only a tool declaration.
ProviderErrorCaptureinterfaceCaptured upstream error body and whether it had to be truncated.
ProviderEventDescriptorinterfaceProvider event name plus its content class.
ProviderEventNametypeUnion of provider event names.
ProviderEventPayloadsinterfacePayload of each provider event. Content-bearing events are accepted explicitly.
ProviderMessagetypeMessage list a host may pass to the compatible provider directly.
ProviderObservationtypeOne observation: event name with its payload.
ProviderObserverinterfaceThe caller can correlate each observation using the original, request-local model options.
ProviderReasoningLeveltypeSupplier wire shape is explicit; levels express requested effort, not measured quality.
ProviderReasoningStrategytypeHow 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.
ProviderSystemMessageinterfaceSystem instruction turn; text only, so the union rejects images and tool fields here.
ProviderToolCalltypeOne tool call the assistant declared, in wire order; aliases the Core shape.
ProviderToolMessageinterfaceTool result answering one declared call.
ProviderUserMessageinterfaceUser turn; the only message type that may carry images, and never tool calls.
ReplyPreviewOptionsinterfaceSettings for createReplyPreview; sink receives every bubble list and is required.
ReplyPreviewRuleinterfaceOne 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.
ReplyPreviewStageinterfaceStage declaration: which tools it exposes and whether it previews text or arguments.
ReplyPreviewToolinterfaceCapability declaration used to derive preview rules. Omitted preview means the capability never previews, so previewing is an explicit opt-in.
ResolvedSessionCallinterfaceOne completed call with host-facing resolution; unknown tools and bad JSON stay non-fatal.
ResolvedSessionResultinterfaceComplete result of one session response after host-facing resolution.
runChildrenfunctionRun 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.
sessionCompletionPolicyconstant
SessionFunctionOptionsinterfaceOptions a session transport may pass through to provider options.
SessionModelTransportRegistrationinterfaceRegistration for one session transport.

上下文与日志 ​

进入分组

符号类别用途
ContextAssemblyOptionsinterfaceAssembly options for placement-based projections.
ContextBuilderinterfaceCompiled builder. It holds no request state and may be shared across invocations.
ContextBuilderOptionsinterfaceShared builder options.
ContextCompressionCallinterfaceOne compression request.
ContextCompressorinterfaceRegistered compressor handler.
ContextFragmentConfiginterfaceSelf-describing fragment declaration: metadata plus a formatter.
contextHandlerCallsfunction
ContextHandlerReferenceinterfaceReference to a registered compressor or selector handler.
ContextHistoryGroupingtypeHow a message history is split into groups for trimming.
contextHistoryStrategiesconstant
ContextModelCallinterfaceSame runner and same fixed invocation result as public model calls.
ContextModelRequestinterfaceOne model call made on behalf of a selector or compressor.
ContextNodeResultinterfaceOutcome of one context node: the built input, its prepared model call and the change report.
ContextPolicytypeDeclared context policy for one stage.
contextPolicyCatalogconstant
ContextProcessingNodeDefinitiontypeDefinition 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.
ContextProcessingOptionsinterfaceRuntime inputs for one processing run.
ContextProcessingReportinterfaceFacts recorded for one processing run.
ContextProjectiontypeOne declared projection: a single fragment or a placement expanded into fragments.
ContextRecentHistoryinterfaceRecent history that compression must keep verbatim.
ContextReductiontypeOne declared reduction step.
contextReductionCatalogconstant
ContextReductionNodeDefinitiontypeDefinition 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.
ContextSelectiontypeSelection is independent of ownership; omitted selection preserves ordered execution.
ContextSelectionCallinterfaceEverything a selector may inspect for one decision.
ContextSelectionCandidateinterfaceCandidate step considered by selection, with its measured cost.
contextSelectionCatalogconstant
ContextSelectionNodeDefinitiontypeDefinition of a selection node: like a processing node, but update receives chosen step IDs.
ContextSelectionResultinterfaceSelection stage result: the chosen step IDs plus the unchanged stage snapshot.
ContextSelectorinterfaceModel or local selector that chooses which reductions to apply.
ContextStageResultinterfaceResult of a selection or reduction stage, before the node's update commits chosen fields.
ContextStrategyinterfaceValidated inputs ready to pass to a context processing node.
ContextStrategyOptionstypeOne history declaration that generates a step, or an explicit step list with optional history fields (fragment, field, preset, targetChars, keepGroups, grouping).
ContextStrategySettingstypeShared 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.
ContextTokenMeasurementinterfaceInjected token measurement for token-triggered policies.
createContextCompressorfunctionBuild 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.
createContextProcessingNodefunctionCreate 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.
createContextReductionNodefunctionCreate 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.
createContextSelectionNodefunctionCreate 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.
createContextSelectorfunctionBuild 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.
createContextStrategyfunctionBuild 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.
defineContextAssemblyfunctionCompile 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.
defineContextFragmentsfunctionCompile 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.
processContextfunctionRun a complete context policy in one call: snapshot, execute and finalize.
reservedContextCallsfunction
selectContextStepsfunctionChoose 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.
transformContextTextfunctionApply 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.
validateContextPolicyfunctionValidate 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.
validateContextSelectionfunctionValidate selector declarations and the selection mode they serve.

配置、清单与策略 ​

进入分组

符号类别用途
defineRegistrationCatalogfunctionCompile 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.
defineSchemafunctionRe-snapshot an existing adapter without changing its behavior. Used to detach a caller-owned adapter from later mutation before it is exposed or reused.
fromJsonSchemafunctionBuild 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.
fromParserSchemafunctionWrap 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.
JsonSchemaOptionsinterfaceOptions for building an adapter from a JSON Schema compiler.
JsonSchemaValidatorinterfaceApp-owned JSON Schema compilers provide synchronous validation.
RegistrationDefinitioninterfaceOne install step.

传输与流 ​

进入分组

符号类别用途
encodeSseEventfunctionEncode 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.
JsonFrameLimitsinterfaceBounds applied while scanning a streamed text.
JsonTransportParttypeOne scanned span: a complete object frame or a character outside any frame.
parseJsonFramesfunctionParse 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.
scanJsonObjectFramesfunctionExtract complete object-shaped spans from surrounding text, without parsing or selecting them.
SseOutputEventinterfaceOne outbound event before wire encoding.
SseWriterinterfaceDestination that reports backpressure instead of buffering without bound.
writeSseFramefunctionWrite 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.

过程观察与诊断 ​

进入分组

符号类别用途
streamEventsfunctionBridge 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 · 可选业务库 ​

配置、清单与策略 ​

进入分组

符号类别用途
AgentCatalogPortsinterfacePorts the catalog reads from the App's registries.
CatalogGoalinterfaceGoal as the catalog sees it: an id plus its declared delegates.
CatalogScopeinterfaceScope as the catalog sees it: an id plus the tools it may use.
CatalogTaskinterfaceThe goal currently accepted for the request, used to narrow the catalog.
CatalogToolinterfaceTool facts the catalog needs, independent of lifecycle details.
defineAgentCatalogfunctionCompile 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.
definePolicySetfunctionCompile 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.
defineRecoveryChainfunctionCompile 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.
DescribedToolinterfaceModel- or host-facing description of one tool.
Policiesconstant
PolicyAssessmentinterfaceResult of assessing every registered policy against one input.
PolicyDefinitioninterfaceOne declarative policy.
RecoveryDefinitioninterfaceOne recovery handler in an ordered chain.
RecoveryResulttypeOutcome of one recovery handler, or of the whole chain.

分支与版本管理 ​

进入分组

符号类别用途
AgentFamilyinterfaceCompiled family API. Every mutation returns the record after the write.
defineAgentFamilyfunctionCompile 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.
Familyconstant
FamilyDefinitioninterfaceApp-owned hooks and limits for one family.
FamilyOperationtypeOne of the four family mutations.
familyOperationsconstant
FamilyRecordinterfaceA whole family: its versions and which version is currently active.
FamilyStoreinterfaceCAS must cover every writer and the active pointer in one real storage commit.
FamilyVersioninterfaceImmutable snapshot of App state at one point on a branch.

过程观察与诊断 ​

进入分组

符号类别用途
AgentOutputEventtypeOne output event of a delivered reply.
publishReplyEventsfunctionStream 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_BOUNDARYconstant
ReplyBubbleInputinterfaceReply pieces accepted by the bubble helpers; non-string entries are ignored.
replyBubbleTextsfunctionCollect the non-empty-text parts of a reply.
ReplyDeliveryOptionsinterfaceHost-controlled delivery of already validated text; not upstream model generation.
serializeOutputEventsfunctionSerialize 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.
textOutputEventsfunctionWrap already-chunked text as text events.

共同合同与辅助入口 ​

进入分组

符号类别用途
Aggregationconstant
Candidatesconstant
CandidateSelectionDefinitioninterfaceDeclares the alternative-proposal envelope. A value without the declared field is treated as a single implicit candidate.
ContentProjectioninterfaceProjection output.
ContentProjectionOptionsinterfaceCandidate strategy for content projection.
createIntentRegistryfunctionCreate and seal a complete catalog; use the constructor for incremental installation.
defineCandidateSelectionfunctionCompile 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.
defineContentProjectionfunctionCompile 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.
defineDeliveryfunctionCompile 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.
defineNormalizationfunctionCompile 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".
defineQueryAggregationfunctionCompile 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.
defineTextSkillLoaderfunctionCompile 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.
defineTreeProjectionfunctionCompile 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.
Deliveryconstant
DeliveryOptionsinterfacePipeline construction options.
DeliveryStageinterfaceOne pipeline stage, identified for reporting and optional observation.
IntentDescriptiontypeRegistered domain Tool with its delegates widened to the definition's delegate literals.
IntentIdtypeUnion of the ids of a definition set, or string when it cannot be narrowed.
IntentPolicyinterfaceRegistration rules for one intent registry.
IntentRegistryclassGoal 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.
IntentToolinterfaceOne domain Tool.
IntentToolRegistrationtypeConfiguration form; object arguments and a Tool proposal are the registration defaults.
mergeByKeyfunctionMerge 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.
ModelBindinginterfaceApp-defined I/O. Registered literal IDs determine input and output types.
ModelCallsclassFrozen 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.
ModelInvocationContextinterfaceOne take consumes one binding invocation attempt, independent of batch size or chat tokens.
ModelInvocationRequestinterfaceOne model call: registered binding id, the input to hand over and its timeout.
Normalizationconstant
NormalizationOptionsinterfacePipeline options.
NormalizationStepinterfaceOne ordered transformation.
projectContinuousExcerptfunctionProject 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.
Projectionconstant
QueryAggregationOptionsinterfaceQuery 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.
RegisteredIntenttypeFrozen registration view: list fields are frozen copies, helper methods are dropped.
splitTextBlocksfunctionSplit 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.
TextBlockinterfaceOne structure-aware block of a long text.
TextBlockOptionsinterfaceSplitting options.
TextBlocksconstant
TextSkillinterfaceLoaded skill: registration plus the parsed document text.
TextSkillHeaderinterfaceHeader every skill document must carry.
TextSkillLoaderinterfaceCompiled loader.
TextSkillLoaderDefinitioninterfaceLoader limits, parsing hooks and rejection wording.
TextSkillReadPortsinterfaceHost port that reads one skill document by path.
TextSkillRegistrationinterfaceCatalog entry of one text skill, before its document is read.
TextSkillsconstant
TreeProjectionOptionsinterfaceDepth- and record-level traversal options for tree projection.
uniqueByfunctionStable 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.

知识、问答与呈现 ​

进入分组

符号类别用途
AnswerCheckinterfaceResult of one local or review check over a generated answer.
AnswerCheckerinterfaceOne named check applied to a generated answer value.
AnswerFlowDefinitioninterfaceStatic handlers and limits; signal, diagnostics and App dependencies arrive at run.
Answeringconstant
AnswerIssueinterfaceValidation problem produced while checking a generated answer.
AnswerIteminterfaceOne unit an answer batch must produce.
AnswerReaderinterfaceApp-owned reader that gathers evidence for one task.
AnswerResultinterfaceFinal outcome for one item.
AnswerTaskDefinitioninterfaceStatic binding of one answerable task.
AnswerTaskPortsinterfaceRegistries a task catalog validates its references against.
CompiledReplyFormatinterfaceA resolved format with its checks bound; callers only inspect replies using it.
defineAnswerCheckCatalogfunctionCompile 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.
defineAnswerFlowfunctionCompile 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.
defineAnswerReaderCatalogfunctionCompile a reader catalog.
defineAnswerTaskCatalogfunctionCompile 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.
defineKnowledgeCatalogfunctionCompile 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.
defineKnowledgePublicationfunctionCompile 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.
defineOutputCatalogfunctionCompile 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.
defineReplyFormatsfunctionCompile reply formats so that checks run only for templates the current turn uses.
defineSemanticSlotsfunctionModels 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.
defineTextTemplatefunctionThe 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.
Knowledgeconstant
KnowledgeCandidateinterfaceA proposed document awaiting publish or reject.
KnowledgeCataloginterfaceCompiled catalog of knowledge documents.
KnowledgeCatalogOptionsinterfaceCatalog construction options.
KnowledgeDocumentinterfaceOne versioned document as supplied by the App.
KnowledgeParttypeDocument content: a text leaf or a nested section.
KnowledgePublicationinterfaceCompiled publication workflow.
knowledgePublicationOperationsconstant
KnowledgePublicationOptionsinterfaceApp-owned guards, store and limits for a publication workflow.
KnowledgePublicationRecordinterfaceStored publication state: one published revision plus pending candidates.
KnowledgePublicationStoreinterfaceSingle-writer store for the publication record.
KnowledgeReadinterfaceA request for one document selection.
KnowledgeSectioninterfaceA named section that may contain text and further sections.
KnowledgeSnapshotinterfaceMaterialized read result.
KnowledgeSourceReferenceinterfaceCitation of the material a candidate was derived from.
mergeReplyBubblesfunctionNormalize a reply that has no declared format: drop blank bubbles and merge overflow into the last allowed one. Text content is preserved.
OutputCatalogOptionsinterfaceCatalog construction options.
OutputComposeInputinterfaceInput for composing one output: model values plus program-assigned group members.
OutputDefinitioninterfaceOne output shape.
OutputFieldinterfaceOne field of an output definition.
OutputIssueinterfaceOutput problem with a guaranteed field path.
OutputProviderinterfaceApp-owned value provider for bound and semantic fields.
OutputResultinterfaceComposed output value.
parseKnowledgeDocumentfunctionPaired, nestable anchors are one text adapter. Other sources supply the same document contract directly.
Presentationconstant
ReplyFormatCheckinterfaceOne check a template declares, evaluated against the rendered bubbles.
replyFormatChecksconstant
ReplyFormatDefinitioninterfaceA template-bound reply format, matched against per-turn facts.
ReplyFormatOptionsinterfaceDeclaration input for defineReplyFormats.
resolvePreferencefunctionResolve 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.
SectionSelectiontypeWhich part of a document a read returns.
selectVariantfunctionPick 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.
SemanticSlotDefinitioninterfaceDeclares the {{namespace:key}} slots a model may use, and how often.
TextTemplateOptionsinterfaceText template construction options.
validateAnswerBatchfunctionValidate that one batch is well formed and fully covered.

产物与恢复 ​

进入分组

符号类别用途
ArtifactReferenceinterfaceReferences locate artifacts; only the App resolver establishes access and current validity.
ArtifactResolverinterfaceApp-registered resolver that turns a reference into an App value.
Artifactsconstant
defineArtifactCatalogfunctionCompile a catalog of artifact resolvers plus a checked resolve entry point.
defineDurableTaskfunctionCompile 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.
Durableconstant
DurableCheckpointinterfacePersisted task progress; the only state a resume reads back.
durableReplayPoliciesconstant
durableStatusesconstant
DurableStepinterfaceOne step of a durable task.
DurableStepContextinterfaceExecution facts handed to a durable step.
DurableStoreinterfaceApp implements an exclusive lock across every writer and validates/serializes stored state.
DurableTaskinterfaceCompiled task: resumes from the store and returns the final state.
DurableTaskDefinitioninterfaceTask definition, including the App hooks that guard every resume.
DurableTaskOptionsinterfaceRuntime options for a compiled durable task.

模型与交互 ​

进入分组

符号类别用途
bindInteractionfunctionBind every registered transfer command to a local handler. Models cannot add handlers.
CommandinterfaceCompiled command.
CommandCatalogclassMode 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.
CommandCatalogOptionsinterfaceEnvelope-level options for a command catalog.
CommandDefinitioninterfaceDeclarative command shape before compilation.
commandSchemafunctionBuild 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.
compileCommandsfunctionCompile 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.
defineCommandfunctionCompile 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.
defineCommandCatalogfunctionCompile definitions and wrap them in a sealed catalog.
defineInteractionProtocolfunctionConstruct a protocol from one definition.
INTERACTION_CATEGORIESconstant
InteractionCategorytypeInteraction purpose, never an authorization level or an assertion of execution success.
InteractionDescriptorinterfaceCatalog metadata for one command, independent of its field shape.
InteractionHandlerstypeHandler map keyed by command id; each handler receives the parsed value and App context.
InteractionProtocolclassWeb/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.
InteractionProtocolDefinitiontypeTransfer envelope plus its registered command family; no change to HTTP or SSE framing.
ProtocolCheckinterfaceOne declarative rejection rule.
ProtocolFieldinterfaceField presence, schema and ownership are declared together; schemas describe model input.
ProtocolPredicatetypePredicate evaluated during validation; any truthy result counts as a failure.
ProtocolReasontypeLazy rejection wording: a fixed message, a pre-built error, or a factory bound to the value.
ProtocolShapeinterfaceCustom protocols may derive dynamic keys without supplying a compiled schema.
RegisteredProtocolinterfaceRuntime extension contract; hosts retain their own version values and validation context.

MockGPT · 模拟模型与调试 ​

进入分组

符号类别用途
CallRecordinterfaceDetached snapshot of one accepted call, exposed through MockGPT.records.
createMockHandlerfunctionCreate a bare Node request listener backed by the mock.
createMockServerfunctionCreate 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.
encodeModelResponsefunctionOptional 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.
GeneratedtypeWhat a rule may produce: plain data, or a descriptor that changes transport behaviour.
GenerationContextinterfaceEverything 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.
GenerationInputinterfaceInput 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.
GenerationOptionsinterfacePer-call options of MockGPT.generate.
GeneratortypeA 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.
generatorNamesconstant
generatorsconstant
HandlerOptionsinterfaceOptions shared by the standalone server and the bare request handler.
HttpFaultinterfaceA simulated HTTP-level failure returned instead of a model reply.
isPublicAddressfunctionDecide whether an address is an acceptable public destination.
JsonValuetypeAny value accepted by the package's JSON snapshot rules: strings, finite numbers, booleans, null, arrays and plain objects.
LoadedPageinterfaceA fetched page body plus the metadata needed for decoding and diagnostics.
MessagetypeOne 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.
MockGPTclassConfigurable mock model instance. Create one per test or per mock server.
MockGPTErrorclassError 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.
MockGPTOptionsinterfaceConstruction options of a MockGPT instance.
ModelOutputinterfaceThe model-authored part of a reply, before it becomes JSON or SSE frames.
ModelRequestinterfaceA 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.
OutputOptionsinterfaceTransport-level knobs of a generated response. All values are simulated: they affect framing and timing of the mock reply, not real model behaviour.
ResponseDescriptionclassWrapper 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.
responsesconstant
routesconstant
RuleinterfaceOne ordered matching rule of a MockGPT instance.
ServerOptionsinterfaceOptions of createMockServer, adding shutdown behaviour.
sourcesconstant
TextOptionsinterfaceCommon options of the text generators.
TextSourcetypeText 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.
ToolCallinterfaceA tool call the mocked assistant emits instead of executing.
UsageinterfaceToken accounting reported by the OpenAI API; validated for internal consistency.
WebOptionsinterfaceConfiguration of sources.web.
WebProfiletypeName of an entry in webHeaderProfiles.

意图与范围 ​

进入分组

符号类别用途
createScopeRegistryfunctionCreate and seal a complete catalog; use the constructor for incremental installation.
RegisteredScopetypeFrozen registration view: every list is a frozen copy, evidence entries are projected.
RegisteredScopeEvidencetypeRegistered evidence entry: public data only, frozen by the registry.
ScopeDefinitioninterfaceOne declarable scope. Ids and aliases share one namespace and must be unique.
ScopeDescriptiontypePlain description with mutable arrays, for documentation and model-facing catalogs.
ScopeRegistryclassGeneric 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.
ScopeRegistryPolicyinterfaceRegistration rules for one scope registry.

检索与证据 ​

进入分组

符号类别用途
defineEvidenceChecklistfunctionCompile 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.
defineEvidenceProjectionfunctionCompile 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.
defineRetrievalfunctionCompile 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.
Evidenceconstant
EvidenceProjectionDefinitioninterfaceProjection configuration, keyed by the tool that produced an observation.
EvidenceProjectionProviderinterfaceDescribes which sources an observation can cite, and how to narrow it to cited ones.
EvidenceProviderinterfaceAdjudicates one evidence kind against real observations.
EvidenceRequirementinterfaceRequirements describe evidence that must already exist, never a model's assertion of success.
FusedRankinterfaceOne fused result with the per-source ranks that produced its score.
RankedListinterfaceOne retriever's ordered result, optionally weighted.
reciprocalRankFusionfunctionFuse 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.
Retrievalconstant
RetrievalDefinitiontypeRetrieval ports specialized to an App operation context.
RetrievalEffectinterfaceOne effect applied after a successful query, in declaration order.
RetrievalPortsinterfaceHost ports and policy for one retrieval kind.
RetrievalReasontypeLazy rejection wording: a fixed message, a pre-built error, or a factory bound to the query.
RetrievalReceiptinterfaceFacts of one accepted query.
RetrievalResultinterfaceAdapter output for one accepted query; the Kit renames each source before returning it.
RetrievalRunnerinterfaceCompiled retrieval runner.
RetrievalSourceinterfaceRequest-local citation reference; the App may separately carry its content entity id.
RetrievalStateinterfaceRequest-owned state. Clearing current evidence must not replenish spent budgets or seen keys.
TextSearchclassOptional 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.
TextSearchHitinterfaceOne ranked match; terms are post-tokenization and only stored fields are returned.
TextSearchOptionsinterfaceApp supplies fields, tokenizer and its own schema/tokenizer revision.
TextSearchQueryinterfaceSearch input: a hard result limit and an App-owned filter, both required on every query.
TextSearchSnapshotinterfaceSerialized index; the revision pair proves the snapshot matches the current configuration.
VectorSearchclassExact 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.
VectorSearchHitinterfaceOne search hit; the document is a cloned snapshot, not the indexed instance.
VectorSearchQueryinterfaceSearch options excluding the query vector, which search takes alongside them.
VectorSearchSpaceinterfaceEmbedding space identity and width; vectors from another space must never be mixed in.

日志复盘与证据报告 ​

进入分组

符号类别用途
defineReflectionfunctionCompile 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.
defineReflectionLogSourcefunctionBuild 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.
Reflectionconstant
ReflectionDefinitioninterfaceConfiguration for compiling a reflection task.
ReflectionEvidenceinterfaceExplicit metadata projection, not an arbitrary original event/payload.
ReflectionFindinginterfaceOne finding, always tied to the evidence it rests on.
reflectionFindingKindsconstant
reflectionIdentityFieldsconstant
ReflectionLogReaderinterfaceStructural port: the App supplies its own FileLogReader, trusted scope and current authorization.
ReflectionPageinterfaceOne page of evidence plus an honest statement of its coverage.
ReflectionQueryinterfaceOne evidence query.
ReflectionReportinterfaceRequest-local reflection result.
ReflectionSourceinterfaceApp-owned evidence source, including its own authorization.
ReflectionTaskinterfaceCompiled reflection task.

工具与能力 ​

进入分组

符号类别用途
LifecycleHooksinterfaceEverything 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".
LifecycleProtocolinterfaceOutput protocol carried by a tool lifecycle.
PolicyinterfaceRegistration policy shared by every tool in the registry.
RegisteredToolDefinitiontypeRegistered snapshot with frozen goal ids and projected hooks.
ToolinterfaceA registered tool: model metadata plus one optional lifecycle block.
ToolFinalizertypeConverts an executed decision into the tool result; must be synchronous.
ToolLifecycleRegistryclassRegistry 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.
ToolModelFieldinterfaceOne model-context field contributed by a tool.
ToolNormalizertypeConverts untrusted input into a decision; must be synchronous.
ToolProtocoltypeProtocol type of a tool's lifecycle invocation.
ToolRegistrationtypeDeclaration form; the registry derives the ModelTool projection from existing handlers.
ToolRuntimeTypesinterfaceOne schema binds lifecycle handler types without introducing platform fields into core.
ToolsOptionsinterfaceConstruction options for a tool registry.

接口参考、使用示例与开发指南。