harness

package
v0.4.1 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const InstructionsKey = "instructions"

InstructionsKey is the reserved section key of the agent's instructions.

Variables

View Source
var AgentDoc = durable.DefineDoc(durable.DocDefinition[AgentState]{
	CommonDocDefinition: durable.CommonDocDefinition[AgentState]{
		Kind:           "pi.agent",
		Version:        1,
		CheckpointWhen: func(AgentState, []durable.Op, durable.CheckpointInfo) bool { return true },
	},
	DocumentSemantics: durable.DocumentSemantics{
		Scope:   durable.ScopeConversation,
		History: durable.HistoryRewindable,
		Fork:    durable.ForkAsOf,
	},
	Initial: func() AgentState { return AgentState{} },
})

AgentDoc is the built-in agent document; rewindable so forks start from the agent at their fork entry.

CompactionTask is the built-in compaction task (spec §8.7, compaction.ts:96-231): it selects an old prefix of the model context, summarizes it, and places a summary entry whose head is the first kept entry. A compaction the generation owns blocks it and appends directly; a conversation-owned one places its summary through a write submission. Its handlers admit submissions, which start generations, so the definition is assigned in init.

View Source
var DefaultCompactionPolicy = durable.CompactionPolicy{
	Enabled:          true,
	ReserveTokens:    16384,
	KeepRecentTokens: 20000,
	BackgroundTokens: 32768,
}

DefaultCompactionPolicy is the built-in compaction policy (agent.ts:25-30).

View Source
var DefaultProgressPolicy = durable.ProgressPolicy{
	PartialIntervalMs: 100,
	OutputIntervalMs:  100,
}

DefaultProgressPolicy is the built-in progress policy.

View Source
var DefaultRetryPolicy = durable.ConversationRetryPolicy{
	Enabled:         true,
	MaxRetries:      3,
	BaseDelayMs:     2000,
	MaxAgentDelayMs: new(60000),
}

DefaultRetryPolicy is the built-in durable generation retry policy (agent.ts:18-23).

View Source
var ErrClosed = errors.New("Harness is closed")

ErrClosed is the error of an operation on a closed Harness.

GenerationTask is the built-in generation task (generation.ts:107-273): it prepares the positional system prompt and tool loadout, requests or polls the model, retries, and classifies the response. The run's inputs live in pi.live.run. Its handlers create successor generations, so the definition is assigned in init.

View Source
var InboxDoc = durable.DefineDoc(durable.DocDefinition[InboxState]{
	CommonDocDefinition: durable.CommonDocDefinition[InboxState]{
		Kind:    "pi.inbox",
		Version: 1,
		CheckpointWhen: func(value InboxState, _ []durable.Op, _ durable.CheckpointInfo) bool {
			return len(value.Items) == 0
		},
	},
	DocumentSemantics: durable.DocumentSemantics{
		Scope:   durable.ScopeConversation,
		History: durable.HistoryLatest,
		Fork:    durable.ForkInitial,
	},
	Initial: func() InboxState { return InboxState{Items: []InboxItem{}} },
})

InboxDoc is the built-in pi.inbox document; a complete base is stored exactly while it is empty (inbox.ts:16-24).

View Source
var LiveDoc = durable.DefineDoc(durable.DocDefinition[LiveState]{
	CommonDocDefinition: durable.CommonDocDefinition[LiveState]{
		Kind:    "pi.live",
		Version: 1,
		CheckpointWhen: func(value LiveState, _ []durable.Op, _ durable.CheckpointInfo) bool {
			if value.Generation != nil {
				return false
			}
			for _, slot := range value.Tools {
				if slot.Status == ToolSlotRunning {
					return false
				}
			}
			return true
		},
	},
	DocumentSemantics: durable.DocumentSemantics{
		Scope:   durable.ScopeConversation,
		History: durable.HistoryLatest,
		Fork:    durable.ForkInitial,
	},
	Initial: func() LiveState { return LiveState{} },
})

LiveDoc is the built-in pi.live document (live.ts:64-77). A complete base is stored whenever nothing runs (spec §8.2): no generation and no running tool slot. That bounds the delta chain to one generation or one round's tools, and a slot holds output only while running, so every base is small.

View Source
var ProviderDoc = durable.DefineDoc(durable.DocDefinition[ProviderState]{
	CommonDocDefinition: durable.CommonDocDefinition[ProviderState]{
		Kind:    "pi.provider",
		Version: 1,
		CheckpointWhen: func(ProviderState, []durable.Op, durable.CheckpointInfo) bool {
			return true
		},
	},
	DocumentSemantics: durable.DocumentSemantics{
		Scope:   durable.ScopeConversation,
		History: durable.HistoryLatest,
		Fork:    durable.ForkInitial,
	},
	Initial: newProviderState,
})

ProviderDoc is the built-in provider state; every fork starts with a fresh identity instead of copying its parent, and every change stores a complete base (provider.ts:12-20).

ToolTask is the built-in tool task (tool.ts:48-120): it resolves the called tool among its phase agent's tools, validates, runs beforeTool, records intent, executes, runs afterTool, and appends the result, all in one call handler so nothing separates resolution from settlement. execute is reached only by recovery and applies the replay rule.

View Source
var UsageDoc = durable.DefineDoc(durable.DocDefinition[UsageState]{
	CommonDocDefinition: durable.CommonDocDefinition[UsageState]{
		Kind:    "pi.usage",
		Version: 1,
		CheckpointWhen: func(UsageState, []durable.Op, durable.CheckpointInfo) bool {
			return true
		},
	},
	DocumentSemantics: durable.DocumentSemantics{
		Scope:   durable.ScopeConversation,
		History: durable.HistoryLatest,
		Fork:    durable.ForkInitial,
	},
	Initial: NewUsageState,
})

UsageDoc is the built-in per-conversation usage ledger. Every change stores a complete base (usage.ts:21).

Functions

func ActiveEntries

func ActiveEntries(ctx context.Context, storage durable.Storage, conversationId durable.ConversationId, bounds *ContextBounds) ([]durable.EntryRecord, error)

ActiveEntries returns the raw active entries within captured bounds, without deriving model context.

func AddCompactionStatus

func AddCompactionStatus(live *delta.Object, status CompactionStatus) error

AddCompactionStatus adds the status of a compaction task created in this commit; statuses stay in task ID order.

func AddTools

func AddTools(tx durable.Tx, conversationId durable.ConversationId, added []string) error

AddTools applies the addTools control of a tool round: an exact list gets each name it lacks appended, {remove} loses the names, and unset tools already offer every tool, so nothing is written.

func AddUsage

func AddUsage(total *ai.Usage, usage ai.Usage)

AddUsage adds every counter of usage to total; optional counters are added once either side reports them (usage.ts:43-57).

func AddUsageState

func AddUsageState(sum *UsageState, state UsageState)

AddUsageState adds every bucket of state into sum (usage.ts:60-74).

func AdmitSubmission

func AdmitSubmission(tx durable.Tx, conversationId durable.ConversationId, draft durable.SubmissionDraft, now float64, queueModes QueueModes) (durable.SubmissionId, error)

AdmitSubmission admits a submission inside a commit (spec §6, submissions.ts:136-207); Conversation.Submit and conversation-owned compactions share it. A known request ID returns its existing submission without writing. A busy conversation queues it in pi.inbox, or rejects whenBusy reject input with ConversationBusy. An idle conversation with queued items queues it behind them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends its entry and settles done, or stale when its head reaches before the active range.

func AgentHooks

func AgentHooks(agent durable.Agent, taskName string) []any

AgentHooks returns the handlers of the selected extensions' hooks for a task name, in extension order.

func AppendToolResult

func AppendToolResult(tx durable.Tx, conversationId durable.ConversationId, call ai.ToolCall, result durable.ToolExecutionResult, timestamp float64) (*durable.TypedEntry[durable.ToolResultEntryData], error)

AppendToolResult appends a pi.tool-result entry (tool.ts:438-460). The content ends with the rendered diagnostics, so the stored message is exactly what the model sees; data keeps the structured list. A result's usage is added to pi.usage in the same commit.

func AssignJson

func AssignJson(target *delta.Object, key string, value durable.JsonValue) error

AssignJson assigns value at target[key] leaf by leaf. Chord records a container assignment as one full set and only emits an append when a string leaf is reassigned with a longer string, so writing the partial whole would store and publish the complete message on every flush.

func BuiltinTasks

func BuiltinTasks() []durable.AnyTask

BuiltinTasks are the built-in task definitions every registry holds; they are not an extension and cannot be removed or replaced.

func CharacterEnd

func CharacterEnd(data []byte, index int) int

CharacterEnd returns the last character boundary at or before index.

func ClearProgress

func ClearProgress(slot *delta.Object)

ClearProgress removes what a tool published while running; its result entry or a rerun replaces it.

func Configure

func Configure(tx durable.Tx, conversationId durable.ConversationId, change AgentChange) error

Configure applies one change to pi.agent: a set field replaces the stored one, a cleared field removes it, and an unset field changes nothing.

func ConvertPartial

func ConvertPartial(tx durable.Tx, live *delta.Object, conversationId durable.ConversationId) error

ConvertPartial appends a committed partial left by an interrupted, aborted, faulted, or orphaned attempt as an aborted assistant entry; the caller replaces or removes generation (generation.ts:346-352).

func CreateAgent

func CreateAgent(tx durable.Tx, conversation durable.ConversationRecord) error

CreateAgent is the built-in part of every Harness commit that creates or forks a conversation, for pi.agent: a fork keeps its asOf copy; a new task-owned conversation copies the stored agent of its owner task's conversation; a new ownerless one starts empty.

func CreateCompaction

func CreateCompaction(tx durable.Tx, conversationId durable.ConversationId, input CompactionInput, owner *durable.TaskId) (durable.TaskId, error)

CreateCompaction creates a compaction task with its status in this commit (compaction.ts:237-251). owner is the generation that waits for it (a blocking compaction); without one it is conversation-owned, and background unless it is manual.

func DefineExtension

func DefineExtension(extension durable.Extension) *durable.Extension

DefineExtension types an extension. Upstream returns its argument; the Go registry compares extensions by pointer, so it returns a pointer to it.

func DefineTool

DefineTool types a tool; the Harness validates arguments against Parameters before Execute.

func DeriveContext

func DeriveContext(ctx context.Context, storage durable.Storage, conversationId durable.ConversationId, bounds *ContextBounds) (durable.ContextView, error)

DeriveContext derives the active transcript and model context of one conversation within captured bounds.

H is the newest visible head marker; the range runs from H.Head (or transcript start) through the tail. Per target, the newest edit in the range wins. Context entries are H followed by the range's non-head entries.

func EndRun

func EndRun(tx durable.Tx, live *delta.Object, taskId durable.TaskId, settlement durable.SubmissionSettlement) error

EndRun ends the run owned by taskId: it settles each of its inputs and removes run. It always removes generation and tools, whose presentation belongs to the ending run (live.ts:88-95).

func EstimateContext

func EstimateContext(view durable.ContextView, extra []ai.Message) int

EstimateContext returns the size of a request over view followed by extra (spec §8.3, compaction.ts:325-341): the usage of the newest assistant appended after the head marker, whose request included the marker, plus estimates of the messages after it; without one, estimates of every message.

func FindCompactionStatus

func FindCompactionStatus(live *delta.Object, taskId durable.TaskId) *delta.Object

FindCompactionStatus returns the status draft of compaction task taskId, or nil when not listed.

func FindToolSlot

func FindToolSlot(live *delta.Object, taskId durable.TaskId) *delta.Object

FindToolSlot returns the slot draft of tool task taskId in the current round, or nil when the round no longer lists it.

func FinishSlot

func FinishSlot(slot *delta.Object, entry *durable.EntryId) error

FinishSlot marks a slot done: the result entry, if any, now carries its running output, details, and diagnostics.

func HarnessError

func HarnessError(code, message string) durable.ToolExecutionResult

HarnessError is an error result the Harness writes itself: no content and one error diagnostic with code (tool.ts:413-415).

func Hook

func Hook[I, S, R, H any](task durable.Task[I, S, R, H], handlers H) durable.HookRegistration

Hook returns hook handlers for tasks with task's name. handlers is the task's hook handler set (for example GenerationHooks); unset members do not run. The handler set's type is the task's hook type, as upstream types handlers by HooksOf<K>.

func IsStale

func IsStale(boundary *Boundary, entry durable.EntryDraft) bool

IsStale reports whether a head write targets an entry before the active range, so placing it would bring back cut history (inbox.ts:111-113).

func OrderToolResults

func OrderToolResults(messages []ai.Message) []ai.Message

OrderToolResults places each assistant's tool results directly after it in call order. Results are taken from the messages before the next assistant; a missing result is synthesized and unmatched results are dropped.

func ReadContext

func ReadContext(ctx context.Context, session lineReader, storage durable.Storage, conversationId durable.ConversationId, at *durable.EntryId) (durable.ContextView, error)

ReadContext returns the committed context of one conversation: bounds captured on the Session line, entries derived off it.

func RecordUsage

func RecordUsage(tx durable.Tx, conversationId durable.ConversationId, bucket UsageBucket, key string, usage ai.Usage) error

RecordUsage adds usage to one bucket of the conversation's pi.usage, in the commit that records the response (usage.ts:25-40).

func RemoveCompactionStatus

func RemoveCompactionStatus(live *delta.Object, taskId durable.TaskId) error

RemoveCompactionStatus removes the status of compaction task taskId, and the list once empty.

func RemoveInboxItem

func RemoveInboxItem(tx durable.Tx, conversationId durable.ConversationId, id durable.SubmissionId) error

RemoveInboxItem removes a withdrawn submission's item; the caller settles the submission.

func ResolveAgent

func ResolveAgent(state *AgentState, snapshot durable.RegistrySnapshot, settings durable.Settings, report func(error)) durable.Agent

ResolveAgent resolves an agent from its stored state (nil: every field unset), a registry snapshot, and resolved settings. A wrapper that panics or renames drops its target and is reported; a wrapper without a target does nothing.

func ResolveSettings

func ResolveSettings(settings *HarnessSettings) durable.Settings

ResolveSettings resolves host settings: every field over its built-in default, object fields merged.

func SanitizeOutput

func SanitizeOutput(text string) string

SanitizeOutput removes control characters that break display and transcripts; tabs and newlines stay. It removes U+0000-U+0008, U+000B-U+001F, and U+FFF9-U+FFFB (output.ts:24).

func ScanAll

func ScanAll[T any](scan func(cursor durable.Cursor) (durable.Page[T, durable.Cursor], error)) ([]T, error)

ScanAll returns every item of a paginated scan, in page order.

func Section

func Section(key string, render func(ctx context.Context, input durable.PromptInput) (*string, error), options ...SectionOptions) *durable.PromptSection

Section returns a prompt section; tagged unless options set Tag false. Without options, or with Tag nil, Tag stays unset, as upstream leaves the field absent when options?.tag is undefined (define.ts:20-26).

func SelectCut

func SelectCut(view durable.ContextView, keepRecentTokens int) (int, bool)

SelectCut returns the index in view.Entries of the first entry a summary keeps; ok is false when there is nothing to compact (spec §8.7, compaction.ts:259-277). It walks back from the tail until keepRecentTokens are kept, then cuts at the first candidate at or after that entry: an entry whose contribution starts with a user or assistant message, never a tool result, and never a user entry that a result of the preceding assistant's calls still follows.

func SerializeConversation

func SerializeConversation(messages []ai.Message) string

SerializeConversation writes messages as plain text, so the summarizer reads a transcript instead of continuing it. System messages are omitted (compaction.ts:369-397).

func SettleSchedulerOutcome

SettleSchedulerOutcome is the Harness cleanup for a terminal outcome the scheduler writes itself (faulted or orphaned), passed to the scheduler, which does not know task kinds (spec §5.4, live.ts:136-164). A run task ends its run; a tool task's slot is marked done without an entry, and context derivation synthesizes the missing result; a compaction task's status is removed. Other kinds are ignored so it never creates pi.live elsewhere. A committed generation partial becomes an aborted assistant entry, exactly as in the generation abort handler, so the transcript keeps what the model produced and pi.usage counts its spend.

func StartRun

func StartRun(tx durable.Tx, conversationId durable.ConversationId, live *delta.Object, inputs []durable.SubmissionId) error

StartRun starts a run for inputs, placed input submissions: a new generation takes pi.live.run.

func SummarizedMessages

func SummarizedMessages(view durable.ContextView, cut int) []ai.Message

SummarizedMessages returns the model messages of the entries before cut: the head marker first, ordered like model context (spec §2.1).

func WithdrawQueuedInputs

func WithdrawQueuedInputs(tx durable.Tx, conversationId durable.ConversationId) error

WithdrawQueuedInputs withdraws every queued input of a conversation, as Conversation.Abort and abort cascades do: each settles unanswered with aborted and leaves the inbox; queued writes stay for later placement (inbox.ts:127-136).

func WrapSection

func WrapSection(key string, wrapper func(section *durable.PromptSection) *durable.PromptSection) durable.Wrap

WrapSection wraps the section key wherever the wrapping extension is selected.

func WrapTool

WrapTool wraps the tool named like tool wherever the wrapping extension is selected.

Types

type AgentChange

type AgentChange struct {
	Model         Change[durable.ModelRef]
	ThinkingLevel Change[ai.ModelThinkingLevel]
	Extensions    Change[ExtensionChange]
	Tools         Change[ToolChange]
	Instructions  Change[string]
	Cwd           Change[string]
}

AgentChange is a change to pi.agent: a set field replaces the stored one, a cleared field removes it, and an unset field changes nothing.

type AgentChangedEvent

type AgentChangedEvent struct {
	Agent AgentState `json:"agent"`
}

func (AgentChangedEvent) EventType

func (AgentChangedEvent) EventType() string

func (AgentChangedEvent) MarshalJSON

func (event AgentChangedEvent) MarshalJSON() ([]byte, error)

type AgentEvent

type AgentEvent interface {
	EventType() string
}

AgentEvent is an experimental agent event, shaped like the coding agent's session events (spec §9.4).

type AgentEventStream

type AgentEventStream struct {
	// Snapshot is the snapshot event at attachment.
	Snapshot SnapshotEvent
	// contains filtered or unexported fields
}

AgentEventStream is the serialized stream of one conversation's event batches, one per commit.

func WatchEvents

func WatchEvents(ctx context.Context, harness Harness, conversationId durable.ConversationId) (*AgentEventStream, error)

WatchEvents attaches to one conversation's agent events (spec §9.4). The snapshot and the registration for later commits are captured atomically on the Session line; overflow replaces undelivered batches with one snapshot.

func (*AgentEventStream) Closed

func (stream *AgentEventStream) Closed() <-chan struct{}

Closed is closed when the stream ends; End returns why.

func (*AgentEventStream) End

func (stream *AgentEventStream) End() durable.WatchEnd

End returns the terminal result once Closed is closed.

func (*AgentEventStream) Start

func (stream *AgentEventStream) Start(listener func(ctx context.Context, events []AgentEvent) error)

Start installs the sole listener; it never runs inline.

func (*AgentEventStream) Stop

func (stream *AgentEventStream) Stop() (durable.WatchEnd, error)

Stop idempotently stops the stream and returns its terminal result.

type AgentState

type AgentState struct {
	Model         *durable.ModelRef     `json:"model,omitempty"`
	ThinkingLevel ai.ModelThinkingLevel `json:"thinkingLevel,omitempty"`
	// Extensions: an exact list selects exactly these extensions, in order; an edit changes the host default selection.
	Extensions *ExtensionSelection `json:"extensions,omitempty"`
	// Tools filters the selected extensions' tools. An exact list offers exactly these, in order.
	Tools *ToolSelection `json:"tools,omitempty"`
	// Instructions render after every extension section, as the section instructions.
	Instructions *string `json:"instructions,omitempty"`
	// Cwd is a directory within the environment's file system, passed to HarnessOptions.Env.
	Cwd *string `json:"cwd,omitempty"`
}

AgentState holds the stored choices of one conversation; names, not objects. Unset fields follow the host.

type AutoRetryEndEvent

type AutoRetryEndEvent struct {
	Attempt int `json:"attempt"`
}

func (AutoRetryEndEvent) EventType

func (AutoRetryEndEvent) EventType() string

func (AutoRetryEndEvent) MarshalJSON

func (event AutoRetryEndEvent) MarshalJSON() ([]byte, error)

type AutoRetryStartEvent

type AutoRetryStartEvent struct {
	Attempt      int     `json:"attempt"`
	At           float64 `json:"at"`
	ErrorMessage string  `json:"errorMessage"`
}

func (AutoRetryStartEvent) EventType

func (AutoRetryStartEvent) EventType() string

func (AutoRetryStartEvent) MarshalJSON

func (event AutoRetryStartEvent) MarshalJSON() ([]byte, error)

type BeforeToolResult

type BeforeToolResult struct {
	Arguments durable.JsonObject
	Block     *string
}

BeforeToolResult is a beforeTool decision: a non-nil Block blocks the call, otherwise non-nil Arguments replace its arguments.

type Boundary

type Boundary struct {
	ConversationId durable.ConversationId
	// Inbox is the pi.inbox draft of the boundary's commit.
	Inbox        *delta.Object
	SteeringMode durable.QueueMode
	FollowUpMode durable.QueueMode
	// Head is the start of the active range, the newest head marker's head; advanced by heads written in this
	// commit. Nil when no head marker exists.
	Head *durable.EntryId
}

Boundary is what a boundary reads before the commit's first table write, and the newest head it has seen so far.

func PrepareBoundary

func PrepareBoundary(tx durable.Tx, conversationId durable.ConversationId, modes QueueModes) (*Boundary, error)

PrepareBoundary reads what a boundary needs. Table reads must precede the commit's first table write, so callers prepare the boundary at the start of their commit (inbox.ts:44-55).

type BoundaryAt

type BoundaryAt string

BoundaryAt is where a boundary runs: after a tool round, or at the end of a run.

const (
	BoundaryPostTools BoundaryAt = "postTools"
	BoundaryFinal     BoundaryAt = "final"
)

type BoundaryResult

type BoundaryResult struct {
	Users []durable.SubmissionId
	Reset bool
}

BoundaryResult holds the selected user items, in ID order, and whether a head "self" write (a reset) was placed.

func ApplyBoundary

func ApplyBoundary(tx durable.Tx, boundary *Boundary, at BoundaryAt, now float64) (BoundaryResult, error)

ApplyBoundary places the queued items a boundary selects (spec §6, inbox.ts:65-108): every write, the first or all steers, and at final the first or all follow-ups. A selected reset turns a postTools boundary into final. Writes are placed first and user items after them, each in ID order, so user items queued before a reset run in the new context. A write whose head targets an entry before the active range, including a range started earlier in this commit, is stale. Selected and stale items are removed positionally.

type BoundedOutput

type BoundedOutput struct {
	Text         string `json:"text"`
	DroppedBytes int    `json:"droppedBytes"`
	DroppedLines int    `json:"droppedLines"`
}

BoundedOutput is retained output and what the limits dropped.

type Change

type Change[T any] struct {
	// contains filtered or unexported fields
}

Change is one field of AgentChange: unset leaves the stored field, Cleared removes it, and SetTo replaces it.

func Cleared

func Cleared[T any]() Change[T]

Cleared returns a change that removes the stored field (upstream null).

func SetTo

func SetTo[T any](value T) Change[T]

SetTo returns a change that replaces the stored field with value.

type CompactionCheckpoint

type CompactionCheckpoint struct {
	Phase string `json:"phase"`
	*SummaryRequest
	Until *float64 `json:"until,omitempty"`
}

CompactionCheckpoint is the durable checkpoint of the compaction task: select, summarize (with the request), or retry (with the request and Until).

func (CompactionCheckpoint) MarshalJSON

func (checkpoint CompactionCheckpoint) MarshalJSON() ([]byte, error)

MarshalJSON writes the select phase without request members.

type CompactionDecision

type CompactionDecision struct {
	Decline bool
	Summary *string
}

CompactionDecision is a beforeCompact decision: Decline, or a Summary to use instead of summarizing.

type CompactionEndEvent

type CompactionEndEvent struct {
	TaskId durable.TaskId           `json:"taskId"`
	Reason durable.CompactionReason `json:"reason"`
}

CompactionEndEvent: the task's receipt tells whether it produced a summary; the summary entry has its own events.

func (CompactionEndEvent) EventType

func (CompactionEndEvent) EventType() string

func (CompactionEndEvent) MarshalJSON

func (event CompactionEndEvent) MarshalJSON() ([]byte, error)

type CompactionHooks

type CompactionHooks struct {
	// BeforeCompact runs after range selection, before summarizing; the first decision wins.
	BeforeCompact func(ctx context.Context, compaction CompactionRequest, api HookApi) (*CompactionDecision, error)
}

CompactionHooks are the hooks of the built-in compaction task. A nil member does not run. Register them as *CompactionHooks.

type CompactionInput

type CompactionInput struct {
	Reason       durable.CompactionReason `json:"reason"`
	Instructions *string                  `json:"instructions,omitempty"`
}

CompactionInput is the input of the built-in compaction task.

type CompactionPolicyPatch

type CompactionPolicyPatch struct {
	Enabled          *bool
	ReserveTokens    *int
	KeepRecentTokens *int
	BackgroundTokens *int
}

CompactionPolicyPatch is Partial<CompactionPolicy>; nil fields keep the defaults.

type CompactionRequest

type CompactionRequest struct {
	Reason       durable.CompactionReason
	Entries      []durable.EntryRecord
	Messages     []ai.Message
	FirstKept    durable.EntryId
	Instructions *string
}

CompactionRequest is what a beforeCompact hook sees: Entries are the active entries the summary replaces, the head marker first, and Messages their model context, the summarizer's source; FirstKept is the first entry kept verbatim.

type CompactionResult

type CompactionResult struct {
	EntryId      *durable.EntryId      `json:"entryId,omitempty"`
	SubmissionId *durable.SubmissionId `json:"submissionId,omitempty"`
}

CompactionResult carries the EntryId of a blocking compaction's summary, or the SubmissionId of a conversation-owned compaction's summary write; both nil when nothing was compacted.

type CompactionStartEvent

type CompactionStartEvent struct {
	TaskId   durable.TaskId           `json:"taskId"`
	Reason   durable.CompactionReason `json:"reason"`
	Blocking bool                     `json:"blocking"`
}

func (CompactionStartEvent) EventType

func (CompactionStartEvent) EventType() string

func (CompactionStartEvent) MarshalJSON

func (event CompactionStartEvent) MarshalJSON() ([]byte, error)

type CompactionStatus

type CompactionStatus struct {
	TaskId durable.TaskId           `json:"taskId"`
	Reason durable.CompactionReason `json:"reason"`
	// Blocking reports whether a generation waits for it: a compaction the generation owns.
	Blocking bool `json:"blocking"`
	Attempt  int  `json:"attempt"`
	// Retry is the durable backoff before the next summarization attempt.
	Retry *RetryStatus `json:"retry,omitempty"`
}

CompactionStatus is the presentation of one live compaction task (spec §8.7, live.ts:34-43).

type ContextBounds

type ContextBounds struct {
	// Head is the newest visible head marker at or below Tail; nil when none.
	Head *durable.EntryRecord
	Tail durable.EntryId
}

ContextBounds are the head marker and newest visible entry that fix one committed context range.

func CaptureContextBounds

func CaptureContextBounds(ctx context.Context, storage durable.Storage, conversationId durable.ConversationId, at *durable.EntryId) (*ContextBounds, error)

CaptureContextBounds captures the bounds of the current context, or of the context cut off at the visible entry at, with two O(1) reads; nil when the conversation has no entry. Run it on the Session line; entries at or below the tail are immutable, so DeriveContext can then scan them off the line.

type Conversation

type Conversation interface {
	Id() durable.ConversationId
	// Agent resolves the agent with the current registry snapshot and settings.
	Agent(ctx context.Context) (durable.Agent, error)
	// Configure applies change in its own commit.
	Configure(ctx context.Context, change AgentChange) error
	// Submit durably admits user input or a passive entry write. A busy conversation, or one with queued items, queues it in pi.inbox; WhenBusy reject fails with ConversationBusy instead and writes nothing.
	Submit(ctx context.Context, submission durable.SubmissionDraft) (durable.Submission, error)
	// Reset admits a write of a pi.reset entry that starts a new context, carrying handoff as a user message when non-nil. It returns after admission; while busy, it is placed at the next boundary.
	Reset(ctx context.Context, handoff *string) error
	// Compact admits a manual compaction task and returns its ID (spec §8.7).
	Compact(ctx context.Context, instructions *string) (durable.TaskId, error)
	// Commit runs a Session commit whose tx.CreateTask defaults to this conversation.
	Commit(ctx context.Context, change func(tx durable.Tx) (any, error)) (any, error)
	Context(ctx context.Context) (durable.ContextView, error)
	// Entries returns the newest-first fork-aware history of this conversation; query.ConversationId is ignored.
	Entries(ctx context.Context, query durable.EntryQuery, limit int, cursor durable.Cursor) (durable.Page[durable.EntryRecord, durable.Cursor], error)
	Fork(ctx context.Context, at durable.EntryId, options ConversationCreateOptions) (Conversation, error)
	// Abort withdraws queued inputs (queued writes stay), marks every live non-background task of the ordinary ownership scope, signals them, and returns once the scope is idle. Background subtrees survive unless options.Background is set.
	Abort(ctx context.Context, options *durable.ConversationAbortOptions) error
	// WaitForIdle returns when the ordinary ownership scope has no live non-background task.
	WaitForIdle(ctx context.Context) error
	// ViewState returns the structural view (spec §9.3) as a disposable read-only Chord state.
	ViewState(ctx context.Context) (durable.AttachedReplicatedState[ConversationView], error)
	// Watch returns the structural view as a serialized exact-frame watch with bounded pending frames.
	Watch(ctx context.Context) (ConversationWatch, error)
}

Conversation is a stateless handle for one conversation, bound to the Harness that returned it. Compare handles by Id.

type ConversationCreateOptions

type ConversationCreateOptions struct {
	Ownership durable.ConversationOwnership
	// Agent is applied in the creating commit after the creation hook's copy, before Init; nil when absent.
	Agent *AgentChange
	Init  ConversationInit
}

ConversationCreateOptions are the options of creating or forking a conversation.

type ConversationInit

type ConversationInit func(tx durable.Tx, conversationId durable.ConversationId) error

ConversationInit runs inside the creating commit, after the creation hook and the agent change. The conversation creation is already a table write, so table reads here fail with ReadAfterWrite; document access remains available.

type ConversationView

type ConversationView struct {
	Conversation durable.ConversationRecord `json:"conversation"`
	// Entries are the raw active entries, as ContextView.Entries: the head marker, then the non-head entries from its head.
	Entries []durable.EntryRecord `json:"entries"`
	// Docs holds the built-in conversation documents keyed by kind; absent documents are absent.
	Docs map[string]durable.JsonObject `json:"docs"`
}

ConversationView is the structural mount of one conversation's active transcript and built-in documents (spec §9.3).

type ConversationViews

type ConversationViews struct {
	// contains filtered or unexported fields
}

ConversationViews holds the Harness's conversation view mounts: at most one per conversation, built on the Session line by its first observer and dropped with its last. Each mount advances from the Session's commit publications, which are durable.

func NewConversationViews

func NewConversationViews(sessionImpl *session.SessionImpl, storage durable.Storage) *ConversationViews

NewConversationViews subscribes the mounts to the Session's commits and close.

func (*ConversationViews) Attach

func (views *ConversationViews) Attach(ctx context.Context, id durable.ConversationId, create func(value ConversationView, release func(), storage durable.Storage) (*ViewObserver, error)) (*ViewObserver, func(), error)

Attach registers an observer created from the current revision, atomically on the Session line: it sees every later publication and nothing earlier. create may read committed Storage, still on the line. The returned detach drops the observer, and the mount with its last observer.

func (*ConversationViews) State

State returns a disposable read-only Chord state of the view.

func (*ConversationViews) Watch

Watch returns a serialized exact-frame watch of the view; cancelling ctx stops it.

type ConversationWatch

type ConversationWatch = durable.WatchHandle[ConversationView]

ConversationWatch is a serialized exact-frame watch of the structural view.

type DeferredPollEvent

type DeferredPollEvent struct {
	PollAt float64 `json:"pollAt"`
}

func (DeferredPollEvent) EventType

func (DeferredPollEvent) EventType() string

func (DeferredPollEvent) MarshalJSON

func (event DeferredPollEvent) MarshalJSON() ([]byte, error)

type DeferredStatus

type DeferredStatus struct {
	PollAt float64 `json:"pollAt"`
}

DeferredStatus is a provider-side deferred response being polled.

type EntryAppendedEvent

type EntryAppendedEvent struct {
	Entry durable.EntryRecord `json:"entry"`
}

func (EntryAppendedEvent) EventType

func (EntryAppendedEvent) EventType() string

func (EntryAppendedEvent) MarshalJSON

func (event EntryAppendedEvent) MarshalJSON() ([]byte, error)

type EnvTarget

type EnvTarget struct {
	ConversationId durable.ConversationId
	// Cwd is the conversation's agent cwd; nil when unset.
	Cwd  *string
	Read durable.DocumentReader
}

EnvTarget is what HarnessOptions.Env builds an environment for.

type ExtensionChange

type ExtensionChange struct {
	Exact  bool
	List   []*durable.Extension
	Add    []*durable.Extension
	Remove []*durable.Extension
}

ExtensionChange is a change to the stored extension selection: an exact list, or an edit with optional Add and Remove lists; a nil Add or Remove is absent.

type ExtensionSelection

type ExtensionSelection struct {
	Exact  bool
	Names  []string
	Add    []string
	Remove []string
}

ExtensionSelection is the stored extensions field of AgentState: an exact list (Exact), or an edit of the host default selection with optional Add and Remove lists. A nil Add or Remove is absent.

func (ExtensionSelection) MarshalJSON

func (selection ExtensionSelection) MarshalJSON() ([]byte, error)

MarshalJSON writes an exact selection as an array and an edit as {add?, remove?}.

func (*ExtensionSelection) UnmarshalJSON

func (selection *ExtensionSelection) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an array as an exact selection and an object as an edit.

type GenerationCheckpoint

type GenerationCheckpoint struct {
	Phase         string                             `json:"phase"`
	Attempt       int                                `json:"attempt,omitempty"`
	Compacted     *durable.TaskId                    `json:"compacted,omitempty"`
	Overflow      *string                            `json:"overflow,omitempty"`
	Model         *durable.ModelRef                  `json:"model,omitempty"`
	ThinkingLevel ai.ModelThinkingLevel              `json:"thinkingLevel,omitempty"`
	StreamOptions *durable.ConversationStreamOptions `json:"streamOptions,omitempty"`
	Cutoff        *durable.EntryId                   `json:"cutoff,omitempty"`
	Until         *float64                           `json:"until,omitempty"`
	Handle        *ai.DeferredHandle                 `json:"handle,omitempty"`
	PollAt        *float64                           `json:"pollAt,omitempty"`
	Assistant     *durable.EntryId                   `json:"assistant,omitempty"`
	Tools         []durable.TaskId                   `json:"tools,omitempty"`
	Pending       []string                           `json:"pending,omitempty"`
}

GenerationCheckpoint is the durable checkpoint of the generation task (generation.ts:49-90). Phase selects the members in use:

  • prepare: Attempt; Compacted is the blocking compaction this generation waited for, which starts no other compaction (spec §8.3); Overflow is the error text of the overflow that started Compacted, checked once when prepare resumes.
  • request: Attempt, Compacted, Model, ThinkingLevel, StreamOptions (the settings' request options when preparation committed; a resend after recovery uses them unchanged), and Cutoff, the newest entry included in the request.
  • retry: Attempt, Compacted, Until.
  • poll: Attempt, Compacted, Model, Cutoff, Handle, PollAt.
  • tools: Assistant (the tool-calling answer), Tools (tool tasks created so far, in call order) and Pending (calls of a sequential round not started yet, in call order). The generation owns the tool tasks (spec §8.5).

func (GenerationCheckpoint) MarshalJSON

func (checkpoint GenerationCheckpoint) MarshalJSON() ([]byte, error)

MarshalJSON keeps the tools phase's tools and pending arrays when they are empty.

type GenerationHooks

type GenerationHooks struct {
	// BeforeRequest runs before every request attempt, including recovery; a non-nil result is used for that request only.
	BeforeRequest func(ctx context.Context, request GenerationRequest, api HookApi) (*GenerationRequest, error)
	// AfterResponse sees every terminal provider message, before classification.
	AfterResponse func(ctx context.Context, message ai.AssistantMessage, api HookApi) error
	// OnYield sees a final answer; the first non-nil result appends a user message and continues the run.
	OnYield func(ctx context.Context, answer ai.AssistantMessage, api HookApi) (*YieldContinue, error)
	// AfterTools runs after every tool of the round is terminal; results are the round's result entries in call order.
	AfterTools func(ctx context.Context, assistant durable.EntryId, results []durable.EntryId, api HookApi) error
}

GenerationHooks are the hooks of the built-in generation task. A nil member does not run. Register them as *GenerationHooks.

type GenerationInput

type GenerationInput struct{}

GenerationInput is the input of the built-in generation task; the run's inputs live in pi.live.run.

type GenerationRequest

type GenerationRequest struct {
	Messages []ai.Message
}

GenerationRequest is the request a beforeRequest hook may replace.

type GenerationResult

type GenerationResult struct {
	EntryId durable.EntryId `json:"entryId"`
}

GenerationResult is the result of the generation task: the answer, or the tool-calling answer of its round.

type Harness

type Harness interface {
	durable.Session
	// Resume enables task scheduling. It is idempotent and panics after close. Calls that ask for progress enable it too: Conversation.Submit, Compact, Abort, WaitForIdle, Submission.Wait, WaitForTask, and Harness.WaitForIdle. Read-only viewers never do.
	Resume()
	// Root returns the reserved root conversation, creating it with options.Agent and options.Init in one commit when absent.
	Root(ctx context.Context, options *RootOptions) (Conversation, error)
	// Conversation returns nil when absent.
	Conversation(ctx context.Context, id durable.ConversationId) (Conversation, error)
	CreateConversation(ctx context.Context, options ConversationCreateOptions) (Conversation, error)
	// GetTask returns nil when absent.
	GetTask(ctx context.Context, id durable.TaskId) (*durable.TaskRecord[durable.JsonValue, durable.JsonValue, durable.JsonValue], error)
	// Inspect returns live tasks and unsettled submissions. It writes nothing and runs no task code.
	Inspect(ctx context.Context) (HarnessInspection, error)
	// Submission reacquires a submission, for example after reopen; nil when absent.
	Submission(ctx context.Context, id durable.SubmissionId) (durable.Submission, error)
	// AbortSubmission returns not_found for an unknown submission or one of another conversation than conversationId, when given.
	AbortSubmission(ctx context.Context, id durable.SubmissionId, conversationId *durable.ConversationId) (durable.SubmissionAbortResult, error)
	// AbortTask commits the abort mark, signals and joins an active run invocation, and schedules the abort invocation. A task whose definition cannot take it settles as orphaned instead. It returns marked or terminal.
	AbortTask(ctx context.Context, id durable.TaskId) (string, error)
	// WaitForTask returns the terminal receipt; cancelling ctx cancels only this wait.
	WaitForTask(ctx context.Context, id durable.TaskId) (durable.SettledTask[durable.JsonValue], error)
	// WaitForIdle returns when the ordinary ownership scope of every ownerless conversation has no live non-background task.
	WaitForIdle(ctx context.Context) error
	// Usage is the Session total: every conversation's pi.usage summed.
	Usage(ctx context.Context) (UsageState, error)
	// TaskGraph returns every live task with its owner edge, status, and owned conversations (spec §9.5), as a disposable Chord state.
	TaskGraph(ctx context.Context) (durable.AttachedReplicatedState[TaskGraph], error)
	// WatchTaskGraph returns the task graph as a serialized exact-frame watch with bounded pending frames.
	WatchTaskGraph(ctx context.Context) (TaskGraphWatch, error)
}

Harness is a durable agent harness over one Session.

func OpenHarness

func OpenHarness(ctx context.Context, storage durable.Storage, options HarnessOptions) (Harness, error)

OpenHarness opens a Harness over storage. The registry may keep changing while the Harness runs.

type HarnessInspection

type HarnessInspection struct {
	Scheduling  string
	Tasks       []TaskInspection
	Submissions []durable.SubmissionRecord
}

HarnessInspection is a point-in-time view of live work: unfinished tasks and submissions, read on the Session line. Scheduling is paused, running, or closing.

type HarnessOptions

type HarnessOptions struct {
	// Models is the pi-ai model access used by generation and compaction: a Model Runtime or a pi-ai collection.
	Models   durable.Models
	Registry RegistryReader
	// Settings returns the current settings at every resolution; nil uses the defaults. Upstream reads a settings object whose fields may be getters.
	Settings func() *HarnessSettings
	// Env builds a conversation's environment at each use. It never runs on the Session line. Nil means no environment.
	Env func(ctx context.Context, target EnvTarget) (env.ExecutionEnv, error)
	// ConversationCreated runs in every commit that creates or forks a conversation, raw tx.CreateConversation included, after the built-in pi.* documents and before the conveniences apply the agent change and run init. A fork already has its copies. Table reads fail with ReadAfterWrite; an error fails the creating commit.
	ConversationCreated func(tx durable.Tx, conversation durable.ConversationRecord) error
	// Now is the Harness clock in milliseconds; nil uses the wall clock.
	Now func() float64
	// OnReport receives extension failures that do not fail the calling operation. It must not panic.
	OnReport func(err error)
}

HarnessOptions are the options of OpenHarness.

type HarnessSettings

type HarnessSettings struct {
	// Extensions is the default extension selection; nil selects every installed extension, in install order.
	Extensions []*durable.Extension
	Stream     *durable.ConversationStreamOptions
	Retry      *RetryPolicyPatch
	Compaction *CompactionPolicyPatch
	Progress   *ProgressPolicyPatch
	// ToolExecution, SteeringMode, and FollowUpMode are empty when unset.
	ToolExecution durable.ToolExecutionMode
	SteeringMode  durable.QueueMode
	FollowUpMode  durable.QueueMode
}

HarnessSettings is the Harness-wide run policy. It is read at every resolution and never copied.

type HookApi

type HookApi interface {
	durable.DocumentReader
	TaskId() durable.TaskId
	ConversationId() durable.ConversationId
	// Memo reads a memo; ok is false when absent.
	Memo(ctx context.Context, name string) (value durable.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 durable.JsonValue) (durable.JsonValue, error)
}

HookApi is what a hook may use: committed reads and the asking task's memos, which hooks and the task share.

type InboxItem

type InboxItem struct {
	Id   durable.SubmissionId `json:"id"`
	Mode InboxMode            `json:"mode"`
	// Content is the JSON representation of the user input; nil for writes.
	Content durable.JsonValue `json:"content,omitempty"`
	// Entry is the JSON representation of the entry draft; nil for user input.
	Entry durable.JsonObject `json:"entry,omitempty"`
}

InboxItem is a queued submission: user input for a run, with Content, or a passive entry write, with Entry, an EntryDraft stored as plain JSON (inbox.ts:8-11).

type InboxMode

type InboxMode string

InboxMode is the mode of a queued submission: user input for a run (steer or followUp) or a passive entry write.

const (
	InboxSteer    InboxMode = "steer"
	InboxFollowUp InboxMode = "followUp"
	InboxWrite    InboxMode = "write"
)

type InboxState

type InboxState struct {
	Items []InboxItem `json:"items"`
}

InboxState is the built-in queue of one conversation's submissions waiting for a boundary, in ID order.

type InboxUpdateEvent

type InboxUpdateEvent struct {
	Items []QueuedItem `json:"items"`
}

func (InboxUpdateEvent) EventType

func (InboxUpdateEvent) EventType() string

func (InboxUpdateEvent) MarshalJSON

func (event InboxUpdateEvent) MarshalJSON() ([]byte, error)

type InvocationBinding

type InvocationBinding struct {
	Signal context.Context
	Check  func() error
}

InvocationBinding is an invocation a conversation handle is bound to: its signal, and a check that fails once it ended.

type LiveGeneration

type LiveGeneration struct {
	Attempt int `json:"attempt"`
	// Message is the committed throttled partial of the in-flight response, as JSON.
	Message durable.JsonObject `json:"message,omitempty"`
	// Retry is the durable backoff before the next attempt.
	Retry *RetryStatus `json:"retry,omitempty"`
	// Deferred is set while a provider-side deferred response is polled.
	Deferred *DeferredStatus `json:"deferred,omitempty"`
}

LiveGeneration is the presentation of the current generation attempt.

type LiveRun

type LiveRun struct {
	TaskId durable.TaskId         `json:"taskId"`
	Inputs []durable.SubmissionId `json:"inputs"`
}

LiveRun is run control: the task that settles the run's inputs, and those inputs.

type LiveState

type LiveState struct {
	// Run is present exactly while busy.
	Run        *LiveRun        `json:"run,omitempty"`
	Generation *LiveGeneration `json:"generation,omitempty"`
	// Tools is the current round in call order, from the tool-calling answer until the generation's tools phase ends
	// it; never empty while present.
	Tools []ToolSlot `json:"tools,omitempty"`
	// Compactions lists live compaction tasks in task ID order; never empty while present.
	Compactions []CompactionStatus `json:"compactions,omitempty"`
}

LiveState is the built-in live conversation state: run control and presentation of the current generation and tool round (live.ts:46-62).

type MessageChange

type MessageChange struct {
	Type         string
	ContentIndex int
	Block        ai.AssistantContentBlock
	Delta        string
	Path         []any
	Message      *ai.AssistantMessage
}

MessageChange is one change to the in-flight assistant message, relative to that message. Type is text_start, thinking_start, toolcall_start (Block), text_delta, thinking_delta (Delta), toolcall_delta (Path, Delta), block (Block), or message (Message).

func (MessageChange) MarshalJSON

func (change MessageChange) MarshalJSON() ([]byte, error)

MarshalJSON encodes the upstream variant of the change's Type (events.ts MessageChange).

type MessageEndEvent

type MessageEndEvent struct {
	Entry durable.EntryRecord `json:"entry"`
}

func (MessageEndEvent) EventType

func (MessageEndEvent) EventType() string

func (MessageEndEvent) MarshalJSON

func (event MessageEndEvent) MarshalJSON() ([]byte, error)

type MessageStartEvent

type MessageStartEvent struct {
	Message ai.Message `json:"message"`
}

func (MessageStartEvent) EventType

func (MessageStartEvent) EventType() string

func (MessageStartEvent) MarshalJSON

func (event MessageStartEvent) MarshalJSON() ([]byte, error)

type MessageUpdateEvent

type MessageUpdateEvent struct {
	Usage   ai.Usage        `json:"usage"`
	Changes []MessageChange `json:"changes"`
}

MessageUpdateEvent carries the partial's current usage, as in the coding agent's JSON mode.

func (MessageUpdateEvent) EventType

func (MessageUpdateEvent) EventType() string

func (MessageUpdateEvent) MarshalJSON

func (event MessageUpdateEvent) MarshalJSON() ([]byte, error)

type OrderedMap

type OrderedMap[T any] struct {
	// contains filtered or unexported fields
}

OrderedMap is a JavaScript Map with string keys: Set keeps an existing key's position, Delete removes it, and a re-added key appends.

func NewOrderedMap

func NewOrderedMap[T any]() *OrderedMap[T]

NewOrderedMap returns an empty map.

func RenderSections

func RenderSections(ctx context.Context, sections []*durable.PromptSection, input durable.PromptInput, shown *OrderedMap[string], report func(error)) (*OrderedMap[string], error)

RenderSections renders the agent's sections in order. A nil text omits a section; tagged text is wrapped as `<key>\n...\n</key>`. A section that fails keeps its shown text, if any, and is reported; errors after ctx is cancelled propagate.

func ReplaySections

func ReplaySections(messages []ai.Message) *OrderedMap[string]

ReplaySections returns the sections in effect after replaying system messages in order: a value sets in place, a nil value deletes, and a re-added key appends.

func (*OrderedMap[T]) Delete

func (items *OrderedMap[T]) Delete(key string)

Delete removes key.

func (*OrderedMap[T]) Get

func (items *OrderedMap[T]) Get(key string) (T, bool)

Get returns the value at key.

func (*OrderedMap[T]) Has

func (items *OrderedMap[T]) Has(key string) bool

Has reports whether key is present.

func (*OrderedMap[T]) Keys

func (items *OrderedMap[T]) Keys() []string

Keys returns the keys in insertion order.

func (*OrderedMap[T]) Len

func (items *OrderedMap[T]) Len() int

Len returns the number of keys.

func (*OrderedMap[T]) Set

func (items *OrderedMap[T]) Set(key string, value T)

Set stores value at key.

func (*OrderedMap[T]) Values

func (items *OrderedMap[T]) Values() []T

Values returns the values in key order.

type OutputBuffer

type OutputBuffer struct {
	// contains filtered or unexported fields
}

OutputBuffer is the bounded running output of one tool call. Accepting a chunk costs time proportional to the chunk: head retention stops storing once the window is full, and tail retention drops stored text the window no longer needs when it snapshots. Counts of the whole stream are kept so the dropped totals stay exact. It is not safe for concurrent use.

func NewOutputBuffer

func NewOutputBuffer(limits OutputLimits) *OutputBuffer

NewOutputBuffer returns an empty buffer bounded by limits.

func (*OutputBuffer) End

func (buffer *OutputBuffer) End()

End flushes an incomplete trailing character as a replacement character; call when the stream ends.

func (*OutputBuffer) PushBytes

func (buffer *OutputBuffer) PushBytes(chunk []byte) bool

PushBytes accepts a byte chunk, decoding UTF-8 across chunk boundaries. It reports whether anything was accepted.

func (*OutputBuffer) PushBytesSkipping

func (buffer *OutputBuffer) PushBytesSkipping(chunk []byte, skipped env.ShellOutputSkip) (bool, error)

PushBytesSkipping is PushStringSkipping for a byte chunk, decoding UTF-8 across the omission as upstream does: bytes of an incomplete character before it end as a replacement character.

func (*OutputBuffer) PushString

func (buffer *OutputBuffer) PushString(chunk string) bool

PushString accepts a text chunk; bytes of an incomplete character from an earlier byte chunk come first, as a replacement character. It reports whether anything was accepted.

func (*OutputBuffer) PushStringSkipping

func (buffer *OutputBuffer) PushStringSkipping(chunk string, skipped env.ShellOutputSkip) (bool, error)

PushStringSkipping accepts a text chunk that follows omitted output: skipped is output omitted right before the chunk, which must be more than the tail window by at least one byte or line (ShellOutputInfo.Skipped). Only tail retention accepts it; head retention returns an error. It reports that the chunk was accepted.

func (*OutputBuffer) Snapshot

func (buffer *OutputBuffer) Snapshot() BoundedOutput

Snapshot returns the retained, sanitized output and what the limits dropped from the whole stream.

func (*OutputBuffer) StoredBytes

func (buffer *OutputBuffer) StoredBytes() int

StoredBytes reports the bytes currently held; bounded by the limits plus one chunk.

type OutputLimits

type OutputLimits struct {
	MaxBytes int
	MaxLines int
	Retain   string
}

OutputLimits are the retention limits of one tool's output. Retain is "head" or "tail".

type OutputSlice

type OutputSlice struct {
	Text         string
	Bytes        int
	DroppedBytes int
	DroppedLines int
}

OutputSlice is an exact slice of the input within the limits, and what it left out.

func BoundOutput

func BoundOutput(text string, limits OutputLimits) OutputSlice

BoundOutput bounds text to whole lines within the limits: the first lines for "head", the last lines for "tail". The result is an exact slice, trailing newline included. A single line longer than MaxBytes is cut at the byte limit on a character boundary.

type Progress

type Progress struct {
	// contains filtered or unexported fields
}

Progress schedules adaptive progress commits: the first change after an idle period commits at once; each commit then delays the next by at least the minimum interval and by its written size at 100 KiB/s. At most one commit is in flight; changes made meanwhile coalesce into the next one. Write runs on a goroutine Progress owns; Stop joins it.

func NewProgress

func NewProgress(write func() (int, error), onError func(error), minIntervalMs float64) *Progress

NewProgress returns a Progress that commits through write, which reports the bytes it wrote; onError receives a failed commit's error. minIntervalMs is the least pause between commits.

func (*Progress) Mark

func (progress *Progress) Mark()

Mark schedules a commit.

func (*Progress) MarkAndWait

func (progress *Progress) MarkAndWait() *ProgressWaiter

MarkAndWait schedules a commit; the returned waiter settles with the commit that includes this change.

func (*Progress) Stop

func (progress *Progress) Stop() []*ProgressWaiter

Stop stops committing and waits for the commit in flight; it returns the waiters the final commit must settle.

type ProgressPolicyPatch

type ProgressPolicyPatch struct {
	PartialIntervalMs *float64
	OutputIntervalMs  *float64
}

ProgressPolicyPatch is Partial<ProgressPolicy>; nil fields keep the defaults.

type ProgressWaiter

type ProgressWaiter struct {
	// contains filtered or unexported fields
}

ProgressWaiter settles with the progress commit that includes its change. It settles once.

func (*ProgressWaiter) Reject

func (waiter *ProgressWaiter) Reject(err error)

Reject settles the waiter with err.

func (*ProgressWaiter) Resolve

func (waiter *ProgressWaiter) Resolve()

Resolve settles the waiter successfully.

func (*ProgressWaiter) Wait

func (waiter *ProgressWaiter) Wait(ctx context.Context) error

Wait blocks until the waiter settles or ctx is cancelled; cancellation ends only this wait.

type ProviderState

type ProviderState struct {
	SessionId string `json:"sessionId"`
}

ProviderState is the stable provider-facing identity of one conversation (provider.ts:6-9).

type QueueModes

type QueueModes struct {
	SteeringMode durable.QueueMode
	FollowUpMode durable.QueueMode
}

QueueModes are the settings a boundary reads, on the Session line.

func QueueModesOf

func QueueModesOf(settings durable.Settings) QueueModes

QueueModesOf returns the queue modes of resolved settings.

type QueuedItem

type QueuedItem struct {
	Id   durable.SubmissionId `json:"id"`
	Mode InboxMode            `json:"mode"`
}

QueuedItem is one queued inbox item as events report it.

type Registry

type Registry interface {
	RegistryReader
	// Install installs extension, or replaces the installed extension with its name in place, and publishes at once. An invalid extension, or a task name collision in the resulting registry, publishes nothing and returns the error.
	Install(extension *durable.Extension) error
	// Uninstall removes the installed extension with extension.Name, whichever object it is. A later install appends.
	Uninstall(extension *durable.Extension)
}

Registry is an application-owned registry of extensions.

func CreateRegistry

func CreateRegistry() Registry

CreateRegistry creates an application-owned registry holding only the built-in tasks.

type RegistryReader

type RegistryReader interface {
	// Snapshot returns an immutable view of the whole current registry.
	Snapshot() durable.RegistrySnapshot
	// Subscribe registers a listener called synchronously after every publication; it wakes the scheduler to reconsider blocked tasks. The result unsubscribes.
	Subscribe(listener func()) func()
}

RegistryReader is the read side of a registry consumed by a Harness.

type RetryPolicyPatch

type RetryPolicyPatch struct {
	Enabled         *bool
	MaxRetries      *int
	BaseDelayMs     *int
	MaxAgentDelayMs *int
}

RetryPolicyPatch is Partial<ConversationRetryPolicy>; nil fields keep the defaults.

type RetryStatus

type RetryStatus struct {
	At    float64 `json:"at"`
	Error string  `json:"error"`
}

RetryStatus is a durable backoff before the next attempt.

type RootOptions

type RootOptions struct {
	Agent *AgentChange
	Init  ConversationInit
}

RootOptions are the options of Harness.Root.

type RunEndEvent

type RunEndEvent struct {
	Inputs []durable.SubmissionId `json:"inputs"`
}

func (RunEndEvent) EventType

func (RunEndEvent) EventType() string

func (RunEndEvent) MarshalJSON

func (event RunEndEvent) MarshalJSON() ([]byte, error)

type RunEvent

type RunEvent struct {
	Inputs []durable.SubmissionId `json:"inputs"`
}

RunEvent carries the inputs of run_start and run_end.

type RunStartEvent

type RunStartEvent struct {
	Inputs []durable.SubmissionId `json:"inputs"`
}

func (RunStartEvent) EventType

func (RunStartEvent) EventType() string

func (RunStartEvent) MarshalJSON

func (event RunStartEvent) MarshalJSON() ([]byte, error)

type SchedulerOutcome

type SchedulerOutcome = anyOutcome

SchedulerOutcome is a terminal outcome the scheduler writes without running task code: faulted or orphaned.

type SectionOptions

type SectionOptions struct {
	// Tag false renders the text unwrapped; nil leaves the section tagged.
	Tag *bool
}

SectionOptions are the options of Section.

type SnapshotEvent

type SnapshotEvent struct {
	Entries []durable.EntryRecord `json:"entries"`
	// Run is nil when idle.
	Run        *RunEvent           `json:"run,omitempty"`
	Generation *SnapshotGeneration `json:"generation,omitempty"`
	Tools      []ToolSlot          `json:"tools"`
	// Compactions are pi.live.compactions: live compactions with their attempt and retry backoff.
	Compactions []CompactionStatus `json:"compactions"`
	Inbox       []QueuedItem       `json:"inbox"`
	// Agent is pi.agent; empty when absent.
	Agent AgentState `json:"agent"`
	Usage UsageState `json:"usage"`
}

SnapshotEvent is the state of a conversation at attachment.

func (SnapshotEvent) EventType

func (SnapshotEvent) EventType() string

func (SnapshotEvent) MarshalJSON

func (event SnapshotEvent) MarshalJSON() ([]byte, error)

type SnapshotGeneration

type SnapshotGeneration struct {
	Attempt  int                  `json:"attempt"`
	Message  *ai.AssistantMessage `json:"message,omitempty"`
	Retry    *RetryStatus         `json:"retry,omitempty"`
	Deferred *DeferredStatus      `json:"deferred,omitempty"`
}

SnapshotGeneration is the current generation attempt: its in-flight partial, retry backoff, or deferred poll.

type SubmissionEvent

type SubmissionEvent struct {
	Record durable.SubmissionRecord `json:"record"`
}

func (SubmissionEvent) EventType

func (SubmissionEvent) EventType() string

func (SubmissionEvent) MarshalJSON

func (event SubmissionEvent) MarshalJSON() ([]byte, error)

type Submissions

type Submissions struct {
	// contains filtered or unexported fields
}

Submissions is admission, waits, and withdrawal of the durable submissions of one Harness (submissions.ts:21-118).

func NewSubmissions

func NewSubmissions(line *session.SessionImpl, storage durable.Storage, now func() float64, queueModes func() QueueModes, resume func()) *Submissions

NewSubmissions subscribes to the Session's commits and close.

func (*Submissions) Abort

func (submissions *Submissions) Abort(ctx context.Context, id durable.SubmissionId, conversationId *durable.ConversationId) (durable.SubmissionAbortResult, error)

Abort withdraws a queued submission and removes its inbox item; placed inputs and settled submissions are reported. conversationId, when given, must own the submission.

func (*Submissions) Get

func (submissions *Submissions) Get(ctx context.Context, id durable.SubmissionId) (durable.Submission, error)

Get returns a handle for an existing submission; nil when absent.

func (*Submissions) Status

func (submissions *Submissions) Status(ctx context.Context, id durable.SubmissionId) (durable.SubmissionRecord, error)

Status returns the committed record of a submission.

func (*Submissions) Submit

func (submissions *Submissions) Submit(ctx context.Context, conversationId durable.ConversationId, draft durable.SubmissionDraft) (durable.Submission, error)

Submit admits a submission in one commit; see AdmitSubmission.

func (*Submissions) Wait

Wait returns the settled record of a submission; cancelling ctx cancels only this wait.

type SummaryRequest

type SummaryRequest struct {
	Attempt       int                               `json:"attempt"`
	Model         durable.ModelRef                  `json:"model"`
	ThinkingLevel ai.ModelThinkingLevel             `json:"thinkingLevel"`
	StreamOptions durable.ConversationStreamOptions `json:"streamOptions"`
	MaxTokens     int                               `json:"maxTokens"`
	// Tail is the newest entry of the context the range was selected from.
	Tail durable.EntryId `json:"tail"`
	// FirstKept is the first entry kept verbatim; the summary's head.
	FirstKept durable.EntryId `json:"firstKept"`
}

SummaryRequest is the pinned summarization request.

type SystemDraft

type SystemDraft = durable.TypedEntryDraft[durable.Never]

SystemDraft is a planned pi.system entry.

func PlanSystemEntries

func PlanSystemEntries(view durable.ContextView, desired *OrderedMap[string], tools []ai.ToolSchema, timestamp int64) []SystemDraft

PlanSystemEntries plans the pi.system entries that make the replayed sections and tools of view equal desired and tools in values and order.

  • A head marker with no later pi.system entry in context: one complete baseline that omits every retained earlier pi.system entry, written even when it restates the replayed values.
  • Otherwise, when a minimal section patch would leave a different order: remove every shown section, then re-add every desired section in order.
  • Otherwise the minimal patch of changed values and removals, or nothing.

Tool changes ride on the last planned entry, or on one entry of their own.

type TaskFailedEvent

type TaskFailedEvent struct {
	TaskId  durable.TaskId `json:"taskId"`
	Kind    string         `json:"kind"`
	Message string         `json:"message"`
}

func (TaskFailedEvent) EventType

func (TaskFailedEvent) EventType() string

func (TaskFailedEvent) MarshalJSON

func (event TaskFailedEvent) MarshalJSON() ([]byte, error)

type TaskGraph

type TaskGraph struct {
	// Tasks holds every live task, keyed by its decimal ID.
	Tasks map[string]TaskGraphNode `json:"tasks"`
}

TaskGraph is every live task of the Session (spec §9.5).

type TaskGraphNode

type TaskGraphNode struct {
	Id             durable.TaskId         `json:"id"`
	Kind           string                 `json:"kind"`
	ConversationId durable.ConversationId `json:"conversationId"`
	// Owner is the owner task; nil for a conversation-owned task.
	Owner          *durable.TaskId `json:"owner,omitempty"`
	Background     bool            `json:"background"`
	AbortRequested bool            `json:"abortRequested"`
	State          TaskGraphState  `json:"state"`
	// Conversations are the conversations this task owns, in ID order.
	Conversations []durable.ConversationId `json:"conversations"`
}

TaskGraphNode is one live task of the graph.

type TaskGraphState

type TaskGraphState struct {
	Status durable.TaskStatus `json:"status"`
	Phase  string             `json:"phase,omitempty"`
	On     []durable.TaskId   `json:"on,omitempty"`
	Policy durable.JoinPolicy `json:"policy,omitempty"`
	// Outcome is the status of the outcome held until its ordinary owned work drains.
	Outcome durable.TaskOutcomeStatus `json:"outcome,omitempty"`
}

TaskGraphState is a live task's durable status without its checkpoint and outcome payloads (spec §9.5): pending or running with Phase, waiting with Phase, On, and Policy, or completing with the held Outcome status.

func (TaskGraphState) MarshalJSON

func (state TaskGraphState) MarshalJSON() ([]byte, error)

MarshalJSON encodes the upstream variant of the state's Status.

type TaskGraphView

type TaskGraphView struct {
	// contains filtered or unexported fields
}

TaskGraphView is the Harness's task graph mount: built on the Session line by its first observer and dropped with its last. It advances from the Session's commit publications, which are durable.

func NewTaskGraphView

func NewTaskGraphView(sessionImpl *session.SessionImpl, storage durable.Storage) *TaskGraphView

NewTaskGraphView subscribes the mount to the Session's commits and close.

func (*TaskGraphView) State

State returns a disposable read-only Chord state of the graph.

func (*TaskGraphView) Watch

func (view *TaskGraphView) Watch(ctx context.Context) (TaskGraphWatch, error)

Watch returns a serialized exact-frame watch of the graph; cancelling ctx stops it.

type TaskGraphWatch

type TaskGraphWatch = durable.WatchHandle[TaskGraph]

TaskGraphWatch is a serialized exact-frame watch of the task graph.

type TaskInspection

type TaskInspection struct {
	Record durable.TaskRecord[durable.JsonValue, durable.JsonValue, durable.JsonValue]
	State  TaskInspectionState
}

TaskInspection is a live task and what the scheduler would do with it under the current registry.

type TaskInspectionKind

type TaskInspectionKind string

TaskInspectionKind is the kind of a TaskInspectionState.

const (
	TaskInspectionRunning    TaskInspectionKind = "running"
	TaskInspectionReady      TaskInspectionKind = "ready"
	TaskInspectionWaiting    TaskInspectionKind = "waiting"
	TaskInspectionCompleting TaskInspectionKind = "completing"
	TaskInspectionBlocked    TaskInspectionKind = "blocked"
)

type TaskInspectionState

type TaskInspectionState struct {
	Kind     TaskInspectionKind
	Migrates bool
	On       []durable.TaskId
	Reason   string
	Error    error
}

TaskInspectionState is what the scheduler would do with a live task: running (an invocation is active); ready (the next scheduling pass reserves it; Migrates when its definition is newer and has a migration); waiting (on these live tasks: the live part of its on, or, when abort-marked, its live ordinary owned work); completing (outcome held until its ordinary owned work drains); blocked (no registered definition can take it, with Reason missing_task, task_too_old, or migration_failed and an optional Error).

type TaskScheduler

type TaskScheduler struct {
	// contains filtered or unexported fields
}

TaskScheduler is the durable task scheduler of one Harness (scheduler.ts:162-1243).

live mirrors every committed non-terminal task record: pending, running, waiting, and completing. The synchronous commit listener updates it on the Session line, so code running on the line reads exactly the committed state from it.

Tasks and conversations form one ownership tree (spec §5.5): a task's parent is its owner task, or its conversation; a conversation's parent is its owner task, if any. Walks up that tree decide cascades, idle scopes, and whether a task's ordinary owned work is live, which holds its outcome as completing and delays its abort handler.

Every task transition is decided and written by one callback serialized on the Session line: reservation, marks, runtime commits, finalization, and the step before each phase. Handlers and joins run off the line. An invocation ends inside the step that decides its end, so a runtime commit it queued either lands before that decision or is rejected. mu guards the in-memory state; it is never held while waiting for the line.

func NewTaskScheduler

func NewTaskScheduler(options TaskSchedulerOptions) *TaskScheduler

NewTaskScheduler returns a scheduler; Open loads it.

func (*TaskScheduler) Abort

func (s *TaskScheduler) Abort(ctx context.Context, id durable.TaskId) (string, error)

Abort commits the abort mark, or settles a task that no registered definition can take as orphaned when nothing it owns is live, then joins the run invocation seen on the line; the commit listener signalled it. The abort invocation starts once the task's ordinary owned work is gone. A completing task is only marked (scheduler.ts:260-283).

func (*TaskScheduler) AbortConversation

func (s *TaskScheduler) AbortConversation(ctx context.Context, conversationId durable.ConversationId, background bool) error

AbortConversation is Conversation.Abort: in one commit, withdraw the queued inputs and mark every live non-background task that ordinary traversal from the conversation reaches; it returns once the scope is idle. With background, traversal crosses background boundaries, and the wait also covers every task it reached (scheduler.ts:318-338).

func (*TaskScheduler) Inspect

func (s *TaskScheduler) Inspect(snapshot durable.RegistrySnapshot) (string, []TaskInspection, error)

Inspect returns the scheduling state and every live task with its derived state; read on the Session line. It runs no task code: a pending migration shows as ready with Migrates, and only a migration the scheduler already tried, or one that cannot exist, shows as failed.

func (*TaskScheduler) Join

func (s *TaskScheduler) Join()

Join waits for every invocation signalled by the close seal and for scheduler passes in flight. It writes nothing.

func (*TaskScheduler) Open

func (s *TaskScheduler) Open(ctx context.Context) error

Open loads live tasks and changes surviving running tasks back to pending. It dispatches nothing.

func (*TaskScheduler) Resume

func (s *TaskScheduler) Resume()

Resume enables scheduling. It is idempotent; the kick does nothing once closing.

func (*TaskScheduler) WaitForIdle

func (s *TaskScheduler) WaitForIdle(ctx context.Context, conversationId *durable.ConversationId) error

WaitForIdle returns when ordinary traversal from the conversation, or from every ownerless conversation when conversationId is nil, reaches no live non-background task.

func (*TaskScheduler) WaitForTask

WaitForTask returns the terminal receipt of a task; cancelling ctx cancels only this wait.

type TaskSchedulerOptions

type TaskSchedulerOptions struct {
	Session  *session.SessionImpl
	Storage  durable.Storage
	Registry RegistryReader
	Models   durable.Models
	// Agent resolves a conversation's agent against a snapshot; the runtime calls it at most once per phase.
	Agent func(ctx context.Context, conversationId durable.ConversationId, snapshot durable.RegistrySnapshot) (durable.Agent, error)
	// Settings resolves the settings; read at each access.
	Settings func() durable.Settings
	// Env builds a conversation's environment with HarnessOptions.Env.
	Env    func(ctx context.Context, conversationId durable.ConversationId) (env.ExecutionEnv, error)
	Now    func() float64
	Report func(err error)
	// SettleOutcome is the Harness cleanup staged in the commit that makes an outcome the scheduler wrote itself
	// terminal.
	SettleOutcome func(tx durable.Tx, record anyTaskRecord, outcome SchedulerOutcome) error
	// WithdrawInputs withdraws a conversation's queued inputs, for conversation abort and abort cascades.
	WithdrawInputs func(tx durable.Tx, conversationId durable.ConversationId) error
	// Conversation returns an invocation-bound handle of an existing conversation, for task runtimes and tools.
	Conversation func(ctx context.Context, id durable.ConversationId, binding InvocationBinding) (durable.ConversationHandle, error)
	// Context is the context of scheduler commits and invocations; it carries no caller cancellation.
	Context context.Context
}

TaskSchedulerOptions configures NewTaskScheduler (scheduler.ts:134-160).

type ToolChange

type ToolChange struct {
	Exact  bool
	List   []*durable.ToolRegistration
	Remove []*durable.ToolRegistration
}

ToolChange is a change to the stored tool filter: an exact list, or {remove}.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolCallId string               `json:"toolCallId"`
	ToolName   string               `json:"toolName"`
	Entry      *durable.EntryRecord `json:"entry,omitempty"`
}

ToolExecutionEndEvent has a nil Entry when the tool task faulted or was orphaned.

func (ToolExecutionEndEvent) EventType

func (ToolExecutionEndEvent) EventType() string

func (ToolExecutionEndEvent) MarshalJSON

func (event ToolExecutionEndEvent) MarshalJSON() ([]byte, error)

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolCallId string             `json:"toolCallId"`
	ToolName   string             `json:"toolName"`
	Args       durable.JsonObject `json:"args"`
}

func (ToolExecutionStartEvent) EventType

func (ToolExecutionStartEvent) EventType() string

func (ToolExecutionStartEvent) MarshalJSON

func (event ToolExecutionStartEvent) MarshalJSON() ([]byte, error)

type ToolExecutionUpdateEvent

type ToolExecutionUpdateEvent struct {
	ToolCallId string
	ToolName   string
	Output     *ToolOutputChange
	// HasDetails reports a details change; Details is nil when they were removed.
	HasDetails  bool
	Details     durable.JsonValue
	Diagnostics []durable.ToolDiagnostic
}

func (ToolExecutionUpdateEvent) EventType

func (ToolExecutionUpdateEvent) EventType() string

func (ToolExecutionUpdateEvent) MarshalJSON

func (event ToolExecutionUpdateEvent) MarshalJSON() ([]byte, error)

MarshalJSON includes details when HasDetails (null when removed) and diagnostics when non-nil.

type ToolHooks

type ToolHooks struct {
	// BeforeTool runs before intent; the first block wins, otherwise arguments replace the call's arguments. An error blocks.
	BeforeTool func(ctx context.Context, call ai.ToolCall, api HookApi) (*BeforeToolResult, error)
	// AfterTool runs after execution, before the result entry; a non-nil result replaces the result.
	AfterTool func(ctx context.Context, call ai.ToolCall, result durable.ToolExecutionResult, api HookApi) (*durable.ToolExecutionResult, error)
}

ToolHooks are the hooks of the built-in tool task. A nil member does not run. Register them as *ToolHooks.

type ToolOutputChange

type ToolOutputChange struct {
	TrimStart *int    `json:"trimStart,omitempty"`
	Append    *string `json:"append,omitempty"`
	Set       *string `json:"set,omitempty"`
}

ToolOutputChange is a front trim and then an append of the retained window (TrimStart, Append), or its replacement (Set).

type ToolSelection

type ToolSelection struct {
	Exact  bool
	Names  []string
	Remove []string
}

ToolSelection is the stored tools field of AgentState: an exact list (Exact), or {remove}.

func (ToolSelection) MarshalJSON

func (selection ToolSelection) MarshalJSON() ([]byte, error)

MarshalJSON writes an exact selection as an array and a filter as {remove}.

func (*ToolSelection) UnmarshalJSON

func (selection *ToolSelection) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an array as an exact selection and an object as {remove}.

type ToolSlot

type ToolSlot struct {
	CallId string `json:"callId"`
	Name   string `json:"name"`
	// TaskId is nil for a call not started yet (sequential round) and for a call its request did not offer, which
	// starts done with the entry generation wrote.
	TaskId *durable.TaskId `json:"taskId,omitempty"`
	Status ToolSlotStatus  `json:"status"`
	// Output is the retained running output; DroppedBytes and DroppedLines are what the bounds dropped.
	Output       *string `json:"output,omitempty"`
	DroppedBytes *int    `json:"droppedBytes,omitempty"`
	DroppedLines *int    `json:"droppedLines,omitempty"`
	// Details is the last details() value; nil when absent.
	Details *durable.JsonValue `json:"details,omitempty"`
	// Diagnostics are those recorded through api.Diagnostic.
	Diagnostics []durable.ToolDiagnostic `json:"diagnostics,omitempty"`
	// Entry is the result entry once done; nil when the tool task faulted or was orphaned.
	Entry *durable.EntryId `json:"entry,omitempty"`
}

ToolSlot is the presentation of one tool call of the current round (live.ts:11-31).

type ToolSlotStatus

type ToolSlotStatus string

ToolSlotStatus is the presentation status of one tool call of the current round.

const (
	ToolSlotPending ToolSlotStatus = "pending"
	ToolSlotRunning ToolSlotStatus = "running"
	ToolSlotDone    ToolSlotStatus = "done"
)

type ToolTaskCheckpoint

type ToolTaskCheckpoint struct {
	Phase     string             `json:"phase"`
	Arguments durable.JsonObject `json:"arguments"`
	Replay    durable.ToolReplay `json:"replay"`
}

ToolTaskCheckpoint is the tool task's checkpoint: call, or execute with the durable intent, the final arguments and the replay policy recorded before execution (tool.ts:35-38).

func (ToolTaskCheckpoint) MarshalJSON

func (checkpoint ToolTaskCheckpoint) MarshalJSON() ([]byte, error)

MarshalJSON writes {"phase":"call"} or the execute intent with its arguments and replay.

type ToolTaskInput

type ToolTaskInput struct {
	Assistant durable.EntryId `json:"assistant"`
	CallId    string          `json:"callId"`
}

ToolTaskInput is the input of the built-in tool task: the tool-calling answer and the call to run.

type ToolTaskResult

type ToolTaskResult struct {
	EntryId durable.EntryId      `json:"entryId"`
	Control *durable.ToolControl `json:"control,omitempty"`
}

ToolTaskResult is the result of the built-in tool task: its result entry and the controls the result requested.

type TurnEndEvent

type TurnEndEvent struct{}

func (TurnEndEvent) EventType

func (TurnEndEvent) EventType() string

func (TurnEndEvent) MarshalJSON

func (event TurnEndEvent) MarshalJSON() ([]byte, error)

type TurnStartEvent

type TurnStartEvent struct{}

func (TurnStartEvent) EventType

func (TurnStartEvent) EventType() string

func (TurnStartEvent) MarshalJSON

func (event TurnStartEvent) MarshalJSON() ([]byte, error)

type TypeError

type TypeError struct{ Message string }

TypeError is upstream's TypeError: a value of the wrong shape.

func (*TypeError) Error

func (err *TypeError) Error() string

type UsageBucket

type UsageBucket string

UsageBucket names one bucket of the usage ledger.

const (
	// UsageModels holds assistant entries and summarization attempts, keyed `provider/modelId`.
	UsageModels UsageBucket = "models"
	// UsageTools holds tool results, keyed by tool name; their usage has no model identity.
	UsageTools UsageBucket = "tools"
)

type UsageChangedEvent

type UsageChangedEvent struct {
	Usage UsageState `json:"usage"`
}

func (UsageChangedEvent) EventType

func (UsageChangedEvent) EventType() string

func (UsageChangedEvent) MarshalJSON

func (event UsageChangedEvent) MarshalJSON() ([]byte, error)

type UsageState

type UsageState struct {
	// Models holds assistant entries and summarization attempts, keyed `provider/modelId`.
	Models map[string]ai.Usage `json:"models"`
	// Tools holds tool results, keyed by tool name.
	Tools map[string]ai.Usage `json:"tools"`
}

UsageState is the ledger of one conversation's own spend: its entries, and compaction summarization attempts, which have none.

func NewUsageState

func NewUsageState() UsageState

NewUsageState returns an empty ledger.

type ViewObserver

type ViewObserver struct {
	Advance func(ctx context.Context, value ConversationView, ops []durable.Op)
	// Publication receives every publication, after the mount took it; ops are the mount's, possibly none.
	Publication  func(ctx context.Context, before, after ConversationView, ops []durable.Op, publication durable.CommitPublication)
	CloseSession func()
}

ViewObserver receives each next revision of a mount, and the Session's close. Advance and Publication may be nil.

type Waiter

type Waiter[T any] struct {
	// contains filtered or unexported fields
}

Waiter is one pending wait registered with Waiters. It settles once: through Resolve, RejectAll, or cancellation of the context it was added with.

func (*Waiter[T]) Done

func (waiter *Waiter[T]) Done() <-chan struct{}

Done is closed once the waiter settles.

func (*Waiter[T]) Wait

func (waiter *Waiter[T]) Wait() (T, error)

Wait blocks until the waiter settles.

type Waiters

type Waiters[K comparable, T any] struct {
	// contains filtered or unexported fields
}

Waiters holds pending waits by key. Keys keep their first-registration order.

func (*Waiters[K, T]) Add

func (waiters *Waiters[K, T]) Add(ctx context.Context, key K) *Waiter[T]

Add registers a wait for key. A cancelled ctx fails it with the cancellation cause, at once when ctx is already done.

func (*Waiters[K, T]) Keys

func (waiters *Waiters[K, T]) Keys() []K

Keys returns the keys with pending waits.

func (*Waiters[K, T]) RejectAll

func (waiters *Waiters[K, T]) RejectAll(err error)

RejectAll fails every pending wait with err.

func (*Waiters[K, T]) Resolve

func (waiters *Waiters[K, T]) Resolve(key K, value T)

Resolve settles every wait of key with value.

type YieldContinue

type YieldContinue struct {
	Continue durable.UserInput
}

YieldContinue is the onYield result that appends a user message and continues the run.

Jump to

Keyboard shortcuts

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