Documentation
¶
Overview ¶
Package durable ports the root module of Pi's @earendil-works/pi-durable: the durable conversation, task, and document runtime types, the ID kinds, the errors, the built-in entry kinds, document and task definitions, and the tool-output truncation helpers.
Ports packages/durable/src/index.ts
Go mapping decisions. Each is forced by a Go language mechanic; observable JSON and runtime behavior follow Pi.
- Chord's Context is context.Context and comes first in every signature. A Promise maps to a blocking call that returns (value, error); a rejection is the error.
- JsonValue is any holding strict JSON (nil, bool, float64, string, []any, map[string]any); JsonObject is map[string]any. Chord delta operations are chord/delta Op tuples, and a document Draft[T] is the revocable chord/delta overlay handle (*delta.Object) that records them.
- Branded numeric IDs are distinct named int64 types, so a TaskId does not assign to a ConversationId. TaskId does not carry its result type: Go methods cannot take type parameters, so typed results are recovered at the generic helpers (CreateTask, DecodeTaskRecord).
- packages/durable/src/types.ts and harness/types.ts import each other. Go packages cannot, so the declarations of harness/types.ts that types.ts references (Agent, Settings, RegistrySnapshot, ToolRegistration, Extension, PromptSection, ContextView, ConversationHandle, Submission, SettledTask, AnyTask, and their closure) live here and durable/harness declares the rest.
- Overloaded methods (Tx.doc, Tx.entry, Session.snapshot, createTask, ...) take erased tokens; generic helpers (TxDoc, TxEntry, TxAppendEntry, Snapshot, SnapshotAsOf, CreateTask) restore the value types. Document tokens carry an erased definition over JSON objects; DecodeDoc[T] reads a value or draft snapshot as T.
- Discriminated record unions whose members share fields (TaskState, TaskOutcome, SubmissionRecord, DocumentRecord, DocumentContent, ContextEdit) are one struct with a status or kind discriminant; the Session keeps the member fields consistent. Unions of distinct payloads (StorageWrite, CommitChange) are sealed interfaces.
- Definition-time TypeErrors (an empty entry kind, a non-positive document version) are panics, as package-level definitions cannot return errors.
Index ¶
- Constants
- Variables
- func AddressId(address DocumentAddress) string
- func CheckRecordScope(definition *AnyDocDefinition, record DocumentCreate) error
- func CheckRecordVersion(definition *AnyDocDefinition, record DocumentCreate, version int) error
- func Commit[T any](ctx context.Context, committer Committer, change func(tx Tx) (T, error)) (T, error)
- func CommitChangeType(change CommitChange) string
- func DecodeDoc[T any](value JsonObject) (*T, error)
- func DecodeMessage(data []byte) (ai.Message, error)
- func DecodeMessages(data []byte) ([]ai.Message, error)
- func DecodeUserContent(value JsonValue) (ai.UserContent, error)
- func FormatSize(bytes int) string
- func FromJsonValue[T any](value JsonValue) (T, error)
- func IdFromNumber[I Id](value int64) I
- func Snapshot[T any](ctx context.Context, reader DocumentReader, token DocTokenOf[T], args ...any) (*T, error)
- func SnapshotAsOf[T any](ctx context.Context, reader DocumentReader, token DocTokenOf[T], at EntryId, ...) (*T, error)
- func StorageWriteType(write StorageWrite) string
- func TxRetireDoc[T any](tx Tx, token DocTokenOf[T], args ...any) error
- func Utf8ByteLength(content string) int
- type Agent
- type AnyDocDefinition
- type AnyDocToken
- type AnyTask
- type AnyTaskDefinition
- type AttachedReplicatedState
- type CheckpointInfo
- type CommitChange
- type CommitPublication
- type Committer
- type CommonDocDefinition
- type CompactionEntryData
- type CompactionPolicy
- type CompactionReason
- type ContextEdit
- type ContextEditAction
- type ContextView
- type ConversationAbortOptions
- type ConversationBusy
- type ConversationDocFamilyToken
- type ConversationDocToken
- type ConversationHandle
- type ConversationId
- type ConversationOwner
- type ConversationOwnership
- type ConversationOwnershipKind
- type ConversationParent
- type ConversationQuery
- type ConversationRecord
- type ConversationRetryPolicy
- type ConversationStreamOptions
- type ConversationWrite
- type CreateConversationOptions
- type Cursor
- type DocDefinition
- type DocFamilyDefinition
- type DocFamilyToken
- type DocToken
- type DocTokenOf
- type DocumentAddress
- type DocumentChange
- type DocumentChangeWrite
- type DocumentCommitChange
- type DocumentContent
- type DocumentContentKind
- type DocumentCopyChange
- type DocumentCopySource
- type DocumentCopyWrite
- type DocumentCreate
- type DocumentCreateWrite
- type DocumentFork
- type DocumentHistory
- type DocumentId
- type DocumentObserver
- type DocumentPoint
- type DocumentQuery
- type DocumentReader
- type DocumentRecord
- type DocumentRecordScope
- type DocumentRetireWrite
- type DocumentScope
- type DocumentSemantics
- type DocumentState
- type DocumentWatch
- type Draft
- type Entry
- type EntryAt
- type EntryDraft
- type EntryId
- type EntryQuery
- type EntryRecord
- type EntryWrite
- type ErasedPhaseHandler
- type ErasedRunningTask
- type ErasedTaskRuntime
- type Extension
- type HookRegistration
- type HookRunner
- type Id
- type InputSubmissionDraft
- type JoinPolicy
- type JsonObject
- type JsonValue
- type ModelRef
- type Models
- type Never
- type NextTaskState
- type Op
- type Page
- type PhaseHandler
- type ProgressPolicy
- type PromptInput
- type PromptSection
- type QueueMode
- type ReadAfterWrite
- type RegistrySection
- type RegistrySnapshot
- type RegistryTool
- type ResolvedAddress
- type RewindableConversationDocFamilyToken
- type RewindableConversationDocToken
- type RunningTask
- type Seq
- type Session
- type SessionDocFamilyToken
- type SessionDocToken
- type Settings
- type SettledSubmissionRecord
- type SettledTask
- type Storage
- type StorageRejected
- type StorageWrite
- type StoredDocument
- type Submission
- type SubmissionAbortResult
- type SubmissionCreate
- type SubmissionDraft
- type SubmissionId
- type SubmissionQuery
- type SubmissionRecord
- type SubmissionSettlement
- type SubmissionStatus
- type SubmissionType
- type SubmissionWrite
- type TableCommitChange
- type Task
- type TaskDefinition
- type TaskDocFamilyToken
- type TaskDocToken
- type TaskId
- type TaskOptions
- type TaskOutcome
- type TaskOutcomeError
- type TaskOutcomeStatus
- type TaskOwnership
- type TaskOwnershipKind
- type TaskQuery
- type TaskRecord
- type TaskRuntime
- type TaskState
- type TaskStatus
- type TaskWrite
- type ToolControl
- type ToolDiagnostic
- type ToolDiagnosticSeverity
- type ToolExecutionApi
- type ToolExecutionMode
- type ToolExecutionResult
- type ToolOutputLimits
- type ToolOutputRetain
- type ToolRegistration
- type ToolReplay
- type ToolResultEntryData
- type TruncatedBy
- type TruncationOptions
- type TruncationResult
- type TruncationTotals
- type Tx
- type TypedEntry
- type TypedEntryDraft
- type UserInput
- type WatchEnd
- type WatchEndReason
- type WatchHandle
- type WhenBusy
- type Wrap
Constants ¶
const ( DEFAULT_MAX_LINES = 2000 //nolint:revive // upstream identifier DEFAULT_MAX_BYTES = 50 * 1024 //nolint:revive // upstream identifier )
Variables ¶
var ( // UserEntry is user input: Model is [UserMessage]. Written by submissions. UserEntry = DefineEntry[Never]("pi.user") // AssistantEntry is a provider result with any stop reason: Model is [AssistantMessage]. Written by generation. AssistantEntry = DefineEntry[Never]("pi.assistant") // SystemEntry is a positional prompt and tool change: Model is [SystemMessage] with empty content. SystemEntry = DefineEntry[Never]("pi.system") // ToolResultEntry is a tool result: Model is [ToolResultMessage], whose content ends with the rendered diagnostics // block; Data holds the structured diagnostics, possibly none. Written by tool tasks, and by generation for calls // it did not offer. ToolResultEntry = DefineEntry[ToolResultEntryData]("pi.tool-result") // ResetEntry is the start of a new context: always head "self", with Model absent for a plain reset or // [UserMessage] carrying the handoff text. Written by Conversation.Reset and the handoff tool control. ResetEntry = DefineEntry[Never]("pi.reset") // CompactionEntry is a compaction summary: Model is [UserMessage] with the wrapped summary, Head the first kept // entry. Written by compaction tasks, directly or through a write submission. CompactionEntry = DefineEntry[CompactionEntryData]("pi.compaction") )
var CurrentPoint = DocumentPoint{Current: true}
CurrentPoint selects the current state.
Functions ¶
func AddressId ¶
func AddressId(address DocumentAddress) string
AddressId returns the stable string identity of one logical address: the JSON text of [kind, scope kind, owner or null, key or null].
func CheckRecordScope ¶
func CheckRecordScope(definition *AnyDocDefinition, record DocumentCreate) error
CheckRecordScope rejects typed access whose token disagrees with the persisted scope, history, or fork semantics.
func CheckRecordVersion ¶
func CheckRecordVersion(definition *AnyDocDefinition, record DocumentCreate, version int) error
CheckRecordVersion rejects typed access to a stored version the supplied definition cannot use.
func Commit ¶
func Commit[T any](ctx context.Context, committer Committer, change func(tx Tx) (T, error)) (T, error)
Commit runs change in one commit and returns its typed result.
func CommitChangeType ¶
func CommitChangeType(change CommitChange) string
CommitChangeType returns the upstream `type` discriminator of a change.
func DecodeDoc ¶
func DecodeDoc[T any](value JsonObject) (*T, error)
DecodeDoc decodes a committed JSON document value as T; nil stays nil.
func DecodeMessage ¶
DecodeMessage decodes one JSON message by its role.
func DecodeMessages ¶
DecodeMessages decodes a JSON message array; JSON null stays nil.
func DecodeUserContent ¶
func DecodeUserContent(value JsonValue) (ai.UserContent, error)
DecodeUserContent decodes user message content held as a JSON value: a string or an array of text and image blocks.
func FormatSize ¶
FormatSize formats bytes as a human-readable size.
func FromJsonValue ¶
FromJsonValue returns a detached copy of a JSON value as T. When T holds JSON kinds (JsonValue, JsonObject, []any) the copy is chord.CopyJSON, so a non-JSON or non-finite value fails as strict JSON; otherwise the value is decoded through its JSON encoding.
func IdFromNumber ¶
IdFromNumber applies an ID kind at a trusted numeric allocation or decoding boundary.
func Snapshot ¶
func Snapshot[T any](ctx context.Context, reader DocumentReader, token DocTokenOf[T], args ...any) (*T, error)
Snapshot returns the committed value of a document, or nil when absent. args are the owner ID and family key as for TxDoc.
func SnapshotAsOf ¶
func SnapshotAsOf[T any](ctx context.Context, reader DocumentReader, token DocTokenOf[T], at EntryId, args ...any) (*T, error)
SnapshotAsOf returns the committed value of a rewindable conversation document as of the visible entry at, or nil when absent. args are the conversation ID, then the family key for families.
func StorageWriteType ¶
func StorageWriteType(write StorageWrite) string
StorageWriteType returns the upstream `type` discriminator of a write.
func TxRetireDoc ¶
func TxRetireDoc[T any](tx Tx, token DocTokenOf[T], args ...any) error
TxRetireDoc retires a document; args are the owner ID and family key as for TxDoc, without a seed.
func Utf8ByteLength ¶
Utf8ByteLength returns the UTF-8 byte length of content. Go strings hold UTF-8 (lone UTF-16 surrogates arrive as U+FFFD or as their 3-byte WTF-8 form), so the length is the byte count, as Node's Buffer.byteLength reports it.
Types ¶
type Agent ¶
type Agent struct {
Model *ModelRef
ThinkingLevel ai.ModelThinkingLevel
Extensions []*Extension
// Tools are the tools a request offers, in order.
Tools []*ToolRegistration
// Sections are the extension sections, then instructions when set.
Sections []*PromptSection
Instructions *string
Cwd *string
}
Agent is a conversation's agent resolved against a registry snapshot and the settings.
type AnyDocDefinition ¶
type AnyDocDefinition struct {
DocumentSemantics
Kind string
Version int
Family bool
// Initial returns the initial value; seed is nil for singletons.
Initial func(seed JsonValue) (JsonObject, error)
// Migrate is nil when the definition has no migration.
Migrate func(value JsonObject, fromVersion int) (JsonObject, error)
// CheckpointWhen is nil when the definition has no checkpoint predicate.
CheckpointWhen func(value JsonObject, ops []Op, info CheckpointInfo) (bool, error)
}
AnyDocDefinition is the erased definition shape the Session uses after token resolution. Values are JSON objects.
type AnyDocToken ¶
type AnyDocToken interface {
AnyDefinition() *AnyDocDefinition
}
AnyDocToken is an erased singleton or family token.
type AnyTask ¶
type AnyTask interface {
AnyDefinition() *AnyTaskDefinition
}
AnyTask is an erased executable task definition, whatever its input, phases, and hooks.
type AnyTaskDefinition ¶
type AnyTaskDefinition struct {
Name string
Version int
// Initial decodes a JSON input and returns the JSON first checkpoint.
Initial func(input JsonValue) (JsonValue, error)
// Phases maps every phase name to its erased handler.
Phases map[string]ErasedPhaseHandler
Abort ErasedPhaseHandler
// Migrate is nil when the definition has no migration.
Migrate func(input JsonValue, checkpoint JsonValue, fromVersion int) (JsonValue, JsonValue, error)
// Hooks is the definition's hook declaration, or nil.
Hooks any
}
AnyTaskDefinition is the erased executable task definition stored in the registry.
type AttachedReplicatedState ¶
type AttachedReplicatedState[T any] = *chord.AttachedReplicatedState[T]
AttachedReplicatedState is a synchronously hydrated publication-only Chord state backed by one source attachment.
type CheckpointInfo ¶
type CheckpointInfo struct {
// DeltasSinceBase counts deltas already stored after the newest base, excluding the change being evaluated.
DeltasSinceBase int
}
CheckpointInfo is the stored replay state supplied to a document's checkpoint predicate.
type CommitChange ¶
type CommitChange interface {
// contains filtered or unexported methods
}
CommitChange is a TableCommitChange or a DocumentCommitChange. Change order within a publication is unspecified.
type CommitPublication ¶
type CommitPublication struct {
Seq Seq
Changes []CommitChange
}
CommitPublication holds every immutable change from one successful Session commit.
type Committer ¶
type Committer interface {
Commit(ctx context.Context, change func(tx Tx) (any, error)) (any, error)
}
Committer runs one atomic Session commit: a Session, a Conversation, or a tool's ToolExecutionApi.
type CommonDocDefinition ¶
type CommonDocDefinition[T any] struct { // Kind is the stable persisted kind; part of the public protocol. Kind string // Version is the positive integer version of the stored value shape. Version int // Migrate converts a value stored by an older version; nil when absent. Migrate func(value JsonObject, fromVersion int) (T, error) // CheckpointWhen returns true to store this ordinary change as a complete base instead of a delta; nil when // absent. CheckpointWhen func(value T, ops []Op, info CheckpointInfo) bool }
CommonDocDefinition holds the definition fields shared by singleton documents and document families.
type CompactionEntryData ¶
type CompactionEntryData struct {
Reason CompactionReason `json:"reason"`
}
CompactionEntryData is the data of a CompactionEntry.
type CompactionPolicy ¶
type CompactionPolicy struct {
// Enabled controls threshold and overflow compaction.
Enabled bool `json:"enabled"`
// ReserveTokens is room kept free for the answer: generation blocks to compact above
// contextWindow - reserveTokens.
ReserveTokens int `json:"reserveTokens"`
// KeepRecentTokens is the approximate size of the recent context a summary keeps verbatim.
KeepRecentTokens int `json:"keepRecentTokens"`
// BackgroundTokens starts background compaction this far below the blocking threshold; 0 disables it.
BackgroundTokens int `json:"backgroundTokens"`
}
CompactionPolicy holds the automatic compaction thresholds (spec §8.7); manual compaction ignores Enabled.
type CompactionReason ¶
type CompactionReason string
CompactionReason is why a compaction runs: Compact(), a threshold in generation preparation, or a context overflow.
const ( CompactionManual CompactionReason = "manual" CompactionThreshold CompactionReason = "threshold" CompactionOverflow CompactionReason = "overflow" )
type ContextEdit ¶
type ContextEdit struct {
// Target is the entry whose model messages are omitted or replaced.
Target EntryId `json:"target"`
Action ContextEditAction `json:"action"`
// Messages are contributed instead of the target entry's model messages; replace only.
Messages []ai.Message `json:"messages,omitempty"`
}
ContextEdit is an immutable override of one visible entry's contribution to model context.
func (ContextEdit) MarshalJSON ¶
func (edit ContextEdit) MarshalJSON() ([]byte, error)
MarshalJSON encodes Messages when they are not nil.
func (*ContextEdit) UnmarshalJSON ¶
func (edit *ContextEdit) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes Messages by message role.
type ContextEditAction ¶
type ContextEditAction string
ContextEditAction is "omit" or "replace".
const ( EditOmit ContextEditAction = "omit" EditReplace ContextEditAction = "replace" )
type ContextView ¶
type ContextView struct {
// Head is the newest applicable head marker; nil when none.
Head *EntryRecord
// Entries are the raw active entries: the head marker followed by non-head entries from its head through the
// tail.
Entries []EntryRecord
// Contributions holds, per entry of Entries, its model messages after edits and excluded stop reasons, before
// tool result ordering.
Contributions [][]ai.Message
// Messages is the model context for the next provider request.
Messages []ai.Message
}
ContextView is the raw active transcript and the derived model context.
type ConversationAbortOptions ¶
type ConversationAbortOptions struct {
// Background crosses background boundaries: mark every live task reached ignoring the background flag when the
// abort is admitted, withdraw the queued inputs of every conversation reached, and wait until those tasks are
// terminal and the conversation is ordinarily idle. Background work created afterwards is neither marked nor
// awaited.
Background bool
}
ConversationAbortOptions holds the options of Conversation.Abort.
type ConversationBusy ¶
type ConversationBusy struct {
ConversationId ConversationId
}
ConversationBusy reports that a submission reached a busy conversation and was not admitted.
func NewConversationBusy ¶
func NewConversationBusy(conversationId ConversationId) *ConversationBusy
NewConversationBusy returns the error for a busy conversation.
func (*ConversationBusy) Error ¶
func (e *ConversationBusy) Error() string
type ConversationDocFamilyToken ¶
type ConversationDocFamilyToken[T, I any] = DocFamilyToken[T, I]
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type ConversationDocToken ¶
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type ConversationHandle ¶
type ConversationHandle interface {
Id() ConversationId
Submit(ctx context.Context, submission InputSubmissionDraft) (Submission, error)
// Abort is Conversation.Abort: withdraw queued inputs, abort the ordinary ownership scope, and wait until it is
// idle.
Abort(ctx context.Context, options *ConversationAbortOptions) error
// WaitForIdle returns when the conversation's ordinary ownership scope has no live non-background task.
WaitForIdle(ctx context.Context) error
}
ConversationHandle holds the invocation-bound conversation operations for tasks and tools. It fails after the invocation ends; passive entries are written with ordinary transaction writes instead.
type ConversationId ¶
type ConversationId int64
ConversationId identifies a conversation.
const ROOT_CONVERSATION_ID ConversationId = 1
ROOT_CONVERSATION_ID is the reserved ID of the root conversation.
type ConversationOwner ¶
type ConversationOwner struct {
ConversationId ConversationId `json:"conversationId"`
TaskId TaskId `json:"taskId"`
}
ConversationOwner is the creator edge used for attribution, subtree abort, and subtree idle waits.
type ConversationOwnership ¶
type ConversationOwnership struct {
Kind ConversationOwnershipKind `json:"kind"`
// TaskId is set only for kind "task".
TaskId TaskId `json:"taskId,omitempty"`
}
ConversationOwnership is selected explicitly whenever a conversation is created.
type ConversationOwnershipKind ¶
type ConversationOwnershipKind string
ConversationOwnershipKind is "ownerless" or "task".
const ( ConversationOwnerless ConversationOwnershipKind = "ownerless" ConversationOwnedByTask ConversationOwnershipKind = "task" )
type ConversationParent ¶
type ConversationParent struct {
ConversationId ConversationId `json:"conversationId"`
At EntryId `json:"at"`
}
ConversationParent is the fork source and inclusive parent entry through which history is inherited.
type ConversationQuery ¶
type ConversationQuery struct {
OwnerConversationId *ConversationId
OwnerTaskId *TaskId
}
ConversationQuery holds optional filters for an ordered conversation scan.
type ConversationRecord ¶
type ConversationRecord struct {
Id ConversationId `json:"id"`
Parent *ConversationParent `json:"parent,omitempty"`
Owner *ConversationOwner `json:"owner,omitempty"`
}
ConversationRecord is the immutable identity, history ancestry, and task ownership of a transcript scope.
type ConversationRetryPolicy ¶
type ConversationRetryPolicy struct {
Enabled bool `json:"enabled"`
MaxRetries int `json:"maxRetries"`
BaseDelayMs int `json:"baseDelayMs"`
MaxAgentDelayMs *int `json:"maxAgentDelayMs,omitempty"`
}
ConversationRetryPolicy holds durable generation attempt retries; the JSON shape of pi-ai RetryPolicy.
type ConversationStreamOptions ¶
type ConversationStreamOptions struct {
Transport ai.Transport `json:"transport,omitempty"`
TimeoutMs *int `json:"timeoutMs,omitempty"`
// MaxRetries is provider/SDK retries inside one request attempt.
MaxRetries *int `json:"maxRetries,omitempty"`
MaxRetryDelayMs *int `json:"maxRetryDelayMs,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Metadata JsonObject `json:"metadata,omitempty"`
CacheRetention ai.CacheRetention `json:"cacheRetention,omitempty"`
Deferred *ai.DeferredOption `json:"deferred,omitempty"`
}
ConversationStreamOptions holds curated pi-ai request options; absent fields use pi-ai defaults.
type ConversationWrite ¶
type ConversationWrite struct{ Value ConversationRecord }
ConversationWrite persists a new conversation.
type CreateConversationOptions ¶
type CreateConversationOptions struct {
Ownership ConversationOwnership
}
CreateConversationOptions selects the ownership of a created or forked conversation.
type Cursor ¶
Cursor is backend-owned JSON continuation state that callers only round-trip to the same scan.
type DocDefinition ¶
type DocDefinition[T any] struct { CommonDocDefinition[T] DocumentSemantics Initial func() T }
DocDefinition is a singleton document definition.
type DocFamilyDefinition ¶
type DocFamilyDefinition[T, I any] struct { CommonDocDefinition[T] DocumentSemantics Initial func(seed I) T }
DocFamilyDefinition is a keyed document family definition; Initial(seed) runs only when a member is absent.
type DocFamilyToken ¶
type DocFamilyToken[T, I any] struct { // contains filtered or unexported fields }
DocFamilyToken is a typed document family token passed explicitly to typed access.
func DefineDocFamily ¶
func DefineDocFamily[T, I any](definition DocFamilyDefinition[T, I]) DocFamilyToken[T, I]
DefineDocFamily defines a keyed document family; Initial(seed) runs only when a member is absent. It panics when the version is not a positive integer.
func (DocFamilyToken[T, I]) AnyDefinition ¶
func (token DocFamilyToken[T, I]) AnyDefinition() *AnyDocDefinition
AnyDefinition returns the erased definition.
type DocToken ¶
type DocToken[T any] struct { // contains filtered or unexported fields }
DocToken is a typed singleton document token passed explicitly to typed access.
func DefineDoc ¶
func DefineDoc[T any](definition DocDefinition[T]) DocToken[T]
DefineDoc defines a singleton document. Scope selects a Session, conversation, or task document; conversation documents also declare History and Fork. It panics when the version is not a positive integer, where upstream throws a TypeError at definition time.
func (DocToken[T]) AnyDefinition ¶
func (token DocToken[T]) AnyDefinition() *AnyDocDefinition
AnyDefinition returns the erased definition.
type DocTokenOf ¶
type DocTokenOf[T any] interface { AnyDocToken // contains filtered or unexported methods }
DocTokenOf is a singleton or family token of value type T.
type DocumentAddress ¶
type DocumentAddress struct {
Kind string
Scope DocumentRecordScope
// Key is nil for the singleton and selects one family member otherwise.
Key *string
}
DocumentAddress is the exact logical identity of a singleton or one keyed family member.
type DocumentChange ¶
type DocumentChange struct {
Record DocumentRecord
// ConversationId owns the document; task documents derive it from their task record. Nil only for Session
// documents.
ConversationId *ConversationId
// Version is the definition version of Value; nil when this commit retired the incarnation.
Version *int
// Value is the exact adopted immutable revision, or nil when this commit retired the incarnation.
Value JsonObject
// Ops are the exact adopted operations for an ordinary update; empty for creation and retirement.
Ops []Op
}
DocumentChange is the committed change of one document incarnation.
type DocumentChangeWrite ¶
type DocumentChangeWrite struct {
Id DocumentId
Content DocumentContent
}
DocumentChangeWrite appends a base or delta to an incarnation.
type DocumentCommitChange ¶
type DocumentCommitChange interface {
CommitChange
// contains filtered or unexported methods
}
DocumentCommitChange is a DocumentChange or a DocumentCopyChange.
type DocumentContent ¶
type DocumentContent struct {
Version int `json:"version"`
Kind DocumentContentKind `json:"kind"`
Value JsonObject `json:"value,omitempty"`
Ops []Op `json:"ops,omitempty"`
}
DocumentContent is a complete checkpoint (base, with Value) or a Chord operation batch (delta, with Ops) selected by the owning Session.
func (DocumentContent) MarshalJSON ¶
func (content DocumentContent) MarshalJSON() ([]byte, error)
MarshalJSON encodes Value for a base and Ops for a delta even when empty: both members are required by their union member.
type DocumentContentKind ¶
type DocumentContentKind string
DocumentContentKind is "base" or "delta".
const ( ContentBase DocumentContentKind = "base" ContentDelta DocumentContentKind = "delta" )
type DocumentCopyChange ¶
type DocumentCopyChange struct {
Record DocumentRecord
ConversationId ConversationId
Source DocumentCopySource
}
DocumentCopyChange is a definition-free child initialization; consumers hydrate through state or watch acquisition.
type DocumentCopySource ¶
type DocumentCopySource struct {
Id DocumentId
At DocumentPoint
}
DocumentCopySource is the exact persisted source selected for a definition-free document copy.
type DocumentCopyWrite ¶
type DocumentCopyWrite struct {
Record DocumentCreate
Source DocumentCopySource
}
DocumentCopyWrite creates an incarnation as a definition-free copy of a persisted source.
type DocumentCreate ¶
type DocumentCreate struct {
Id DocumentId `json:"id"`
Kind string `json:"kind"`
Key *string `json:"key,omitempty"`
Scope DocumentRecordScope `json:"scope"`
History DocumentHistory `json:"history,omitempty"`
Fork DocumentFork `json:"fork,omitempty"`
}
DocumentCreate holds the fields supplied when storage creates and stamps a new DocumentRecord.
func BuildDocumentCreate ¶
func BuildDocumentCreate(definition *AnyDocDefinition, address DocumentAddress, id DocumentId) DocumentCreate
BuildDocumentCreate builds the storage create record for a new incarnation at an address (upstream documentCreate).
type DocumentCreateWrite ¶
type DocumentCreateWrite struct {
Record DocumentCreate
Content DocumentContent
}
DocumentCreateWrite creates an incarnation from a complete base; Content.Kind is always base.
type DocumentFork ¶
type DocumentFork string
DocumentFork is how a fork initializes a conversation document; empty for other scopes.
const ( // ForkAsOf initializes from the source state at the fork cutoff; rewindable documents only. ForkAsOf DocumentFork = "asOf" // ForkCurrent initializes from the current source state. ForkCurrent DocumentFork = "current" // ForkInitial initializes from the definition's initial value. ForkInitial DocumentFork = "initial" )
type DocumentHistory ¶
type DocumentHistory string
DocumentHistory is how much history a conversation document keeps; empty for other scopes.
const ( // HistoryLatest retains only the current state. HistoryLatest DocumentHistory = "latest" // HistoryRewindable retains the history needed for as-of reads. HistoryRewindable DocumentHistory = "rewindable" )
type DocumentObserver ¶
type DocumentObserver interface {
// WatchDocErased returns a watch of the document's JSON value, or nil when absent. Typed watches use WatchDoc.
WatchDocErased(ctx context.Context, token AnyDocToken, args ...any) (WatchHandle[JsonObject], error)
}
DocumentObserver is the non-creating document watch acquisition shared by Session and invocation APIs.
type DocumentPoint ¶
DocumentPoint is the current state (Current) or one historical commit sequence used for document membership and content reads.
type DocumentQuery ¶
type DocumentQuery struct {
Scope DocumentRecordScope
At DocumentPoint
Kind *string
}
DocumentQuery is an ordered scan of document incarnations alive in one exact scope at one point.
type DocumentReader ¶
type DocumentReader interface {
// Snapshot returns the committed value of a document as JSON, or nil when absent. args are the owner ID and family
// key as for Tx.Doc. Typed reads use the Snapshot helper.
SnapshotErased(ctx context.Context, token AnyDocToken, args ...any) (JsonObject, error)
// SnapshotAsOfErased returns the committed value of a rewindable conversation document as of the visible entry at;
// args are the conversation ID, then the family key for families.
SnapshotAsOfErased(ctx context.Context, token AnyDocToken, at EntryId, args ...any) (JsonObject, error)
}
DocumentReader holds committed document reads (Session.snapshot and snapshotAsOf).
type DocumentRecord ¶
type DocumentRecord struct {
// Id is the unique incarnation ID; never reused when the same logical document is recreated.
Id DocumentId `json:"id"`
// Kind is the stable document definition kind.
Kind string `json:"kind"`
// Key is the family member key; nil for singleton documents.
Key *string `json:"key,omitempty"`
// CreatedAt is the commit that created the incarnation, stamped by storage.
CreatedAt Seq `json:"createdAt"`
// RetiredAt is the commit that retired the incarnation; nil while it is current.
RetiredAt *Seq `json:"retiredAt,omitempty"`
Scope DocumentRecordScope `json:"scope"`
// History and Fork are set only for conversation scope.
History DocumentHistory `json:"history,omitempty"`
Fork DocumentFork `json:"fork,omitempty"`
}
DocumentRecord is the persisted lifecycle record for one create-to-retire document incarnation.
func (DocumentRecord) AsCreate ¶
func (record DocumentRecord) AsCreate() DocumentCreate
AsCreate returns the create fields of a record, without the storage stamps.
type DocumentRecordScope ¶
type DocumentRecordScope struct {
Kind DocumentScope `json:"kind"`
// ConversationId is set only for conversation scope.
ConversationId ConversationId `json:"conversationId,omitempty"`
// TaskId is set only for task scope.
TaskId TaskId `json:"taskId,omitempty"`
}
DocumentRecordScope is the owner of a document incarnation.
type DocumentRetireWrite ¶
type DocumentRetireWrite struct{ Id DocumentId }
DocumentRetireWrite retires an incarnation.
type DocumentScope ¶
type DocumentScope string
DocumentScope is the owner kind of a document.
const ( ScopeSession DocumentScope = "session" ScopeConversation DocumentScope = "conversation" ScopeTask DocumentScope = "task" )
type DocumentSemantics ¶
type DocumentSemantics struct {
Scope DocumentScope
History DocumentHistory
Fork DocumentFork
}
DocumentSemantics is the ownership and lifetime of a document; only conversation documents declare history and fork behavior.
type DocumentState ¶
type DocumentState[T any] = *chord.AttachedReplicatedState[JsonObject]
DocumentState is disposable, read-only Chord state bound to one committed document incarnation of type T; its value is nil once the incarnation is retired. The state holds the JSON value (T is phantom, as for Draft); DecodeDoc[T](state.Value()) reads it as T.
type DocumentWatch ¶
type DocumentWatch[T any] = WatchHandle[*T]
DocumentWatch is a watch of one document incarnation; the value is nil once retired.
type Draft ¶
Draft is the revocable mutable working copy of a document of type T inside one commit. Reads and writes go through the Chord overlay handle, which records the exact operations; DecodeDoc[T](draft.Snapshot()) reads it as T. Using it after its commit settles panics with delta.ErrRevoked, as upstream throws.
type Entry ¶
Entry is a typed entry kind with a narrowing guard.
func DefineEntry ¶
DefineEntry defines a typed entry kind whose Is guard matches by EntryRecord.Kind. It panics when kind is empty, where upstream throws a TypeError at definition time.
func (Entry[D]) As ¶
func (token Entry[D]) As(entry *EntryRecord) (*TypedEntry[D], error)
As returns entry with its Data decoded as D; nil when entry is absent or has another kind.
func (Entry[D]) Draft ¶
func (token Entry[D]) Draft(value TypedEntryDraft[D]) (EntryDraft, error)
Draft returns the untyped draft of a typed draft.
func (Entry[D]) Is ¶
func (token Entry[D]) Is(entry *EntryRecord) bool
Is reports whether entry is present and has this kind.
type EntryAt ¶
type EntryAt struct {
Entry EntryRecord
CommitSeq Seq
}
EntryAt is an entry and the sequence of the commit that persisted it.
type EntryDraft ¶
type EntryDraft struct {
Kind string `json:"kind"`
Model []ai.Message `json:"model,omitempty"`
Data JsonValue `json:"data,omitempty"`
Edits []ContextEdit `json:"edits,omitempty"`
// Head starts active context at an entry; HeadSelf starts it at the newly assigned entry ID.
Head *EntryId `json:"-"`
HeadSelf bool `json:"-"`
}
EntryDraft is entry content supplied before the Session assigns identity and task attribution.
func (EntryDraft) MarshalJSON ¶
func (draft EntryDraft) MarshalJSON() ([]byte, error)
MarshalJSON encodes HeadSelf as head "self".
func (*EntryDraft) UnmarshalJSON ¶
func (draft *EntryDraft) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes head "self" as HeadSelf.
type EntryQuery ¶
type EntryQuery struct {
ConversationId ConversationId
// MinEntryId is the oldest entry ID that may be returned.
MinEntryId *EntryId
// MaxEntryId is the newest entry ID that may be returned.
MaxEntryId *EntryId
}
EntryQuery holds inclusive ID bounds for a newest-first scan of one conversation's fork-aware history.
type EntryRecord ¶
type EntryRecord struct {
Id EntryId `json:"id"`
ConversationId ConversationId `json:"conversationId"`
// Kind is the application-defined entry discriminator.
Kind string `json:"kind"`
// Model holds the messages contributed to model context; nil for display or bookkeeping entries.
Model []ai.Message `json:"model,omitempty"`
// Data is the JSON payload consumed by views, extensions, or bookkeeping logic; HasData reports presence.
Data JsonValue `json:"data,omitempty"`
// Head is the first entry in the active context selected by this entry.
Head *EntryId `json:"head,omitempty"`
// Edits are context-only overrides of earlier visible entries.
Edits []ContextEdit `json:"edits,omitempty"`
// ByTaskId is the task that appended this entry, when it was produced by durable work.
ByTaskId *TaskId `json:"byTaskId,omitempty"`
}
EntryRecord is an immutable transcript event with separate model-facing and application-facing payloads.
func (EntryRecord) MarshalJSON ¶
func (entry EntryRecord) MarshalJSON() ([]byte, error)
MarshalJSON encodes Model when it is not nil, even when empty.
func (*EntryRecord) UnmarshalJSON ¶
func (entry *EntryRecord) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes Model by message role.
type ErasedPhaseHandler ¶
type ErasedPhaseHandler = func(ctx context.Context, task ErasedRunningTask, runtime ErasedTaskRuntime) error
ErasedPhaseHandler runs one phase, or the abort handler, of an erased task definition.
type ErasedRunningTask ¶
type ErasedRunningTask = RunningTask[JsonValue, JsonValue, JsonValue]
ErasedRunningTask is a running task record with JSON input, checkpoint, and result.
type ErasedTaskRuntime ¶
type ErasedTaskRuntime = TaskRuntime[JsonValue, JsonValue, JsonValue, any]
ErasedTaskRuntime is a task runtime over JSON input, checkpoint, and result, with an untyped hook runner.
type Extension ¶
type Extension struct {
Name string
Tools []*ToolRegistration
Sections []*PromptSection
Hooks []HookRegistration
// Wraps apply where this extension is selected, in order.
Wraps []Wrap
// Tasks are resolved by name for every task, whichever conversations select this extension.
Tasks []AnyTask
}
Extension is a named bundle of code, installed in a registry and selected by conversations by name.
type HookRegistration ¶
HookRegistration is built by Hook; it matches tasks by name.
type HookRunner ¶
type HookRunner[H any] interface { // Each calls invoke with each matching handler set. An ordinary error from invoke is reported and the next handler // runs; once the invocation is signalled, the error propagates. Composition happens inside invoke. Go has no // keyed member access, so invoke receives the handler set and selects the member named name; handler sets that // leave name unset are skipped. Each(name string, invoke func(handlers H) error) error }
HookRunner dispatches one hook of a task to every matching registered handler, in registry order of the phase snapshot.
type Id ¶
type Id interface {
~int64
}
Id is any durable record ID; every kind shares the Session-global numeric namespace.
type InputSubmissionDraft ¶
type InputSubmissionDraft = SubmissionDraft
InputSubmissionDraft is a SubmissionDraft of type input.
type JoinPolicy ¶
type JoinPolicy string
JoinPolicy is how a waiting task treats the tasks it waits on (spec §5.5).
const ( JoinFailFast JoinPolicy = "failFast" JoinAllSettled JoinPolicy = "allSettled" )
type JsonObject ¶
JsonObject is the JSON object used as the root of every durable document.
func MaterializeDocument ¶
func MaterializeDocument(definition *AnyDocDefinition, stored StoredDocument) (JsonObject, error)
MaterializeDocument validates and materializes a detached stored value for typed access.
func MaterializeDocumentValue ¶
func MaterializeDocumentValue(definition *AnyDocDefinition, record DocumentCreate, version int, value JsonObject) (JsonObject, error)
MaterializeDocumentValue validates and materializes one detached value before its first persisted incarnation.
func ToJsonObject ¶
func ToJsonObject(value any) (JsonObject, error)
ToJsonObject returns the JSON object representation of value; it fails when value does not encode as an object.
type JsonValue ¶
type JsonValue = any
JsonValue is a strict JSON value: nil, bool, float64 or another JSON number, string, []any, or map[string]any.
func ToJsonValue ¶
ToJsonValue returns a detached strict JSON copy of value: nil, bool, float64, string, []any, or map[string]any. It is Chord's copyJson: JSON kinds are copied and checked by chord.CopyJSON, and typed Go values (structs, values with a JSON encoding) are copied through their JSON encoding. A non-finite number fails with a strict JSON error, as copyJson throws.
type Models ¶
type Models interface {
// GetModel looks up a chat model by provider and model ID against the last-known lists; nil when absent.
GetModel(provider, id string) *ai.Model
// StreamSimple streams one assistant message; failures end the stream with an error message.
StreamSimple(ctx context.Context, model *ai.Model, request ai.Context, options ...ai.StreamOptions) *ai.AssistantMessageEventStream
// CompleteSimple returns the terminal message of StreamSimple.
CompleteSimple(ctx context.Context, model *ai.Model, request ai.Context, options ...ai.StreamOptions) *ai.AssistantMessage
// FetchDeferred fetches the result of a deferred request.
FetchDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, options ...ai.DeferredFetchOptions) *ai.AssistantMessage
// CancelDeferred cancels a deferred request.
CancelDeferred(ctx context.Context, model *ai.Model, handle ai.DeferredHandle, options ...ai.DeferredCancelOptions) error
}
Models is the pi-ai Models access of a task runtime and the Harness (types.ts:425, scheduler.ts:136): the methods generation and compaction call. The coding worker passes its Model Runtime, and a bare pi-ai collection (*ai.Models) also satisfies it. Each optional options argument is the pi-ai optional parameter.
type NextTaskState ¶
NextTaskState is the next state a task commits for itself: a replacement checkpoint (running), a wait, or its outcome (terminal). A returned terminal state is stored as completing while ordinary owned work below the task is live (spec §5.5).
type Page ¶
type Page[T, C any] struct { Items []T // Next is nil when the scan is complete. Next *C }
Page is one ordered scan result and its optional continuation state.
type PhaseHandler ¶
type PhaseHandler[I, S, R any, H any] = func(ctx context.Context, task RunningTask[I, S, R], runtime TaskRuntime[I, S, R, H]) error
PhaseHandler runs one checkpoint phase. It must commit a changed checkpoint or a terminal outcome through runtime.Commit; returning without durable progress faults the task.
type ProgressPolicy ¶
type ProgressPolicy struct {
// PartialIntervalMs is the minimum pause between commits of the answer being generated.
PartialIntervalMs float64 `json:"partialIntervalMs"`
// OutputIntervalMs is the minimum pause between commits of running tool output; large commits also pause in
// proportion to their size.
OutputIntervalMs float64 `json:"outputIntervalMs"`
}
ProgressPolicy is how often running progress is committed. Each progress commit is a storage write; a host whose storage is remote can commit less often, so live answers and tool output appear in larger steps.
type PromptInput ¶
type PromptInput struct {
ConversationId ConversationId
// Agent is the request's resolution; Agent.Tools are the tools offered in this request.
Agent Agent
// Env is built by HarnessOptions.env for this preparation; nil without an environment.
Env env.ExecutionEnv
// Shown holds the sections already in effect after replaying the active transcript.
Shown map[string]string
// Read holds committed document reads.
Read DocumentReader
}
PromptInput is the input to system prompt section rendering for one request preparation.
type PromptSection ¶
type PromptSection struct {
Key string
// Render returns nil to omit the section.
Render func(ctx context.Context, input PromptInput) (*string, error)
// Tag defaults to true: wrap the text as `<key>\n...\n</key>`.
Tag *bool
}
PromptSection is one system prompt section; the agent's sections render in order before each request.
type QueueMode ¶
type QueueMode string
QueueMode is how many queued items of one mode a boundary places: the first, or all of them.
type ReadAfterWrite ¶
type ReadAfterWrite struct {
Method string
}
ReadAfterWrite reports that a transaction read a table after its first table write. Read every required row before writing.
func NewReadAfterWrite ¶
func NewReadAfterWrite(method string) *ReadAfterWrite
NewReadAfterWrite returns the error for the Tx method that read after a write.
func (*ReadAfterWrite) Error ¶
func (e *ReadAfterWrite) Error() string
type RegistrySection ¶
type RegistrySection struct {
Extension *Extension
Section *PromptSection
}
RegistrySection is an installed prompt section with its extension.
type RegistrySnapshot ¶
type RegistrySnapshot interface {
Installed() []*Extension
// Extension returns nil when absent.
Extension(name string) *Extension
// Tools returns every installed tool with its extension, in install order. Names may repeat across extensions.
Tools() []RegistryTool
Sections() []RegistrySection
// Tasks returns the built-in and installed task definitions.
Tasks() []AnyTask
// Task returns nil when absent.
Task(name string) AnyTask
}
RegistrySnapshot is an immutable view of one published registry state.
type RegistryTool ¶
type RegistryTool struct {
Extension *Extension
Tool *ToolRegistration
}
RegistryTool is an installed tool with its extension.
type ResolvedAddress ¶
type ResolvedAddress struct {
Address DocumentAddress
Id string
// NextArgument is the index after the owner and family key.
NextArgument int
}
ResolvedAddress is a logical address plus its string identity for maps.
func ResolveAddress ¶
func ResolveAddress(definition *AnyDocDefinition, args []any) (ResolvedAddress, error)
ResolveAddress resolves an overloaded argument list and returns the index after the owner and family key.
type RewindableConversationDocFamilyToken ¶
type RewindableConversationDocFamilyToken[T, I any] = DocFamilyToken[T, I]
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type RewindableConversationDocToken ¶
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type RunningTask ¶
type RunningTask[I, S, R any] = TaskRecord[I, S, R]
RunningTask is a live task record reserved by one invocation; State.Status is TaskRunning.
type Seq ¶
type Seq int64
Seq is the strictly increasing sequence assigned to one atomic storage commit; gaps are permitted.
func SeqFromNumber ¶
SeqFromNumber applies the commit-sequence kind at a trusted storage boundary.
type Session ¶
type Session interface {
DocumentObserver
DocumentReader
// Commit runs one atomic transaction on the Session mutation line.
Commit(ctx context.Context, change func(tx Tx) (any, error)) (any, error)
// Close seals admission, settles admitted commits, then closes storage.
Close(ctx context.Context) error
// SubscribeCommits observes complete commits synchronously after adoption. The listener must not panic, block,
// or call Session APIs.
SubscribeCommits(listener func(ctx context.Context, publication CommitPublication)) func()
// SubscribeClose observes close synchronously when it begins. The listener must not panic, block, or call
// Session APIs.
SubscribeClose(listener func()) func()
// DocumentStateErased returns a disposable state of the document's JSON value, or nil when absent. Typed states
// use the DocumentStateOf helper.
DocumentStateErased(ctx context.Context, token AnyDocToken, args ...any) (AttachedReplicatedState[JsonObject], error)
}
Session owns one mutation line, its records, and its tracked documents.
type SessionDocFamilyToken ¶
type SessionDocFamilyToken[T, I any] = DocFamilyToken[T, I]
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type SessionDocToken ¶
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type Settings ¶
type Settings struct {
// Extensions is nil for every installed extension, in install order.
Extensions []*Extension
Stream ConversationStreamOptions
Retry ConversationRetryPolicy
Compaction CompactionPolicy
Progress ProgressPolicy
ToolExecution ToolExecutionMode
SteeringMode QueueMode
FollowUpMode QueueMode
}
Settings holds the resolved settings: every field over its built-in default, object fields merged.
type SettledSubmissionRecord ¶
type SettledSubmissionRecord = SubmissionRecord
SettledSubmissionRecord is a SubmissionRecord whose status is done or unanswered.
type SettledTask ¶
type SettledTask[R any] = TaskRecord[JsonValue, JsonValue, R]
SettledTask is a task record in the terminal state.
type Storage ¶
type Storage interface {
// Commit atomically persists one batch and returns its sequence. Once it returns, later reads through this
// storage observe it.
Commit(ctx context.Context, writes []StorageWrite) (Seq, error)
// MintId returns a fresh candidate from the Session-global numeric ID namespace.
MintId() (int64, error)
// Conversation looks up one conversation by exact ID; nil when absent.
Conversation(ctx context.Context, id ConversationId) (*ConversationRecord, error)
// ScanConversations scans conversations in ascending ID order.
ScanConversations(ctx context.Context, query ConversationQuery, limit int, cursor Cursor) (Page[ConversationRecord, Cursor], error)
// Entry looks up one global entry and the sequence of the commit that persisted it; nil when absent.
Entry(ctx context.Context, id EntryId) (*EntryAt, error)
// VisibleEntry looks up one entry only when it is visible through the requested conversation's ancestry.
VisibleEntry(ctx context.Context, conversationId ConversationId, id EntryId) (*EntryAt, error)
// FindLatestHeadMarker returns the newest visible entry with a Head at or below the optional inclusive cutoff.
// The returned entry is the marker; its Head is the range's actual lower bound.
FindLatestHeadMarker(ctx context.Context, conversationId ConversationId, atOrBeforeEntryId *EntryId) (*EntryRecord, error)
// ScanEntries scans the inclusive visible range newest-first, returning at most limit entries.
ScanEntries(ctx context.Context, query EntryQuery, limit int, cursor Cursor) (Page[EntryRecord, Cursor], error)
// Task looks up the latest complete record for one task; nil when absent.
Task(ctx context.Context, id TaskId) (*TaskRecord[JsonValue, JsonValue, JsonValue], error)
// ScanTasks scans task records matching every supplied filter.
ScanTasks(ctx context.Context, query TaskQuery, limit int, cursor Cursor) (Page[TaskRecord[JsonValue, JsonValue, JsonValue], Cursor], error)
// Submission looks up the latest complete record for one admitted submission; nil when absent.
Submission(ctx context.Context, id SubmissionId) (*SubmissionRecord, error)
// ScanSubmissions scans submissions matching every supplied filter in ascending ID order.
ScanSubmissions(ctx context.Context, query SubmissionQuery, limit int, cursor Cursor) (Page[SubmissionRecord, Cursor], error)
// SubmissionByRequest finds a submission by its conversation-scoped host deduplication key; nil when absent.
SubmissionByRequest(ctx context.Context, conversationId ConversationId, requestId string) (*SubmissionRecord, error)
// FindDocument resolves the incarnation occupying one exact logical address at the selected point; nil when
// absent.
FindDocument(ctx context.Context, address DocumentAddress, at DocumentPoint) (*DocumentRecord, error)
// Document materializes one specific incarnation by ID at the selected point without following a replacement at
// its address; nil when absent.
Document(ctx context.Context, id DocumentId, at DocumentPoint) (*StoredDocument, error)
// ScanDocuments scans incarnations alive in one exact scope at the selected point.
ScanDocuments(ctx context.Context, query DocumentQuery, limit int, cursor Cursor) (Page[DocumentRecord, Cursor], error)
// Close releases backend resources; all later operations must fail.
Close(ctx context.Context) error
}
Storage is the atomic persistence boundary for Session records.
Storage trusts the owning Session to supply semantically valid records, references, ancestry, and transitions. Implementations enforce atomicity, global ID ownership, immutable conversation/entry creation, document record consistency, and detached values; Session serializes commits.
type StorageRejected ¶
StorageRejected reports that storage rejected a batch before any durable effect; the owning Session may continue safely.
func NewStorageRejected ¶
func NewStorageRejected(message string, cause error) *StorageRejected
NewStorageRejected returns a StorageRejected error; cause may be nil.
func (*StorageRejected) Error ¶
func (e *StorageRejected) Error() string
type StorageWrite ¶
type StorageWrite interface {
// contains filtered or unexported methods
}
StorageWrite is one record or document mutation in an atomic storage commit.
type StoredDocument ¶
type StoredDocument struct {
Record DocumentRecord
Version int
Value JsonObject
// DeltasSinceBase counts the deltas replayed after the selected base to materialize Value.
DeltasSinceBase int
}
StoredDocument is the detached materialized value and stored definition version at a selected point.
type Submission ¶
type Submission interface {
Id() SubmissionId
Status(ctx context.Context) (SubmissionRecord, error)
Wait(ctx context.Context) (SettledSubmissionRecord, error)
Abort(ctx context.Context) (SubmissionAbortResult, error)
}
Submission is the awaitable host object for one durably admitted submission.
type SubmissionAbortResult ¶
type SubmissionAbortResult string
SubmissionAbortResult is the result of aborting one submission.
const ( SubmissionAborted SubmissionAbortResult = "aborted" SubmissionAlreadyPlaced SubmissionAbortResult = "already_placed" SubmissionSettled SubmissionAbortResult = "settled" SubmissionNotFound SubmissionAbortResult = "not_found" )
type SubmissionCreate ¶
type SubmissionCreate struct {
ConversationId ConversationId `json:"conversationId"`
RequestId *string `json:"requestId,omitempty"`
Type SubmissionType `json:"type"`
Status SubmissionStatus `json:"status"`
Entry *EntryId `json:"entry,omitempty"`
Answer *EntryId `json:"answer,omitempty"`
Reason *string `json:"reason,omitempty"`
Detail JsonValue `json:"detail,omitempty"`
}
SubmissionCreate holds the submission fields supplied before the Session assigns an ID.
func (SubmissionCreate) Record ¶
func (create SubmissionCreate) Record(id SubmissionId) SubmissionRecord
Record returns the submission record of a create with its assigned ID.
type SubmissionDraft ¶
type SubmissionDraft struct {
// RequestId is nil when absent.
RequestId *string
Type SubmissionType
Content UserInput
WhenBusy WhenBusy
Entry *EntryDraft
}
SubmissionDraft is a host submission: user input (type input, with Content and an optional WhenBusy) that may start a run, or a passive entry write (type write, with Entry).
type SubmissionQuery ¶
type SubmissionQuery struct {
ConversationId *ConversationId
Status *SubmissionStatus
}
SubmissionQuery holds optional filters for an ordered scan of submission records.
type SubmissionRecord ¶
type SubmissionRecord struct {
Id SubmissionId `json:"id"`
ConversationId ConversationId `json:"conversationId"`
// RequestId is the host-provided deduplication key, scoped to the conversation; nil when absent.
RequestId *string `json:"requestId,omitempty"`
Type SubmissionType `json:"type"`
Status SubmissionStatus `json:"status"`
Entry *EntryId `json:"entry,omitempty"`
Answer *EntryId `json:"answer,omitempty"`
Reason *string `json:"reason,omitempty"`
Detail JsonValue `json:"detail,omitempty"`
}
SubmissionRecord is the durable lifecycle of one admitted user input or passive entry write.
Upstream encodes each (type, status) pair as a union member; the Go struct carries every field and the Session keeps them consistent: Entry is set for placed and done records and optional for unanswered input; Answer only for done input; Reason and Detail only for unanswered records.
type SubmissionSettlement ¶
type SubmissionSettlement struct {
Status SubmissionStatus `json:"status"`
Answer EntryId `json:"answer,omitempty"`
Reason string `json:"reason,omitempty"`
Detail JsonValue `json:"detail,omitempty"`
}
SubmissionSettlement is the terminal status staged for a submission; identity, type, and entry come from its current record. Status is done (with Answer) or unanswered (with Reason and optional Detail).
type SubmissionStatus ¶
type SubmissionStatus string
SubmissionStatus is the lifecycle status of a submission.
const ( // SubmissionQueued is admitted but not yet represented in the transcript. SubmissionQueued SubmissionStatus = "queued" // SubmissionPlaced is input added to the transcript and owned by an active run. SubmissionPlaced SubmissionStatus = "placed" // SubmissionDone is successfully answered input or a successfully appended passive entry. SubmissionDone SubmissionStatus = "done" // SubmissionUnanswered is terminal input that can no longer receive an answer, or a passive write that could not // be placed. SubmissionUnanswered SubmissionStatus = "unanswered" )
type SubmissionType ¶
type SubmissionType string
SubmissionType is "input" or "write".
const ( SubmissionTypeInput SubmissionType = "input" SubmissionTypeWrite SubmissionType = "write" )
type SubmissionWrite ¶
type SubmissionWrite struct{ Value SubmissionRecord }
SubmissionWrite persists the complete replacement record of a submission.
type TableCommitChange ¶
type TableCommitChange interface {
StorageWrite
CommitChange
}
TableCommitChange is a complete table record committed without another publication copy: a ConversationWrite, EntryWrite, TaskWrite, or SubmissionWrite.
type Task ¶
type Task[I, S, R any, H any] struct { Definition *TaskDefinition[I, S, R, H] // contains filtered or unexported fields }
Task is a typed executable task definition.
func DefineTask ¶
func DefineTask[I, S, R, H any](definition TaskDefinition[I, S, R, H]) Task[I, S, R, H]
DefineTask defines an executable task. Register it in the registry so a Harness can run tasks of its kind.
func (Task[I, S, R, H]) AnyDefinition ¶
func (task Task[I, S, R, H]) AnyDefinition() *AnyTaskDefinition
AnyDefinition returns the erased definition.
type TaskDefinition ¶
type TaskDefinition[I, S, R any, H any] struct { // Name is the registered task kind persisted in TaskRecord.Kind. Name string // Version is the definition version persisted with live input and checkpoints. Version int // Initial returns the first durable checkpoint for a newly created task. Initial func(input I) S // Phases is the exhaustive phase map, keyed by the checkpoint's JSON "phase" member. Phases map[string]PhaseHandler[I, S, R, H] // Abort runs in a fresh invocation after an abort mark and must commit a terminal outcome. Abort func(ctx context.Context, task RunningTask[I, S, R], runtime TaskRuntime[I, S, R, H]) error // Migrate converts a record stored by any older supported version; runs at reservation. Nil when absent. Migrate func(input JsonValue, checkpoint JsonValue, fromVersion int) (I, S, error) // Hooks is the zero value when the task declares no hooks. Hooks H }
TaskDefinition is an executable durable state machine definition, registered in the registry by Name.
type TaskDocFamilyToken ¶
type TaskDocFamilyToken[T, I any] = DocFamilyToken[T, I]
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type TaskDocToken ¶
The scope-refined token names of upstream. Go cannot refine a struct type by a field value, so each name aliases the general token and the Session checks the scope when it resolves an address.
type TaskId ¶
type TaskId int64
TaskId identifies a task. Upstream brands it with the task's result type; Go methods cannot take type parameters, so the result type is recovered at the generic helpers instead.
func CreateTask ¶
func CreateTask[I, S, R, H any](tx Tx, task Task[I, S, R, H], input I, options TaskOptions) (TaskId, error)
CreateTask creates a task in a commit and returns its ID.
type TaskOptions ¶
type TaskOptions struct {
// Ownership is required: a task always names its owner (spec §5.5).
Ownership TaskOwnership
// ConversationId defaults to the owner task's conversation, or the transaction's bound conversation; required for
// conversation-owned tasks created by Session commits that are not bound to a conversation.
ConversationId *ConversationId
// Background applies to conversation-owned tasks only: excluded from ordinary idle waits, conversation aborts, and
// cascades.
Background bool
}
TaskOptions holds the creation options for a durable task.
type TaskOutcome ¶
type TaskOutcome[R any] struct { Status TaskOutcomeStatus `json:"status"` Result *R `json:"result,omitempty"` Error *TaskOutcomeError `json:"error,omitempty"` Reason *string `json:"reason,omitempty"` }
TaskOutcome is the durable reason and optional result recorded when a task becomes terminal. Result is required for completed and optional for failed and aborted; Error is required for failed and faulted; Reason is optional for aborted and required for orphaned.
func (TaskOutcome[R]) MarshalJSON ¶
func (outcome TaskOutcome[R]) MarshalJSON() ([]byte, error)
MarshalJSON encodes a present Result, including JSON null; a completed outcome always carries one.
func (*TaskOutcome[R]) UnmarshalJSON ¶
func (outcome *TaskOutcome[R]) UnmarshalJSON(data []byte) error
UnmarshalJSON keeps a present JSON-null result as a non-nil Result.
type TaskOutcomeError ¶
type TaskOutcomeError struct {
Message string `json:"message"`
// Detail is optional structured diagnostic data for inspection or recovery.
Detail JsonValue `json:"detail,omitempty"`
}
TaskOutcomeError is the JSON-safe error snapshot persisted instead of a runtime error.
type TaskOutcomeStatus ¶
type TaskOutcomeStatus string
TaskOutcomeStatus classifies a terminal task.
const ( OutcomeCompleted TaskOutcomeStatus = "completed" // OutcomeFailed is an expected task or domain failure explicitly committed by its implementation. OutcomeFailed TaskOutcomeStatus = "failed" // OutcomeAborted is explicit cancellation handled by the task's abort protocol. OutcomeAborted TaskOutcomeStatus = "aborted" // OutcomeOrphaned is a task that cannot resume because its definition or migration is unavailable. OutcomeOrphaned TaskOutcomeStatus = "orphaned" // OutcomeFaulted is a runtime-detected contract failure, such as an uncaught error or no durable progress. OutcomeFaulted TaskOutcomeStatus = "faulted" )
type TaskOwnership ¶
type TaskOwnership struct {
Kind TaskOwnershipKind `json:"kind"`
// TaskId is set only for kind "task".
TaskId TaskId `json:"taskId,omitempty"`
}
TaskOwnership names who owns a task: its conversation (a top-level task) or another task of the same conversation (a child task).
type TaskOwnershipKind ¶
type TaskOwnershipKind string
TaskOwnershipKind is "conversation" or "task".
const ( TaskOwnedByConversation TaskOwnershipKind = "conversation" TaskOwnedByTask TaskOwnershipKind = "task" )
type TaskQuery ¶
type TaskQuery struct {
ConversationId *ConversationId
Kind *string
Status *TaskStatus
AbortRequested *bool
Background *bool
}
TaskQuery holds optional filters for an ordered scan of durable task records.
type TaskRecord ¶
type TaskRecord[I, S, R any] struct { Id TaskId `json:"id"` ConversationId ConversationId `json:"conversationId"` // Kind is the registered task definition name. Kind string `json:"kind"` // Version is the definition version used to migrate live input and checkpoints. Version int `json:"version"` // Input is the original task input retained while the task is live or terminal. Input I `json:"input"` // Owner is the owning task of a child task; nil for a task its conversation owns. Immutable. Owner *TaskId `json:"owner,omitempty"` // Background reports whether this conversation-owned task is excluded from ordinary idle waits, conversation // aborts, and cascades. Background bool `json:"background"` // AbortRequested is the durable abort mark checked before run-mode progress is committed. AbortRequested bool `json:"abortRequested"` State TaskState[S, R] `json:"state"` // Memos are small first-writer-wins values retained while the task can run; nil once completing or terminal. Memos map[string]JsonValue `json:"memos,omitempty"` }
TaskRecord is the complete replacement record for one durable task state machine.
func DecodeTaskRecord ¶
func DecodeTaskRecord[I, S, R any](record TaskRecord[JsonValue, JsonValue, JsonValue]) (TaskRecord[I, S, R], error)
DecodeTaskRecord decodes an erased task record into typed input, checkpoint, and result.
func EncodeTaskRecord ¶
func EncodeTaskRecord[I, S, R any](record TaskRecord[I, S, R]) (TaskRecord[JsonValue, JsonValue, JsonValue], error)
EncodeTaskRecord encodes a typed task record into its erased JSON form.
type TaskRuntime ¶
type TaskRuntime[I, S, R any, H any] interface { DocumentObserver DocumentReader TaskId() TaskId ConversationId() ConversationId // Signal is cancelled when the run is signalled by abortTask(), the Harness closes, or the invocation ends. Signal() context.Context // Registry is the registry snapshot of the current phase; refreshed at every phase boundary. Registry() RegistrySnapshot // Agent resolves the task's conversation's agent at most once per phase, at first use, fixed for the phase. Agent(ctx context.Context) (Agent, error) // Settings returns HarnessOptions.settings, resolved at each access. Settings() Settings Models() Models // Env calls HarnessOptions.env for the task's conversation; nil without an environment. Env(ctx context.Context) (env.ExecutionEnv, error) // Hooks returns the handlers of this task's name from the extensions its conversation selects, in extension // order. Hooks() HookRunner[H] // Commit commits on the Session line after rereading the task. It fails when the task is terminal, the // invocation ended, the Harness is closing, or, in a run invocation, the task carries an abort mark. A returned // state replaces the task's state in the same commit; nil leaves it unchanged. tx.CreateTask defaults to the task's // conversation. Commit(ctx context.Context, change func(tx Tx, current RunningTask[I, S, R]) (*NextTaskState[S, R], error)) error // Memo reads a durable memo of this task; ok is false when absent. Memo(ctx context.Context, name string) (value JsonValue, ok bool, err error) // MemoCandidate stores candidate unless a memo already exists and returns the durable winner. MemoCandidate(ctx context.Context, name string, candidate JsonValue) (JsonValue, error) // GetTask returns the committed task record; nil when absent. GetTask(ctx context.Context, id TaskId) (*TaskRecord[JsonValue, JsonValue, JsonValue], error) // WaitForTask returns the task's terminal receipt; it fails when the invocation ends. WaitForTask(ctx context.Context, id TaskId) (SettledTask[JsonValue], error) // Outcomes returns the outcomes of terminal tasks, in order; it fails when one is missing or not terminal. Outcomes(ctx context.Context, ids []TaskId) ([]TaskOutcome[JsonValue], error) // Conversation returns an invocation-bound handle of an existing conversation; nil when absent. Its operations // and the submissions it returns fail after the invocation ends; admitted work stays durable. Conversation(ctx context.Context, id ConversationId) (ConversationHandle, error) // Entry returns a committed entry visible from the task's conversation; nil when absent. Entry(ctx context.Context, id EntryId) (*EntryRecord, error) // Context returns the committed raw active transcript and model context, cut off at the visible entry at when at // is not nil. Context(ctx context.Context, conversationId ConversationId, at *EntryId) (ContextView, error) // Now returns the Harness clock. Now() float64 // Report forwards a non-fatal failure to HarnessOptions.onReport. Report(err error) // Sleep returns once the Harness clock reaches until; it fails when the invocation or ctx is cancelled. Sleep(ctx context.Context, until float64) error }
TaskRuntime holds the operations of one task invocation. Every operation fails after the invocation ends; watches acquired through it stop at invocation end.
type TaskState ¶
type TaskState[S, R any] struct { Status TaskStatus `json:"status"` Checkpoint *S `json:"checkpoint,omitempty"` On []TaskId `json:"on,omitempty"` Policy JoinPolicy `json:"policy,omitempty"` Outcome *TaskOutcome[R] `json:"outcome,omitempty"` }
TaskState is the complete durable execution state of a task. Live statuses (pending, running, waiting) carry Checkpoint; waiting also carries On and Policy; completing and terminal carry Outcome.
func (TaskState[S, R]) MarshalJSON ¶
MarshalJSON encodes On for a waiting state even when it is empty: the waiting member requires it.
type TaskStatus ¶
type TaskStatus string
TaskStatus is the execution status of a task.
const ( // TaskPending is eligible for scheduling. TaskPending TaskStatus = "pending" // TaskRunning is reserved by one in-memory task invocation. TaskRunning TaskStatus = "running" // TaskWaiting is parked without an invocation until every task in On is terminal; then resumes at Checkpoint. TaskWaiting TaskStatus = "waiting" // TaskCompleting has its outcome decided; it becomes terminal once no ordinary owned work below is live and runs // no more code. TaskCompleting TaskStatus = "completing" // TaskTerminal is the permanently settled durable result receipt. TaskTerminal TaskStatus = "terminal" )
type TaskWrite ¶
type TaskWrite struct {
Value TaskRecord[JsonValue, JsonValue, JsonValue]
}
TaskWrite persists the complete replacement record of a task.
type ToolControl ¶
type ToolControl struct {
// AddTools is nil when absent; an empty non-nil list is written as [].
AddTools []string `json:"addTools,omitempty"`
// Terminate is Pi's `terminate?: true`: false is absent.
Terminate bool `json:"terminate,omitempty"`
// Handoff is nil when absent.
Handoff *string `json:"handoff,omitempty"`
}
ToolControl holds the post-tools controls requested by a tool result.
func (ToolControl) MarshalJSON ¶
func (control ToolControl) MarshalJSON() ([]byte, error)
MarshalJSON writes the controls as Pi stores them after dropping undefined keys (tool.ts copyJson with omitUndefinedProperties): an absent key is omitted, and an empty addTools list is kept.
type ToolDiagnostic ¶
type ToolDiagnostic struct {
Severity ToolDiagnosticSeverity `json:"severity"`
Message string `json:"message"`
Code string `json:"code,omitempty"`
}
ToolDiagnostic is a remark about a call for the model and the UI, such as truncation or a spill path; never part of the tool's data.
type ToolDiagnosticSeverity ¶
type ToolDiagnosticSeverity string
ToolDiagnosticSeverity is "info", "warn", or "error".
const ( SeverityInfo ToolDiagnosticSeverity = "info" SeverityWarn ToolDiagnosticSeverity = "warn" SeverityError ToolDiagnosticSeverity = "error" )
type ToolExecutionApi ¶
type ToolExecutionApi interface {
DocumentObserver
DocumentReader
TaskId() TaskId
ConversationId() ConversationId
CallId() string
// Registry is the tool task's phase snapshot.
Registry() RegistrySnapshot
// Agent is the calling conversation's agent, as the tool task's phase resolved it.
Agent(ctx context.Context) (Agent, error)
// Env is built by HarnessOptions.env for this call; nil without an environment.
Env() env.ExecutionEnv
// Output appends running output, a string or []byte; it becomes the result content when the result omits
// Content.
Output(chunk any)
// OutputSkipping is Output of a chunk that follows output an environment omitted, as reported by an environment
// given OutputWindow (ShellOutputInfo.Skipped). The omitted output is more than the tail window by at least one
// byte or line, and only tail retention accepts it. Upstream's output(chunk, skipped) is Output and this method.
OutputSkipping(chunk any, skipped env.ShellOutputSkip)
// OutputWindow is the tail this call's output keeps and the pace of its progress commits, for
// ShellExecOptions.Window; nil when the tool keeps the head of its output, which cannot accept skips. A wrapper
// that replaces Output and transforms text must also replace this with nil, so skipped text cannot bypass its
// transform.
OutputWindow() *env.ShellOutputWindow
// Diagnostic records a model-visible remark about this call.
Diagnostic(diagnostic ToolDiagnostic)
// Details replaces running details; the last value becomes the result details when the result omits Details.
Details(ctx context.Context, value JsonValue) error
Commit(ctx context.Context, change func(tx Tx) (any, error)) (any, error)
// Memo reads a durable memo of the tool task; ok is false when absent.
Memo(ctx context.Context, name string) (value JsonValue, ok bool, err error)
// MemoCandidate stores candidate unless a memo already exists and returns the durable winner.
MemoCandidate(ctx context.Context, name string, candidate JsonValue) (JsonValue, error)
// CreateTaskErased creates a task in the calling conversation; options.ConversationId is ignored.
CreateTaskErased(ctx context.Context, task AnyTask, input JsonValue, options TaskOptions) (TaskId, error)
// GetTask returns nil when absent.
GetTask(ctx context.Context, id TaskId) (*TaskRecord[JsonValue, JsonValue, JsonValue], error)
WaitForTask(ctx context.Context, id TaskId) (SettledTask[JsonValue], error)
// Conversation returns an invocation-bound handle of an existing conversation, such as one this tool created in
// Commit; nil when absent.
Conversation(ctx context.Context, id ConversationId) (ConversationHandle, error)
}
ToolExecutionApi holds the operations available to one tool invocation. Every operation fails after the invocation ends.
type ToolExecutionMode ¶
type ToolExecutionMode string
ToolExecutionMode is whether the tools of one round run at once or one after another in call order.
const ( ToolExecutionParallel ToolExecutionMode = "parallel" ToolExecutionSequential ToolExecutionMode = "sequential" )
type ToolExecutionResult ¶
type ToolExecutionResult struct {
// Content is nil when omitted: the retained output() text becomes the content.
Content []ai.ToolResultMessageContent
IsError *bool
// Details is omitted when HasDetails is false: the last details() value becomes the details.
Details JsonValue
HasDetails bool
// Diagnostics are added after those recorded through api.Diagnostic.
Diagnostics []ToolDiagnostic
// Usage is the spend of the execution itself, such as a model call; stored on the result and in pi.usage.tools.
Usage *ai.Usage
Control *ToolControl
}
ToolExecutionResult is the result of one tool execution.
type ToolOutputLimits ¶
type ToolOutputLimits struct {
MaxBytes *int
MaxLines *int
Retain ToolOutputRetain
}
ToolOutputLimits bounds the retained output of a tool; nil fields use the defaults.
type ToolOutputRetain ¶
type ToolOutputRetain string
ToolOutputRetain is which end of oversized output a tool keeps.
const ( RetainHead ToolOutputRetain = "head" RetainTail ToolOutputRetain = "tail" )
type ToolRegistration ¶
type ToolRegistration struct {
ai.ToolSchema
// Replay defaults to unsafe.
Replay ToolReplay
// ExecutionMode defaults to the settings' toolExecution. One sequential call makes its whole round sequential.
ExecutionMode ToolExecutionMode
// PrepareArguments repairs arguments models commonly get wrong before validation, such as a JSON string where an
// array belongs. It must be pure and must not mutate args: it runs again when a call is retried before its intent
// is recorded. Its result is still validated against Parameters. Nil when absent.
PrepareArguments func(args any) (any, error)
OutputLimits *ToolOutputLimits
Execute func(ctx context.Context, args any, api ToolExecutionApi) (ToolExecutionResult, error)
}
ToolRegistration is an executable tool registered in a registry. Only the pi-ai Tool fields enter the transcript. Arguments are validated against Parameters before Execute; DefineTool types both.
type ToolReplay ¶
type ToolReplay string
ToolReplay is whether an interrupted execution may rerun on recovery.
const ( ReplaySafe ToolReplay = "safe" ReplayUnsafe ToolReplay = "unsafe" )
type ToolResultEntryData ¶
type ToolResultEntryData struct {
Diagnostics []ToolDiagnostic `json:"diagnostics"`
}
ToolResultEntryData is the data of a ToolResultEntry.
type TruncatedBy ¶
type TruncatedBy string
TruncatedBy is which limit truncated the content: "lines", "bytes", or empty when not truncated (upstream null).
const ( TruncatedByLines TruncatedBy = "lines" TruncatedByBytes TruncatedBy = "bytes" )
func (TruncatedBy) MarshalJSON ¶
func (by TruncatedBy) MarshalJSON() ([]byte, error)
MarshalJSON encodes the empty value as null.
func (*TruncatedBy) UnmarshalJSON ¶
func (by *TruncatedBy) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes null as the empty value.
type TruncationOptions ¶
type TruncationOptions struct {
// MaxLines defaults to DEFAULT_MAX_LINES.
MaxLines *int
// MaxBytes defaults to DEFAULT_MAX_BYTES.
MaxBytes *int
}
TruncationOptions holds the limits; nil uses the default.
type TruncationResult ¶
type TruncationResult struct {
// Content is the truncated content.
Content string `json:"content"`
// Truncated reports whether truncation occurred.
Truncated bool `json:"truncated"`
// TruncatedBy is the limit that was hit; empty when not truncated.
TruncatedBy TruncatedBy `json:"truncatedBy"`
// TotalLines is the number of lines in the original content.
TotalLines int `json:"totalLines"`
// TotalBytes is the number of UTF-8 bytes in the original content.
TotalBytes int `json:"totalBytes"`
// OutputLines is the number of complete lines in the truncated output.
OutputLines int `json:"outputLines"`
// OutputBytes is the number of bytes in the truncated output.
OutputBytes int `json:"outputBytes"`
// LastLinePartial reports whether the last line was partially truncated (only for the tail truncation edge case).
LastLinePartial bool `json:"lastLinePartial"`
// FirstLineExceedsLimit reports whether the first line exceeded the byte limit (for head truncation).
FirstLineExceedsLimit bool `json:"firstLineExceedsLimit"`
// MaxLines is the line limit that was applied.
MaxLines int `json:"maxLines"`
// MaxBytes is the byte limit that was applied.
MaxBytes int `json:"maxBytes"`
}
TruncationResult describes one truncation.
func TruncateHead ¶
func TruncateHead(content string, options TruncationOptions) TruncationResult
TruncateHead truncates content from the head, keeping the first lines and bytes. It suits file reads where the beginning matters.
It never returns partial lines. When the first line exceeds the byte limit, it returns empty content with FirstLineExceedsLimit set.
func TruncateHeadOf ¶
func TruncateHeadOf(prefix string, totals TruncationTotals, options TruncationOptions) TruncationResult
TruncateHeadOf is TruncateHead of a text known by a prefix and its totals. The prefix must be the whole text, or longer than MaxBytes + 1 UTF-8 bytes, or hold at least MaxLines newlines; then the result equals TruncateHead of the whole text.
type TruncationTotals ¶
TruncationTotals are the line and byte counts of a whole text: lines counted like TruncateHead, ignoring a trailing newline.
type Tx ¶
type Tx interface {
// Conversation returns nil when absent.
Conversation(id ConversationId) (*ConversationRecord, error)
// Entry returns nil when absent.
Entry(id EntryId) (*EntryRecord, error)
// Task returns nil when absent.
Task(id TaskId) (*TaskRecord[JsonValue, JsonValue, JsonValue], error)
ScanConversations(query ConversationQuery, limit int, cursor Cursor) (Page[ConversationRecord, Cursor], error)
ScanEntries(query EntryQuery, limit int, cursor Cursor) (Page[EntryRecord, Cursor], error)
// LatestHeadMarker returns the newest visible entry of the conversation that carries a Head; nil when none.
LatestHeadMarker(conversationId ConversationId) (*EntryRecord, error)
ScanTasks(query TaskQuery, limit int, cursor Cursor) (Page[TaskRecord[JsonValue, JsonValue, JsonValue], Cursor], error)
// SubmissionByRequest returns the committed submission with a conversation-scoped request ID; nil when absent.
SubmissionByRequest(conversationId ConversationId, requestId string) (*SubmissionRecord, error)
// CreateConversation creates a conversation with explicitly selected ownership.
CreateConversation(options CreateConversationOptions) (ConversationRecord, error)
// ForkConversation creates a history fork at one concrete visible entry with explicitly selected ownership.
ForkConversation(parentConversationId ConversationId, at EntryId, options CreateConversationOptions) (ConversationRecord, error)
// AppendEntry returns a Session-owned immutable record that may be shared with commit listeners.
AppendEntry(conversationId ConversationId, value EntryDraft) (EntryRecord, error)
// CreateTaskErased creates a task of an erased definition with an already JSON-encoded input.
CreateTaskErased(task AnyTask, input JsonValue, options TaskOptions) (TaskId, error)
// CreateSubmission creates a raw submission record with a fresh ID. No admission rules apply: no busy check, no
// inbox queueing, no placement. Use Conversation.Submit or a conversation handle unless the caller implements
// admission itself.
CreateSubmission(create SubmissionCreate) (SubmissionRecord, error)
// SettleSubmission settles a queued or placed submission; only a placed input can be answered, and a settled
// submission stays unchanged. Resolved against this transaction's latest record of the submission, so it works
// after table writes. Run tasks settle the inputs they answer.
SettleSubmission(id SubmissionId, settlement SubmissionSettlement) error
// PlaceSubmission places a queued submission at entry: an input becomes placed, a write done. Resolved like
// SettleSubmission. Inbox boundaries place the submissions they select.
PlaceSubmission(id SubmissionId, entry EntryId) error
// Doc returns the draft of a document, creating it when absent. args are the owner ID (conversation or task
// scope), then the family key and seed (families). A family access without a seed fails as upstream's undefined
// seed does.
Doc(token AnyDocToken, args ...any) (*delta.Object, error)
// RetireDoc retires a document; args are the owner ID and family key as for Doc, without a seed.
RetireDoc(token AnyDocToken, args ...any) error
}
Tx is the transaction surface of one Session commit callback. Table reads and creation results are trusted immutable values and may be shared with internal commit state.
Upstream overloads doc, retireDoc, entry, appendEntry, and createTask by token type; Go methods cannot take type parameters, so the methods take erased tokens and the generic helpers (TxDoc, TxEntry, TxAppendEntry, CreateTask) restore the types.
type TypedEntry ¶
type TypedEntry[D any] struct { EntryRecord TypedData D }
TypedEntry is an entry whose Data has type D; D is Never when the kind carries no data.
func TxAppendEntry ¶
func TxAppendEntry[D any](tx Tx, token Entry[D], conversationId ConversationId, value TypedEntryDraft[D]) (*TypedEntry[D], error)
TxAppendEntry appends an entry of the token's kind.
type TypedEntryDraft ¶
type TypedEntryDraft[D any] struct { Model []ai.Message Data D Edits []ContextEdit Head *EntryId HeadSelf bool }
TypedEntryDraft is entry content of a typed kind; the token supplies Kind.
type WatchEnd ¶
type WatchEnd struct {
Reason WatchEndReason
Error error
}
WatchEnd is the terminal result of one document watch; Error is set only for listener_error.
type WatchEndReason ¶
type WatchEndReason string
WatchEndReason is why a watch ended.
const ( WatchStopped WatchEndReason = "stopped" WatchCancelled WatchEndReason = "cancelled" WatchSessionClosed WatchEndReason = "session_closed" WatchRetired WatchEndReason = "retired" WatchListenerError WatchEndReason = "listener_error" )
type WatchHandle ¶
type WatchHandle[T any] interface { // Value is the acquisition revision before Start and the latest delivered immutable revision afterward. Value() T // Start installs the sole asynchronous listener. It never invokes it inline. Start(listener func(ctx context.Context, value T, ops []Op) error) // Stop idempotently stops future callbacks and returns this watch's terminal result. Stop() (WatchEnd, error) // Closed returns a channel closed when the watch terminates and the terminal result; an already-running callback // remains caller-owned. Closed() <-chan struct{} // End returns the terminal result once Closed is closed. End() WatchEnd }
WatchHandle is a serialized exact-frame observation of an immutable value with bounded pending delivery.
type Wrap ¶
type Wrap struct {
Tool string
WrapTool func(tool *ToolRegistration) *ToolRegistration
Section string
WrapSection func(section *PromptSection) *PromptSection
}
Wrap is built by WrapTool (Tool and WrapTool set) and WrapSection (Section and WrapSection set); it targets a tool name or a section key. Wrappers are pure.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package durabletest holds runner-independent conformance cases and benchmark workloads for durable.Storage implementations.
|
Package durabletest holds runner-independent conformance cases and benchmark workloads for durable.Storage implementations. |
|
Package env declares the portable execution environment of pi-durable: a file system and a shell that tools and prompt sections use through a conversation's environment.
|
Package env declares the portable execution environment of pi-durable: a file system and a shell that tools and prompt sections use through a conversation's environment. |
|
node
Package node is the local execution environment of pi-durable: NodeExecutionEnv runs on the host file system and shell.
|
Package node is the local execution environment of pi-durable: NodeExecutionEnv runs on the host file system and shell. |
|
Package session ports the pi-durable Session kernel: one mutation line, the loaded document tracker cache, transactions, document forks, and committed publication and observation.
|
Package session ports the pi-durable Session kernel: one mutation line, the loaded document tracker cache, transactions, document forks, and committed publication and observation. |
|
sessiontest
Package sessiontest holds the shared Session test support: a controlled memory storage and an opened Session kernel with its publications.
|
Package sessiontest holds the shared Session test support: a controlled memory storage and an opened Session kernel with its publications. |
|
Package storage holds the in-memory reference implementation of the durable Storage contract.
|
Package storage holds the in-memory reference implementation of the durable Storage contract. |
|
internal/ops
Package ops replays stored Chord operation batches for the storage backends.
|
Package ops replays stored Chord operation batches for the storage backends. |
|
internal/writes
Package writes normalizes durable storage writes for the storage backends.
|
Package writes normalizes durable storage writes for the storage backends. |
|
jsonl
Package jsonl is the portable JSONL implementation of the durable Storage contract: one main commit log and per-document and per-task sidecar logs in one directory, accessed through a file system capability.
|
Package jsonl is the portable JSONL implementation of the durable Storage contract: one main commit log and per-document and per-task sidecar logs in one directory, accessed through a file system capability. |
|
jsonl/node
Package node opens JSONL durable storage on the local file system, the Go counterpart of Pi's Node JSONL adapter.
|
Package node opens JSONL durable storage on the local file system, the Go counterpart of Pi's Node JSONL adapter. |
|
sqlite
Package sqlite is the portable SQLite storage core of pi-durable: the database facade, the schema migrations, and SqliteStorage.
|
Package sqlite is the portable SQLite storage core of pi-durable: the database facade, the schema migrations, and SqliteStorage. |
|
sqlite/node
Package node adapts a native SQLite connection to the portable durable SQLite facade.
|
Package node adapts a native SQLite connection to the portable durable SQLite facade. |
|
Package tools is the coding tools of pi-durable: read, write, edit and bash over an execution environment.
|
Package tools is the coding tools of pi-durable: read, write, edit and bash over an execution environment. |