Core · 接口与运行保证
传输与流
| 符号 | 类别 | 用途 |
|---|---|---|
abortableStream | function | Re-yield an async iterable, but reject as soon as signal aborts. The abort reason is propagated unchanged, so callers can tell user cancellation from a provider failure without inspecting messages. |
readSse | function | Decode an SSE response body into events. Framing contract: - A network chunk is not an event. Bytes are buffered until a blank line, because UTF-8 sequences, CRLF pairs and data: lines may all straddle chunk boundaries. - \r\n, \r and \n all terminate a line; a trailing \r at the end of a chunk is held back until the next chunk shows whether an \n follows. - Comment lines (leading :) are discarded; they are used as heartbeats. - The size limit applies per line and per event (1 MiB), not per network read, so many complete events coalesced into one chunk after backpressure remain valid. - Cancellation is checked between lines, so aborting while the consumer is paused stops emitting the remaining buffered events of the same chunk. |
SseEvent | interface | One dispatched SSE event, assembled from all lines up to a blank line. |
SseIdleTimeoutError | class | Raised when no bytes arrive within the configured idle window. A distinct type lets callers treat a silent connection as retryable instead of mixing it with transport or decoding failures. |
SseReadOptions | type | Per-read configuration; snapshotted when readSse starts. |
执行与工作流
| 符号 | 类别 | 用途 |
|---|---|---|
AgentBranch | interface | Immutable identity of one branch of an agent. The three required ids are generated per engine unless the host restores a branch; the optional ids are only present on a fork and record the exact origin, so a forked run can be attributed without consulting external storage. |
AgentCacheAddress | interface | Exact immutable address passed to the App port, including cancellation for this visit. |
AgentCacheOptions | interface | Persistent and volatile storage are independent; there is no implicit fallback or mirroring. |
AgentCachePort | interface | App-owned storage. Capacity, expiry, serialization and user isolation belong to the App. |
AgentCheckpoint | interface | In-memory checkpoint with a copy-on-read accessor. The stored data is already a clone, and read clones again, so a caller cannot mutate the checkpoint by mutating what it read. |
AgentCheckpointRecord | interface | Host-owned serializable data, never a saved credential, model budget or executable handler. |
AgentCoreEngine | class | Bounded execution shared by applications; business rules are registered by each host. Configuration is bound before a run and may be bound only once per model, tool runtime and workflow. A run resolves its signal from the engine, the request runtime and the caller, then executes either the bound workflow or a supplied step function until the round budget, cancellation or a completion stops it. |
AgentCoreEngineOptions | interface | Engine construction options. |
AgentCoreEngineSetup | type | Engine construction options. Combines round budget and error factories with exactly one model shape (a single bound model or a named catalog), an optional tool runtime, an optional branch identity, and an optional workflow together with its App dependencies. |
AgentModelBinding | type | Model binding accepted by the engine. Execution scope belongs to the engine, so a bound model may not carry its own signal or execution options. |
AgentModelRuntime | type | The subset of a runner an engine may drive; kept small so the App can supply it. |
AgentWorkflow | class | Executable catalog: validate references and bounded cycles before any handler runs. Validation happens once, at construction, so traversal can assume every target exists and every cycle is budget-bounded. |
AgentWorkflowDefinition | type | The graph an engine executes. |
AttemptBudget | class | Successful acquisitions consume attempts; a refused acquisition never grants another. available is a snapshot of the counter, not a reservation: a caller must still call take and honor its boolean result before acting. |
CacheContext | interface | Cache access shared by workflow visits and the low-level $step loop. |
CacheReadOptions | interface | Only reads may name another node. Partition names are not authorization boundaries. |
CoreStep | type | One loop iteration. Must be re-entrant: the same step object runs every round. |
defineWorkflow | function | Build a validated workflow from a definition. |
EngineCacheOptions | interface | Optional Engine memory bounds; TTL is measured from the latest write. |
ExecutionEventDescriptor | interface | Event name, content class and the producing execution identity. |
ExecutionObserver | interface | Live consumer of Core facts. |
LoopEvent | interface | Progress fact for one loop round, correlated with the enclosing diagnostics span. |
NodeAgentCache | interface | Async node view. Writes and clear can only address the current partition. |
NodeCache | interface | Synchronous view of the current node's Engine-owned memory. Values retain identity. |
requireWorkflowValue | function | Read a state field that must already be present. Used by requires declarations and terminal deliveries, so a node cannot observe a field as undefined and silently produce a wrong result. |
route | function | |
StepOutcome | type | Decision a step returns to the engine. |
WorkflowChain | interface | Observed visits, never merged by static node id or synthesized from adjacency. |
WorkflowChainCoverage | interface | Capture completeness is independent of whether diagnostic content was included. |
WorkflowChainNode | interface | A single node visit, with flat ordered subflow records including every independent fix. |
WorkflowChainNodeEvent | interface | Node-local lifecycle facts; payload remains subject to the source's content policy. |
WorkflowChainSource | type | App resolves authorization, retention, pagination and storage paths before returning. |
WorkflowChainTransition | interface | Actual handoff evidence; a target span does not prove its enter event was captured. |
WorkflowContext | interface | Execution facts available to every node of a running workflow. |
WorkflowEvent | interface | Metadata only: never includes state, prompt, parameters, results or raw errors. |
WorkflowExtension | interface | Additional nodes and routes merged into an existing definition. |
WorkflowFailure | interface | Error retained only while entering a registered failure phase. |
WorkflowGraph | interface | Pure registered topology; routes sharing a target share an edge within one kind. |
WorkflowGraphEdge | interface | Completion has no target node; recovery edges remain distinct from normal edges. |
WorkflowGraphNode | interface | Node metadata and derived incident edges, without executable callbacks. |
WorkflowGraphRoute | interface | Declaration order is retained even when multiple routes share a topology edge. |
WorkflowModel | interface | Model and tool access for one workflow invocation. Every call is charged to the workflow's shared budget. Overloads select the transport: a prepared call, the default plain-text transport, or one registered transport with its typed result. |
WorkflowNode | type | One node of the graph. |
WorkflowNodeReport | interface | Detail an App node reports about its current visit. |
WorkflowRoute | type | One route out of a node. Routes are evaluated in array order and the first match wins. A route either continues at targetNodeId or completes the workflow through complete; declaring both is invalid. |
WorkflowSubflowRecord | type | Historical subflow snapshots may omit recorder fields or descriptive content. |
共同合同与辅助入口
| 符号 | 类别 | 用途 |
|---|---|---|
AgentErrorInfo | interface | Stable error metadata for App diagnostics. Unknown retryability is deliberately omitted. |
AsyncSink | type | Awaitable sink for an ordered stream. A rejection propagates to the emitter. |
BudgetError | class | A configured allowance (rounds, model calls, attempts) is exhausted. The optional message states which allowance ran out; code is the stable marker. |
CheckResult | interface | Verdict of one registered check. unavailable and not-run are not verdicts on the value: they state that the check could not produce an answer, so callers must not treat them as failures. |
commonPrefixLength | function | Length of the longest common prefix of two strings. Implemented as a binary search over slice comparisons so long prompts stay on the native string comparison path instead of running a JavaScript character loop. |
configureBreakWhile | function | Install the host-owned break observer. No logging or persistence is enabled by default; passing no argument (or an empty config) removes any previously installed observer. |
DurationMs | type | Elapsed time in milliseconds; never an absolute instant. |
ErrorContext | interface | Boundary metadata is recorded internally, without replacing the original thrown value. |
ExecutionContext | interface | Required execution facts available inside a running call. |
ExecutionOptions | interface | Optional controls accepted by any public Core call. |
getErrorInfo | function | Produce a frozen diagnostic view of any thrown value. Inspection is guarded: an exotic error (revoked proxy, throwing getter, null prototype) degrades to UNKNOWN_ERROR instead of raising a second failure while handling the first. |
Id | type | Opaque identifier. Format and meaning belong to the App or to the registering module. |
InvocationMetadata | interface | Identity and timing shared by every invocation receipt. |
InvocationResult | interface | A produced value together with the receipt of the invocation that produced it. |
InvocationStatus | type | Terminal state of one invocation; cancelled is distinct from a failure. |
Issue | interface | One validation problem, locatable by code and, when available, by field path. |
JsonSchema | type | JSON Schema as consumed by the App's validator; Core never interprets its contents. |
MaybePromise | type | A value that may already be resolved or still pending. |
ModelCallRecord | interface | Receipt of a model call that returned successfully. |
ModelResult | type | Model call result with its model-call receipt. |
Observer | type | Notification callback. A rejected promise propagates to the emitter. |
OperationContext | interface | Execution context plus the App-owned host object. app carries services, identity and per-request dependencies supplied by the host; Core treats it as opaque and must not depend on application-specific fields. |
ProtocolRegistry | class | Append-only protocol registry. Extending Map keeps lookup semantics familiar while set rejects every invalid registration, which makes the instance effectively immutable after wiring. |
ReadonlyCatalog | interface | Read-only projection of a definition set; the implementation owns ordering and validation. |
Registry | interface | Mutable catalog. Registrations append; seal freezes the set against later writes. |
retrievalQueryKey | function | Serialize a query into a stable structural key. Object keys are sorted recursively while array positions are preserved. Values that JSON cannot represent, such as functions or undefined, make JSON.stringify return undefined and therefore produce an error instead of a colliding key. |
SchemaAdapter | interface | Compiled schema pair: the JSON form shown to the model and the runtime parser. |
SearchHit | interface | One search result. score semantics stay algorithm-specific (direction and scale are not part of this contract), and document may be a projection that only exposes stored fields rather than the full record. |
TimestampMs | type | Wall-clock instant in milliseconds since the Unix epoch. |
ToolCallRecord | interface | Receipt of a tool call that returned successfully. |
ToolResult | type | Tool call result with its tool-call receipt. |
ValidationError | class | Rejected input or output that failed one or more registered checks. The message is fixed; consumers should read issues for the actual reasons. |
WorkflowContractError | class | The workflow definition violates Core's execution contract, as opposed to failing business logic. Examples: unknown model binding, asynchronous predicate, unmatched route, missing state field. It is a programming error, so callers should not treat it as retryable. |
模型与交互
| 符号 | 类别 | 用途 |
|---|---|---|
AggregatedToolCall | interface | One completed native tool call in provider index order. |
AsIntent | type | Demand-discovery metadata; it has no identity independent of its tool. |
ChatProvider | class | Streaming model provider. Implementations must stop producing when context.signal aborts and should surface transport failures by rejecting the iteration rather than ending it silently. |
createModelTransport | function | Compose a registered selection transport. The capability source may be a static catalog or a function of the stage id; the resulting definitions are captured when prepare runs and are used both to build the instruction and to reject unknown capability ids at finish time. requireStrictArguments is a registration-time assertion: a transport cannot demand strict arguments from an adapter that does not support them. |
createToolCallCollector | function | Create a collector for one response. |
FunctionCallDelta | interface | One streamed fragment of a function call; fragments with the same index must be joined. |
IntentOptions | interface | Demand-facing hints attached to one Tool; no independent identity is created. |
jsonObjectInteraction | constant | |
ModelAssistantToolMessage | type | Assistant turn that may declare tool calls and may carry an empty text body. |
ModelCallRequest | type | One model call request. The input shape selects prompt mode or message mode. |
ModelCallTrace | interface | Accumulated facts of one model call, reported on success and on failure. |
ModelChildOptions | interface | Request-bound isolated runner settings; provider and ancestor budgets cannot be replaced. |
ModelChildPolicy | interface | Request-wide limits, shared by every descendant. They cannot be enlarged by a child. |
ModelFunction | interface | Provider-neutral function definition. Execution and authorization stay with the host. |
ModelImage | interface | Model message primitives shared by every provider adapter. These shapes are deliberately provider-neutral: they describe text, optional images, streamed parts and the options a call may carry. Provider-specific wire formats stay in support/model. Exports: ModelImage, ModelMessage, ModelToolCall, ModelAssistantToolMessage, ModelToolResultMessage, ModelUsage, ModelFunction, FunctionCallDelta, ModelPart, ModelOptions. |
ModelInputMeasurement | interface | Exact prepared-request accounting; token values exist only with an explicit model counter. |
ModelInteractionAdapter | interface | Pluggable implementations all consume the same business registry. No automatic fallback. |
ModelMessage | interface | One provider-neutral turn; images are user visual input and are not part of the text budget. |
ModelOptions | interface | Per-call provider options; Core passes them through and does not normalize provider ranges. |
ModelOutputEvent | type | Delivery sink, awaited in order. Parts are unvalidated proposals, never execution receipts. |
ModelPart | type | One streamed response part: assistant text or a function-call fragment. |
ModelPrepareRequest | interface | Transport selection for prepare; omitted fields take the runner defaults. |
modelProtocolError | function | Throw a model protocol validation error. |
ModelProviderContext | interface | Per-call facts a provider receives besides the messages themselves. |
ModelResponseCollector | interface | Accumulates streamed parts for one call and resolves them into the transport's result. |
ModelRunner | class | Execute registered model stages under one request's budgets and lifetime. Invariants: at most one call is in flight per runner; callCount and journal are local to the runner while totalCallCount includes descendants; every call is charged to the shared budget before I/O and every failure is annotated with its stage before it propagates. No business prompts, domain stages or provider SDKs are built into this runner. |
modelRunnerDefaults | constant | |
ModelRunnerOptions | type | Full runner construction options: provider, transports, sinks and named limits. |
ModelRunnerPorts | interface | Host ports a model runner needs in addition to its provider and transports. |
ModelRunnerSettings | interface | Named settings keep all model limits together; output token reservation stays per call. |
ModelRuntimeConfig | interface | Per-request model runtime limits. |
ModelSelection | type | A model's chosen capability together with its parsed arguments. |
ModelSessionCall | interface | One completed tool call in a session response. |
ModelSessionResult | interface | Complete result of one session response. |
ModelTokenBudget | interface | Provider-injected token accounting. Core never guesses a character-to-token conversion, so token budgets exist only when a host supplies a real counter. |
ModelTool | interface | Common selectable model interface; resolution proposes a value without business execution. |
ModelToolCall | interface | One tool call the assistant declared, in provider order. |
ModelToolCatalog | type | A compiled entity catalog also supports the minimal stage source contract. |
ModelToolRegistration | type | Registration form: input typing is erased, output typing is preserved. |
ModelToolRegistry | class | A request/stage projection is a sealed registry. Hosts filter availability before projection. |
ModelToolResultMessage | type | Tool result turn; toolCallId is required and images/tool declarations are rejected. |
ModelToolSource | interface | Minimal source a stage needs: enumerate tools and resolve one selection. |
ModelTransportDefinition | interface | One registered transport: a wire format prepared for a stage. |
ModelTransportRegistration | interface | Binds an adapter to the tools one transport serves. |
ModelUsage | interface | Provider-reported token counts for one call; used for accounting, never for admission. |
NativeFunctionCall | interface | Request-local native call buffer; never an execution receipt. |
nativeFunctionInteraction | constant | |
PreparedModelCall | interface | Request-bound, single-use transport snapshot. Repeated measurements do not prepare or spend calls. |
PreparedModelInteraction | interface | Adapter output for one stage, before the caller binds capability resolution. |
PreparedModelTransport | interface | Prepared transport handed to the runner, including sampling defaults. |
RegisteredModelTool | type | Frozen snapshot stored by a registry after schema validation. |
RegisteredTransportOutput | type | Result type of a transport selected by id. core:plain-text yields string, a registered id yields its declared result, and an id the runner does not know yields unknown rather than a guessed type. |
retryMultipleModelCalls | function | Retry once when the failure is a rejected multi-call proposal. Only the MODEL_MULTIPLE_CALLS code is retried; every other failure is rethrown unchanged. The caller owns the fallback prompt and the budget it consumes. |
ToolCallCollector | interface | Aggregation entry point for streamed function-call deltas. |
ToolCallFailure | type | Report a protocol violation and stop; callers decide how the failure is classified. |
ToolCondition | type | Activation is independent of participation in demand discovery. |
ToolContext | type | Read-only host data without changing explicit any/unknown erasure into an object constraint. |
ToolProposal | interface | A model proposal, not an authorization or execution receipt. |
上下文与日志
| 符号 | 类别 | 用途 |
|---|---|---|
assembleContextPlan | function | Build the model input for a context plan. |
assembleFragments | function | Build the model input from fragments. Metadata remains program-side: data never becomes a system instruction. |
BuiltContext | interface | Assembled context plus the accounting needed to explain the budget decision. |
ContextFragment | interface | One piece of model-visible input before assembly. |
ContextFragmentUsage | interface | Accounting entry reported for one fragment that actually entered the context. |
ContextJournal | class | Request-local context projection of execution receipts; not a separate persistent log store. |
ContextLifetime | type | Declared validity window of a fragment's content. |
ContextPlan | interface | Unassembled input; App-side nodes may process it before the Core budget boundary. |
ContextRecord | type | One journal entry: a model call, a tool request or a tool result. The three variants are distinguished by type; value/input stay unknown because their domain meaning belongs to the App. |
ContextTrust | type | Who produced the content, and therefore how much it may influence the model. |
validateContextBudget | function | Enforce the character budget of the whole model input. |
validateContextFragment | function | Validate one fragment and return the text it contributes to the model input. |
配置、清单与策略
| 符号 | 类别 | 用途 |
|---|---|---|
BreakCheck | interface | Each rule owns a semantic/readability group and its tags, independently of shared errors. |
BreakEvent | interface | Diagnostic metadata only; rule inputs and request data are not included. |
BreakPredicate | type | Each predicate is evaluated only after the preceding predicates passed. |
BreakReason | type | Lazy reasons preserve error construction and message evaluation on the rejection path only. |
breakWhile | function | Reject as soon as one of several conditions holds. Ordinary processing stays an ordinary if; this helper is for validation tables whose entries are evaluated in order and stop at the first failure. Behaviour that depends on earlier entries is expressed with a callback form. Reject when any predicate holds, reporting the given observer tags. Reject when any structured check holds. Each check may carry its own reason and tags; the first match stops the evaluation. Reject when a single value is truthy. Ordinary truthiness applies, so a function passed as a value counts as a failure; use the predicate form to evaluate it instead. Reject when a single value is truthy, reporting the given observer tags. |
BreakWhileConfig | interface | Global rejection observer installed once per process. |
matchRule | function | Dispatch to the first matching rule. A rule without a pattern matches unconditionally, so the table's order decides precedence. The first match owns the result even when its handler returns undefined, and later rules are not consulted. |
MatchRule | interface | Order is priority. Patterns may inspect values, types, state or regular expressions. |
WalkRule | interface | Synchronous traversal; local rules may omit catalog metadata. |
walkRules | function | Walk every rule in order, mutating the shared input. Later rules observe the mutations of earlier ones, which is why traversal is strictly sequential and every participant must be synchronous. Throwing stops the walk immediately; remaining rules are skipped. Walk every rule in order, mutating the shared input. |
过程观察与诊断
| 符号 | 类别 | 用途 |
|---|---|---|
CoreDiagnosticRecord | interface | Persisted data is untrusted: normalization checks the current envelope, not arbitrary payloads. |
CoreEvent | type | A recorded Core fact. Every variant carries the same envelope: a version marker, unique event id, producing span's identity, a per-producer monotonic sequence, the occurrence instant and optional reported sub-steps. subStepsDropped/subStepsTruncated state that reported detail was bounded. |
coreEventCatalog | constant | |
CoreEventDescriptor | interface | Event classification used when deciding whether a sink accepts an event. metadata events carry identity, timing and status only; content events may carry user, model or tool content and therefore require an explicit acceptance decision. |
CoreEventName | type | Union of every Core event name; the key set of CoreEventPayloads. |
CoreEventPayloads | interface | Payload of every Core event, keyed by event name. Fields are the event's own facts only. |
CoreLogOutput | interface | Destination for recorded facts; implementations decide filtering and durability. |
createDiagnostics | function | Configure the optional log consumer of the shared execution fact source. |
CreateDiagnosticsOptions | interface | Options for creating a root diagnostic scope. |
DebugStepsOutput | interface | Debug material a handler contributes to a diagnostic event. |
DiagnosticContext | interface | Recording scope bound to one execution identity. A child scope inherits the sink and observer of its parent; only identity changes. |
diagnosticError | function | Convert a thrown value into a plain record suitable as a log payload. |
DiagnosticIdentity | interface | Execution identity only: never message, account or HTTP identity. |
DiagnosticSpanFields | type | Identity fields a child span may override; the parent supplies run, span and parent span. |
NodeReportingContext | interface | Reporting surface handed to a node or tool for the duration of one visit. |
normalizeDiagnosticEvent | function | Validate a persisted diagnostic record and return a detached copy. Persisted data is untrusted, so the envelope version, event type, identity, ordering and the bounded sub-step shape are checked; the payload itself is not interpreted. The copy is deep cloned, so a store cannot hand back a record that later shares structure with the caller. |
RecordedSubStep | interface | A step already accepted by a logger, carrying recorder-assigned bookkeeping fields. |
ReportedStep | interface | One step as reported by a node; fields beyond identity are optional detail. |
ReportedStepStatus | type | A status a node may report; derived from the catalog, never declared separately. |
reportedStepStatusCatalog | constant | |
reportedStepStatuses | constant | |
ScopedSubFlowLogger | class | Non-inheriting delegate. Stores only the original logger and its bound subnode identity. |
ScopedSubFlowStepInput | type | Scoped writes cannot supply or override the identity bound by their delegate. |
SubFlowLog | interface | Common read/write surface for both independently implemented logger classes. |
SubFlowLogger | class | Full execution-owned recorder. Owns its store and may issue restricted delegates. |
SubFlowStepFix | interface | Explicit revision whitelist: identity, grouping and business type are never patchable. |
SubFlowStepInput | interface | Input accepted by write; the logger assigns the step id and sequence. |
SubFlowValue | type | JSON-like value accepted in reported payloads; depth and size are bounded by the recorder. |
SubStepProgress | interface | Compact progress notification emitted for each accepted sub-step write or fix. |
工具与能力
| 符号 | 类别 | 用途 |
|---|---|---|
ErasedTool | interface | Type-erased tool shape the registry executes after parsing at the boundary. |
ExecutableTool | interface | One registered tool, typed by its input, output, host context and id literal. |
executeInvocation | function | Run one synchronous invocation and record its effects. |
InvocationHandler | interface | A named handler invoked by a tool lifecycle step. |
RegisteredTool | type | Registered snapshot: public data is retained, implementation helpers are not a contract. |
ToolDefinition | type | Configuration form; Support supplies the identity resolver when omitted. |
ToolExecutionContext | interface | Execution facts handed to a tool for one invocation. |
ToolExecutionEvent | interface | Fact emitted when one tool call settles, correlated by invocationId. |
ToolInvocationPorts | interface | Optional tools the lifecycle resolves from the host context for one invocation. |
ToolInvocationRequest | interface | One invocation request; the registry supplies signal and diagnostics when omitted. |
ToolJournal | interface | Request-local execution receipts; the host decides their domain content. |
ToolJournalFinish | interface | Closing record for one tool call, written once with the terminal outcome. |
ToolJournalStart | interface | Opening record for one tool call, written before the handler runs. |
ToolRegistry | class | Registry mechanism only: visibility, authorization policy, schemas and semantic metadata are host registrations. A registry is mutable until sealed and keeps its own call log. |
ToolRegistryOptions | interface | Registry construction options. |
ToolRegistryPorts | interface | Host ports a tool registry needs in addition to the tool definitions. |