Skip to content
English

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.

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