durable

package
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 23 Imported by: 0

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, or an object); JsonObject is *delta.JsonObject, an object that keeps JavaScript's property order. 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

View Source
const (
	DEFAULT_MAX_LINES = 2000      //nolint:revive // upstream identifier
	DEFAULT_MAX_BYTES = 50 * 1024 //nolint:revive // upstream identifier
)
View Source
const (
	ReasonThrew            = "threw"
	ReasonRestartLimit     = "restart_limit"
	ReasonMissingTask      = "missing_task"
	ReasonIncompatibleTask = "incompatible_task"
)

The reasons a report carries in ReportInfo.Reason.

View Source
const DefaultRestartLimit = 5

DefaultRestartLimit is the default of HarnessSettings.RestartLimit.

Variables

View Source
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")
)
View Source
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

func DecodeMessage(data []byte) (ai.Message, error)

DecodeMessage decodes one JSON message by its role.

func DecodeMessages

func DecodeMessages(data []byte) ([]ai.Message, error)

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 ErrorMessage

func ErrorMessage(thrown any) (message string)

ErrorMessage is the message of a thrown (panicked) value, without panicking itself (errors.ts errorMessage): formatting a value can panic, as a String method that panics does (String() throws for Object.create(null) upstream), and code that formats an error must not fail for the value it formats. The fallback is upstream's Object.prototype.toString.call tag of an object.

func FindAssistantToolCall

func FindAssistantToolCall(model []ai.Message, callId string) (ai.ToolCall, bool)

FindAssistantToolCall is the tool call callId of the first message of an assistant entry's model messages.

func FormatSize

func FormatSize(bytes int) string

FormatSize formats bytes as a human-readable size.

func FromJsonValue

func FromJsonValue[T any](value JsonValue) (T, error)

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. A T that is a Go map decodes from the JSON encoding, since the copy of an object is a *delta.JsonObject.

func IdFromNumber

func IdFromNumber[I Id](value int64) I

IdFromNumber applies an ID kind at a trusted numeric allocation or decoding boundary.

func NativeTimer

func NativeTimer(callback func(), delayMs float64, background bool) (disarm func())

NativeTimer is the default HarnessOptions.SetTimer: a Go timer, waiting out delays beyond setTimeout's limit in steps (timers.ts nativeTimer). Go timers never keep a process alive and cannot hold a Durable Object awake, so a background timer is never declined here.

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 TaskAssistantToolCall

func TaskAssistantToolCall[I, S, R, H any](ctx context.Context, runtime TaskRuntime[I, S, R, H], id EntryId, callId string) (ai.ToolCall, bool, error)

TaskAssistantToolCall returns tool call callId of the assistant entry id visible from the task's conversation; found is false when the entry is absent, is not an assistant entry, or has no such call. It is TaskEntry and a scan of the entry's first message, through the runtime's AssistantCallReader when it has one.

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

func Utf8ByteLength(content string) int

Utf8ByteLength is chord/output.Utf8ByteLength, the one implementation shared with the output buffer (truncate.ts re-exports it).

Types

type AfterFailedRun

type AfterFailedRun string

AfterFailedRun is what a failed run does with the inputs queued behind it (HarnessSettings.afterFailedRun).

const (
	AfterFailedRunKeep     AfterFailedRun = "keep"
	AfterFailedRunContinue AfterFailedRun = "continue"
	AfterFailedRunWithdraw AfterFailedRun = "withdraw"
)

The failed-run policies: keep leaves the inputs queued until the next input or queued write, continue starts the next run with them, as an answer would, and withdraw settles them unanswered with reason run_failed.

type Agent

type Agent struct {
	Model         *ModelRef
	ThinkingLevel ai.ModelThinkingLevel
	Extensions    []*Extension
	// Tools are the tools a request offers, in order: enabled, callable by the model, and selected by modelTools.
	Tools []*ToolRegistration
	// Callable are the tools nested calls (executeTool()) resolve among, in order: enabled and callable by tools.
	Callable []*ToolRegistration
	// Deferred are the enabled deferred tools the model may call and is not offered yet, in registry order: what tool_search loads.
	Deferred []*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 decides whether an ordinary change is stored as a complete base. Every definition has one: DefineDoc
	// and DefineDocFamily reject a definition with neither CheckpointWhen nor CheckpointWhenRaw, as upstream's types require
	// checkpointWhen on every definition (documents.ts AnyDocDefinition, types.ts CommonDocDefinition).
	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 struct {
	Definition *AnyTaskDefinition
}

AnyTask is an erased executable task definition stored in the registry, whatever its input, phases, and hooks (harness/types.ts AnyTask = { readonly definition: {...} }).

func (AnyTask) AnyDefinition

func (task AnyTask) AnyDefinition() *AnyTaskDefinition

AnyDefinition returns the erased definition.

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 AssistantCallReader

type AssistantCallReader interface {
	// AssistantToolCall returns tool call callId of assistant entry id, visible from the task's conversation, as the
	// caller's own copy; found is false when the entry is absent, is not an assistant entry, or has no such call.
	AssistantToolCall(ctx context.Context, id EntryId, callId string) (call ai.ToolCall, found bool, err error)
}

AssistantCallReader is implemented by a task runtime that serves one tool call of an assistant entry without copying the whole entry for every read: a round of k parallel calls reads one entry k times, and the entry holds all k.

type AttachedReplicatedState

type AttachedReplicatedState[T any] = *chord.AttachedReplicatedState[T]

AttachedReplicatedState is a synchronously hydrated publication-only Chord state backed by one source attachment.

func DocumentStateOf

func DocumentStateOf[T any](ctx context.Context, session Session, token DocTokenOf[T], args ...any) (AttachedReplicatedState[*T], error)

DocumentStateOf returns a disposable replicated state of a document's committed value decoded as T, or nil when the document is absent; the value is nil once the document retires. args are the owner ID and family key as for TxDoc. The erased form is Session.DocumentStateErased. A listener's failure goes to the Session's report, as Pi's documentState passes `onError: (error) => this.report(error)` (session.ts documentState).

func DocumentStateOfWithOptions

func DocumentStateOfWithOptions[T any](ctx context.Context, session Session, token DocTokenOf[T], options chord.ReplicatedStateSourceOptions, args ...any) (AttachedReplicatedState[*T], error)

DocumentStateOfWithOptions is DocumentStateOf with the attached state's options: OnError also receives a revision that does not decode as T.

type BlockedReason

type BlockedReason string

BlockedReason is why a pending task cannot run here (Pi scheduler.ts BlockedReason): no registered definition takes it (missing_task, task_too_old), its state could not be migrated (migration_failed), or the restart limit parked it (restart_limit). Derived, never persisted; TaskGraph nodes carry it as Blocked.

const (
	BlockedMissingTask     BlockedReason = "missing_task"
	BlockedTaskTooOld      BlockedReason = "task_too_old"
	BlockedMigrationFailed BlockedReason = "migration_failed"
	BlockedRestartLimit    BlockedReason = "restart_limit"
)

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
	// Initial returns the document's first value.
	Initial func() T
	// Migrate converts a value stored by an older version; nil when absent.
	Migrate func(value JsonObject, fromVersion int) (T, error)
	// CheckpointWhen is the required policy: it returns true to store this ordinary change as a complete base instead of
	// a delta. There is no default; a definition without CheckpointWhen and CheckpointWhenRaw is rejected by DefineDoc.
	CheckpointWhen func(value T, ops []Op, info CheckpointInfo) bool
	// CheckpointWhenRaw is CheckpointWhen over the exact prepared JSON object, with no typed decode, and satisfies the
	// requirement in its place. It takes precedence over CheckpointWhen when both are set; a definition that sets both
	// must make them agree. Built-in documents set it so the per-commit predicate costs nothing in the size of the value.
	CheckpointWhenRaw func(value JsonObject, ops []Op, info CheckpointInfo) bool
}

CommonDocDefinition holds the definition fields shared by singleton documents and document families (types.ts:69-79). The singleton definition embeds it; a family definition has its fields except Initial, as upstream's `Omit<CommonDocDefinition<T>, "initial">`.

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"`
	// ModelOverrides is the resolved CompactionSettings.modelOverrides, keyed by exact "provider/modelId"; nil without
	// any. PolicyFor applies it.
	//portlint:allow emptydrop a nil map is Pi's absent modelOverrides (Settings spreads only the keys a host set); an explicit {} is kept
	ModelOverrides map[string]CompactionPolicyOverride `json:"modelOverrides,omitzero"`
}

CompactionPolicy holds the automatic compaction thresholds (spec §8.7); manual compaction ignores Enabled.

func (CompactionPolicy) PolicyFor

func (policy CompactionPolicy) PolicyFor(model ModelRef) CompactionPolicy

PolicyFor is compaction.ts compactionPolicy: the model's modelOverrides entry over the Harness-wide policy, field by field. The result carries no overrides.

type CompactionPolicyOverride

type CompactionPolicyOverride struct {
	Enabled          *bool `json:"enabled,omitempty"`
	ReserveTokens    *int  `json:"reserveTokens,omitempty"`
	KeepRecentTokens *int  `json:"keepRecentTokens,omitempty"`
	BackgroundTokens *int  `json:"backgroundTokens,omitempty"`
}

CompactionPolicyOverride is Partial<CompactionPolicy>: one model's entry of modelOverrides; nil fields keep the Harness-wide value.

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 ContextOptions

type ContextOptions struct {
	// At cuts the context off at this visible entry: the view Fork(At) would start with.
	At *EntryId
}

ContextOptions is the optional argument of a context read.

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

func (*ConversationBusy) Name

func (*ConversationBusy) Name() string

Name is the `name` property, "ConversationBusy".

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

type ConversationDocToken[T any] = DocToken[T]

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
	// Order defaults to ScanAscending; with a cursor, the cursor's order.
	Order *ScanOrder
}

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        map[string]any     `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

type Cursor = map[string]JsonValue

Cursor is backend-owned JSON continuation state that callers only round-trip to the same scan. It carries the scan's order: a scan given a cursor continues in that order, and rejects a different Order in its query.

type DocDefinition

type DocDefinition[T any] struct {
	CommonDocDefinition[T]
	DocumentSemantics
}

DocDefinition is a singleton document definition.

type DocFamilyDefinition

type DocFamilyDefinition[T, I 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 is the required policy: it returns true to store this ordinary change as a complete base instead of
	// a delta. There is no default; DefineDocFamily rejects a definition without it.
	CheckpointWhen func(value T, ops []Op, info CheckpointInfo) bool
	DocumentSemantics
	// Family is upstream's required literal `family: true` (documents.ts FamilyInput); DefineDocFamily panics when it is false.
	Family  bool
	Initial func(seed I) T
}

DocFamilyDefinition is a keyed document family definition; Initial(seed) runs only when a member is absent. It has the fields of CommonDocDefinition except Initial, which takes the seed (types.ts:84-89 `Omit<CommonDocDefinition<T>, "initial"> & ...`).

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, DocumentSemantics is not a member of upstream's union (types.ts:42-60), CheckpointWhen is absent (see DefineDoc), or Family is not true: upstream's FamilyInput requires `family: true` at compile time (documents.ts:31-34), and the erased definition's family flag is what addressing reads (resolveAddress).

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, when DocumentSemantics is not a member of upstream's union (types.ts:42-60), which upstream's overloads reject at compile time, and when the definition has neither CheckpointWhen nor CheckpointWhenRaw: upstream's types require checkpointWhen with no default (types.ts:77-78), so the Go definition names its policy too, `func(T, []Op, CheckpointInfo) bool { return false }` to keep every change a delta.

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.

func (*DocumentContent) UnmarshalJSON

func (content *DocumentContent) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Ops as a delta.Ops batch, so an object an operation carries keeps its JSON key order, as Pi's storage JSON.parse does (storage/sqlite/storage.ts:63, storage/jsonl/storage.ts:118). Value is a JsonObject, which decodes in order itself.

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 DocumentId

type DocumentId int64

DocumentId identifies one document incarnation.

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

type DocumentPoint struct {
	Current bool
	Seq     Seq
}

DocumentPoint is the current state (Current) or one historical commit sequence used for document membership and content reads.

func AtSeq

func AtSeq(seq Seq) DocumentPoint

AtSeq selects one historical commit sequence.

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.

func (DocumentRecord) MarshalJSON

func (record DocumentRecord) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in the order Pi's storages build a record, not the declaration order: the create's own members, then the createdAt and retiredAt that storage stamps (memory.ts and sqlite/storage.ts spread the create first and add retiredAt last).

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.

func WatchDoc

func WatchDoc[T any](ctx context.Context, observer DocumentObserver, token DocTokenOf[T], args ...any) (DocumentWatch[T], error)

WatchDoc returns a watch of a document's committed value decoded as T, or nil when the document is absent; the value is nil once the document retires. args are the owner ID and family key as for TxDoc. The erased form is DocumentObserver.WatchDocErased.

type Draft

type Draft[T any] = *delta.Object

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.

func TxDoc

func TxDoc[T any](tx Tx, token DocTokenOf[T], args ...any) (Draft[T], error)

TxDoc returns the draft of a document in a commit, creating it when absent. args are the owner ID (conversation or task scope), then the family key and seed (families).

type Entry

type Entry[D any] struct {
	Kind string
}

Entry is a typed entry kind with a narrowing guard.

func DefineEntry

func DefineEntry[D any](kind string) Entry[D]

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. MarshalJSON writes either as the
	// wire member head: an entry ID, or "self".
	Head     *EntryId `json:"head,omitempty"`
	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", and Model and Edits when they are not nil, even when empty.

func (*EntryDraft) UnmarshalJSON

func (draft *EntryDraft) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes head "self" as HeadSelf.

type EntryId

type EntryId int64

EntryId identifies a transcript entry.

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
	// Order defaults to ScanDescending; with a cursor, the cursor's order.
	Order *ScanOrder
}

EntryQuery holds inclusive ID bounds for a 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 and Edits when they are not nil, even when empty: upstream keeps a present empty list.

func (*EntryRecord) UnmarshalJSON

func (entry *EntryRecord) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes Model by message role.

type EntryWrite

type EntryWrite struct{ Value EntryRecord }

EntryWrite persists a new entry.

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

type HookRegistration struct {
	Task     string
	Handlers any
}

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 HostCallback

type HostCallback string

HostCallback is a host callback, by its HarnessOptions name; env is the environment builder, models a provider call.

const (
	HostCallbackNow      HostCallback = "now"
	HostCallbackSettings HostCallback = "settings"
	HostCallbackRegistry HostCallback = "registry"
	HostCallbackEnv      HostCallback = "env"
	HostCallbackModels   HostCallback = "models"
	HostCallbackSetTimer HostCallback = "setTimer"
	HostCallbackOnWake   HostCallback = "onWake"
)

The host callbacks a report can name.

type Id

type Id interface {
	~int64
}

Id is any durable record ID; every kind shares the Session-global numeric namespace.

type InputEntry

type InputEntry struct {
	// Kind is a non-empty string that does not start with "pi.".
	Kind string `json:"kind"`
	// Data is the JSON payload of the placed entry; nil when absent.
	Data JsonValue `json:"data,omitempty"`
}

InputEntry is the entry an input is placed as, instead of pi.user: an application kind, and data the transcript shows, such as its author. Its model message is still the input's user message (types.ts InputEntry).

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

type JsonObject = *delta.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 an object. Objects that durable decodes or copies are *delta.JsonObject, which keeps JavaScript's property order; a Go map a caller supplies has no order and is copied in own-key order.

func CopyJson

func CopyJson(value JsonValue) (JsonValue, error)

CopyJson returns a detached copy of a JSON value.

func ToJsonValue

func ToJsonValue(value any) (JsonValue, error)

ToJsonValue returns a detached strict JSON copy of value: nil, bool, float64, string, []any, or *delta.JsonObject. 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 LatestConversationSemantics

type LatestConversationSemantics struct {
	DocumentSemantics
}

LatestConversationSemantics is a conversation document that retains only its current state: the DocumentSemantics member {scope: "conversation", history: "latest"} whose fork is current or initial (types.ts:41-46). Go has no literal types, so NewLatestConversationSemantics fixes the scope and history and DefineDoc rejects a fork a latest document cannot have.

func NewLatestConversationSemantics

func NewLatestConversationSemantics(fork DocumentFork) LatestConversationSemantics

NewLatestConversationSemantics is the latest conversation semantics with the given fork, ForkCurrent or ForkInitial.

type ModelRef

type ModelRef struct {
	Provider string `json:"provider"`
	ModelId  string `json:"modelId"`
}

ModelRef is a provider and model ID resolved through pi-ai Models.

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 NestedCallOptions

type NestedCallOptions struct {
	// Key names the call among this call's nested calls, so a rerun finds it. It is a path segment of the nested call's
	// ID: non-empty, without "/", not "__proto__", and not a positive integer, which default keys use. Nil: the call's
	// order among this call's nested calls.
	Key *string
	// Progress false commits no running output, details, or diagnostics to the call's slot; the result still gets them.
	Progress *bool
	// ArgumentsJSON is args as JSON text in the caller's member order, such as the text a script's object came from. A Go
	// map has no order, and Pi keeps the order of the arguments object: the stored call, its slot, validation, hooks and
	// the execute intent write args' members in this order. Members it lacks follow in sorted order. Nil: sorted order.
	ArgumentsJSON json.RawMessage
}

NestedCallOptions are the options of ExecuteTool (types.ts ToolExecutionApi.executeTool).

type NestedToolExecutionResult

type NestedToolExecutionResult struct {
	// TaskId is the nested call's tool task.
	TaskId TaskId
	// StructuredOutput is the tool's value for programs, present when HasStructuredOutput. A tool with a schema: its
	// validated structured output, also on an error result that has one; absent otherwise, and an error's text is then in an
	// error diagnostic. A tool without: its bounded output, success or error, as a string for one text item, an ImageContent
	// for one image, "" for none, and the content list otherwise. Absent on an error result the Harness wrote itself
	// (unavailable, invalid, blocked, interrupted, aborted); Diagnostics say what went wrong.
	StructuredOutput    JsonValue
	HasStructuredOutput bool
	IsError             bool
	Details             JsonValue
	HasDetails          bool
	Diagnostics         []ToolDiagnostic
	Usage               *ai.Usage
	// DurationMs is the execution time of the attempt that produced the result; nil when it never executed.
	DurationMs *int64
}

NestedToolExecutionResult is the result of a nested call, as ExecuteTool returns it. Programs read StructuredOutput; the output for the model is not kept, and Control does not apply.

func (NestedToolExecutionResult) MarshalJSON

func (result NestedToolExecutionResult) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in declaration order, leaving out the absent ones.

func (*NestedToolExecutionResult) UnmarshalJSON

func (result *NestedToolExecutionResult) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a result written by MarshalJSON; a present null member is a value.

type Never

type Never struct{}

Never is the data type of entry kinds that carry no data.

type NextTaskState

type NextTaskState[S, R any] = TaskState[S, R]

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 Op

type Op = delta.Op

Op is one Chord delta operation (packages/chord/src/delta).

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.

const (
	QueueAll        QueueMode = "all"
	QueueOneAtATime QueueMode = "one-at-a-time"
)

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

func (*ReadAfterWrite) Name

func (*ReadAfterWrite) Name() string

Name is the `name` property, "ReadAfterWrite".

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 ReportFrom

type ReportFrom struct {
	Type      ReportFromType
	Extension string
	Callback  HostCallback
}

ReportFrom is whose code a task's runtime.Report is about when not the task's own: an extension's (Extension, when known), or a host callback (Callback).

type ReportFromType

type ReportFromType string

ReportFromType is whose code a task's runtime.Report is about when not the task's own.

const (
	ReportFromExtension ReportFromType = "extension"
	ReportFromHost      ReportFromType = "host"
)

The sources ReportFrom names.

type ReportInfo

type ReportInfo struct {
	Type           ReportType
	Task           *ReportTask
	Extension      string
	Reason         string
	Callback       HostCallback
	ConversationId *ConversationId
}

ReportInfo says what a report to HarnessOptions.OnReport is about. Extension, where set, names the extension whose code failed, when known; for a task's own code, the one that installed the definition the task ran. Task is set for the task types, and for an extension_error or host_error that a task caused. ConversationId is set for an extension_error outside a task. Reason is set for task_faulted and task_outdated; Callback for host_error.

type ReportTask

type ReportTask struct {
	Id TaskId `json:"id"`
	// Kind is the task's registered name.
	Kind           string         `json:"kind"`
	ConversationId ConversationId `json:"conversationId"`
}

ReportTask is the task a report is about.

type ReportType

type ReportType string

ReportType is what a report to HarnessOptions.OnReport is about.

const (
	// ReportSessionFailed: the error failed the Session, which closes: a Storage error, often a platform reset.
	ReportSessionFailed ReportType = "session_failed"
	// ReportTaskFaulted: the task ended faulted: its phase threw (ReasonThrew), or its abort handler was cut off
	// settings.restartLimit times (ReasonRestartLimit).
	ReportTaskFaulted ReportType = "task_faulted"
	// ReportTaskParked: the restart limit parked the task until Harness.RetryTask.
	ReportTaskParked ReportType = "task_parked"
	// ReportMigrationFailed: the task's stored state could not be migrated; it is blocked until the registry changes.
	ReportMigrationFailed ReportType = "migration_failed"
	// ReportTaskOutdated: a running task keeps running under its old definition, which was uninstalled (missing_task)
	// or replaced by one that cannot take over its state (incompatible_task).
	ReportTaskOutdated ReportType = "task_outdated"
	// ReportTaskError: the task's own runtime.Report, or a failure in running it.
	ReportTaskError ReportType = "task_error"
	// ReportExtensionError: a hook, a section, a wrapper, or a tool's invalid structured output; with the task that ran
	// it, or, outside a task, the conversation whose agent was resolved.
	ReportExtensionError ReportType = "extension_error"
	// ReportHostError: a host callback threw; with the task that called it, if one did.
	ReportHostError ReportType = "host_error"
	// ReportListenerError: a commit, close, watch, view, or document listener threw.
	ReportListenerError ReportType = "listener_error"
)

The report types.

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

type RewindableConversationDocToken[T any] = DocToken[T]

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 RewindableConversationSemantics

type RewindableConversationSemantics struct {
	DocumentSemantics
}

RewindableConversationSemantics is a conversation document whose history remains addressable for as-of reads: the DocumentSemantics member {scope: "conversation", history: "rewindable"} whose fork is asOf, current or initial (types.ts:48-53).

func NewRewindableConversationSemantics

func NewRewindableConversationSemantics(fork DocumentFork) RewindableConversationSemantics

NewRewindableConversationSemantics is the rewindable conversation semantics with the given fork, ForkAsOf, ForkCurrent or ForkInitial.

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 ScanOrder

type ScanOrder string

ScanOrder is the ID order of a scan.

const (
	// ScanAscending is oldest first.
	ScanAscending ScanOrder = "ascending"
	// ScanDescending is newest first.
	ScanDescending ScanOrder = "descending"
)

type SectionWrap

type SectionWrap struct {
	Section string
	Wrap    func(section *PromptSection) *PromptSection
}

SectionWrap is the `{ section: string; wrap(section: PromptSection<Tool>): PromptSection<Tool> }` member of Wrap.

type Seq

type Seq int64

Seq is the strictly increasing sequence assigned to one atomic storage commit; gaps are permitted.

func SeqFromNumber

func SeqFromNumber(value int64) Seq

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. Inside the callback read only through tx: Snapshot, DocumentState, WatchDoc, GetTask and the other Session and runtime reads may queue on the line the callback holds, and then never return.
	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()
	// Closed returns a channel closed once the Session ended: after close reached the backend, or a failure ended it.
	Closed() <-chan struct{}
	// End returns how the Session ended once Closed is closed.
	End() SessionEnd
	// 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) (DocumentState[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

type SessionDocToken[T any] = DocToken[T]

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 SessionEnd

type SessionEnd struct {
	Reason SessionEndReason
	Error  error
}

SessionEnd is the terminal result of one Session; Error is the first error that failed it, set only for failed.

type SessionEndReason

type SessionEndReason string

SessionEndReason is how a Session ended: closed by its owner, or failed.

const (
	SessionEndClosed SessionEndReason = "closed"
	SessionEndFailed SessionEndReason = "failed"
)

type SessionFailed

type SessionFailed struct {
	Cause error
}

SessionFailed reports that the Session failed, so nothing runs or commits any more. It fails when a Storage method fails, a commit cannot be adopted, or the Harness's own bookkeeping fails (a scheduler commit, an internal commit listener, a registry whose snapshot fails). Cause is that first error. Reopen the Session; reopening recovers from what was committed.

func NewSessionFailed

func NewSessionFailed(cause error) *SessionFailed

NewSessionFailed returns the error for a Session that failed with cause.

func (*SessionFailed) Error

func (*SessionFailed) Error() string

func (*SessionFailed) Name

func (*SessionFailed) Name() string

Name is the `name` property, "SessionFailed".

func (*SessionFailed) Unwrap

func (e *SessionFailed) Unwrap() error

Unwrap returns the cause.

type SetTimer

type SetTimer func(callback func(), delayMs float64, background bool) (disarm func())

SetTimer is a host timer, given as HarnessOptions.SetTimer: call callback once, about delayMs from now, and return a function that disarms it. Background timers only free memory, and a host may decline one by returning nil, for example where a pending timer keeps the process from hibernating; the Harness then frees that memory at later commits. Other timers pace or resume work: one the host panics on or declines is armed with a Go timer. A timer should not fire early; callers check their clock again when it fires.

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
	// ContextRetentionMs is how long an idle conversation keeps its last context read in memory, so its next run reads
	// only newer entries. Busy conversations always keep it; 0 drops it once the conversation is idle.
	ContextRetentionMs float64
	// DocumentRetentionMs is how long a loaded document that no watch or document state observes stays in memory after
	// its last read or write; the next access loads it from Storage. Observed documents always stay. Default ten
	// minutes; 0 drops one right after use; +Inf keeps them.
	DocumentRetentionMs float64
	// AfterFailedRun is what a run that fails (model_error, no_model) does with the inputs queued behind it.
	AfterFailedRun AfterFailedRun
	// RestartLimit is how many times in a row a task may be cut off by a crash, eviction, or reset (a close does not
	// count) without changing its state before it is parked as blocked (restart_limit); Harness.RetryTask runs it
	// again. +Inf never parks.
	RestartLimit float64
}

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 query.Order (default ascending) by ID.
	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 in query.Order (default descending), 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 in query.Order (default ascending) by ID.
	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 query.Order (default ascending) by ID.
	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 StorageRequestError

type StorageRequestError struct {
	Message string
}

StorageRequestError reports that a Storage read rejected an invalid request, such as an unknown conversation or a cursor from another scan, with no durable effect. Unlike any other error a Storage returns, it fails only that read, not the Session; from a commit it is fatal like any other.

func NewStorageRequestError

func NewStorageRequestError(message string) *StorageRequestError

NewStorageRequestError returns the error for a rejected read request.

func (*StorageRequestError) Error

func (e *StorageRequestError) Error() string

func (*StorageRequestError) Name

func (*StorageRequestError) Name() string

Name is the `name` property, "StorageRequestError".

func (*StorageRequestError) Unwrap

func (*StorageRequestError) Unwrap() error

Unwrap returns nil: a StorageRequestError has no cause.

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 {
	Trace          telemetry.TelemetryCarrier `json:"trace,omitzero"`
	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

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
	// InputEntry places an input as that entry; nil places it as pi.user without data. Only input submissions carry it
	// (types.ts SubmissionDraft: an input's `entry` is an InputEntry, a write's is an EntryDraft).
	InputEntry *InputEntry
	Entry      *EntryDraft
}

SubmissionDraft is a host submission: user input (type input, with Content, an optional WhenBusy and an optional InputEntry) that may start a run, or a passive entry write (type write, with Entry).

type SubmissionId

type SubmissionId int64

SubmissionId identifies a submission.

type SubmissionQuery

type SubmissionQuery struct {
	ConversationId *ConversationId
	Status         *SubmissionStatus
	// Order defaults to ScanAscending; with a cursor, the cursor's order.
	Order *ScanOrder
}

SubmissionQuery holds optional filters for an ordered scan of submission records.

type SubmissionRecord

type SubmissionRecord struct {
	// Trace is the adapter-owned context of the admission span; absent without propagation.
	Trace          telemetry.TelemetryCarrier `json:"trace,omitzero"`
	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.

func (Task[I, S, R, H]) Erased

func (task Task[I, S, R, H]) Erased() AnyTask

Erased returns the task as the erased AnyTask a registry, an Extension and CreateTaskErased take. Pi's Task is assignable to AnyTask because it has a definition property; Go's Task has a typed Definition, so the erased form is explicit. The zero Task has no definition and erases to the zero AnyTask.

type TaskAbortReason

type TaskAbortReason string

TaskAbortReason is why a task's abort mark was set when not by an abort request.

const AbortedByRestart TaskAbortReason = "restart"

AbortedByRestart marks a task abandoned after a restart (TaskOptions.AbandonOnRestart), or below one.

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

type TaskDocToken[T any] = DocToken[T]

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 {
	// Trace omitted (nil) inherits the creator's carrier; a Carrier overrides it; Root starts at the adapter root
	// without a stored carrier.
	Trace *TaskTrace
	// Links are immutable creation-time links, attached to the spans of this task's first invocation.
	Links []telemetry.TelemetryCarrier
	// 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
	// AbandonOnRestart marks a task whose creator awaits it only in memory and does not resume after a restart, so it is
	// pointless once the Harness that created it is gone. When scheduling starts in a later Harness, the task, if still
	// live, is abort-marked with reason "restart", and the mark cascades to its ordinary owned work, before any of it
	// runs again. Nil is unset: a task a tool that is not replay-safe creates through its api then defaults to true
	// (tool.ts:338); false keeps it off.
	AbandonOnRestart *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
	// Order defaults to ScanAscending; with a cursor, the cursor's order.
	Order *ScanOrder
}

TaskQuery holds optional filters for an ordered scan of durable task records.

type TaskRecord

type TaskRecord[I, S, R any] struct {
	// Trace is the adapter-owned context that created this task; phase invocations extract it as their parent.
	Trace telemetry.TelemetryCarrier `json:"trace,omitzero"`
	// Links are the immutable creation-time links for the task's first invocation.
	Links          []telemetry.TelemetryCarrier `json:"links,omitzero"`
	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"`
	// AbortReason is why the mark was set when not by an abort request: "restart" for a task abandoned after a restart
	// (TaskOptions.AbandonOnRestart) or below one. Such a task waits for its definition instead of becoming orphaned. A
	// later abort request clears it. Empty when absent.
	AbortReason TaskAbortReason `json:"abortReason,omitempty"`
	// AbandonOnRestart is set from TaskOptions.AbandonOnRestart. Immutable.
	AbandonOnRestart bool            `json:"abandonOnRestart,omitempty"`
	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"`
	// StartedAt is the wall-clock time in milliseconds of the first change to running, stamped by the Session. It is
	// kept through waits and recovery, so the span to EndedAt includes them. Nil before the task first runs, and on
	// records written by earlier versions.
	StartedAt *float64 `json:"startedAt,omitempty"`
	// EndedAt is the wall-clock time in milliseconds of the change to terminal, stamped by the Session; nil while live.
	EndedAt *float64 `json:"endedAt,omitempty"`
	// Restarts is how many times in a row a crash, eviction, or reset cut the task off while it ran, without the task
	// changing its state since; open counts them, and a close does not. At HarnessSettings.RestartLimit the task is
	// parked as blocked until Harness.RetryTask. Zero when absent.
	Restarts int `json:"restarts,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)
	// AbortOwned aborts a task this task owns, as Harness.AbortTask does, and returns once it is terminal. It fails
	// for a task another owns, and returns at once for a terminal one.
	AbortOwned(ctx context.Context, id TaskId) error
	// OwnedTasks returns the live tasks this task owns directly, in ID order: also those an earlier invocation created,
	// before a restart. Tasks in conversations it owns are not included. The records are copies of the committed ones.
	OwnedTasks(ctx context.Context) ([]TaskRecord[JsonValue, JsonValue, 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
	// options.At when it is set.
	Context(ctx context.Context, conversationId ConversationId, options *ContextOptions) (ContextView, error)
	// Now returns the Harness clock.
	Now() float64
	// Report forwards a non-fatal failure to HarnessOptions.OnReport with this task in its info: a task_error about the
	// task's own code, or, with from, an extension_error about extension code it called, such as a section, or a
	// host_error about a host callback, such as the environment builder.
	Report(err error, from ...ReportFrom)
	// SetTimer calls callback once after about delayMs on the Harness's timer (HarnessOptions.SetTimer), for pacing
	// work inside a phase, such as throttled progress commits. It is not durable: the invocation's end disarms it, and
	// after its end nothing is armed. The returned function disarms it. Wait for time between phases with SleepUntil.
	SetTimer(callback func(), delayMs float64) (disarm func())
	// SleepUntil commits a sleep: the task holds no invocation until the Harness clock reaches until, then resumes at
	// checkpoint. It returns once the sleep is stored, not when the time comes; the phase returns right after.
	// Returning a TaskSleeping state from Commit is the same sleep, for one that must commit together with other
	// writes.
	SleepUntil(ctx context.Context, until float64, checkpoint S) 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 TaskSource

type TaskSource interface {
	AnyDefinition() *AnyTaskDefinition
}

TaskSource is anything that holds an erased task definition: a Task, or an AnyTask.

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"`
	Until      *float64        `json:"until,omitempty"`
	Outcome    *TaskOutcome[R] `json:"outcome,omitempty"`
}

TaskState is the complete durable execution state of a task. Live statuses (pending, running, waiting, sleeping) carry Checkpoint; waiting also carries On and Policy; sleeping also carries Until; completing and terminal carry Outcome.

func (TaskState[S, R]) MarshalJSON

func (state TaskState[S, R]) MarshalJSON() ([]byte, error)

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"
	// TaskSleeping is parked without an invocation until the Harness clock reaches Until, in milliseconds on the
	// HarnessOptions.Now clock; then resumes at Checkpoint. An abort mark does not wait for it.
	TaskSleeping TaskStatus = "sleeping"
	// 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 TaskTrace

type TaskTrace struct {
	// Root selects `"root"`; Carrier is then ignored.
	Root    bool
	Carrier telemetry.TelemetryCarrier
}

TaskTrace is TaskOptions.trace, `TelemetryCarrier | "root"`: an explicit carrier override, or Root to start at the adapter root without a stored carrier. A nil *TaskTrace is upstream's omitted or undefined trace.

type TaskWrite

type TaskWrite struct {
	Value TaskRecord[JsonValue, JsonValue, JsonValue]
}

TaskWrite persists the complete replacement record of a task.

type Timers

type Timers struct {
	// Foreground arms a timer that paces or resumes work; when the host panics on or declines it, a Go timer arms it
	// instead.
	Foreground func(callback func(), delayMs float64) (disarm func())
	// Background arms a timer that only frees memory; nil when the host declines it.
	Background func(callback func(), delayMs float64) (disarm func())
}

Timers are the timers the Session and Harness arm through the host's SetTimer (timers.ts Timers).

func HostTimers

func HostTimers(setTimer SetTimer, report func(err error)) Timers

HostTimers wraps a host SetTimer (timers.ts hostTimers). A foreground timer must fire, or work stalls: one the host panics on or declines is armed with NativeTimer, and the first such failure is reported. A background one the host panics on is reported and declined.

type ToolCaller

type ToolCaller string

ToolCaller is a kind of caller a tool admits (types.ts ToolRegistration.callers).

const (
	CallerModel ToolCaller = "model"
	CallerTools ToolCaller = "tools"
)

The kinds of tool callers.

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)
	// Models is HarnessOptions.models: the catalog, credentials, and request transforms generation uses.
	Models() Models
	// Env is built by HarnessOptions.env for this call; nil without an environment.
	Env() env.ExecutionEnv
	// Now is the Harness clock (HarnessOptions.Now), for times a rerun after a restart compares against.
	Now() float64
	// Output appends running output, a string or []byte; it becomes the result content when the result omits
	// Content. The optional skipped marks 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. Only the first skipped counts.
	Output(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
	// RetainedOutput is the output retained so far, as the model will see it when the result omits Output, and whether
	// earlier output was dropped; for a tool that also returns that text in its StructuredOutput.
	RetainedOutput() (text string, truncated bool)
	// 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 one commit in the calling conversation; options.ConversationId is ignored. A
	// child task of a tool that is not replay-safe defaults to AbandonOnRestart: the tool never resumes after a restart,
	// so nothing awaits the child then (harness/types.ts:232-234).
	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)
	// ExecuteTool calls another tool as a nested call: its own pi.tool task owned by this call, which runs validation, the
	// ToolTask hooks (whose ToolHookCall carries the parent), and the tool, and whose result comes back here, not in
	// the transcript. A nested call that ends in an error result still returns it; the error return is for a call that
	// could not be made or waited for. Calls made without a key are keyed by their order, so a rerun that calls in the
	// same order reattaches to the calls it made. Cancelling ctx stops only the wait.
	ExecuteTool(ctx context.Context, name string, args map[string]any, options ...NestedCallOptions) (NestedToolExecutionResult, 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 {
	// Output is for the model; nil when omitted: the retained output() text becomes the output.
	Output []ai.ToolResultMessageContent
	// StructuredOutput is for programs that call the tool (executeTool() callers, code mode scripts), present only when
	// HasStructuredOutput is true. A tool that declares a structured output schema must return one unless the result is
	// an error, and it is validated against the schema; a tool without a schema must not return one, and programs get
	// the output itself.
	StructuredOutput    JsonValue
	HasStructuredOutput bool
	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
	// StructuredOutputSchema is the JSON schema of StructuredOutput, which programs that call the tool receive. Nil: they
	// receive the result's bounded output, success or error.
	StructuredOutputSchema map[string]any
	// Callers is who may call the tool: the model, other tools through executeTool(), or both (nil, the default). A
	// code mode tool is {CallerModel}, so scripts cannot start scripts; tools behind code mode, such as MCP tools, can
	// be {CallerTools}, so the model is never offered them.
	Callers []ToolCaller
	// Deferred tools are not offered to the model until loaded: the model gets the tool only when modelTools names it, in
	// its exact list or its add, which a tool such as tool_search writes with the addTools control. Other tools can call it
	// any time.
	Deferred bool
	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.

func (*ToolRegistration) CallableBy

func (tool *ToolRegistration) CallableBy(caller ToolCaller) bool

CallableBy reports whether the tool admits the caller kind: a tool without callers admits 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 ToolWrap

type ToolWrap struct {
	Tool string
	Wrap func(tool *ToolRegistration) *ToolRegistration
}

ToolWrap is the `{ tool: string; wrap(tool: Tool): Tool }` member of Wrap.

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

type TruncationTotals struct {
	Lines int
	Bytes int
}

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 TaskEntry

func TaskEntry[D, I, S, R, H any](ctx context.Context, runtime TaskRuntime[I, S, R, H], token Entry[D], id EntryId) (*TypedEntry[D], error)

TaskEntry returns the committed entry visible from the task's conversation when it is present and has the token's kind; nil otherwise (types.ts:219, the typed overload of TaskRuntime.entry).

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.

func TxEntry

func TxEntry[D any](tx Tx, token Entry[D], id EntryId) (*TypedEntry[D], error)

TxEntry returns the entry when it is present and has the token's kind; nil otherwise.

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 UserInput

type UserInput = ai.UserContent

UserInput is the content of a user message.

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 and session_failed.

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"
	// WatchSessionFailed ends a watch when the Session failed; Error is the failure.
	WatchSessionFailed WatchEndReason = "session_failed"
)

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 WhenBusy

type WhenBusy string

WhenBusy is the busy policy of an input submission.

const (
	WhenBusySteer    WhenBusy = "steer"
	WhenBusyFollowUp WhenBusy = "followUp"
	WhenBusyReject   WhenBusy = "reject"
)

type Wrap

type Wrap interface {
	// contains filtered or unexported methods
}

Wrap is upstream's `{ tool; wrap(tool) } | { section; wrap(section) }` (harness/types.ts:263-265): a sealed union of ToolWrap, built by WrapTool, and SectionWrap, built by WrapSection. A wrap targets a tool name or a section key. Wrappers are pure.

Directories

Path Synopsis
Package codemode is durable code mode: a tool that runs model-written JavaScript in a QuickJS sandbox, whose script survives a restart.
Package codemode is durable code mode: a tool that runs model-written JavaScript in a QuickJS sandbox, whose script survives a restart.
Package core is PiG's synchronous Durable core (docs/plan/durable-core, ADR-0001): one deterministic state machine per Session that takes an ABI 1 event and returns a step of commits, reads, notices and effects.
Package core is PiG's synchronous Durable core (docs/plan/durable-core, ADR-0001): one deterministic state machine per Session that takes an ABI 1 event and returns a step of commits, reads, notices and effects.
abi
Package abi is the Durable core host ABI 1 (docs/plan/durable-core/ABI.md): the event, step and value types, their wire codecs, the step builder every core package emits into, and ID, the abi_id every build exports.
Package abi is the Durable core host ABI 1 (docs/plan/durable-core/ABI.md): the event, step and value types, their wire codecs, the step builder every core package emits into, and ID, the abi_id every build exports.
abi/abitest
Package abitest reads ABI event scripts and runs them through a native core.
Package abitest reads ABI event scripts and runs them through a native core.
abi/payload
Package payload holds the JSON shapes of ABI 1 event and effect payloads as hosts send and read them (ABI sections 5-7).
Package payload holds the JSON shapes of ABI 1 event and effect payloads as hosts send and read them (ABI sections 5-7).
abi/spec
Package spec holds the normative tables of ABI 1 (docs/plan/durable-core/ABI.md sections 4-8) and computes abi_id, the sha256 of their canonical rendering.
Package spec holds the normative tables of ABI 1 (docs/plan/durable-core/ABI.md sections 4-8) and computes abi_id, the sha256 of their canonical rendering.
abi/spec/cmd/abigen command
Command abigen writes durable/core/abi/id.go (the abi_id constant the core exports) and durable/core/abi/abi.json (the tables and abi_id the JavaScript hosts read) from the tables in package spec.
Command abigen writes durable/core/abi/id.go (the abi_id constant the core exports) and durable/core/abi/abi.json (the tables and abi_id the JavaScript hosts read) from the tables in package spec.
budget/coldhints command
Command coldhints marks the functions that the first turn of a session runs in a core built by build-wasm.sh, as WebAssembly compilation hints, so that a host that enables hints compiles them with Liftoff when it compiles the module instead of one at a time on its first call.
Command coldhints marks the functions that the first turn of a session runs in a core built by build-wasm.sh, as WebAssembly compilation hints, so that a host that enables hints compiles them with Liftoff when it compiles the module instead of one at a time on its first call.
budget/tinygo/patchdata command
Command patchdata writes the start address of .data, and the ranges of the globals that hold no heap pointers, into a TinyGo core built with the runtime fork in budget/tinygo.
Command patchdata writes the start address of .data, and the ranges of the globals that hold no heap pointers, into a TinyGo core built with the runtime fork in budget/tinygo.
cmd/corenative command
Command corenative serves the Durable core, built natively, to a host in another process over two FIFOs: the same exports as the WASI reactor (cmd/corewasm), one request and one response at a time.
Command corenative serves the Durable core, built natively, to a host in another process over two FIFOs: the same exports as the WASI reactor (cmd/corewasm), one request and one response at a time.
contracttest
Package contracttest is the Go side of the Durable core conformance gate (docs/plan/durable-core/CONTRACT.md sections 5-7).
Package contracttest is the Go side of the Durable core conformance gate (docs/plan/durable-core/CONTRACT.md sections 5-7).
contracttest/boundary
Package boundary checks that the production core links none of the reflection-driven standard-library packages TinyGo cannot build faithfully (go list -deps over the core packages, the Go and the Wasm configuration).
Package boundary checks that the production core links none of the reflection-driven standard-library packages TinyGo cannot build faithfully (go list -deps over the core packages, the Go and the Wasm configuration).
contracttest/cmd/benchhost command
Command benchhost runs the durable-bench scenario (CONTRACT section 6: W1, W2, W4c, X1 and the H handoff rows) on the production Durable core packages as a native bench host.
Command benchhost runs the durable-bench scenario (CONTRACT section 6: W1, W2, W4c, X1 and the H handoff rows) on the production Durable core packages as a native bench host.
contracttest/cmd/countgate command
Command countgate measures what the Durable core costs on a recorded workload (package counts): bytes allocated, mallocs, Wasm instructions on an instrumented module, native instructions under callgrind, and the growth of the live set per turn.
Command countgate measures what the Durable core costs on a recorded workload (package counts): bytes allocated, mallocs, Wasm instructions on an instrumented module, native instructions under callgrind, and the growth of the live set per turn.
contracttest/cmd/replayhost command
Command replayhost is a script-driven stand-in for a native Durable core host: it applies the statements of a recorded trace to a SQLite store, one transaction per commit, and writes its own trace with contracttest.Writer.
Command replayhost is a script-driven stand-in for a native Durable core host: it applies the statements of a recorded trace to a SQLite store, one transaction per commit, and writes its own trace with contracttest.Writer.
contracttest/cmd/scprovider command
Command scprovider serves the core's write encoder to the storage conformance suite (CONTRACT 3.10, the SC row): the suite's Storage is pi-durable's SqliteStorage for every read, and this process for commit and mintId.
Command scprovider serves the core's write encoder to the storage conformance suite (CONTRACT 3.10, the SC row): the suite's Storage is pi-durable's SqliteStorage for every read, and this process for commit and mintId.
contracttest/counts
Package counts is the Durable core's deterministic count gate (Durable plan 2, item 9) and its flight recorder format.
Package counts is the Durable core's deterministic count gate (Durable plan 2, item 9) and its flight recorder format.
contracttest/fuel
Package fuel meters a WebAssembly module: Instrument rewrites a module so that every basic block adds its own length to a counter, the Wasm instruction count the count gate ratchets (docs/plan/durable-core, Durable plan 2 item 9).
Package fuel meters a WebAssembly module: Instrument rewrites a module so that every basic block adds its own length to a counter, the Wasm instruction count the count gate ratchets (docs/plan/durable-core, Durable plan 2 item 9).
contracttest/guard
Package guard bounds a native host process of the conformance gate: a request that runs too long, a heap that grows past a limit, or a parent that has gone.
Package guard bounds a native host process of the conformance gate: a request that runs too long, a heap that grows past a limit, or a parent that has gone.
contracttest/storehost
Package storehost is the synchronous SQLite host of ABI section 3 for the store alone: tooling that drives store.Store (the benchmark engine, the storage-conformance provider) applies a step's commits and answers its reads with it.
Package storehost is the synchronous SQLite host of ABI section 3 for the store alone: tooling that drives store.Store (the benchmark engine, the storage-conformance provider) applies a step's commits and answers its reads with it.
docs
Package docs holds the built-in conversation documents of src/harness/agent.ts and provider.ts that no machine owns: pi.agent and pi.provider, and the conversation-creation step for pi.agent.
Package docs holds the built-in conversation documents of src/harness/agent.ts and provider.ts that no machine owns: pi.agent and pi.provider, and the conversation-creation step for pi.agent.
driver
Package driver holds the native Go effect executors of the Durable core (docs/plan/durable-core/ABI.md section 6, ADR-0001 D17).
Package driver holds the native Go effect executors of the Durable core (docs/plan/durable-core/ABI.md section 6, ADR-0001 D17).
history
Package history is the transcript half of the Durable core: entries, forks, head markers, context edits, compaction ranges and reset, and the context derivation that turns them into the model's messages.
Package history is the transcript half of the Durable core: entries, forks, head markers, context edits, compaction ranges and reset, and the context derivation that turns them into the model's messages.
history/internal/buildcheck command
Command buildcheck links the history package into a program so that TinyGo (-target=wasip1 -scheduler=none), Go wasip1 and native Go build the same source.
Command buildcheck links the history package into a program so that TinyGo (-target=wasip1 -scheduler=none), Go wasip1 and native Go build the same source.
inbox
Package inbox is the Session-side submission queue of src/harness/inbox.ts and submissions.ts: the built-in pi.inbox document, the boundaries that place queued items, and admission, abort and withdrawal of submissions.
Package inbox is the Session-side submission queue of src/harness/inbox.ts and submissions.ts: the built-in pi.inbox document, the boundaries that place queued items, and admission, abort and withdrawal of submissions.
internal/delta
Package delta ports Chord's immutable JSON deltas (@earendil-works/chord 1.0.4 `delta`: operations, the immutable applier and the overlay draft tracker) onto the ordered value model of package jv.
Package delta ports Chord's immutable JSON deltas (@earendil-works/chord 1.0.4 `delta`: operations, the immutable applier and the overlay draft tracker) onto the ordered value model of package jv.
jv
Package jv is the ordered JSON value model of the Durable core's session layer.
Package jv is the ordered JSON value model of the Durable core's session layer.
probe
Package probe is a small ABI 1 core that exists to test hosts.
Package probe is a small ABI 1 core that exists to test hosts.
rec
Package rec is the record layer for the records the core rewrites: pi-durable's conversation, task, submission and document records (spec §2, §3.2, §5.1, §6), written in pi-durable main da866ada's shapes and read tolerantly from 1.0.4 and newer stores (CONTRACT section 2.3).
Package rec is the record layer for the records the core rewrites: pi-durable's conversation, task, submission and document records (spec §2, §3.2, §5.1, §6), written in pi-durable main da866ada's shapes and read tolerantly from 1.0.4 and newer stores (CONTRACT section 2.3).
session
Package session is the Durable core's Session layer: the Session line, the transaction that stages one atomic commit (conversations, entries, tasks, submissions and documents), the document cache, and the task scheduler.
Package session is the Durable core's Session layer: the Session line, the transaction that stages one atomic commit (conversations, entries, tasks, submissions and documents), the document cache, and the task scheduler.
session/cmd/tgprobe command
Command tgprobe links the session layer's packages so the TinyGo build can prove they compile without reflection.
Command tgprobe links the session layer's packages so the TinyGo build can prove they compile without reflection.
session/hopcost
Package hopcost derives, in microtask ticks, how long Pi's Storage adapters take, so the core can park a line job on a hops chain as long as Pi's job (ABI.md section 5.3).
Package hopcost derives, in microtask ticks, how long Pi's Storage adapters take, so the core can park a line job on a hops chain as long as Pi's job (ABI.md section 5.3).
session/sessiontest
Package sessiontest provides an in-memory session.Store that keeps all committed state, as pi-durable's MemoryStorage does.
Package sessiontest provides an in-memory session.Store that keeps all committed state, as pi-durable's MemoryStorage does.
sqlhost
Package sqlhost is the native Go host of the Durable core (docs/plan/durable-core/ABI.md section 11, ADR-0001 D17).
Package sqlhost is the native Go host of the Durable core (docs/plan/durable-core/ABI.md section 11, ADR-0001 D17).
sqlhost/cmd/bench command
Command bench is the native candidate of the Durable conformance gate (durable/contract/impls/native.mjs): the bench scenario (durable/contract/scenarios/bench.mjs) run through the native session on the core, with its statements written as a trace of statements only (contracttest.Writer), which the Node tools replay onto the starting store.
Command bench is the native candidate of the Durable conformance gate (durable/contract/impls/native.mjs): the bench scenario (durable/contract/scenarios/bench.mjs) run through the native session on the core, with its statements written as a trace of statements only (contracttest.Writer), which the Node tools replay onto the starting store.
store
Package store owns pi-durable's SQLite format inside the core: the SQL table, the rows every commit writes (CONTRACT section 3.1, row identity with pi-durable main), the single-writer guard, the in-memory metadata, cold open of the live state (ADR D5), loads of committed non-live records, and the pig_ sidecar (ADR D6).
Package store owns pi-durable's SQLite format inside the core: the SQL table, the rows every commit writes (CONTRACT section 3.1, row identity with pi-durable main), the single-writer guard, the in-memory metadata, cold open of the live state (ADR D5), loads of committed non-live records, and the pig_ sidecar (ADR D6).
turn
Ports packages/ai/src/utils/overflow.ts (OVERFLOW_PATTERNS, NON_OVERFLOW_PATTERNS) Ports packages/ai/src/utils/retry.ts (RETRYABLE_PROVIDER_ERROR_PATTERN, NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN)
Ports packages/ai/src/utils/overflow.ts (OVERFLOW_PATTERNS, NON_OVERFLOW_PATTERNS) Ports packages/ai/src/utils/retry.ts (RETRYABLE_PROVIDER_ERROR_PATTERN, NON_RETRYABLE_PROVIDER_LIMIT_ERROR_PATTERN)
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.
env
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 images is the image processor of pi-durable: it prepares the images read returns so the model can take them.
Package images is the image processor of pi-durable: it prepares the images read returns so the model can take them.
cloudflare
Package cloudflare is the image processor for Cloudflare Workers and Durable Objects.
Package cloudflare is the image processor for Cloudflare Workers and Durable Objects.
node
Package node is the image processor for hosts that load Photon's WebAssembly from an installed package.
Package node is the image processor for hosts that load Photon's WebAssembly from an installed package.
internal
detach
Package detach deep-copies the durable records that cross a storage or Harness boundary, so the copy shares no mutable memory with what it was read from.
Package detach deep-copies the durable records that cross a storage or Harness boundary, so the copy shares no mutable memory with what it was read from.
entryscan
Package entryscan is the read-only range seam between the Harness context derivation and the storages that retain decoded entries.
Package entryscan is the read-only range seam between the Harness context derivation and the storages that retain decoded entries.
ordered
Package ordered gives the dynamic JSON members of a decoded Go value the key order of their JSON text.
Package ordered gives the dynamic JSON members of a decoded Go value the key order of their JSON text.
schemabackup
Package schemabackup copies a file-backed durable SQLite store before PiG upgrades its schema (D188).
Package schemabackup copies a file-backed durable SQLite store before PiG upgrades its schema (D188).
search
Package search ranks tools for code mode's searchTools() and the tool_search tool with BM25.
Package search ranks tools for code mode's searchTools() and the tool_search tool with BM25.
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/scan
Package scan resolves the order and position of a built-in storage scan.
Package scan resolves the order and position of a built-in storage scan.
internal/serial
Package serial is the one operation queue of the SQLite database adapters: operations run in call order and a transaction holds the queue until it settles (Pi's SerialQueue and the promise chain of NodeSqliteDatabase).
Package serial is the one operation queue of the SQLite database adapters: operations run in call order and a transaction holds the queue until it settles (Pi's SerialQueue and the promise chain of NodeSqliteDatabase).
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 durable schema, its migrations, and SqliteStorage.
Package sqlite is the portable SQLite storage core of pi-durable: the durable schema, its migrations, and SqliteStorage.
sqlite/cloudflare
Package cloudflare opens durable storage on the SQLite storage of a Cloudflare Durable Object.
Package cloudflare opens durable storage on the SQLite storage of a Cloudflare Durable Object.
sqlite/node
Package node opens durable storage on a native SQLite connection.
Package node opens durable storage on a native SQLite connection.
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.
Package toolsearch is the `tool_search` tool, a copy of the coding agent's: the model searches the deferred tools it is not offered yet, and the matches are loaded with the addTools control, so the next request offers them.
Package toolsearch is the `tool_search` tool, a copy of the coding agent's: the model searches the deferred tools it is not offered yet, and the matches are loaded with the addTools control, so the next request offers them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL