Documentation
¶
Overview ¶
Package agent 定义引擎无关的 AI 对话抽象。
设计原则(接口皆可换,中枢不可换):
- 核心自持有 Tool 定义(名称 + JSON Schema + handler),不依赖任何框架类型; eino、HTTP MCP 各自做薄适配。
- Engine 的抽象层级是「跑完一次明确模式的模型任务」:Deep 可含完整 tool 循环,OneShot 是受控单次生成;这样可保持替换模型框架时的边界稳定。
- 产品聊天记录由调用方落库;支持持久会话的引擎自行管理完整 agent 轨迹, History 只用于首次建立引擎会话时的种子上下文。
Index ¶
- Constants
- Variables
- func ApplyTaskContextMutation(bucket TaskContextBucket, m TaskContextMutation) (TaskContextBucket, TaskContextRecord, error)
- func ClassifyTurnFailure(err error) string
- func CompileToolContract(t Tool) (*jsonschema.Schema, error)
- func DeliverTaskOutbox(ctx context.Context, store TaskOutboxStore, publisher TaskEventPublisher, ...) (bool, error)
- func DeliverTaskOutboxBatch(ctx context.Context, store TaskOutboxStore, publisher TaskEventPublisher, ...) (int, error)
- func IsBackgroundTask(ctx context.Context) bool
- func NewPublicError(code, message string, cause error) error
- func PollUntil[T any](ctx context.Context, interval time.Duration, ...) (T, error)
- func PublicToolTitle(name, title string) string
- func ReadTaskResultInput(ctx context.Context, ref TaskResultInput) ([]byte, error)
- func ReportProgress(ctx context.Context, snapshot progress.Snapshot) (sent bool)
- func ReportStatus(ctx context.Context, text string) (sent bool)
- func ResolveToolInputReferences(ctx context.Context, raw json.RawMessage, prefixes []string, maxBytes int) (json.RawMessage, error)
- func RuntimeSpan(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, trace.Span)
- func TaskFailureJSON(err error, execution string, admitted bool, receipt string, ...) (string, bool)
- func TaskGoalID(ctx context.Context) string
- func TaskID(ctx context.Context) string
- func TaskObservationIdentity(row TaskObservation) string
- func TaskProtocolVersion(version int) error
- func TaskResultIdentity(record TaskResultRecord) string
- func TaskResultInputSchema() map[string]any
- func TaskScope(req *TurnRequest) string
- func TaskTraceID(ctx context.Context) string
- func TaskWakeDepth(ctx context.Context) int
- func TaskWakeID(ctx context.Context) string
- func ToolContinuationText() string
- func ToolInvocationKey(ctx context.Context) string
- func ValidateTaskContextMutation(m TaskContextMutation) error
- func ValidateTaskGoalLimits(l TaskGoalLimits) error
- func ValidateTaskObservation(row TaskObservation) error
- func ValidateTaskQoSConfig(c TaskQoSConfig) error
- func ValidateTaskResult(record TaskResultRecord) error
- func VerifyTaskWebhookHMAC(secret []byte, maxAge time.Duration) func(context.Context, *http.Request, []byte) error
- func WithProgressReporter(ctx context.Context, report func(progress.Snapshot)) context.Context
- func WithStatusReporter(ctx context.Context, report func(string)) context.Context
- func WithTaskWake(ctx context.Context, id string, depth ...int) context.Context
- func WithToolInvocationKey(ctx context.Context, key string) context.Context
- func WrapTaskStorage(err error) error
- type ApprovalTool
- type Engine
- type MemoryTaskContextStore
- func (s *MemoryTaskContextStore) CollectContexts(ctx context.Context, now time.Time) error
- func (s *MemoryTaskContextStore) CommitContext(ctx context.Context, m TaskContextMutation) (TaskContextRecord, error)
- func (s *MemoryTaskContextStore) GetContext(ctx context.Context, scope, id string) (TaskContextRecord, error)
- func (s *MemoryTaskContextStore) ListContexts(ctx context.Context, scope, after string, limit int) (TaskContextPage, error)
- type MemoryTaskControlStore
- func (s *MemoryTaskControlStore) CollectControls(ctx context.Context, now time.Time) error
- func (s *MemoryTaskControlStore) CompareControl(ctx context.Context, row TaskControlState, expected int64) (bool, error)
- func (s *MemoryTaskControlStore) LoadControl(ctx context.Context, key string) (TaskControlState, error)
- type MemoryTaskEventStore
- func (s *MemoryTaskEventStore) CollectEvents(ctx context.Context, now time.Time) error
- func (s *MemoryTaskEventStore) CreateEventSource(ctx context.Context, row TaskEventSource) (TaskEventSource, bool, error)
- func (s *MemoryTaskEventStore) GetEventSource(ctx context.Context, scope, id string) (TaskEventSource, error)
- func (s *MemoryTaskEventStore) ListEventSources(ctx context.Context, scope, after string, limit int) ([]TaskEventSource, error)
- func (s *MemoryTaskEventStore) ReplaceEventSource(ctx context.Context, row TaskEventSource, revision int64) (bool, error)
- type MemoryTaskObservationStore
- func (s *MemoryTaskObservationStore) AppendObservation(ctx context.Context, row TaskObservation) (bool, error)
- func (s *MemoryTaskObservationStore) CollectObservations(ctx context.Context, now time.Time) error
- func (s *MemoryTaskObservationStore) ListObservations(ctx context.Context, scope string, q TaskObservationQuery) ([]TaskObservation, error)
- type MemoryTaskResultStore
- func (s *MemoryTaskResultStore) CollectResults(ctx context.Context, now time.Time) error
- func (s *MemoryTaskResultStore) GetResult(ctx context.Context, scope, id string) (TaskResultRecord, error)
- func (s *MemoryTaskResultStore) PutResult(ctx context.Context, record TaskResultRecord) (TaskResultRecord, error)
- func (s *MemoryTaskResultStore) ReadResult(ctx context.Context, scope, id string, offset int64, limit int) ([]byte, error)
- type MemoryTaskStore
- func (s *MemoryTaskStore) Collect(ctx context.Context, now time.Time) error
- func (s *MemoryTaskStore) CreateTask(ctx context.Context, r TaskRecord) (TaskRecord, bool, error)
- func (s *MemoryTaskStore) CreateWait(ctx context.Context, r TaskWaitRecord) (TaskWaitRecord, bool, error)
- func (s *MemoryTaskStore) FindTask(ctx context.Context, scope, key string) (TaskRecord, error)
- func (s *MemoryTaskStore) FindWait(ctx context.Context, scope, key string) (TaskWaitRecord, error)
- func (s *MemoryTaskStore) GetTask(ctx context.Context, scope, id string) (TaskRecord, error)
- func (s *MemoryTaskStore) GetWait(ctx context.Context, scope, id string) (TaskWaitRecord, error)
- func (s *MemoryTaskStore) ListTasks(ctx context.Context, scope string, query TaskScan) ([]TaskRecord, error)
- func (s *MemoryTaskStore) ListWaits(ctx context.Context, scope string, query TaskScan) ([]TaskWaitRecord, error)
- func (s *MemoryTaskStore) ReplaceTask(ctx context.Context, r TaskRecord, revision int64) (bool, error)
- func (s *MemoryTaskStore) ReplaceWait(ctx context.Context, r TaskWaitRecord, revision int64) (bool, error)
- type Message
- type NativeApprovalEngine
- type PendingApproval
- type PollResult
- type PublicErrorDetails
- type ReasoningMode
- type ResumeRequest
- type Role
- type Skill
- type Step
- type StepKind
- type TaskBudgetError
- type TaskBudgetLease
- type TaskBudgetLimit
- type TaskBudgetView
- type TaskConfig
- type TaskContextBucket
- type TaskContextDocument
- type TaskContextMatch
- type TaskContextMutation
- type TaskContextPage
- type TaskContextReceipt
- type TaskContextRecord
- type TaskContextReference
- type TaskContextStore
- type TaskContextSummary
- type TaskContextVersion
- type TaskControlState
- type TaskControlStore
- type TaskEventCondition
- type TaskEventMatch
- type TaskEventPage
- type TaskEventPublisher
- func (p TaskEventPublisher) CloseSource(ctx context.Context, scope, id string, expected int64, successor string) (TaskEventSource, error)
- func (p TaskEventPublisher) OpenSource(ctx context.Context, scope, key, label string) (TaskEventSource, error)
- func (p TaskEventPublisher) Publish(ctx context.Context, scope, id string, event TaskExternalEvent) (TaskExternalEvent, error)
- func (p TaskEventPublisher) RenewSource(ctx context.Context, scope, id string, expected int64, until time.Time) (TaskEventSource, error)
- type TaskEventSource
- type TaskEventStore
- type TaskExternalEvent
- type TaskFailure
- func ParseTaskFailureJSON(value string) (*TaskFailure, bool)
- func TaskFailureFrom(err error, execution string, admitted bool, receipt string, ...) *TaskFailure
- func TaskStorageCommitFailure(err error, execution, receipt string, result *TaskResultRef) *TaskFailure
- func TaskStorageFailure(err error, execution string, admitted bool, receipt string, ...) *TaskFailure
- type TaskGoalBinding
- type TaskGoalCharge
- type TaskGoalLimits
- type TaskGoalView
- type TaskInfo
- type TaskObservation
- type TaskObservationPage
- type TaskObservationQuery
- type TaskObservationStore
- type TaskObservationSummary
- type TaskOutboxAdminStore
- type TaskOutboxEntry
- type TaskOutboxFailureStore
- type TaskOutboxGroup
- func (g *TaskOutboxGroup) AckOutbox(ctx context.Context, e TaskOutboxEntry) error
- func (g *TaskOutboxGroup) ClaimOutbox(ctx context.Context, owner string, lease time.Duration) (TaskOutboxEntry, bool, error)
- func (g *TaskOutboxGroup) FailOutbox(ctx context.Context, e TaskOutboxEntry, code string, at time.Time, dead bool) error
- func (g *TaskOutboxGroup) RetryOutbox(ctx context.Context, e TaskOutboxEntry, at time.Time) error
- func (g *TaskOutboxGroup) TaskStoreHealth(ctx context.Context) error
- type TaskOutboxStore
- type TaskPage
- type TaskQoSConfig
- type TaskReadiness
- type TaskRecord
- type TaskResourceGrant
- type TaskResourcePolicy
- type TaskResourceRequest
- type TaskResultInput
- type TaskResultInputReader
- type TaskResultPage
- type TaskResultRecord
- type TaskResultRef
- type TaskResultStore
- type TaskRuntime
- func (r *TaskRuntime) ArchiveEventSource(ctx context.Context, scope, id string, expected int64) (TaskEventSource, error)
- func (r *TaskRuntime) AwaitResult(ctx context.Context, scope, id string, allowed map[string]bool) (TaskInfo, error)
- func (r *TaskRuntime) BindContext(ctx context.Context, scope string) (context.Context, error)
- func (r *TaskRuntime) BindWaitContext(ctx context.Context, scope, id string) (context.Context, error)
- func (r *TaskRuntime) Budget(ctx context.Context) ([]TaskBudgetView, error)
- func (r *TaskRuntime) Call(ctx context.Context, scope, turn, key string, tool Tool, args json.RawMessage) (string, error)
- func (r *TaskRuntime) Cancel(scope, id string, allowed map[string]bool) (TaskInfo, error)
- func (r *TaskRuntime) CancelAll() error
- func (r *TaskRuntime) CancelWaits(ctx context.Context, scope string) error
- func (r *TaskRuntime) ChargeGoal(ctx context.Context, amount TaskGoalCharge) error
- func (r *TaskRuntime) CheckExecutionEpoch(ctx context.Context, scope, epoch string) error
- func (r *TaskRuntime) ClaimWake(ctx context.Context, scope, consumer string) (*TaskWaitRecord, error)
- func (r *TaskRuntime) Close()
- func (r *TaskRuntime) Collect(ctx context.Context) error
- func (r *TaskRuntime) Completed() <-chan TaskInfo
- func (r *TaskRuntime) ContinueGoal(ctx context.Context, scope string, source context.Context) (context.Context, error)
- func (r *TaskRuntime) CooldownResource(ctx context.Context, key string, until time.Time) error
- func (r *TaskRuntime) DeleteContext(ctx context.Context, scope, turn, key, id string, expected int64) (TaskContextRecord, error)
- func (r *TaskRuntime) Done(scope, id string, allowed map[string]bool) (<-chan struct{}, error)
- func (r *TaskRuntime) Drain(ctx context.Context) error
- func (r *TaskRuntime) EndTurn(scope, turn string, keep bool)
- func (r *TaskRuntime) EventPublisher() TaskEventPublisher
- func (r *TaskRuntime) EventSources(ctx context.Context, scope, after string, limit int) ([]TaskEventSource, string, error)
- func (r *TaskRuntime) ExecutionEpoch(ctx context.Context, scope string) (string, error)
- func (r *TaskRuntime) GoalBudget(ctx context.Context) (TaskGoalView, error)
- func (r *TaskRuntime) List(ctx context.Context, scope, after string, limit int, allowed map[string]bool) (TaskPage, error)
- func (r *TaskRuntime) ListContexts(ctx context.Context, scope, after string, limit int) (TaskContextPage, error)
- func (r *TaskRuntime) ListWaitPage(ctx context.Context, scope, after string, limit int) ([]TaskWaitRecord, string, error)
- func (r *TaskRuntime) ObservationStats(ctx context.Context, scope string, q TaskObservationQuery) (TaskObservationSummary, error)
- func (r *TaskRuntime) Observations(ctx context.Context, scope string, q TaskObservationQuery) (TaskObservationPage, error)
- func (r *TaskRuntime) OpenResultInput(ctx context.Context, scope string, ref TaskResultInput, ...) (io.ReadCloser, error)
- func (r *TaskRuntime) PollInterval() time.Duration
- func (r *TaskRuntime) Read(scope string, ids []string, allowed map[string]bool) ([]TaskInfo, error)
- func (r *TaskRuntime) ReadContext(ctx context.Context, scope, id string) (TaskContextRecord, error)
- func (r *TaskRuntime) ReadEvents(ctx context.Context, scope, id string, after uint64, limit int) (TaskEventPage, error)
- func (r *TaskRuntime) ReadResult(ctx context.Context, scope, id string, offset int64, limit int, ...) (TaskResultPage, error)
- func (r *TaskRuntime) Readiness(ctx context.Context) (TaskReadiness, error)
- func (r *TaskRuntime) Reconcile(ctx context.Context, scope, id string, tools []Tool) (TaskInfo, error)
- func (r *TaskRuntime) RecordObservation(ctx context.Context, scope string, row TaskObservation) error
- func (r *TaskRuntime) ResolveResultInput(ctx context.Context, scope string, ref TaskResultInput, ...) ([]byte, error)
- func (r *TaskRuntime) ResultInputContext(ctx context.Context, scope string, tools []Tool) context.Context
- func (r *TaskRuntime) SaveContext(ctx context.Context, scope, turn, key, id string, expected int64, ...) (TaskContextRecord, error)
- func (r *TaskRuntime) SchedulingBudget(ctx context.Context) ([]TaskSchedulingView, error)
- func (r *TaskRuntime) Scope() string
- func (r *TaskRuntime) ScopeStatus(ctx context.Context) (TaskScopeStatus, error)
- func (r *TaskRuntime) Shutdown(ctx context.Context) error
- func (r *TaskRuntime) Start(ctx context.Context, scope, turn, key string, tool Tool, args json.RawMessage) (TaskInfo, error)
- func (r *TaskRuntime) Status() TaskRuntimeStatus
- func (r *TaskRuntime) Store() TaskStore
- func (r *TaskRuntime) Suspend(ctx context.Context, scope, turn, key string, spec TaskWaitSpec, ...) (TaskWaitRecord, error)
- func (r *TaskRuntime) TraceContext(ctx context.Context, scope, turn string) context.Context
- func (r *TaskRuntime) UpdateWake(ctx context.Context, scope, id, consumer, action string) error
- func (r *TaskRuntime) UseContext(ctx context.Context, scope string) (context.Context, error)
- func (r *TaskRuntime) UseTurnGoal(ctx context.Context, scope, turn string) (context.Context, error)
- func (r *TaskRuntime) Wait(ctx context.Context, scope string, ids []string, allowed map[string]bool, ...) ([]TaskInfo, error)
- func (r *TaskRuntime) WatchContext(ctx context.Context, scope string) (context.Context, func(), error)
- type TaskRuntimeStatus
- type TaskScan
- type TaskSchedulingView
- type TaskScopeStatus
- type TaskStore
- type TaskStoreHealth
- type TaskWaitRecord
- type TaskWaitSpec
- type TaskWebhook
- type TextCompaction
- type TextSummarizer
- type Tool
- type ToolCompletion
- type ToolContract
- type ToolExposure
- type ToolLoadMode
- type ToolMaturity
- type ToolMetadata
- type ToolMetadataProvider
- type ToolResultKind
- type TurnMode
- type TurnRequest
- type TurnResult
- type Usage
Constants ¶
const ( ToolEffectRead = "read" ToolEffectWrite = "write" ToolEffectExecute = "execute" ToolEffectUnknown = "unknown" )
const MaxTaskBudgetLeases = 5000
MaxTaskBudgetLeases 为共享协调文档设置总容量上限,避免不相交的资源组合无限增长。
const MaxTaskWakeEnvelopeBytes = 128 << 10
MaxTaskWakeEnvelopeBytes 限制内部恢复事实的JSON传输;正文另有配额,用户输入不能取得此内部额度。
const SummaryInstruction = `` /* 1154-byte string literal not displayed */
const TaskStorageDurable = "durable"
const TaskStorageMemory = "memory"
const TaskStorageVersion = 1
Variables ¶
var ErrTaskConflict = errors.New("agent: task record changed")
var ErrTaskContextCapacity = errors.New("agent: task context capacity reached")
var ErrTaskContextInvalid = errors.New("agent: invalid task context mutation")
var ErrTaskContract = errors.New("agent: tool contract violation")
var ErrTaskDraining = errors.New("agent: runtime draining")
var ErrTaskEventCapacity = errors.New("agent: event source capacity exhausted")
var ErrTaskEventClosed = errors.New("agent: event source closed")
var ErrTaskEventCursor = errors.New("agent: invalid event cursor")
var ErrTaskNotFound = errors.New("agent: task record unavailable")
var ErrTaskPolicyConflict = errors.New("agent: resource policy conflict")
ErrTaskPolicyConflict 表示宿主配置版本不一致,AI 不能通过重试或修改额度修复。
var ErrTaskResultExpired = errors.New("agent: result body expired")
var ErrTaskResultRange = errors.New("agent: invalid result byte range")
var ErrTaskStopped = errors.New("agent: task scope stopped")
ErrTaskStopped 表示调用所属代次已停止;重新执行必须来自新的明确轮次。
var ErrTaskStorageConfiguration = errors.New("agent: incomplete durable storage")
ErrTaskStorageUnavailable 表示存储边界未能确认,不暴露驱动、地址或响应原文。
var ErrTaskStorageVersion = errors.New("agent: incompatible storage protocol")
var ErrTaskWakeBudget = errors.New("agent: task wake budget exhausted")
ErrTaskWakeBudget 表示当前目标的自动恢复预算已用完,须公开报告而非继续注册循环。
var ErrTextContextLimit = errors.New("text context compaction limit")
Functions ¶
func ApplyTaskContextMutation ¶
func ApplyTaskContextMutation(bucket TaskContextBucket, m TaskContextMutation) (TaskContextBucket, TaskContextRecord, error)
ApplyTaskContextMutation 是通用原子更新规则;宿主须在同一bucket版本CAS成功后才返回该结果。
func ClassifyTurnFailure ¶
ClassifyTurnFailure 只返回稳定分类,不返回供应商错误正文,供宿主日志、历史与公开文案复用。
func CompileToolContract ¶
func CompileToolContract(t Tool) (*jsonschema.Schema, error)
CompileToolContract 复用标准 JSON Schema 实现;不允许 schema 通过远端 $ref 进行网络访问。
func DeliverTaskOutbox ¶
func DeliverTaskOutbox(ctx context.Context, store TaskOutboxStore, publisher TaskEventPublisher, owner string) (bool, error)
DeliverTaskOutbox 每次最多投递一项。发布成功但 ACK 丢失时只重发同一事件键,不调用业务。
func DeliverTaskOutboxBatch ¶
func DeliverTaskOutboxBatch(ctx context.Context, store TaskOutboxStore, publisher TaskEventPublisher, owner string, limit int) (int, error)
DeliverTaskOutboxBatch 有界推进已提交事实,不调度业务。失败项已隔离时继续处理其余项,避免批首阻塞。
func IsBackgroundTask ¶
IsBackgroundTask 区分显式后台方式和同步记账,不因内部协程改变模型选择。
func NewPublicError ¶
NewPublicError 将经过审定的公开说明与私有原因分离;cause 只供服务端 errors.Is/As。 code 限小写标识符,message 限 2048 字节。无效说明退回通用错误,不透传 cause。
func PollUntil ¶
func PollUntil[T any](ctx context.Context, interval time.Duration, probe func(context.Context) (PollResult[T], error), notify func(string)) (T, error)
PollUntil 只重复调用只读探针,不创建任务、不重试错误或重放写操作。 interval 是相邻探针开始时刻的最小间隔(0默认1秒),长轮询不会再额外等待。 截止时间、授权及是否后台执行由调用方的上下文和已有 TaskRuntime 决定。 probe 必须响应取消,notify 必须快速返回;停止等待不会取消原远端业务。
func PublicToolTitle ¶
PublicToolTitle 校验宿主或引擎声明的展示名称;缺失时返回空,由界面使用本地化通用标题。 不把工具名或长篇模型说明猜成用户文案,原技术标识保留在调用详情中。
func ReadTaskResultInput ¶
func ReadTaskResultInput(ctx context.Context, ref TaskResultInput) ([]byte, error)
ReadTaskResultInput 供显式支持引用的 Handler 使用;引用原样参加原权限/确认/幂等校验。 不把大正文展开到工具参数,也不绕过原 Handler 的目标权限检查。
func ReportProgress ¶
ReportProgress 仅报告经校验的公开事实;旧宿主继续收到 Message,取消后不再报告。
func ReportStatus ¶
ReportStatus 上报有界纯文本进度;没有通道、已取消或回调异常时返回 false,不创建后台工作。
func ResolveToolInputReferences ¶
func ResolveToolInputReferences(ctx context.Context, raw json.RawMessage, prefixes []string, maxBytes int) (json.RawMessage, error)
ResolveToolInputReferences 仅向宿主声明的参数前缀填充不可变引用;确认与幂等仍冻结原引用参数。 不执行表达式、不选择 URL/方法/权限,展开后的参数仍由原工具 schema 和实时权限验证。
func RuntimeSpan ¶
func RuntimeSpan(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, trace.Span)
RuntimeSpan 接入宿主标准 OTel provider;未配置 provider 时是 no-op,不建立私有 exporter 或日志系统。
func TaskFailureJSON ¶
func TaskFailureJSON(err error, execution string, admitted bool, receipt string, result *TaskResultRef) (string, bool)
TaskFailureJSON 使用通用错误信封;not_admitted 只用于确知尚未接纳的情况。
func TaskGoalID ¶
TaskGoalID 返回可信目标的非授权关联标识,供展示、日志等关联恢复轮次;不能据此访问目标或重置预算。
func TaskObservationIdentity ¶
func TaskObservationIdentity(row TaskObservation) string
TaskObservationIdentity 对白名单元数据求指纹,持久适配器可拒绝同ID不同内容。
func TaskProtocolVersion ¶
TaskProtocolVersion 是存储读写协议,独立于记录 CAS 修订和工具版本。零版本仅用于显式兼容旧记录。
func TaskResultIdentity ¶
func TaskResultIdentity(record TaskResultRecord) string
TaskResultIdentity 对不可变内容及执行事实求指纹,适配器可用于原子去重;不包含重试时间。
func TaskResultInputSchema ¶
TaskResultInputSchema 供支持引用的工具直接复用,不需要各接口重复定义句柄协议。
func TaskTraceID ¶
TaskTraceID 读取受管关联身份,不从业务JSON或浏览器请求编号取得授权。
func TaskWakeDepth ¶
TaskWakeDepth 保留同一目标的恢复深度,不能随轮次重建而重置预算。
func TaskWakeID ¶
TaskWakeID 读取可信队列的恢复身份,不采用客户端 RequestID 作为权限依据。
func ToolContinuationText ¶
func ToolContinuationText() string
ToolContinuationText is shared by native assistant and host transports. A saved authoritative receipt permits a new authorized turn, not another write.
func ToolInvocationKey ¶
ToolInvocationKey returns the opaque identity assigned by the Agent runtime. It is empty for direct/MCP calls that do not provide a durable invocation.
func ValidateTaskContextMutation ¶
func ValidateTaskContextMutation(m TaskContextMutation) error
ValidateTaskContextMutation 校验存储协议边界,防止绕过运行时写入超大目录或模糊删除版本。
func ValidateTaskGoalLimits ¶
func ValidateTaskGoalLimits(l TaskGoalLimits) error
ValidateTaskGoalLimits 拒绝负额度及无界保留配置,生产与内存宿主使用同一约束。
func ValidateTaskObservation ¶
func ValidateTaskObservation(row TaskObservation) error
ValidateTaskObservation 仅允许有界关联字段和枚举式状态,原始业务文本不能进入观测目录。
func ValidateTaskQoSConfig ¶
func ValidateTaskQoSConfig(c TaskQoSConfig) error
ValidateTaskQoSConfig 供宿主启动配置和运行时共用,避免等到模型请求才发现非法策略。
func ValidateTaskResult ¶
func ValidateTaskResult(record TaskResultRecord) error
ValidateTaskResult 校验写入契约;存储适配器必须拒绝与大小/摘要不一致的正文。
func VerifyTaskWebhookHMAC ¶
func VerifyTaskWebhookHMAC(secret []byte, maxAge time.Duration) func(context.Context, *http.Request, []byte) error
VerifyTaskWebhookHMAC 签名 method、escaped path、时间戳、幂等键和原正文(逐项以换行分隔)。 幂等键必须被签名,防止窃取原请求后换键重复注入;密钥来自宿主配置,不自行创建密钥文件。
func WithProgressReporter ¶
WithProgressReporter 为当前执行绑定结构化进度;与纯文本通道共存,不创建额外线程。
func WithStatusReporter ¶
WithStatusReporter 为宿主工具绑定现有轮次的状态通道;保留原上下文和取消条件。 进度只作展示,不代表执行回执、用户授权或模型新增轮次。
func WithTaskWake ¶
WithTaskWake 仅供可信宿主附加恢复身份和预算深度,不赋予工具权限。
func WithToolInvocationKey ¶
WithToolInvocationKey attaches the runtime-owned identity of one logical write/execute invocation. Domain handlers may use it as an idempotency key; user input must never be trusted as this value. 空值显式清除继承身份,防止从无 invocation 的原提案借入其他轮次的授权键。
func WrapTaskStorage ¶
WrapTaskStorage 由明确持久边界调用;已知语义错误保持原判定,其他错误以固定公开类型标记。
Types ¶
type ApprovalTool ¶
type ApprovalTool struct {
ToolCallID string `json:"tool_call_id"`
InterruptID string `json:"interrupt_id"`
ToolName string `json:"tool_name"`
Args json.RawMessage `json:"args"`
}
type Engine ¶
type Engine interface {
// RunTurn 阻塞直到本轮完成(模型给出最终文本或出错)。
RunTurn(ctx context.Context, req *TurnRequest) (*TurnResult, error)
// Name 引擎标识(配置值),用于日志与会话落库。
Name() string
}
Engine 跑一轮带工具的对话。实现:einoengine。
type MemoryTaskContextStore ¶
type MemoryTaskContextStore struct {
// contains filtered or unexported fields
}
MemoryTaskContextStore 供内存宿主与协议测试共享;生产宿主须注入持久适配。
func NewMemoryTaskContextStore ¶
func NewMemoryTaskContextStore() *MemoryTaskContextStore
NewMemoryTaskContextStore 创建独立上下文目录,多个运行时可共享同一实例。
func (*MemoryTaskContextStore) CollectContexts ¶
CollectContexts 回收正文、墓碑与去重窗口,不执行任何任务。
func (*MemoryTaskContextStore) CommitContext ¶
func (s *MemoryTaskContextStore) CommitContext(ctx context.Context, m TaskContextMutation) (TaskContextRecord, error)
CommitContext 在同一锁内执行通用quota/CAS/dedup,不会部分提交。
func (*MemoryTaskContextStore) GetContext ¶
func (s *MemoryTaskContextStore) GetContext(ctx context.Context, scope, id string) (TaskContextRecord, error)
GetContext 返回当前可核对版本;墓碑只含删除事实而不含旧正文。
func (*MemoryTaskContextStore) ListContexts ¶
func (s *MemoryTaskContextStore) ListContexts(ctx context.Context, scope, after string, limit int) (TaskContextPage, error)
ListContexts 仅列当前作用域,显式游标不会拼接其他身份的目录。
type MemoryTaskControlStore ¶
type MemoryTaskControlStore struct {
// contains filtered or unexported fields
}
MemoryTaskControlStore 为测试及单进程宿主提供共享协调,生产应注入持久适配。
func NewMemoryTaskControlStore ¶
func NewMemoryTaskControlStore() *MemoryTaskControlStore
NewMemoryTaskControlStore 创建独立的内存协调根,多个运行时可显式共享同一实例。
func (*MemoryTaskControlStore) CollectControls ¶
CollectControls 回收已超过目标期限和账本保留期的内存账户,停止代次与共享策略不随之清除。
func (*MemoryTaskControlStore) CompareControl ¶
func (s *MemoryTaskControlStore) CompareControl(ctx context.Context, row TaskControlState, expected int64) (bool, error)
CompareControl 原子创建或替换指定版本,失败不留下部分资源接纳。
func (*MemoryTaskControlStore) LoadControl ¶
func (s *MemoryTaskControlStore) LoadControl(ctx context.Context, key string) (TaskControlState, error)
LoadControl 返回副本,调用者不能绕过 CAS 修改代次或资源预留。
type MemoryTaskEventStore ¶
type MemoryTaskEventStore struct {
// contains filtered or unexported fields
}
MemoryTaskEventStore用于内存宿主/协议测试,多个运行时可共享同一实例。
func NewMemoryTaskEventStore ¶
func NewMemoryTaskEventStore() *MemoryTaskEventStore
NewMemoryTaskEventStore创建隔离事件目录,不宣称可跨进程恢复。
func (*MemoryTaskEventStore) CollectEvents ¶
CollectEvents先清正文,保留序号/指纹;源过期后才删除去重记录。
func (*MemoryTaskEventStore) CreateEventSource ¶
func (s *MemoryTaskEventStore) CreateEventSource(ctx context.Context, row TaskEventSource) (TaskEventSource, bool, error)
CreateEventSource在一个锁内固定宿主幂等键,重复创建只返回原源。
func (*MemoryTaskEventStore) GetEventSource ¶
func (s *MemoryTaskEventStore) GetEventSource(ctx context.Context, scope, id string) (TaskEventSource, error)
GetEventSource核对作用域和源保留期,返回副本而非可绕过CAS的可变记录。
func (*MemoryTaskEventStore) ListEventSources ¶
func (s *MemoryTaskEventStore) ListEventSources(ctx context.Context, scope, after string, limit int) ([]TaskEventSource, error)
ListEventSources只列当前作用域元数据,省略所有事件正文。
func (*MemoryTaskEventStore) ReplaceEventSource ¶
func (s *MemoryTaskEventStore) ReplaceEventSource(ctx context.Context, row TaskEventSource, revision int64) (bool, error)
ReplaceEventSource同时核对版本与固定源身份,旧发布者不能覆盖后来的事件。
type MemoryTaskObservationStore ¶
type MemoryTaskObservationStore struct {
// contains filtered or unexported fields
}
MemoryTaskObservationStore 提供内存观测目录,重用同实例可验证重建后查询与去重。
func NewMemoryTaskObservationStore ¶
func NewMemoryTaskObservationStore() *MemoryTaskObservationStore
NewMemoryTaskObservationStore 创建独立目录,不宣称进程重启持久。
func (*MemoryTaskObservationStore) AppendObservation ¶
func (s *MemoryTaskObservationStore) AppendObservation(ctx context.Context, row TaskObservation) (bool, error)
AppendObservation 原子去重,同一ID不同事实必须拒绝而不是覆盖旧追踪。
func (*MemoryTaskObservationStore) CollectObservations ¶
CollectObservations 只执行保留策略,观测过期不能改变调用或等待的真实状态。
func (*MemoryTaskObservationStore) ListObservations ¶
func (s *MemoryTaskObservationStore) ListObservations(ctx context.Context, scope string, q TaskObservationQuery) ([]TaskObservation, error)
ListObservations 只读未过期快照并保持游标有序,过滤条件不扩大作用域。
type MemoryTaskResultStore ¶
type MemoryTaskResultStore struct {
// contains filtered or unexported fields
}
MemoryTaskResultStore 供内存宿主和协议测试使用;生产宿主须注入持久实现。
func NewMemoryTaskResultStore ¶
func NewMemoryTaskResultStore() *MemoryTaskResultStore
NewMemoryTaskResultStore 创建隔离的结果目录,供会话内宿主或协议测试复用。
func (*MemoryTaskResultStore) CollectResults ¶
CollectResults 分别回收正文和最终事实,避免正文失效被误当作调用从未执行。
func (*MemoryTaskResultStore) GetResult ¶
func (s *MemoryTaskResultStore) GetResult(ctx context.Context, scope, id string) (TaskResultRecord, error)
GetResult 只返回元数据,正文过期后仍可核对执行事实。
func (*MemoryTaskResultStore) PutResult ¶
func (s *MemoryTaskResultStore) PutResult(ctx context.Context, record TaskResultRecord) (TaskResultRecord, error)
PutResult 校验完整正文后不可变提交,重复写入只接受同一执行事实。
func (*MemoryTaskResultStore) ReadResult ¶
func (s *MemoryTaskResultStore) ReadResult(ctx context.Context, scope, id string, offset int64, limit int) ([]byte, error)
ReadResult 每次核对作用域、保留期和字节范围,不依赖后台清理及时运行。
type MemoryTaskStore ¶
type MemoryTaskStore struct {
// contains filtered or unexported fields
}
MemoryTaskStore 供不需要重启恢复的宿主和测试使用;生产宿主可接入同一 CAS 存储协议。
func NewMemoryTaskStore ¶
func NewMemoryTaskStore() *MemoryTaskStore
NewMemoryTaskStore 创建独立内存账本,不宣称支持进程重启恢复。
func (*MemoryTaskStore) CreateTask ¶
func (s *MemoryTaskStore) CreateTask(ctx context.Context, r TaskRecord) (TaskRecord, bool, error)
CreateTask 原子绑定调用键与参数指纹,重复受理不创建第二个执行者。
func (*MemoryTaskStore) CreateWait ¶
func (s *MemoryTaskStore) CreateWait(ctx context.Context, r TaskWaitRecord) (TaskWaitRecord, bool, error)
CreateWait 原子保存等待条件,相同登记只能取回原记录。
func (*MemoryTaskStore) FindTask ¶
func (s *MemoryTaskStore) FindTask(ctx context.Context, scope, key string) (TaskRecord, error)
FindTask 按稳定调用键查询原回执,不以重放代替恢复。
func (*MemoryTaskStore) FindWait ¶
func (s *MemoryTaskStore) FindWait(ctx context.Context, scope, key string) (TaskWaitRecord, error)
FindWait 在资源预留前查询同一逻辑登记;重复调用不重复消耗等待额度。
func (*MemoryTaskStore) GetTask ¶
func (s *MemoryTaskStore) GetTask(ctx context.Context, scope, id string) (TaskRecord, error)
GetTask 核对作用域并返回副本,避免调用方绕过 CAS 修改记录。
func (*MemoryTaskStore) GetWait ¶
func (s *MemoryTaskStore) GetWait(ctx context.Context, scope, id string) (TaskWaitRecord, error)
GetWait 返回原等待条件的副本,交付控制仍须校验版本。
func (*MemoryTaskStore) ListTasks ¶
func (s *MemoryTaskStore) ListTasks(ctx context.Context, scope string, query TaskScan) ([]TaskRecord, error)
ListTasks 有序分页只返回元数据;活跃扫描不受历史正文大小影响。
func (*MemoryTaskStore) ListWaits ¶
func (s *MemoryTaskStore) ListWaits(ctx context.Context, scope string, query TaskScan) ([]TaskWaitRecord, error)
ListWaits 按稳定游标查询条件,活跃扫描跳过已交付的历史。
func (*MemoryTaskStore) ReplaceTask ¶
func (s *MemoryTaskStore) ReplaceTask(ctx context.Context, r TaskRecord, revision int64) (bool, error)
ReplaceTask 同时核对版本与调用身份,拒绝过期执行者覆盖恢复后的状态。
func (*MemoryTaskStore) ReplaceWait ¶
func (s *MemoryTaskStore) ReplaceWait(ctx context.Context, r TaskWaitRecord, revision int64) (bool, error)
ReplaceWait 用 CAS 串行化交付租约、确认与取消,不依赖进程内锁。
type NativeApprovalEngine ¶
NativeApprovalEngine explicitly advertises the suspension contract. Merely implementing Engine does not imply RequireApproval will be honored.
type PendingApproval ¶
type PendingApproval struct {
CheckPointID string `json:"checkpoint_id"`
Tools []ApprovalTool `json:"tools"`
}
PendingApproval is an opaque runtime checkpoint with exact tool invocations. Persist it privately; expose only redacted signed cards to clients.
type PollResult ¶
type PollResult[T any] struct { Value T Done bool Progress string // ProgressSnapshot 优先报告给当前结构化通道,notify 仅作纯文本兼容。 ProgressSnapshot *progress.Snapshot }
PollResult 由宿主解释原回执后提供;Done 表示停止等待,不等同于业务成功。 Value 保留原始结果,Progress 是宿主提供的公开进度,内核不解析业务字段。
type PublicErrorDetails ¶
type PublicErrorDetails struct {
Code string `json:"code" bson:"code"`
Message string `json:"message" bson:"message"`
}
PublicErrorDetails 是宿主明确审定可公开的失败原因,不改变执行状态或重试权限。 Code 和 Message 必须来自宿主的公开错误映射,不能填入响应原文、凭据或用户输入。
type ReasoningMode ¶
type ReasoningMode string
ReasoningMode controls provider reasoning for a specific call. Product Deep turns use the configured default; bounded internal selectors can disable reasoning when the provider supports it.
const ( ReasoningDefault ReasoningMode = "" ReasoningDisabled ReasoningMode = "disabled" )
type ResumeRequest ¶
type ResumeRequest struct {
CheckPointID string
Decisions map[string]bool
// ToolCallID is host-owned display correlation, not resume authority.
ToolCallID string
}
ResumeRequest targets explicit interrupt IDs. False rejects without invoking the handler; omitted targets remain suspended. It requires the exact original EngineSession and capability set, plus fresh host-owned tool handlers.
type Step ¶
type Step struct {
// Progress 是可选公开事实;Result 保留旧宿主可读摘要。
Progress *progress.Snapshot
// ToolCallID correlates call/result evidence across suspended segments.
ToolCallID string
// ApprovalPending is an unresolved call, never successful execution evidence.
ApprovalPending bool
// ApprovalRejected means this call was explicitly denied before execution.
ApprovalRejected bool
Kind StepKind
ToolName string
// ToolTitle 沿执行证据保存声明式展示名称,避免引擎内置工具在实时与历史中退化为技术标识。
ToolTitle string
Args json.RawMessage
Result string
Err string
Completion ToolCompletion
// Replayed means the model repeated the exact same write/execute invocation
// in one turn. The original call remains in Steps; this entry is evidence of
// the suppressed replay and did not invoke the business handler again.
Replayed bool
}
Step 一次引擎轮次内的执行轨迹条目,用于审计与回放。
type TaskBudgetError ¶
type TaskBudgetError struct {
Resource string `json:"resource"`
Kind string `json:"kind"`
RetryAfterMS int64 `json:"retry_after_ms"`
}
TaskBudgetError 明确表示尚未接纳,不表示工具或原业务失败;AI 可选择等待或调整并发。
func (*TaskBudgetError) Error ¶
func (e *TaskBudgetError) Error() string
type TaskBudgetLease ¶
type TaskBudgetLease struct {
ID string `bson:"id"`
Scope string `bson:"scope"`
Epoch string `bson:"epoch"`
Owner string `bson:"owner"`
Kind string `bson:"kind"`
Resources []string `bson:"resources"`
Claims []TaskResourceRequest `bson:"claims,omitempty"`
Grants []TaskResourceGrant `bson:"grants,omitempty"`
ExpiresAt time.Time `bson:"expiresAt"`
Running bool `bson:"running"`
}
TaskBudgetLease 是共享池中的有期限预留;同一池的全部资源在一次 CAS 中接纳。
type TaskBudgetLimit ¶
TaskBudgetLimit 由可信宿主定义共享资源额度,模型只能查询,不能扩大。
type TaskBudgetView ¶
type TaskBudgetView struct {
Resource string `json:"resource"`
MaxActive int `json:"max_active"`
ActiveRemaining int `json:"active_remaining"`
MaxConcurrent int `json:"max_concurrent"`
ConcurrentRemaining int `json:"concurrent_remaining"`
MaxWaiting int `json:"max_waiting"`
WaitingRemaining int `json:"waiting_remaining"`
}
TaskBudgetView 提供当前限制和剩余额度快照;查询不构成资源预留。
type TaskConfig ¶
type TaskConfig struct {
// StorageMode 明确声明持久能力;durable 禁止任何权威组件回退内存。
StorageMode string
MaxConcurrent, MaxTasks, MaxResultBytes, MaxWakeAttempts, MaxWakeDepth int
Timeout, LeaseDuration, ResultRetention, LedgerRetention, PollInterval time.Duration
// Results 保存完整回执;MaxResultBytes 只限制向模型内联的正文,不决定执行成败。
Results TaskResultStore
MaxStoredResultBytes int
ResultSaveTimeout time.Duration
Store TaskStore
Scope string
OnComplete func(TaskInfo)
// OnProgress 在公开进度/终态持久成功后通知;未上报进度的终态也通知,此时 Progress 为 nil。
// 有界邮箱合并中间进度,投递前重读原账本。
OnProgress func(TaskInfo)
ControlStore TaskControlStore
ControlNamespace string
BudgetPool string
Budgets []TaskBudgetLimit
Observations TaskObservationStore
ObservationRetention, ObservationTimeout time.Duration
// Contexts 保存AI可见的长期工作事实,独立于有损聊天历史和业务授权。
Contexts TaskContextStore
ContextRetention time.Duration
MaxContexts, MaxContextBytes, MaxContextMutations int
Events TaskEventStore
MaxEventRecords int
Outbox TaskOutboxStore
GoalLimits TaskGoalLimits
QoS TaskQoSConfig
BudgetPolicyVersion int64
}
TaskConfig 约束资源与记录保留,不决定业务步骤。Store 必须由宿主绑定可信命名空间。
type TaskContextBucket ¶
type TaskContextBucket struct {
Scope string `bson:"scope"`
Revision int64 `bson:"revision"`
Records map[string]TaskContextRecord `bson:"records"`
Receipts map[string]TaskContextReceipt `bson:"receipts"`
ExpiresAt time.Time `bson:"expiresAt"`
}
TaskContextBucket 将同一作用域的 CAS、配额与去重合在一次原子提交中,适配不要求数据库事务。 最高128个64KiB文档和4096个轻量回执,保持协调文档低于Mongo的16MiB限制。
func CloneTaskContextBucket ¶
func CloneTaskContextBucket(bucket TaskContextBucket) TaskContextBucket
CloneTaskContextBucket 使存储适配器可以在副本上执行协议,失败时不泄露部分原地修改。
func CollectTaskContextBucket ¶
func CollectTaskContextBucket(bucket TaskContextBucket, now time.Time) TaskContextBucket
CollectTaskContextBucket 回收过期文档与去重回执;墓碑过期前仍计入配额,避免创建/删除绕开容量。
type TaskContextDocument ¶
type TaskContextDocument struct {
Goal string `json:"goal" bson:"goal"`
Constraints []string `json:"constraints,omitempty" bson:"constraints,omitempty"`
Pending []string `json:"pending,omitempty" bson:"pending,omitempty"`
Evidence []TaskContextReference `json:"evidence,omitempty" bson:"evidence,omitempty"`
Notes string `json:"notes,omitempty" bson:"notes,omitempty"`
State string `json:"state" bson:"state"`
}
TaskContextDocument 保存 AI 公开维护的目标、约束与工作事实,不保存隐藏推理或可执行业务流程。 State 是 AI 对工作进度的声明,不代表已取得授权或原业务执行成功。
type TaskContextMatch ¶
type TaskContextMatch struct {
ID string `json:"id" bson:"id"`
ExpectedRevision int64 `json:"expected_revision" bson:"expectedRevision"`
CurrentRevision int64 `json:"current_revision,omitempty" bson:"currentRevision,omitempty"`
State string `json:"state" bson:"state"`
}
TaskContextMatch 记录认领时的引用状态,不把新版本等同于原目标,也不自动决定后续业务。
type TaskContextMutation ¶
type TaskContextMutation struct {
ID, Scope, Key, Digest string
ExpectedRevision int64
Document TaskContextDocument
Delete bool
Now, ExpiresAt time.Time
MaxRecords, MaxMutations, MaxBytes int
}
TaskContextMutation 的限制来自宿主,模型参数不能改变配额或指纹;Key 绑定可信逻辑调用。
type TaskContextPage ¶
type TaskContextPage struct {
Contexts []TaskContextSummary `json:"contexts"`
Next string `json:"next,omitempty"`
RecordsUsed int `json:"records_used"`
MutationsUsed int `json:"mutations_used"`
RecordCapacity int `json:"record_capacity,omitempty"`
MutationCapacity int `json:"mutation_capacity,omitempty"`
RemainingRecords int `json:"remaining_records"`
RemainingMutations int `json:"remaining_mutations"`
MaxDocumentBytes int `json:"max_document_bytes"`
}
TaskContextPage 明确分页和剩余额度,不能把部分目标目录误当作完整工作上下文。
func TaskContextBucketPage ¶
func TaskContextBucketPage(bucket TaskContextBucket, now time.Time, after string, limit int) (TaskContextPage, error)
TaskContextBucketPage 返回显式排序的可见目录;删除和过期正文不从目录泄露。
type TaskContextReceipt ¶
type TaskContextReceipt struct {
ID string `bson:"id"`
Digest string `bson:"digest"`
Revision int64 `bson:"revision"`
ExpiresAt time.Time `bson:"expiresAt"`
}
TaskContextReceipt 保留轻量去重事实,重复保存返回当前版本与原已应用版本,不覆盖后续更新。
type TaskContextRecord ¶
type TaskContextRecord struct {
ID string `json:"id" bson:"id"`
Scope string `json:"-" bson:"scope"`
Revision int64 `json:"revision" bson:"revision"`
Document TaskContextDocument `json:"document" bson:"document"`
Deleted bool `json:"deleted,omitempty" bson:"deleted,omitempty"`
CreatedAt time.Time `json:"created_at" bson:"createdAt"`
UpdatedAt time.Time `json:"updated_at" bson:"updatedAt"`
ExpiresAt time.Time `json:"expires_at" bson:"expiresAt"`
AppliedRevision int64 `json:"applied_revision,omitempty" bson:"-"`
Replayed bool `json:"replayed,omitempty" bson:"-"`
DeleteKey string `json:"-" bson:"deleteKey,omitempty"`
DeleteDigest string `json:"-" bson:"deleteDigest,omitempty"`
}
TaskContextRecord 是当前可见版本;删除保留墓碑,不能让旧创建重投复活同一上下文。
type TaskContextReference ¶
type TaskContextReference struct {
Kind string `json:"kind" bson:"kind"`
ID string `json:"id" bson:"id"`
Revision int64 `json:"revision,omitempty" bson:"revision,omitempty"`
}
TaskContextReference 仅记录证据句柄与观察版本,不授权运行时读取或执行其指向的业务。
type TaskContextStore ¶
type TaskContextStore interface {
CommitContext(context.Context, TaskContextMutation) (TaskContextRecord, error)
GetContext(context.Context, string, string) (TaskContextRecord, error)
ListContexts(context.Context, string, string, int) (TaskContextPage, error)
CollectContexts(context.Context, time.Time) error
}
TaskContextStore 的 Commit 必须原子核对版本、去重和作用域配额,不得以最后写入覆盖冲突。
type TaskContextSummary ¶
type TaskContextSummary struct {
ID string `json:"id"`
Revision int64 `json:"revision"`
Goal string `json:"goal"`
State string `json:"state"`
UpdatedAt time.Time `json:"updated_at"`
ExpiresAt time.Time `json:"expires_at"`
}
TaskContextSummary 是轻量目录;正文仅在按号读取时返回,墓碑不出现在目录中。
type TaskContextVersion ¶
type TaskContextVersion struct {
ID string `json:"id" bson:"id"`
Revision int64 `json:"revision" bson:"revision"`
}
TaskContextVersion 固定登记时观察到的长期工作上下文版本,引用本身不赋予执行授权。 恢复后由AI读取当前版本核对差异,不把旧引用伪装成最新事实或隐藏推理。
type TaskControlState ¶
type TaskControlState struct {
StorageVersion int `bson:"storageVersion,omitempty" json:"storage_version,omitempty"`
Key string `bson:"_id"`
Revision int64 `bson:"revision"`
Epoch string `bson:"epoch,omitempty"`
Leases []TaskBudgetLease `bson:"leases,omitempty"`
UpdatedAt time.Time `bson:"updatedAt"`
// Payload 供通用协调协议保存有界状态,不允许模型直接读写。
Payload []byte `bson:"payload,omitempty"`
ExpiresAt time.Time `bson:"expiresAt,omitempty"`
}
TaskControlState 用同一 CAS 协议保存独立的停止代次文档和共享预算池文档。 停止代次不可重置为旧值;预算租约到期可以回收,不能把失联执行者重新接纳为原执行者。
type TaskControlStore ¶
type TaskControlStore interface {
LoadControl(context.Context, string) (TaskControlState, error)
CompareControl(context.Context, TaskControlState, int64) (bool, error)
}
TaskControlStore 的 expected=0 表示原子创建;其他值必须与当前 Revision 匹配。 存储必须跨会话/实例共享,不能为预算池隐式加会话前缀。
type TaskEventCondition ¶
type TaskEventCondition struct {
SourceID string `json:"source_id" bson:"sourceID"`
After uint64 `json:"after" bson:"after"`
Types []string `json:"types,omitempty" bson:"types,omitempty"`
}
TaskEventCondition 只引用宿主已授权的事件源,不携带URL、发布权限或业务后续步骤。
type TaskEventMatch ¶
type TaskEventMatch struct {
SuccessorID string `json:"successor_id,omitempty" bson:"successorID,omitempty"`
SourceID string `json:"source_id" bson:"sourceID"`
Seq uint64 `json:"seq,omitempty" bson:"seq,omitempty"`
State string `json:"state" bson:"state"`
}
TaskEventMatch固定触发等待的事件序号;重投不能换成后来另一条事实。
type TaskEventPage ¶
type TaskEventPage struct {
Source TaskEventSource `json:"source"`
Events []TaskExternalEvent `json:"events"`
Next uint64 `json:"next"`
More bool `json:"more"`
UntrustedData bool `json:"untrusted_data"`
}
TaskEventPage明确事件属于数据事实;payload不授予权限,正文失效不表示事件从未发生。
type TaskEventPublisher ¶
type TaskEventPublisher struct {
Store TaskEventStore
Retention, BodyRetention time.Duration
MaxRecords int
Observe func(context.Context, string, TaskObservation) error
}
TaskEventPublisher是可信Go宿主入口;模型工具不提供创建源或发布事件的能力。
func (TaskEventPublisher) CloseSource ¶
func (p TaskEventPublisher) CloseSource(ctx context.Context, scope, id string, expected int64, successor string) (TaskEventSource, error)
CloseSource 停止接收新事实,但同键重投仍可核对原指纹;后继必须是同作用域的真实源。
func (TaskEventPublisher) OpenSource ¶
func (p TaskEventPublisher) OpenSource(ctx context.Context, scope, key, label string) (TaskEventSource, error)
OpenSource以宿主提供的稳定键创建授权源,标签是数据而不是系统提示。
func (TaskEventPublisher) Publish ¶
func (p TaskEventPublisher) Publish(ctx context.Context, scope, id string, event TaskExternalEvent) (TaskExternalEvent, error)
Publish去重键与内容指纹必须一致;乱序的生产者序号仍按持久到达顺序交付,不能跳过迟到事件。
func (TaskEventPublisher) RenewSource ¶
func (p TaskEventPublisher) RenewSource(ctx context.Context, scope, id string, expected int64, until time.Time) (TaskEventSource, error)
RenewSource 只延长仍存活源及去重保留,不复活已过期正文或已关闭源。
type TaskEventSource ¶
type TaskEventSource struct {
State string `json:"state,omitempty" bson:"state,omitempty"`
SuccessorID string `json:"successor_id,omitempty" bson:"successorID,omitempty"`
ID string `json:"id" bson:"_id"`
Scope string `json:"-" bson:"scope"`
Key string `json:"-" bson:"key"`
Label string `json:"label" bson:"label"`
Revision int64 `json:"-" bson:"revision"`
Capacity int `json:"capacity" bson:"capacity"`
Head uint64 `json:"head" bson:"head"`
CreatedAt time.Time `json:"created_at" bson:"createdAt"`
ExpiresAt time.Time `json:"expires_at" bson:"expiresAt"`
Records []TaskExternalEvent `json:"-" bson:"records"`
}
TaskEventSource 由可信宿主创建;Key仅用于宿主幂等,模型不能指定其他租户或发布者。 Records保留去重指纹至源到期,正文可更早回收;满额必须拒绝,不能静默覆盖未读取事件。
func AllocateEventSegment ¶
func AllocateEventSegment(ctx context.Context, control TaskControlStore, namespace, scope, stream, label string, publisher TaskEventPublisher) (TaskEventSource, error)
AllocateEventSegment 用共享 CAS 预留源内发布位置,避免每个操作占一整个源、也避免并发填满同一段。 预留失败可留下空位,不会重执行业务;原 outbox 固定源句柄,重投不会换段。
type TaskEventStore ¶
type TaskEventStore interface {
CreateEventSource(context.Context, TaskEventSource) (TaskEventSource, bool, error)
GetEventSource(context.Context, string, string) (TaskEventSource, error)
ListEventSources(context.Context, string, string, int) ([]TaskEventSource, error)
ReplaceEventSource(context.Context, TaskEventSource, int64) (bool, error)
CollectEvents(context.Context, time.Time) error
}
TaskEventStore按(scope,key)原子创建源,按revision原子追加;同一源序号与去重在一次CAS中提交。 List只返回源元数据,Get供可信运行时进行源内筛选;适配器仍须绑定租户与会话命名空间。
type TaskExternalEvent ¶
type TaskExternalEvent struct {
Seq uint64 `json:"seq" bson:"seq"`
Key string `json:"key" bson:"key"`
Type string `json:"type" bson:"type"`
Digest string `json:"-" bson:"digest"`
ProducerSequence string `json:"producer_sequence,omitempty" bson:"producerSequence,omitempty"`
OccurredAt time.Time `json:"occurred_at,omitempty" bson:"occurredAt,omitempty"`
PublishedAt time.Time `json:"published_at" bson:"publishedAt"`
BodyExpiresAt time.Time `json:"body_expires_at" bson:"bodyExpiresAt"`
Payload json.RawMessage `json:"payload,omitempty" bson:"payload,omitempty"`
Availability string `json:"availability" bson:"availability"`
}
TaskExternalEvent 的Seq是本源的持久到达顺序;ProducerSequence/OccurredAt只是来源事实,不决定交付次序。
type TaskFailure ¶
type TaskFailure struct {
Code string `json:"code" bson:"code"`
ExecutionState string `json:"execution_state" bson:"executionState"`
Message string `json:"message" bson:"message"`
Admitted bool `json:"admitted" bson:"admitted"`
AdmissionState string `json:"admission_state" bson:"admissionState"`
ReceiptID string `json:"receipt_id,omitempty" bson:"receiptID,omitempty"`
ResultRef *TaskResultRef `json:"result_ref,omitempty" bson:"resultRef,omitempty"`
RetryAfterMS int64 `json:"retry_after_ms,omitempty" bson:"retryAfterMS,omitempty"`
// Public 仅保存宿主显式公开的原因,独立于框架 Code 与执行事实。
Public *PublicErrorDetails `json:"public,omitempty" bson:"public,omitempty"`
// contains filtered or unexported fields
}
TaskFailure 是可公开的失败事实;它不授予重试、业务执行或新的工具权限。 cause 只在进程内供 errors.Is/As 核对,不能持久化或发送原错误文本。
func ParseTaskFailureJSON ¶
func ParseTaskFailureJSON(value string) (*TaskFailure, bool)
ParseTaskFailureJSON 读取框架公开失败信封。任意 message 都会重新规范化,不能借此公开原错误文本。 只处理失败协议;普通业务 JSON 与异步受理回执不应被解释为失败。
func TaskFailureFrom ¶
func TaskFailureFrom(err error, execution string, admitted bool, receipt string, result *TaskResultRef) *TaskFailure
TaskFailureFrom 在已知执行阶段分类错误。未知工具错误不会被猜成未执行或可安全重试。
func TaskStorageCommitFailure ¶
func TaskStorageCommitFailure(err error, execution, receipt string, result *TaskResultRef) *TaskFailure
TaskStorageCommitFailure 用于提交应答丢失:可能已经落库,必须查询原ID或重投同一幂等键核对。
func TaskStorageFailure ¶
func TaskStorageFailure(err error, execution string, admitted bool, receipt string, result *TaskResultRef) *TaskFailure
TaskStorageFailure 用于明确的持久读写边界;错误说明不包含数据库地址或原驱动文本。 写入应答丢失时由调用者保留unknown和回执ID,不能据此重复业务执行。
func (*TaskFailure) Error ¶
func (e *TaskFailure) Error() string
Error 仅提供固定公开说明,禁止把底层凭据、地址或响应原文串入模型错误。
type TaskGoalBinding ¶
type TaskGoalBinding struct {
ID string `json:"id" bson:"id"`
Scope string `json:"scope" bson:"scope"`
Deadline time.Time `json:"deadline" bson:"deadline"`
}
TaskGoalBinding 在可信上下文及等待记录传递,AI 创建 context 文档不能重置它。
type TaskGoalCharge ¶
type TaskGoalCharge struct {
ModelCalls int64 `json:"model_calls"`
ToolCalls int64 `json:"tool_calls"`
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
CostMicros int64 `json:"cost_micros"`
// Quoted 表示宿主确认 tokens/费用为上界,不是模型自报或粗略估计。
Quoted bool `json:"-"`
}
TaskGoalCharge 是一次调用的保守预留;失联/缺失 usage 不退还,以免突破预算。
type TaskGoalLimits ¶
type TaskGoalLimits struct {
ModelCalls int64 `json:"model_calls" yaml:"model_calls"`
ToolCalls int64 `json:"tool_calls" yaml:"tool_calls"`
InputTokens int64 `json:"input_tokens" yaml:"input_tokens"`
OutputTokens int64 `json:"output_tokens" yaml:"output_tokens"`
CostMicros int64 `json:"cost_micros" yaml:"cost_micros"`
Duration time.Duration `json:"duration" yaml:"duration"`
}
TaskGoalLimits 由宿主限定一个明确指令及其所有恢复轮次的累计消耗;零额度表示不限制该维度。 金额采用宿主统一币种的微单位;仅可信供应商报价可作为费用上界,不能用字符估算费用。
type TaskGoalView ¶
type TaskGoalView struct {
Binding TaskGoalBinding `json:"goal"`
Limits TaskGoalLimits `json:"limits"`
Reserved TaskGoalCharge `json:"reserved"`
}
TaskGoalView 返回目标额度与保守预留,不能作为新的执行授权。
type TaskInfo ¶
type TaskInfo struct {
ID string `json:"id" bson:"id"`
ContractVersion string `json:"contract_version,omitempty" bson:"contractVersion,omitempty"`
ParentID string `json:"parent_id,omitempty" bson:"parentID,omitempty"`
Tool string `json:"tool" bson:"tool"`
Title string `json:"title,omitempty" bson:"title,omitempty"`
GoalID string `json:"goal_id,omitempty" bson:"goalID,omitempty"`
State string `json:"state" bson:"state"`
Completion ToolCompletion `json:"completion,omitempty" bson:"completion,omitempty"`
TraceID string `json:"trace_id,omitempty" bson:"traceID,omitempty"`
// Background 是调用方选择的执行方式,与原业务是否异步完成无关。
Background bool `json:"background" bson:"background"`
Result string `json:"result,omitempty" bson:"result,omitempty"`
Error string `json:"error,omitempty" bson:"error,omitempty"`
Input json.RawMessage `json:"arguments,omitempty" bson:"-"`
ResultExpired bool `json:"result_expired,omitempty" bson:"resultExpired,omitempty"`
ResolutionRef *TaskResultRef `json:"resolution_ref,omitempty" bson:"resolutionRef,omitempty"`
ResultRef *TaskResultRef `json:"result_ref,omitempty" bson:"resultRef,omitempty"`
Failure *TaskFailure `json:"failure,omitempty" bson:"failure,omitempty"`
// Progress 是 Handler 最近报告的公开事实;保留原时间,不能代替完成回执。
Progress *progress.Snapshot `json:"progress,omitempty" bson:"progress,omitempty"`
}
TaskInfo 的 completed 表示 Handler 已返回,不能代替原异步业务的完成状态。
type TaskObservation ¶
type TaskObservation struct {
ID string `json:"id" bson:"id"`
Scope string `json:"-" bson:"scope"`
TraceID string `json:"trace_id" bson:"traceID"`
TaskID string `json:"task_id,omitempty" bson:"taskID,omitempty"`
ParentID string `json:"parent_id,omitempty" bson:"parentID,omitempty"`
InvocationID string `json:"invocation_id,omitempty" bson:"invocationID,omitempty"`
TurnID string `json:"turn_id,omitempty" bson:"turnID,omitempty"`
WaitID string `json:"wait_id,omitempty" bson:"waitID,omitempty"`
WakeID string `json:"wake_id,omitempty" bson:"wakeID,omitempty"`
ContextID string `json:"context_id,omitempty" bson:"contextID,omitempty"`
SourceID string `json:"source_id,omitempty" bson:"sourceID,omitempty"`
SubscriptionID string `json:"subscription_id,omitempty" bson:"subscriptionID,omitempty"`
EventID string `json:"event_id,omitempty" bson:"eventID,omitempty"`
Tool string `json:"tool,omitempty" bson:"tool,omitempty"`
Kind string `json:"kind" bson:"kind"`
State string `json:"state,omitempty" bson:"state,omitempty"`
Code string `json:"code,omitempty" bson:"code,omitempty"`
Revision int64 `json:"revision,omitempty" bson:"revision,omitempty"`
InputTokens int64 `json:"input_tokens,omitempty" bson:"inputTokens,omitempty"`
OutputTokens int64 `json:"output_tokens,omitempty" bson:"outputTokens,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty" bson:"durationMS,omitempty"`
At time.Time `json:"at" bson:"at"`
ExpiresAt time.Time `json:"expires_at" bson:"expiresAt"`
}
TaskObservation 只包含关联和状态事实,不接受参数、正文、检查点或事件载荷。 ID 按时间排序;InvocationID是摘要,不能反推出宿主调用身份或授权内容。
func PrepareTaskObservation ¶
func PrepareTaskObservation(scope string, row TaskObservation, retention time.Duration) (TaskObservation, error)
PrepareTaskObservation 供可信宿主发布器归一化白名单元数据,不调用存储或解释业务载荷。
type TaskObservationPage ¶
type TaskObservationPage struct {
Records []TaskObservation `json:"records"`
Next string `json:"next,omitempty"`
Dropped uint64 `json:"local_dropped"`
Failed uint64 `json:"local_failed"`
Pending int64 `json:"local_pending"`
}
TaskObservationPage 明确给出下一游标和本地观测损失,不隐瞒有界队列背压。
type TaskObservationQuery ¶
type TaskObservationQuery struct {
After string
Limit int
TaskID, WaitID, TraceID, Kind, ContextID, SourceID, SubscriptionID, EventID string
From, To time.Time
}
TaskObservationQuery 为快照分页,不能把并发写入期间的一页当作完整实时事件流。
type TaskObservationStore ¶
type TaskObservationStore interface {
AppendObservation(context.Context, TaskObservation) (bool, error)
ListObservations(context.Context, string, TaskObservationQuery) ([]TaskObservation, error)
CollectObservations(context.Context, time.Time) error
}
TaskObservationStore 必须按(scope,ID)原子去重,按ID升序分页并服从ctx取消。 收到完整记录才表示持久成功;观测不是调用账本,也不能决定是否重放业务。
type TaskObservationSummary ¶
type TaskObservationSummary struct {
Count int `json:"count"`
Counts map[string]int `json:"counts"`
Truncated bool `json:"truncated"`
Next string `json:"next,omitempty"`
Dropped uint64 `json:"local_dropped"`
Failed uint64 `json:"local_failed"`
Pending int64 `json:"local_pending"`
}
TaskObservationSummary 仅汇总返回的有界快照;Truncated/Next表示还有数据而非全量统计。
type TaskOutboxAdminStore ¶
type TaskOutboxAdminStore interface {
ListOutbox(context.Context, string, int) ([]TaskOutboxEntry, error)
RequeueOutbox(context.Context, string, int64) error
}
TaskOutboxAdminStore 供可信宿主诊断和显式重投;重投只保留原事实,不能替换载荷或重做业务。
type TaskOutboxEntry ¶
type TaskOutboxEntry struct {
TraceParent string `bson:"traceparent,omitempty" json:"-"`
TraceState string `bson:"tracestate,omitempty" json:"-"`
StorageVersion int `bson:"storageVersion,omitempty" json:"-"`
Attempts int `bson:"attempts" json:"attempts"`
FailureCode string `bson:"failureCode,omitempty" json:"failure_code,omitempty"`
Dead bool `bson:"dead" json:"dead"`
Route int `bson:"-" json:"-"`
ID string `bson:"_id" json:"id"`
Scope string `bson:"scope" json:"-"`
SourceID string `bson:"sourceID" json:"source_id"`
Event TaskExternalEvent `bson:"event" json:"event"`
Revision int64 `bson:"revision" json:"-"`
Owner string `bson:"owner" json:"-"`
LeaseUntil time.Time `bson:"leaseUntil" json:"-"`
RetryAt time.Time `bson:"retryAt" json:"-"`
Delivered bool `bson:"delivered" json:"delivered"`
CreatedAt time.Time `bson:"createdAt" json:"created_at"`
ExpiresAt time.Time `bson:"expiresAt" json:"expires_at"`
}
TaskOutboxEntry 是与业务事实原子提交的事件,不含重放业务 Handler 的能力。 ID 必须由业务提交身份稳定导出;同 ID 的事实不能改变,ACK 前不允许清除正文。
func NewTaskOutboxEntry ¶
func NewTaskOutboxEntry(scope, source, id, kind string, payload json.RawMessage, retention time.Duration) (TaskOutboxEntry, error)
NewTaskOutboxEntry 固定事件身份与内容,供宿主在真正原子边界插入。
func (TaskOutboxEntry) WithTrace ¶
func (e TaskOutboxEntry) WithTrace(ctx context.Context) TaskOutboxEntry
WithTrace 由可信提交者关联 W3C 追踪,不携带 baggage 或改变原事件事实。
type TaskOutboxFailureStore ¶
type TaskOutboxFailureStore interface {
FailOutbox(context.Context, TaskOutboxEntry, string, time.Time, bool) error
}
TaskOutboxFailureStore 在同一 Owner/Revision 租约下记录失败、死信和下一次可领取时间。
type TaskOutboxGroup ¶
type TaskOutboxGroup struct {
Stores []TaskOutboxStore
// contains filtered or unexported fields
}
TaskOutboxGroup 复用同一投递器接入多个实际事务边界,Route 仅为本地可信适配选择。
func (*TaskOutboxGroup) AckOutbox ¶
func (g *TaskOutboxGroup) AckOutbox(ctx context.Context, e TaskOutboxEntry) error
func (*TaskOutboxGroup) ClaimOutbox ¶
func (g *TaskOutboxGroup) ClaimOutbox(ctx context.Context, owner string, lease time.Duration) (TaskOutboxEntry, bool, error)
func (*TaskOutboxGroup) FailOutbox ¶
func (g *TaskOutboxGroup) FailOutbox(ctx context.Context, e TaskOutboxEntry, code string, at time.Time, dead bool) error
func (*TaskOutboxGroup) RetryOutbox ¶
func (g *TaskOutboxGroup) RetryOutbox(ctx context.Context, e TaskOutboxEntry, at time.Time) error
func (*TaskOutboxGroup) TaskStoreHealth ¶
func (g *TaskOutboxGroup) TaskStoreHealth(ctx context.Context) error
TaskStoreHealth 检查各真实投递边界,未配置发布器不导致副作用。
type TaskOutboxStore ¶
type TaskOutboxStore interface {
ClaimOutbox(context.Context, string, time.Duration) (TaskOutboxEntry, bool, error)
AckOutbox(context.Context, TaskOutboxEntry) error
RetryOutbox(context.Context, TaskOutboxEntry, time.Time) error
}
TaskOutboxStore 只负责租约投递。写入必须由宿主在原业务事务/同文档更新完成,不能分开双写。 Claim 只取未交付且到期可用的记录;Ack/Retry 必须按 Revision、Owner 和有效租约 CAS。 未投递过期记录必须保留为阻塞事实供运维处理,不能删除或重做原业务。
type TaskPage ¶
type TaskPage struct {
Tasks []TaskInfo `json:"tasks"`
Next string `json:"next,omitempty"`
Waits []TaskWaitRecord `json:"waits,omitempty"`
WaitNext string `json:"wait_next,omitempty"`
}
TaskPage 显式提供游标,避免账本增长后把部分元数据当成完整清单。
type TaskQoSConfig ¶
type TaskQoSConfig struct{ Policies []TaskResourcePolicy }
TaskQoSConfig 只提供可信资源策略,具体业务编排交由 AI。
type TaskReadiness ¶
type TaskReadiness struct {
Mode string `json:"mode"`
ProtocolVersion int `json:"protocol_version"`
Components map[string]string `json:"components"`
}
TaskReadiness 返回实际装配结果;持久模式缺少任何权威存储时拒绝启动。
func CheckTaskReadiness ¶
func CheckTaskReadiness(ctx context.Context, c TaskConfig) (TaskReadiness, error)
CheckTaskReadiness 只检查装配和存储,不启动维护、投递或业务执行 goroutine。
type TaskRecord ¶
type TaskRecord struct {
StorageVersion int `bson:"storageVersion,omitempty" json:"storage_version,omitempty"`
Epoch string `bson:"epoch,omitempty"`
ID string `bson:"_id"`
Scope string `bson:"scope"`
Key string `bson:"key"`
Digest string `bson:"digest"`
Turn string `bson:"turn"`
Args []byte `bson:"args,omitempty"`
Invocation string `bson:"invocation,omitempty"`
Effect string `bson:"effect"`
Info TaskInfo `bson:"info"`
Revision int64 `bson:"revision"`
Owner string `bson:"owner"`
Started bool `bson:"started"`
CancelRequested bool `bson:"cancelRequested"`
CreatedAt time.Time `bson:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt"`
Deadline time.Time `bson:"deadline"`
LeaseUntil time.Time `bson:"leaseUntil"`
ResultExpiresAt time.Time `bson:"resultExpiresAt,omitempty"`
ExpiresAt time.Time `bson:"expiresAt,omitempty"`
}
TaskRecord 是持久调用账本;参数只存于宿主受控存储,不向浏览器或任务列表透传。 Revision 与 Owner/LeaseUntil 形成 fencing,失去租约的执行器不能覆盖恢复后的状态。
type TaskResourceGrant ¶
type TaskResourceGrant struct {
TaskResourceRequest
Fence int64 `json:"fence" bson:"fence"`
}
TaskResourceGrant 将本次租约的条件版本与 fencing 交给实际提供者校验。
func TaskResourceGrants ¶
func TaskResourceGrants(ctx context.Context) []TaskResourceGrant
TaskResourceGrants 返回本次执行的租约与单调 fencing;真正的陈旧写入防护需要提供者校验。
type TaskResourcePolicy ¶
type TaskResourcePolicy struct {
Key string `json:"key" yaml:"key"`
RatePerSecond float64 `json:"rate_per_second" yaml:"rate_per_second"`
Burst int `json:"burst" yaml:"burst"`
Version int64 `json:"version" yaml:"version"`
}
TaskResourcePolicy 使用宿主规范化的资源键,令牌桶算法复用 x/time/rate。 默认不配置策略,不限速。RatePerSecond/Burst 同为 0 是显式关闭策略。 Version 必须随启停或参数变更单调递增;旧实例不能以旧配置扩大新策略。
type TaskResourceRequest ¶
type TaskResourceRequest struct {
Key string `json:"key" bson:"key"`
IfVersion string `json:"if_version,omitempty" bson:"ifVersion,omitempty"`
}
TaskResourceRequest 是工具声明的协作资源;IfVersion 由实际提供者核验,运行时不伪造业务版本。
type TaskResultInput ¶
type TaskResultInput struct {
ID string `json:"id"`
SHA256 string `json:"sha256"`
Pointer string `json:"pointer,omitempty"`
}
TaskResultInput 固定不可变结果及可选 RFC6901 JSON Pointer,不接受其他作用域或文件路径。
type TaskResultInputReader ¶
type TaskResultInputReader func(context.Context, TaskResultInput) ([]byte, error)
TaskResultInputReader 由当前可信运行时提供,不能用模型参数替换权限边界。
type TaskResultPage ¶
type TaskResultPage struct {
Result TaskResultRef `json:"result"`
Offset int64 `json:"offset"`
NextOffset int64 `json:"next_offset"`
EOF bool `json:"eof"`
Text string `json:"text,omitempty"`
Data string `json:"data,omitempty"`
}
TaskResultPage 使用正文的字节偏移,NextOffset 可直接用于下一段。UTF-8 分段不截断字符。
type TaskResultRecord ¶
type TaskResultRecord struct {
Scope string `bson:"scope"`
TaskID string `bson:"taskID"`
Digest string `bson:"digest"`
State string `bson:"state"`
Error string `bson:"error,omitempty"`
Failure *TaskFailure `bson:"failure,omitempty"`
Started bool `bson:"started"`
Size int64 `bson:"size"`
SHA256 string `bson:"sha256"`
Encoding string `bson:"encoding"`
Availability string `bson:"availability"`
CreatedAt time.Time `bson:"createdAt"`
ExpiresAt time.Time `bson:"expiresAt"`
LedgerExpiresAt time.Time `bson:"ledgerExpiresAt"`
Body []byte `bson:"-"`
}
TaskResultRecord 是不可变的最终执行事实与正文提交。Body 只用于写入,元数据查询不得返回它。 Store 仅在正文全部持久后发布此记录;正文过期后仍保留事实,不能靠重放恢复结果。
type TaskResultRef ¶
type TaskResultRef struct {
ID string `json:"id" bson:"id"`
Size int64 `json:"size_bytes" bson:"size"`
SHA256 string `json:"sha256" bson:"sha256"`
Encoding string `json:"encoding" bson:"encoding"`
Availability string `json:"availability" bson:"availability"`
ExpiresAt time.Time `json:"expires_at" bson:"expiresAt"`
}
TaskResultRef 将执行事实与模型传输额度分离,句柄始终由当前授权作用域解析。
type TaskResultStore ¶
type TaskResultStore interface {
PutResult(context.Context, TaskResultRecord) (TaskResultRecord, error)
GetResult(context.Context, string, string) (TaskResultRecord, error)
ReadResult(context.Context, string, string, int64, int) ([]byte, error)
CollectResults(context.Context, time.Time) error
}
TaskResultStore 必须在(scope,taskID)内原子发布不可变结果,重复补写相同事实须成功。 GetResult 在正文过期后仍返回元数据;ReadResult 必须独立核对正文期限和范围。
type TaskRuntime ¶
type TaskRuntime struct {
// contains filtered or unexported fields
}
TaskRuntime 只保留在途 goroutine;已完成调用由账本查询,不再占用执行容量。 进程失去的 goroutine 不会重建:过期租约经 CAS 转为取消/未知,禁止盲目重放。
func NewTaskRuntime ¶
func NewTaskRuntime(ctx context.Context, cfg TaskConfig) (*TaskRuntime, error)
NewTaskRuntime 默认使用内存账本;宿主接入持久 TaskStore 后具备跨实例/重启记录恢复能力。
func (*TaskRuntime) ArchiveEventSource ¶
func (r *TaskRuntime) ArchiveEventSource(ctx context.Context, scope, id string, expected int64) (TaskEventSource, error)
ArchiveEventSource 在所有活跃等待均已交付/退出后回收关闭源正文,保留序号和去重指纹。
func (*TaskRuntime) AwaitResult ¶
func (r *TaskRuntime) AwaitResult(ctx context.Context, scope, id string, allowed map[string]bool) (TaskInfo, error)
AwaitResult 统一提供带取消和错误的等待;远端存储失败必须返回错误,不能只遗留一个永不关闭的 channel。
func (*TaskRuntime) BindContext ¶
BindContext 为新的明确指令冻结当前停止代次。存储期限独立于返回上下文,不能缩短整轮生命周期。
func (*TaskRuntime) BindWaitContext ¶
func (r *TaskRuntime) BindWaitContext(ctx context.Context, scope, id string) (context.Context, error)
BindWaitContext 恢复的是原等待代次,不是新的用户指令;停止后的旧事件不能借新代次重新取得执行资格。
func (*TaskRuntime) Budget ¶
func (r *TaskRuntime) Budget(ctx context.Context) ([]TaskBudgetView, error)
Budget 查询可信宿主绑定的共享额度,不向模型开放其他租户的资源选择参数。
func (*TaskRuntime) Call ¶
func (r *TaskRuntime) Call(ctx context.Context, scope, turn, key string, tool Tool, args json.RawMessage) (string, error)
Call 让同步与后台调用共用账本。已完成/未知的同一调用只返回原事实,绝不再调 Handler。
func (*TaskRuntime) CancelAll ¶
func (r *TaskRuntime) CancelAll() error
CancelAll 先立即停止本地工作,再持久取消本作用域的活跃调用和等待;远程执行器经心跳响应。
func (*TaskRuntime) CancelWaits ¶
func (r *TaskRuntime) CancelWaits(ctx context.Context, scope string) error
CancelWaits 逐项重读并 CAS,不能把并发续租导致的版本冲突当成取消成功。
func (*TaskRuntime) ChargeGoal ¶
func (r *TaskRuntime) ChargeGoal(ctx context.Context, amount TaskGoalCharge) error
ChargeGoal 在实际调用前原子扣减;存储失败或无可靠报价时拒绝受约束的调用。 预留不自动退款:超时、供应商内部重试和进程退出可能已经产生费用。
func (*TaskRuntime) CheckExecutionEpoch ¶
func (r *TaskRuntime) CheckExecutionEpoch(ctx context.Context, scope, epoch string) error
CheckExecutionEpoch 查询当前权威代次;停止后的旧授权不能在新轮次取得新的执行资格。
func (*TaskRuntime) ClaimWake ¶
func (r *TaskRuntime) ClaimWake(ctx context.Context, scope, consumer string) (*TaskWaitRecord, error)
ClaimWake 只按 AI 保存的条件匹配。CAS 与可续租交付防止多个实例重复入队。 不查询任何业务特定字段,也不自动重试原 Handler。
func (*TaskRuntime) Collect ¶
func (r *TaskRuntime) Collect(ctx context.Context) error
Collect 先将失联调用转成可核对的终态,再执行宿主存储的分层保留策略。
func (*TaskRuntime) Completed ¶
func (r *TaskRuntime) Completed() <-chan TaskInfo
Completed 是有界本地通知提示;可靠状态/唤醒以持久账本为准,慢消费者不会阻塞工作收尾。
func (*TaskRuntime) ContinueGoal ¶
func (r *TaskRuntime) ContinueGoal(ctx context.Context, scope string, source context.Context) (context.Context, error)
ContinueGoal 让显式批准/总结继承原目标账户,同时保留当前消息的停止代次与追踪。 source 必须是宿主保存的可信上下文;不能接受模型传入预算 ID。
func (*TaskRuntime) CooldownResource ¶
CooldownResource 接收可信提供者的 Retry-After,不能由模型创建任意资源键。
func (*TaskRuntime) DeleteContext ¶
func (r *TaskRuntime) DeleteContext(ctx context.Context, scope, turn, key, id string, expected int64) (TaskContextRecord, error)
DeleteContext 写入墓碑,原文不会继续从读取/目录返回,也不会因此取消已执行的业务。
func (*TaskRuntime) Done ¶
func (r *TaskRuntime) Done(scope, id string, allowed map[string]bool) (<-chan struct{}, error)
Done 本地句柄在执行器退出后关闭,远程句柄在观察到账本终态后关闭,不重建执行工作。 本地退出不保证最终回执已持久成功;需要可核对终态/观察错误时使用带 context 的 Wait。
func (*TaskRuntime) Drain ¶
func (r *TaskRuntime) Drain(ctx context.Context) error
Drain 拒绝新的执行接纳,等待已受理工作真实收尾;不提升停止代次,不重放工作。
func (*TaskRuntime) EndTurn ¶
func (r *TaskRuntime) EndTurn(scope, turn string, keep bool)
EndTurn 正常结束仅解除轮次绑定;错误/停止取消原轮在途调用,不删除账本。
func (*TaskRuntime) EventPublisher ¶
func (r *TaskRuntime) EventPublisher() TaskEventPublisher
EventPublisher返回宿主可调用的发布器,不向模型传递任何凭据或发布工具。
func (*TaskRuntime) EventSources ¶
func (r *TaskRuntime) EventSources(ctx context.Context, scope, after string, limit int) ([]TaskEventSource, string, error)
EventSources分页列当前授权作用域的源,模型不能扩大范围。
func (*TaskRuntime) ExecutionEpoch ¶
ExecutionEpoch 返回当前作用域的执行代次,供持久授权等受控能力绑定停止屏障。
func (*TaskRuntime) GoalBudget ¶
func (r *TaskRuntime) GoalBudget(ctx context.Context) (TaskGoalView, error)
GoalBudget 查询同一可信目标的累计保守预留,恢复不会产生新的额度。
func (*TaskRuntime) ListContexts ¶
func (r *TaskRuntime) ListContexts(ctx context.Context, scope, after string, limit int) (TaskContextPage, error)
ListContexts 返回轻量目录及宿主额度快照,不把全部长期正文塞回模型上下文。
func (*TaskRuntime) ListWaitPage ¶
func (r *TaskRuntime) ListWaitPage(ctx context.Context, scope, after string, limit int) ([]TaskWaitRecord, string, error)
ListWaitPage 只返回当前作用域的活跃等待,独立游标不混淆调用记录与事件登记。
func (*TaskRuntime) ObservationStats ¶
func (r *TaskRuntime) ObservationStats(ctx context.Context, scope string, q TaskObservationQuery) (TaskObservationSummary, error)
ObservationStats 只汇总最多1024条返回记录,明确报告截断和后续游标。
func (*TaskRuntime) Observations ¶
func (r *TaskRuntime) Observations(ctx context.Context, scope string, q TaskObservationQuery) (TaskObservationPage, error)
Observations 查询当前可信作用域的持久追踪快照,不暴露其他租户查询参数。
func (*TaskRuntime) OpenResultInput ¶
func (r *TaskRuntime) OpenResultInput(ctx context.Context, scope string, ref TaskResultInput, allowed map[string]bool) (io.ReadCloser, error)
OpenResultInput 以受控范围流读取不可变结果,二进制也可使用;到 EOF 时校验完整摘要。 提前关闭只读取所需范围,存储适配器仍须核验块摘要;不访问宿主文件系统。
func (*TaskRuntime) PollInterval ¶
func (r *TaskRuntime) PollInterval() time.Duration
PollInterval 仅控制状态检查,不产生模型轮询调用。
func (*TaskRuntime) ReadContext ¶
func (r *TaskRuntime) ReadContext(ctx context.Context, scope, id string) (TaskContextRecord, error)
ReadContext 读取当前作用域的显式工作事实;它不赋予原引用资源的读取或执行授权。
func (*TaskRuntime) ReadEvents ¶
func (r *TaskRuntime) ReadEvents(ctx context.Context, scope, id string, after uint64, limit int) (TaskEventPage, error)
ReadEvents仅读取授权源的有序事实;cursor不接受尚未发生的未来序号。
func (*TaskRuntime) ReadResult ¶
func (r *TaskRuntime) ReadResult(ctx context.Context, scope, id string, offset int64, limit int, allowed map[string]bool) (TaskResultPage, error)
ReadResult 读取当前仍获准工具的完整结果片段,不接受模型指定新的存储路径或作用域。
func (*TaskRuntime) Readiness ¶
func (r *TaskRuntime) Readiness(ctx context.Context) (TaskReadiness, error)
Readiness 查询已注入适配器健康状态;默认不把数据库地址或驱动错误返回给调用者。
func (*TaskRuntime) Reconcile ¶
func (r *TaskRuntime) Reconcile(ctx context.Context, scope, id string, tools []Tool) (TaskInfo, error)
Reconcile 使用当前获准的只读回执恢复钩子核对原调用;新增证据,不篡改原执行事实或重放 Handler。
func (*TaskRuntime) RecordObservation ¶
func (r *TaskRuntime) RecordObservation(ctx context.Context, scope string, row TaskObservation) error
RecordObservation 接受白名单元数据并有界异步提交;旧代次收尾也应记录,因此不执行新的权限/业务准入。
func (*TaskRuntime) ResolveResultInput ¶
func (r *TaskRuntime) ResolveResultInput(ctx context.Context, scope string, ref TaskResultInput, allowed map[string]bool) ([]byte, error)
ResolveResultInput 先核对当前源权限与摘要,再复用受控分段读取,不重新执行源工具。
func (*TaskRuntime) ResultInputContext ¶
func (r *TaskRuntime) ResultInputContext(ctx context.Context, scope string, tools []Tool) context.Context
ResultInputContext 绑定本轮仍可访问的源工具集合;调用者必须来自可信宿主。
func (*TaskRuntime) SaveContext ¶
func (r *TaskRuntime) SaveContext(ctx context.Context, scope, turn, key, id string, expected int64, doc TaskContextDocument) (TaskContextRecord, error)
SaveContext 保存 AI 明确维护的当前版本;冲突要求先读取再决定合并,不自动覆盖。
func (*TaskRuntime) SchedulingBudget ¶
func (r *TaskRuntime) SchedulingBudget(ctx context.Context) ([]TaskSchedulingView, error)
SchedulingBudget 让 AI 根据实际限流和冷却事实选择等待或其他工作,不替它安排业务。
func (*TaskRuntime) ScopeStatus ¶
func (r *TaskRuntime) ScopeStatus(ctx context.Context) (TaskScopeStatus, error)
ScopeStatus 只读检查与 CancelAll 相同的可信作用域,不创建代次或恢复执行。 计数只包含当前代次;旧任务即使尚未完成取消收尾,也不能恢复已停止的操作入口。
func (*TaskRuntime) Shutdown ¶
func (r *TaskRuntime) Shutdown(ctx context.Context) error
Shutdown 有界取消并等待;超时只报告仍未退出,不能把忽略取消的执行者伪称已停止。
func (*TaskRuntime) Start ¶
func (r *TaskRuntime) Start(ctx context.Context, scope, turn, key string, tool Tool, args json.RawMessage) (TaskInfo, error)
Start 在创建 goroutine 前原子保存调用键与冻结参数;重复调用只读原记录。
func (*TaskRuntime) Status ¶
func (r *TaskRuntime) Status() TaskRuntimeStatus
Status 是不触发维护或业务调用的瞬时诊断快照。
func (*TaskRuntime) Suspend ¶
func (r *TaskRuntime) Suspend(ctx context.Context, scope, turn, key string, spec TaskWaitSpec, allowed map[string]bool) (TaskWaitRecord, error)
Suspend 保存 AI 主动声明的等待条件。该记录本身不包含新的业务授权。
func (*TaskRuntime) TraceContext ¶
TraceContext 为同一公开规划/续办保留追踪身份;它只关联记录,不赋予执行权限。
func (*TaskRuntime) UpdateWake ¶
func (r *TaskRuntime) UpdateWake(ctx context.Context, scope, id, consumer, action string) error
UpdateWake 对交付租约做 CAS;只有持有者可续租/确认。失败重投仍使用同一个 RequestID。
func (*TaskRuntime) UseContext ¶
UseContext 保留已经受理的代次并验证它仍有效;只有未绑定的可信调用才取得当前代次。 旧排队消息或后台续办不能通过出队时重新绑定,洗成停止之后的新指令。
func (*TaskRuntime) UseTurnGoal ¶
UseTurnGoal 持久绑定可信 InvocationScope,原生 checkpoint 恢复及宿主重试仍使用原账户。 新的用户请求须由宿主提供新的 InvocationScope;AI 不能通过工具调用指定它。
func (*TaskRuntime) Wait ¶
func (r *TaskRuntime) Wait(ctx context.Context, scope string, ids []string, allowed map[string]bool, timeout time.Duration, all bool) ([]TaskInfo, error)
Wait 通过本地事件与跨实例查询唤醒;等待超时不取消原调用。
func (*TaskRuntime) WatchContext ¶
func (r *TaskRuntime) WatchContext(ctx context.Context, scope string) (context.Context, func(), error)
WatchContext 将整轮推理绑定到停止代次,覆盖尚未调用工具的规划和排队后的执行。 观察只查询控制记录,不调用模型;存储不可确认时停止旧消费者,调用方须在收尾调用返回的 release。
type TaskRuntimeStatus ¶
type TaskRuntimeStatus struct {
Draining bool `json:"draining"`
Active int `json:"local_active"`
Admitting int `json:"local_admitting"`
MaxActive int `json:"max_active"`
MaxConcurrent int `json:"max_concurrent"`
CallbackDropped uint64 `json:"callback_dropped"`
}
TaskRuntimeStatus 只包含本实例的容量和通知损失;共享权威状态仍以持久存储为准。
type TaskSchedulingView ¶
type TaskSchedulingView struct {
Key string `json:"key"`
CapacityVersion int64 `json:"capacity_version"`
RateVersion int64 `json:"rate_version"`
RatePerSecond float64 `json:"rate_per_second"`
Burst int `json:"burst"`
CooldownUntil time.Time `json:"cooldown_until,omitempty"`
}
TaskSchedulingView 是本身份可见资源的有效策略快照,不暴露其他任务、账户或租约。
type TaskScopeStatus ¶
TaskScopeStatus 是当前运行时可停止范围的账本快照,不返回参数、结果或外部作用域标识。
type TaskStore ¶
type TaskStore interface {
CreateTask(context.Context, TaskRecord) (TaskRecord, bool, error)
GetTask(context.Context, string, string) (TaskRecord, error)
FindTask(context.Context, string, string) (TaskRecord, error)
ReplaceTask(context.Context, TaskRecord, int64) (bool, error)
ListTasks(context.Context, string, TaskScan) ([]TaskRecord, error)
GetWait(context.Context, string, string) (TaskWaitRecord, error)
FindWait(context.Context, string, string) (TaskWaitRecord, error)
CreateWait(context.Context, TaskWaitRecord) (TaskWaitRecord, bool, error)
ReplaceWait(context.Context, TaskWaitRecord, int64) (bool, error)
ListWaits(context.Context, string, TaskScan) ([]TaskWaitRecord, error)
Collect(context.Context, time.Time) error
}
TaskStore 的 Create 必须原子去重(scope,key),Replace 必须 CAS;List 按 ID 排序分页。 空 scope 仅用于宿主绑定命名空间内的维护,不允许模型直接指定。 Collect 只清理终态:先清结果/参数保留幂等记录,账本保留期之后才允许删除。
type TaskStoreHealth ¶
TaskStoreHealth 由适配器执行轻量就绪检查,不能创建业务记录或隐式迁移。
type TaskWaitRecord ¶
type TaskWaitRecord struct {
// TraceParent/TraceState 只保存 W3C 追踪头,不保存 baggage 或业务上下文。
TraceParent string `bson:"traceparent,omitempty" json:"-"`
TraceState string `bson:"tracestate,omitempty" json:"-"`
StorageVersion int `bson:"storageVersion,omitempty" json:"storage_version,omitempty"`
Goal TaskGoalBinding `bson:"goal,omitempty" json:"-"`
ContextMatches []TaskContextMatch `bson:"contextMatches,omitempty" json:"context_matches,omitempty"`
TraceID string `bson:"traceID,omitempty" json:"trace_id,omitempty"`
EventMatches []TaskEventMatch `bson:"eventMatches,omitempty" json:"event_matches,omitempty"`
Epoch string `bson:"epoch,omitempty" json:"-"`
Attempts int `bson:"attempts" json:"-"`
Depth int `bson:"depth" json:"-"`
ID string `bson:"_id" json:"id"`
Scope string `bson:"scope" json:"-"`
Key string `bson:"key" json:"-"`
Digest string `bson:"digest" json:"-"`
Turn string `bson:"turn" json:"-"`
Spec TaskWaitSpec `bson:"spec" json:"condition"`
State string `bson:"state" json:"state"`
Reason string `bson:"reason,omitempty" json:"reason,omitempty"`
Revision int64 `bson:"revision" json:"-"`
Owner string `bson:"owner" json:"-"`
LeaseUntil time.Time `bson:"leaseUntil" json:"-"`
RetryAt time.Time `bson:"retryAt" json:"-"`
CreatedAt time.Time `bson:"createdAt" json:"-"`
ExpiresAt time.Time `bson:"expiresAt" json:"-"`
}
TaskWaitRecord 保存条件、交付租约与处理状态;delivered 不表示原业务全部完成。
type TaskWaitSpec ¶
type TaskWaitSpec struct {
Contexts []TaskContextVersion `json:"contexts,omitempty" bson:"contexts,omitempty"`
Events []TaskEventCondition `json:"events,omitempty" bson:"events,omitempty"`
Timeout time.Duration `json:"-" bson:"timeout"`
IDs []string `json:"ids" bson:"ids"`
All bool `json:"all" bson:"all"`
Deadline time.Time `json:"deadline" bson:"deadline"`
Checkpoint string `json:"checkpoint" bson:"checkpoint"`
}
TaskWaitSpec 只保存 AI 选择的等待条件和工作上下文,不保存接口专用后续步骤。
type TaskWebhook ¶
type TaskWebhook struct {
Publisher TaskEventPublisher
Scope, SourceID, EventType string
Verify func(context.Context, *http.Request, []byte) error
}
TaskWebhook 是默认未挂载的可信输入适配;作用域/源/事件类型及验签实现均由宿主固定。 原子事件键/指纹兼作 durable inbox,只有 Publish 确认持久后才返回 202。
func (TaskWebhook) ServeHTTP ¶
func (h TaskWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request)
type TextCompaction ¶
TextCompaction is display-independent, tool-free context compression. Hosts authorize and bill the owning turn before invoking it, recheck authorization for every summary request, and persist Summary/Removed with their native conversation generation. Summaries are untrusted context, never authority.
func CompactTextHistory ¶
func CompactTextHistory(ctx context.Context, summary string, history []Message, summarize TextSummarizer) (TextCompaction, error)
type Tool ¶
type Tool struct {
Name string
// Title 是可信工具定义提供的简短展示名称,可由宿主按界面语言本地化;不能从模型参数推断。
// Name 仍是协议标识,Title 不参与执行授权、去重或业务编排。
Title string
// ResultKind 只选择共享的公开结果投影,不能公开任意 Handler 正文或改变工具完成语义。
ResultKind ToolResultKind
Description string
// Contract 是宿主声明的能力语义,参与持久会话与调用身份绑定。
Contract ToolContract
// ResolveResources 从可信实现计算资源身份,不能由模型指定任意锁名。
ResolveResources func(context.Context, json.RawMessage) ([]TaskResourceRequest, error)
// Maturity is explicit governance metadata. The zero value is stable;
// experimental tools remain usable but are surfaced separately in the
// capability catalog so operators can review adoption and failures.
Maturity ToolMaturity
// Domain 是稳定的能力领域标识(people/work/workers/...),供能力检索、
// 展示和审计使用;外部工具未声明时归入 extension。
Domain string
// Effect 描述工具的外部影响,供能力检索、审计和动作证据判断使用。
// 未声明的第三方工具按 unknown 处理。
Effect string
// LoadMode separates authorization from cognitive exposure. Authorized tools
// remain executable, while only immediate tools and turn-relevant deferred
// tools expose their full schema to the model.
LoadMode ToolLoadMode
// Completion describes what a successful handler return means. Most tools
// complete synchronously; worker and workflow dispatchers only accept durable
// asynchronous work and must not be presented as already finished.
Completion ToolCompletion
// RequiredAction 是宿主解释的主动权限标识;runtime 不授予任何权限。
// 外部工具应显式声明,空值的策略由宿主决定。
RequiredAction string
// ResolvePermissionTarget derives the canonical capability target from one
// invocation. It lets the common authorization wrapper enforce resource
// scopes (for example one Telegram group) without teaching it business
// argument names. Nil means the handler owns any target-level check.
ResolvePermissionTarget func(context.Context, json.RawMessage) (string, error)
GroupSensitive bool // true 表示不得暴露给群共享会话
// ApprovalRequired marks a destructive capability for the host's approval
// wrapper. Runtime alone does not verify approvals; hosts must gate execution.
// ScopeTargets 是宿主明确允许范围授权的资源选择字段(RFC6901);空值保持单项确认。
// 只声明资源身份字段,不能声明操作模式、修改值或业务版本检查字段。
ScopeTargets []string
ApprovalRequired bool
// InputSchema 是 JSON Schema(object 类型)。
InputSchema map[string]any
// NormalizeInput applies the same schema-aware normalization used by the
// handler. Agent runtimes use it only to derive stable per-turn invocation
// identities; nil means canonical JSON is sufficient.
NormalizeInput func(json.RawMessage) json.RawMessage
// RecoverResult performs a read-only reconstruction after the durable
// invocation boundary exists but its exact result was not persisted. It is
// reserved for handlers whose domain transaction stores an invocation-scoped
// recovery record; ordinary write tools must leave it nil.
RecoverResult func(ctx context.Context, args json.RawMessage) (result string, recovered bool, err error)
// ResultPersisted runs after the durable invocation receipt contains the
// exact result. It may erase short-lived recovery plaintext; failures do not
// invalidate the already durable tool result.
ResultPersisted func(ctx context.Context, args json.RawMessage, result string) error
// Handler 执行工具并返回给模型的文本结果。
// 业务错误(权限不足、目标不存在)应返回 (提示文本, nil) 让模型自行转述;
// 只有系统性故障才返回 error。
Handler func(ctx context.Context, args json.RawMessage) (string, error)
}
Tool 是领域能力暴露给 AI 的最小单元。
type ToolCompletion ¶
type ToolCompletion string
ToolCompletion describes the lifecycle represented by a successful tool handler return. It is metadata about the operation, not an agent completion protocol.
const ( ToolCompletionImmediate ToolCompletion = "" ToolCompletionAsynchronous ToolCompletion = "asynchronous" )
type ToolContract ¶
type ToolContract struct {
Version string `json:"version,omitempty"`
IdempotencyScope string `json:"idempotency_scope,omitempty"`
Cancellation string `json:"cancellation,omitempty"`
OutputSchema map[string]any `json:"output_schema,omitempty"`
ResultInputs bool `json:"result_inputs,omitempty"`
ResourceFencing bool `json:"resource_fencing,omitempty"`
}
ToolContract 仅声明能力,不替 AI 选择并行、等待、重试或业务步骤。 零值表示未承诺;声明幂等不等于运行时获得自动重放许可。
type ToolExposure ¶
type ToolExposure struct {
AgentIterations int
ModelCalls int
ContextCompactions int // Eino 原生摘要实际执行次数,不把普通模型请求计为压缩。
PeakToolCount int
PeakSchemaChars int
PeakTools []string
}
ToolExposure records what the model actually saw after framework middleware applied deferred-tool selection. It intentionally differs from the full authorized catalog supplied in TurnRequest.Tools.
type ToolLoadMode ¶
type ToolLoadMode string
ToolLoadMode controls when an authorized tool schema enters the model's working set. The zero value is deferred so new tools remain scalable by default; immediate is reserved for a very small, generic capability kernel.
const ( ToolLoadDeferred ToolLoadMode = "" ToolLoadImmediate ToolLoadMode = "immediate" )
type ToolMaturity ¶
type ToolMaturity string
ToolMaturity describes operational confidence, not authorization. Keeping it on the tool definition avoids inferring governance policy from naming.
const ( ToolMaturityStable ToolMaturity = "stable" ToolMaturityExperimental ToolMaturity = "experimental" )
type ToolMetadata ¶
type ToolMetadata struct {
Name string
Title string
ResultKind ToolResultKind
}
ToolMetadata 只描述公开展示,不携带 handler、Schema、参数或任何调用权限。
func ResolveToolMetadata ¶
func ResolveToolMetadata(tool Tool, provider any) ToolMetadata
ResolveToolMetadata 优先使用调用方本次已绑定的定义,再查询引擎补充元数据;不会扩大工具集合。
type ToolMetadataProvider ¶
type ToolMetadataProvider interface {
LookupToolMetadata(name string) (ToolMetadata, bool)
}
ToolMetadataProvider 允许引擎公开其内部工具的声明式标题;查到标题不意味着该工具本轮可执行。 普通宿主工具仍以本轮已授权的 Tool 定义为准,历史补齐也不得据此恢复授权。
type ToolResultKind ¶
type ToolResultKind string
ToolResultKind 是可信定义显式选择的公开结果结构;零值不公开原始 Handler 返回值。
const ( ToolResultTask ToolResultKind = "task" ToolResultTaskList ToolResultKind = "task_list" )
type TurnMode ¶
type TurnMode string
TurnMode defines the orchestration contract for a model call. It is selected by the call site, never inferred from user wording.
const ( // TurnModeDeep enables the full autonomous agent loop. It is also the default // for the zero value so product conversations cannot silently lose capability. TurnModeDeep TurnMode = "deep" // TurnModeOneShot performs exactly one tool-free model generation for bounded // internal transformations such as extraction, summarization, and rendering. TurnModeOneShot TurnMode = "one_shot" )
type TurnRequest ¶
type TurnRequest struct {
// RequireApproval enables native suspension for ApprovalRequired tools.
// The host must persist PendingApproval and authenticate decisions; this is
// not business authorization. Handlers must still enforce live permission.
RequireApproval bool
// Resume is trusted host state, never decoded directly from browser input.
Resume *ResumeRequest
// Mode selects the orchestration profile. Empty defaults to TurnModeDeep.
Mode TurnMode
// SessionID 是 host 侧会话 ID(落库主键),引擎可用它做日志关联。
SessionID string
// InvocationScope identifies one logical Agent execution for side-effect
// idempotency. Retries of the same execution must reuse it; distinct user
// turns or automation occurrences must not. Empty falls back to SessionID.
InvocationScope string
// EngineSession 是引擎侧持久会话标识。空表示由引擎创建;调用方应保存
// TurnResult 返回值并在下一轮传回。
EngineSession string
// DisableSession disables engine-managed history for channels whose context
// can receive out-of-band messages (for example passive group listening).
DisableSession bool
// SessionCapability identifies the stable permission-scoped capability set.
// It may be broader than Tools for a transient read-only turn, preventing
// unnecessary session rotation while handlers still enforce the narrower set.
SessionCapability string
// System 系统提示,由 chat 编排器组装(身份、角色、当前时间等)。
System string
// History 本会话既往文本消息(不含本轮),按时间升序。
History []Message
// UserText 本轮用户输入。
UserText string
// Model 是本轮使用的模型名覆盖;空值表示使用引擎默认配置。
Model string
// Tasks 是宿主会话持有的通用后台执行器;nil 不暴露后台调度工具。
// 不能由浏览器参数构造,不与其他用户或权限会话共用。
Tasks *TaskRuntime
// AllowTaskSuspend 由具备恢复事件消费器的宿主声明;不向无唤醒实现的调用方许诺自动继续。
AllowTaskSuspend bool
// WakeID 是可信事件的稳定恢复身份,不能从用户 JSON 直接采用。
WakeID string
WakeAdmitted bool
// DisableTools 明确关闭本轮全部工具能力,包括受管控制原语与skills;空业务目录不等于关闭工具。
DisableTools bool
// Tools 本轮可用工具集(已按用户权限裁剪)。
Tools []Tool
// Skills 是已按语义相关性和用户/渠道作用域裁剪的候选执行方法。
// 引擎只暴露元数据,由模型按需加载完整 Content。
Skills []Skill
// OnEvent 可选回调:工具调用与文本产出实时上报(审计/流式)。
// 引擎在任意 goroutine 调用它,实现方需自行保证并发安全。
OnEvent func(Step)
// OnDelta 可选:流式渐进显示回调(eino 流式)。nil = 不流式。传入的是【当前
// 助手消息累积到目前的可显示文本快照】,网关应「替换」显示而非
// 追加;新消息开始时快照重置(短),网关随之刷新。收尾以 TurnResult.Text 为准。
// 与 OnEvent 一样可能在任意 goroutine 调用,实现方自行保证并发安全。
OnDelta func(text string)
// StreamReasoning 为 true 时,OnDelta 会包含模型 ReasoningContent;默认 false,
// 只流式展示最终正文,避免把内部推理暴露给用户。
StreamReasoning bool
// MaxOutputTokens bounds this call independently from the engine default.
// It is primarily used by internal OneShot selectors and extractors.
MaxOutputTokens int
// MaxIterations optionally lowers the DeepAgent lifecycle limit for bounded
// background work. Zero keeps the engine-wide limit; callers cannot raise
// the configured ceiling.
MaxIterations int
// Reasoning controls provider reasoning for this call. Unsupported providers
// keep their normal behavior.
Reasoning ReasoningMode
// JSONOutput asks compatible providers for a JSON object. Callers must still
// validate the decoded structure and all selected identifiers.
JSONOutput bool
}
TurnRequest 一轮对话请求。
type TurnResult ¶
type TurnResult struct {
// Waiting 表示 AI 主动挂起,宿主按持久条件恢复新的受管轮次,不继承写权限。
Waiting *TaskWaitRecord
// PendingApproval means the run is suspended, not successfully completed.
PendingApproval *PendingApproval
// Text 模型最终答复(给用户看的)。
Text string
// EngineSession 引擎侧会话标识;调用方应持久化以便下一轮传回。
EngineSession string
// FinishReason 是底层模型返回的结束原因(如 stop/length/max_tokens)。
FinishReason string
// OutputLikelyTruncated 表示底层模型疑似耗尽输出预算。对思考型模型来说,
// 这常表现为 output tokens 打满,但可见正文只有一两个词。
OutputLikelyTruncated bool
// Steps 本轮完整执行轨迹(含 tool 调用),用于审计。
Steps []Step
Usage Usage
ToolExposure ToolExposure
}
TurnResult 一轮对话结果。
Source Files
¶
- agent.go
- failure.go
- input_references.go
- poll.go
- progress.go
- public_error.go
- task_context.go
- task_context_refs.go
- task_control.go
- task_delivery.go
- task_epoch.go
- task_errors.go
- task_event_lifecycle.go
- task_events.go
- task_goal.go
- task_observation.go
- task_outbox.go
- task_progress.go
- task_progress_notifications.go
- task_qos.go
- task_reconcile.go
- task_result_reader.go
- task_results.go
- task_runtime_protocol.go
- task_scope_status.go
- task_shutdown.go
- task_store.go
- task_turn_context.go
- task_waits.go
- task_webhook.go
- tasks.go
- telemetry.go
- text_compaction.go
- tool_contract.go
- tool_metadata.go
- tool_validation.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package einoengine 用 eino ADK 实现 ai.Engine:直接调模型 API(Claude / OpenAI 兼容), tool 循环在本进程内执行。
|
Package einoengine 用 eino ADK 实现 ai.Engine:直接调模型 API(Claude / OpenAI 兼容), tool 循环在本进程内执行。 |
|
sqlstore
Package sqlstore persists Eino events and opaque checkpoints in PostgreSQL.
|
Package sqlstore persists Eino events and opaque checkpoints in PostgreSQL. |
|
internal
|
|
|
Package mongostore 为 agent 的持久协议提供 Mongo 适配。
|
Package mongostore 为 agent 的持久协议提供 Mongo 适配。 |
|
Package providerstream decodes bounded provider SSE into terminal JSON envelopes.
|
Package providerstream decodes bounded provider SSE into terminal JSON envelopes. |
|
Package storetest 提供持久适配器共用的协议验收,不编排任何业务接口。
|
Package storetest 提供持久适配器共用的协议验收,不编排任何业务接口。 |