runtime

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package runtime owns the durable AgentHarness runtime: lane control projections, serialized commands, and installed drive passes with their effect gates. Lane and its drive procedures share this package to preserve their mutual calls without a Go import cycle.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssistantReadyAtBoundary

func AssistantReadyAtBoundary(lane *Lane, state LaneState, scope session.OperationScope, triggerEntryID string, overflowRecoveryUsed bool) session.OperationState

AssistantReadyAtBoundary captures a fresh assistant step after boundary input placement.

func BoundaryPlacementEvents

func BoundaryPlacementEvents(placement BoundaryPlacement, commit session.CommitResult, firstWriteIndex int, lane, runID string) []agentharness.HarnessEvent

BoundaryPlacementEvents materializes committed input and the optional queue update in order.

func ChainEntries

func ChainEntries(parentID *string, entries []session.Entry) []session.Entry

ChainEntries places each entry after the previous entry, starting at parentID.

func Command

func Command[T any](ctx harness.Context, lane *Lane, plan func(LaneState, session.SessionReader) (LaneCommand[T], error)) (T, error)

Command is the typed form of Lane.Command (Go has no generic methods).

func CommittedEntryEvents

func CommittedEntryEvents(entries []session.Entry, commit session.CommitResult, lane, runID string, firstWriteIndex int) []agentharness.HarnessEvent

CommittedEntryEvents uses storage-assigned sequence numbers and timestamps for the inserted entries.

func DriveOperation

func DriveOperation(ctx harness.Context, lane *Lane, drive *Drive) (agentharness.DriveOutcome, error)

DriveOperation runs one installed pass through durable procedures until settlement or a durable wait.

func DurableBranchPreparation

func DurableBranchPreparation(preparation compaction.BranchPreparation) session.DurableStructuralPreparation

DurableBranchPreparation encodes abandoned branch content for the operation preparation namespace.

func DurableCompactionPreparation

func DurableCompactionPreparation(preparation compaction.CompactionPreparation) session.DurableStructuralPreparation

DurableCompactionPreparation encodes compaction content for the operation preparation namespace.

func EntryLifecycleEvents

func EntryLifecycleEvents(entry session.Entry, lane, runID string) []agentharness.HarnessEvent

EntryLifecycleEvents projects one committed entry into ordered message and entry events. Empty runID omits run identity.

func MaterializeReady

func MaterializeReady(ctx harness.Context, lane *Lane, drive *Drive, capability session.OperationState, sources ToolBatchSource, recovery bool) error

MaterializeReady publishes and places the contiguous source-order prefix of staged tool outcomes.

func NormalizedRetryPolicy

func NormalizedRetryPolicy(lane *Lane) session.NormalizedRetryPolicy

NormalizedRetryPolicy captures the current retry budget for one operation step.

func OperationCleanupWrites

func OperationCleanupWrites(ctx harness.Context, reader session.SessionReader, operationID string, state session.OperationState) ([]session.Write, error)

OperationCleanupWrites builds the operation-owned suffix of a terminal transaction without changing lane-owned input.

func OperationResultRecord

func OperationResultRecord(meta session.OperationMeta, status string, tipID *string, operationError *session.OperationError) (session.OperationResultRecord, error)

OperationResultRecord constructs the immutable terminal observation; only a failed result carries an error.

func ReadAssistantFrames

func ReadAssistantFrames(ctx context.Context, reader session.SessionReader, operationID, responseEntryID string) ([]ai.AssistantMessageFrame, error)

ReadAssistantFrames reads the committed frame prefix in ascending sequence order without interpreting frames or changing storage.

func ReadDeferredSourceHandle

func ReadDeferredSourceHandle(ctx harness.Context, reader session.SessionReader, deferred session.OperationState) (ai.DeferredHandle, error)

ReadDeferredSourceHandle reads and validates the captured provider handle from the durable source entry.

func ReadLaneQueues

func ReadLaneQueues(ctx context.Context, reader session.SessionReader, inbox []session.InboxItem) ([]agentharness.LaneQueuedItem, error)

ReadLaneQueues resolves ordered inbox payloads with owned, joined reads.

func RetryNotBefore

func RetryNotBefore(policy session.NormalizedRetryPolicy, attempt int, now int64) int64

RetryNotBefore adds the capped retry delay to now, saturating unsafe JavaScript integer deadlines.

func SettleOperation

SettleOperation is the typed form of Lane.SettleOperation.

func ToolCallFor

func ToolCallFor(sources ToolBatchSource, call session.ToolCall) (ai.ToolCall, error)

ToolCallFor resolves one source index in a validated batch.

func WaitUntil

func WaitUntil(ctx context.Context, notBefore int64) error

WaitUntil waits until the Unix-millisecond deadline, releasing its timer on cancellation and returning the signal's cause.

func WithToolBatch

WithToolBatch replaces the tools leaf while retaining only its uniform operation scope.

Types

type AbortRequested

type AbortRequested = execution.AbortRequested

AbortRequested is the expected internal control flow when cancellation wins effect admission (upstream AbortRequested); it is the execution gate's refusal error.

type AgentHarnessOptions

type AgentHarnessOptions struct {
	Session            session.Session
	Models             Models
	Model              *ai.Model
	ThinkingLevel      ai.ThinkingLevel
	ActiveToolNames    []string
	Tools              []harness.AgentHarnessTool
	ToolContext        ToolContextFactory
	SystemPrompt       SystemPromptFactory
	Resources          agentharness.Resources
	StreamOptions      harness.AgentHarnessStreamOptions
	Retry              *ai.RetryPolicy
	Compaction         *harness.CompactionSettings
	SteeringMode       agent.QueueMode
	FollowUpMode       agent.QueueMode
	ToolExecution      agent.ToolExecutionMode
	ToProviderMessages ProviderMessageConverter
	EntryProjectors    map[string]session.EntryProjector
}

AgentHarnessOptions selects the session, provider collection and initial configuration. Nil ActiveToolNames derives the initial selection from Tools; an empty slice selects no tools. Ports packages/agent/src/harness/agent-harness.ts (AgentHarnessOptions).

type AssistantResponseLifecycle

type AssistantResponseLifecycle struct {
	Observer      execution.AssistantStreamObserver
	AfterResponse func(harness.Context, *ai.AssistantMessage, execution.AssistantResponseMetadata) (*ai.AssistantMessage, error)
	Close         func() error
}

AssistantResponseLifecycle owns frame persistence, hook mediation, and live message publication for one reserved response.

func OpenAssistantResponse

func OpenAssistantResponse(lane *Lane, drive *Drive, responseEntryID string, recovery bool) AssistantResponseLifecycle

OpenAssistantResponse persists frames off the provider loop and drains them before after_response.

type BoundaryFinishPending

type BoundaryFinishPending struct{ EntryIDs []string }

BoundaryFinishPending asks the finish hook to mediate a planned boundary.

type BoundaryPlacement

type BoundaryPlacement struct {
	Entries        []session.Entry
	Writes         []session.Write
	TipID          *string
	Inbox          []session.InboxItem
	TriggerEntryID *string
	Queues         []agentharness.LaneQueuedItem
}

BoundaryPlacement contains ordered input placement without committing it. Nil TriggerEntryID and Queues mean absent.

func PlanBoundaryInbox

func PlanBoundaryInbox(ctx harness.Context, lane *Lane, drive *Drive, state LaneState, scope session.OperationScope, reader session.SessionReader, tipID *string, followUpWhenNoTrigger bool) (BoundaryPlacement, error)

PlanBoundaryInbox materializes one boundary's lane-owned input in admission order without committing it.

type ClassifiedLaneStorage

type ClassifiedLaneStorage struct {
	Kind          string
	Tip           *session.StoredValue[*string]
	Configuration *session.StoredValue[session.LaneConfiguration]
	LaneState     *session.StoredValue[session.LaneState]
}

ClassifiedLaneStorage distinguishes absent storage, a plain Branch, and a complete configured lane. Tip is present for branch and lane; Configuration and LaneState are present only for lane.

func ReadLaneStorage

func ReadLaneStorage(ctx context.Context, reader session.SessionReader, lane string) (ClassifiedLaneStorage, error)

ReadLaneStorage reads and classifies one lane's control values without a mutation barrier. Callers needing a coherent view supply a Session mutation reader. Invalid address keys return an error.

type CommandJob

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

CommandJob owns an admitted asynchronous command through event delivery and result observation.

func (*CommandJob) Done

func (job *CommandJob) Done() <-chan struct{}

func (*CommandJob) Wait

func (job *CommandJob) Wait() (any, error)

type CommandKind

type CommandKind string

CommandKind discriminates LaneCommand and OperationCommand.

const (
	CommandCommit CommandKind = "commit"
	CommandFinish CommandKind = "finish"
	CommandReturn CommandKind = "return"
	CommandReject CommandKind = "reject"
)

Command kinds.

type Config

type Config struct {
	Tools              []harness.AgentHarnessTool
	Resources          agentharness.Resources
	StreamOptions      harness.AgentHarnessStreamOptions
	RetryPolicy        ai.RetryPolicy
	Compaction         harness.CompactionSettings
	SteeringMode       agent.QueueMode
	FollowUpMode       agent.QueueMode
	ToolExecution      agent.ToolExecutionMode
	ToolContext        ToolContextFactory
	SystemPrompt       SystemPromptFactory
	ToProviderMessages ProviderMessageConverter
	EntryProjectors    map[string]session.EntryProjector
}

Config is the current process-local harness configuration (upstream Config). Values are replaced, never mutated in place.

type ContinueOperationResult

type ContinueOperationResult[T any] struct {
	CancelRequested bool
	Value           T
}

ContinueOperationResult is the outcome of continuing an operation: either the operation's cancellation was requested, or Value was produced.

func ContinueOperation

ContinueOperation is the typed form of Lane.ContinueOperation.

func PrepareCompactionThreshold

func PrepareCompactionThreshold(ctx harness.Context, lane *Lane, drive *Drive, checkpoint session.OperationState) (ContinueOperationResult[*StructuralPreparation], error)

PrepareCompactionThreshold prepares threshold compaction unless a newer compaction guards the triggering entry.

func ReadBoundedContext

func ReadBoundedContext(ctx context.Context, lane *Lane, drive *Drive, capability session.OperationState) (ContinueOperationResult[[]agent.AgentMessage], error)

ReadBoundedContext projects bounded entries outside the mutation line through the configured entry projectors.

func ReadBoundedEntries

func ReadBoundedEntries(ctx context.Context, lane *Lane, drive *Drive, capability session.OperationState) (ContinueOperationResult[[]session.Entry], error)

ReadBoundedEntries reads the current context segment on the lane's mutation line unless cancellation already won.

type CreatedHarness

type CreatedHarness struct {
	Harness *Harness
	Open    []agentharness.OpenOperation
}

CreatedHarness contains the attached runtime and the operations left open by its previous owner.

func CreateAgentHarness

func CreateAgentHarness(ctx context.Context, options AgentHarnessOptions) (CreatedHarness, error)

CreateAgentHarness restores durable control state without starting provider, tool, hook or timer effects.

type Drive

type Drive struct {
	OperationID  string
	Gate         *execution.Gate
	Context      harness.Context
	WaitForRetry bool
	// CloseSignal is cancelled, with the close error as cause, by CloseGate.
	CloseSignal harness.Context
	// DeferredPermits counts permitted deferred polls. Upstream mutates it
	// only from the lane's serialized procedures; access it the same way.
	DeferredPermits int
	// contains filtered or unexported fields
}

Drive is one installed process-local drive pass (upstream Drive). Its Context keeps the caller's values without the caller's cancellation. The effect gate is procedure-facing; BeginAbort/SignalAbort/CloseGate are the owner-facing controls. Completion settles once, with the first of Settle, Fail or CloseGate.

func NewDrive

func NewDrive(ctx harness.Context, options agentharness.DriveOptions) *Drive

NewDrive installs a drive pass for options.OperationID.

func (*Drive) BeginAbort

func (drive *Drive) BeginAbort(cancellation func() error)

BeginAbort closes effect admission with an AbortRequested carrying cancellation, without signalling admitted effects yet.

func (*Drive) CloseGate

func (drive *Drive) CloseGate(err error)

CloseGate permanently refuses admission with err, cancels CloseSignal and rejects completion unless it already settled. If the pass is publishing its outcome, rejection becomes observable after that synchronous callback and lane cleanup finish; the first close error still wins.

func (*Drive) Completion

func (drive *Drive) Completion(ctx harness.Context) (agentharness.DriveOutcome, error)

Completion waits for the drive completion. A cancelled ctx stops only this wait and returns its abort error (upstream awaitWithContext on completion).

func (*Drive) Done

func (drive *Drive) Done() <-chan struct{}

Done is closed once the completion has settled.

func (*Drive) Fail

func (drive *Drive) Fail(err error)

Fail rejects the completion with err unless already settled.

func (*Drive) Settle

func (drive *Drive) Settle(outcome agentharness.DriveOutcome)

Settle resolves the completion with outcome unless already settled.

func (*Drive) SignalAbort

func (drive *Drive) SignalAbort()

SignalAbort signals admitted effects after the abort marker is durable.

type EmitBatch

type EmitBatch func(harness.Context, []agentharness.HarnessEvent) (func() error, error)

EmitBatch binds a batch synchronously and returns its deferred delivery. Delivery runs after the Session mutation line is released.

type EventsForCommit

type EventsForCommit func(commit session.CommitResult) []agentharness.HarnessEvent

EventsForCommit derives the events published after a commit.

type Harness

type Harness struct {
	Session session.Session
	Models  Models
	// contains filtered or unexported fields
}

Harness manages configured lanes attached to one Session. It is not itself a lane.

func (*Harness) Close

func (owner *Harness) Close(ctx context.Context) error

Close seals all lanes and waits for admitted Session mutations, idle callbacks and owned fault publication.

func (*Harness) Events

func (owner *Harness) Events() *agentharness.HarnessEventBus

Events returns the runtime's passive event bus.

func (*Harness) Fault

func (owner *Harness) Fault(ctx harness.Context, cause error) error

Fault seals every lane and publishes the first storage or invariant fault.

func (*Harness) GetCompactionSettings

func (owner *Harness) GetCompactionSettings(context.Context) (harness.CompactionSettings, error)

GetCompactionSettings returns the current compaction settings.

func (*Harness) GetFollowUpMode

func (owner *Harness) GetFollowUpMode(context.Context) (agent.QueueMode, error)

GetFollowUpMode returns the current follow-up selection mode.

func (*Harness) GetLabel

func (owner *Harness) GetLabel(ctx context.Context, targetID string) (*string, error)

GetLabel reads one global entry label.

func (*Harness) GetName

func (owner *Harness) GetName(ctx context.Context) (*string, error)

GetName reads the Session's global name.

func (*Harness) GetResources

func (owner *Harness) GetResources(context.Context) (agentharness.Resources, error)

GetResources returns the current skills and templates.

func (*Harness) GetRetryPolicy

func (owner *Harness) GetRetryPolicy(context.Context) (ai.RetryPolicy, error)

GetRetryPolicy returns the current retry policy.

func (*Harness) GetSteeringMode

func (owner *Harness) GetSteeringMode(context.Context) (agent.QueueMode, error)

GetSteeringMode returns the current steering selection mode.

func (*Harness) GetStreamOptions

func (owner *Harness) GetStreamOptions(context.Context) (harness.AgentHarnessStreamOptions, error)

GetStreamOptions returns the current provider request options.

func (*Harness) GetTools

func (owner *Harness) GetTools(context.Context) ([]harness.AgentHarnessTool, error)

GetTools returns the current tool definitions.

func (*Harness) Hooks

func (owner *Harness) Hooks() *agentharness.HookRegistry

Hooks returns the runtime's hook registry.

func (*Harness) Lane

func (owner *Harness) Lane(ctx context.Context, name string, options *agentharness.AcquireLaneOptions) (*Lane, error)

Lane atomically gets or creates a complete lane. CreateAt applies only to an absent Branch.

func (*Harness) Lanes

func (owner *Harness) Lanes(ctx context.Context) ([]agentharness.LaneInfo, error)

Lanes returns configured lanes in publication order.

func (*Harness) ReadConfig

func (owner *Harness) ReadConfig() Config

ReadConfig captures the current process-local configuration.

func (*Harness) SetCompactionSettings

func (owner *Harness) SetCompactionSettings(ctx context.Context, settings harness.CompactionSettings) error

SetCompactionSettings validates and replaces compaction settings, then delivers config_update.

func (*Harness) SetFollowUpMode

func (owner *Harness) SetFollowUpMode(ctx context.Context, mode agent.QueueMode) error

SetFollowUpMode replaces the follow-up mode and delivers config_update.

func (*Harness) SetLabel

func (owner *Harness) SetLabel(ctx context.Context, targetID string, label *string) error

SetLabel commits an entry label before delivering its value_update event. Nil clears the label.

func (*Harness) SetName

func (owner *Harness) SetName(ctx context.Context, name *string) error

SetName commits the global name before delivering its value_update event. Nil clears the name.

func (*Harness) SetResources

func (owner *Harness) SetResources(ctx context.Context, resources agentharness.Resources) error

SetResources replaces skills and templates and delivers config_update.

func (*Harness) SetRetryPolicy

func (owner *Harness) SetRetryPolicy(ctx context.Context, policy ai.RetryPolicy) error

SetRetryPolicy validates and replaces the retry policy, then delivers config_update.

func (*Harness) SetSteeringMode

func (owner *Harness) SetSteeringMode(ctx context.Context, mode agent.QueueMode) error

SetSteeringMode replaces the steering mode and delivers config_update.

func (*Harness) SetStreamOptions

func (owner *Harness) SetStreamOptions(ctx context.Context, options harness.AgentHarnessStreamOptions) error

SetStreamOptions replaces request options and publishes their previous and current values.

func (*Harness) SetTools

func (owner *Harness) SetTools(ctx context.Context, tools []harness.AgentHarnessTool) error

SetTools validates unique names, replaces the definitions and delivers config_update.

func (*Harness) WatchSession

WatchSession reports the pinned runtime's unimplemented session watcher.

type Lane

type Lane struct {
	Session     session.Session
	Models      Models
	Hooks       *agentharness.HookRegistry
	State       LaneState
	ActiveDrive *Drive
	ClosedError error
	// contains filtered or unexported fields
}

Lane owns the live projection of one durable lane. Commands serialize through its Session. State and ActiveDrive are command-owned; concurrent observers use SnapshotState and CurrentDrive.

func NewLane

func NewLane(name string, sess session.Session, models Models, hooks *agentharness.HookRegistry, state LaneState, onFault func(harness.Context, error) error, emitBatch EmitBatch, installWatch LaneWatchInstaller, readConfig func() Config) *Lane

NewLane binds one restored lane to its process-local collaborators.

func (*Lane) Abort

func (lane *Lane) Abort(ctx harness.Context) (agentharness.AbortOutcome, error)

func (*Lane) Accept

Accept atomically appends input and durable operation preparation, publishes control state and awaits direct listeners without driving effects.

func (*Lane) AppendCustomEntry

func (lane *Lane) AppendCustomEntry(ctx harness.Context, customType string, data *session.JsonValue) (string, error)

func (*Lane) AppendMessage

func (lane *Lane) AppendMessage(ctx harness.Context, message agent.AgentMessage) (string, error)

func (*Lane) AssertOpen

func (lane *Lane) AssertOpen() error

func (*Lane) CancelQueued

func (lane *Lane) CancelQueued(ctx harness.Context, id string) (agentharness.CancelQueuedKind, error)

func (*Lane) Command

func (lane *Lane) Command(ctx harness.Context, plan func(LaneState, session.SessionReader) (LaneCommand[any], error)) (any, error)

Command plans against the latest committed state. Commit, memory publication, materialization and event binding precede release of the Session line. Expected rejections and delivery occur outside the fault boundary.

func (*Lane) CommandAsync

func (lane *Lane) CommandAsync(ctx harness.Context, plan func(LaneState, session.SessionReader) (LaneCommand[any], error)) (*CommandJob, error)

CommandAsync admits an ordinary command synchronously to the Session line. Idle-owned commands await that owner before admission. Callers join the job to observe failures and completion.

func (*Lane) Compact

func (lane *Lane) Compact(ctx harness.Context, instructions *string) (agentharness.CompactionOutcome, error)

func (*Lane) ContinueOperation

ContinueOperation refuses ordinary forward progress after cancellation without invoking its planner.

func (*Lane) CurrentDrive

func (lane *Lane) CurrentDrive() *Drive

func (*Lane) Drive

Drive installs one owned pass or joins an existing pass. Caller cancellation affects only observation, while close rejects observation without waiting for non-cooperative effects.

func (*Lane) EmitBatch

func (lane *Lane) EmitBatch(ctx harness.Context, events []agentharness.HarnessEvent) error

EmitBatch publishes effects outside the mutation line and waits for delivery.

func (*Lane) Fault

func (lane *Lane) Fault(ctx harness.Context, err error) error

func (*Lane) FindEntries

func (lane *Lane) FindEntries(ctx harness.Context, query *session.BranchScan) ([]session.Entry, error)

func (*Lane) FindEntry

func (lane *Lane) FindEntry(ctx harness.Context, query *session.BranchScan) (*session.Entry, error)

func (*Lane) FollowUp

func (lane *Lane) FollowUp(ctx harness.Context, message agent.AgentMessage) (string, error)

func (*Lane) FollowUpText

func (lane *Lane) FollowUpText(ctx harness.Context, text string, images []ai.ImageContent) (string, error)

func (*Lane) FollowUpWithImages

func (lane *Lane) FollowUpWithImages(ctx harness.Context, message agent.AgentMessage, images []ai.ImageContent) (string, error)

func (*Lane) GetActiveTools

func (lane *Lane) GetActiveTools(harness.Context) ([]string, error)

func (*Lane) GetModel

func (lane *Lane) GetModel(harness.Context) (*ai.Model, error)

func (*Lane) GetResult

func (lane *Lane) GetResult(ctx harness.Context, operationID string) (*session.OperationResultRecord, error)

func (*Lane) GetThinkingLevel

func (lane *Lane) GetThinkingLevel(harness.Context) (ai.ThinkingLevel, error)

func (*Lane) GetTipID

func (lane *Lane) GetTipID(harness.Context) (*string, error)

func (*Lane) InspectExecution

func (lane *Lane) InspectExecution(ctx harness.Context) (agentharness.LaneExecutionInfo, error)

func (*Lane) Mismatch

func (lane *Lane) Mismatch(expected string, current, last *string) *harness.OperationMismatch

func (*Lane) Name

func (lane *Lane) Name() string

func (*Lane) NavigateTree

func (lane *Lane) NavigateTree(ctx harness.Context, target *string, options *agentharness.NavigateOptions) (agentharness.NavigationOutcome, error)

func (*Lane) NextRun

func (lane *Lane) NextRun(ctx harness.Context, message agent.AgentMessage) (string, error)

func (*Lane) NextRunText

func (lane *Lane) NextRunText(ctx harness.Context, text string, images []ai.ImageContent) (string, error)

func (*Lane) NextRunWithImages

func (lane *Lane) NextRunWithImages(ctx harness.Context, message agent.AgentMessage, images []ai.ImageContent) (string, error)

func (*Lane) Prompt

func (lane *Lane) Prompt(ctx harness.Context, text string, images []ai.ImageContent) (agentharness.RunOutcome, error)

func (*Lane) PromptFromTemplate

func (lane *Lane) PromptFromTemplate(ctx harness.Context, name string, args []string) (agentharness.RunOutcome, error)

func (*Lane) PromptMessages

func (lane *Lane) PromptMessages(ctx harness.Context, messages []agent.AgentMessage) (agentharness.RunOutcome, error)

func (*Lane) ReadConfig

func (lane *Lane) ReadConfig() Config

func (*Lane) RecordUsage

func (lane *Lane) RecordUsage(ctx harness.Context, usage ai.Usage, options *agentharness.RecordUsageOptions) (string, error)

func (*Lane) RequestAbort

func (lane *Lane) RequestAbort(ctx harness.Context, operationID string) (agentharness.AbortRequest, error)

func (*Lane) RequestOperationAbort

func (lane *Lane) RequestOperationAbort(ctx harness.Context, operationID string) (agentharness.AbortRequest, error)

RequestOperationAbort closes effect admission before persisting cancellation and signals already-admitted effects only after the cancellation marker commits.

func (*Lane) Resume

func (lane *Lane) Resume(ctx harness.Context) (agentharness.RunOutcome, error)

func (*Lane) RunWhenIdle

func (lane *Lane) RunWhenIdle(ctx harness.Context, callback func(harness.Context) error) (err error)

RunWhenIdle owns the idle window until callback returns. Reads remain coherent; competing commands wait, and close drains an already-running callback.

func (*Lane) Seal

func (lane *Lane) Seal(err error) <-chan struct{}

Seal refuses new work, rejects drive observation, and returns the completion of any already-running idle callback. Admitted commits may still publish.

func (*Lane) SetActiveTools

func (lane *Lane) SetActiveTools(ctx harness.Context, names []string) error

func (*Lane) SetModel

func (lane *Lane) SetModel(ctx harness.Context, model agentharness.ModelIdentity) error

func (*Lane) SetThinkingLevel

func (lane *Lane) SetThinkingLevel(ctx harness.Context, level ai.ThinkingLevel) error

func (*Lane) SettleOperation

SettleOperation settles admitted work against the latest durable control, including cancellation. The capability identifies the caller's leaf type, not a stale state snapshot to publish.

func (*Lane) Skill

func (lane *Lane) Skill(ctx harness.Context, name string, instructions *string) (agentharness.RunOutcome, error)

func (*Lane) SnapshotState

func (lane *Lane) SnapshotState() LaneState

func (*Lane) Steer

func (lane *Lane) Steer(ctx harness.Context, message agent.AgentMessage) (string, error)

func (*Lane) SteerText

func (lane *Lane) SteerText(ctx harness.Context, text string, images []ai.ImageContent) (string, error)

func (*Lane) SteerWithImages

func (lane *Lane) SteerWithImages(ctx harness.Context, message agent.AgentMessage, images []ai.ImageContent) (string, error)

func (*Lane) WaitForIdle

func (lane *Lane) WaitForIdle(ctx harness.Context) error

WaitForIdle waits for durable operations even when no drive pass has been installed.

func (*Lane) Watch

Watch installs a buffered subscription and captures its snapshot under the same Session read barrier. A failed capture unsubscribes before faulting the lane.

type LaneCommand

type LaneCommand[T any] struct {
	Kind        CommandKind
	Writes      []session.Write
	Materialize Materializer[T]
	Events      EventsForCommit
	Next        LaneState
	Result      T
	Error       error
}

LaneCommand is one effect-free decision made on a lane's serialized mutation line (upstream LaneCommand):

  • commit: Writes, Materialize, optional Events, and Next lane state;
  • return: Result without writing;
  • reject: Error without writing.

type LanePatch

type LanePatch struct {
	SetTipID         bool
	TipID            *string
	SetConfiguration bool
	Configuration    session.LaneConfiguration
	SetInbox         bool
	Inbox            []session.InboxItem
}

LanePatch updates selected lane fields together with an operation transition (upstream Partial<Pick<LaneState, "tipId" | "configuration" | "inbox">>). A false Set* flag leaves the field unchanged; SetTipID with a nil TipID sets the tip to the root.

type LaneSnapshotReduction

type LaneSnapshotReduction string

LaneSnapshotReduction is empty for an applied or ignored event, or "rebase" when the caller must capture a fresh snapshot.

func ReduceLaneSnapshot

func ReduceLaneSnapshot(snapshot *agentharness.LaneSnapshot, event agentharness.HarnessEvent) LaneSnapshotReduction

ReduceLaneSnapshot applies one harness event to a mutable lane snapshot. Navigation completion returns "rebase" without changing the snapshot. Nullable string values are copied; object payload references are retained. Event delivery and snapshot capture own isolation from authoritative state.

type LaneState

type LaneState struct {
	TipID           *string
	Configuration   session.LaneConfiguration
	Inbox           []session.InboxItem
	LastOperationID *string
	Operation       *session.Operation
}

LaneState is the current durable state owned by one lane (upstream LaneState). Operation is nil when the lane is idle.

func RestoreLane

func RestoreLane(ctx context.Context, opened session.Session, lane string) (LaneState, error)

RestoreLane restores one configured lane without starting work or interpreting referenced payloads.

func RestoreLaneState

func RestoreLaneState(ctx context.Context, reader session.SessionReader, lane string, stored ClassifiedLaneStorage) (LaneState, error)

RestoreLaneState reconstructs a complete configured lane's control projection, validating current-operation identity, ownership, and intent/state reachability. Nullable string values are copied; object payload references are retained. stored must be the lane variant of ReadLaneStorage.

type LaneWatchInstaller

LaneWatchInstaller binds a watcher before capturing a lane snapshot.

type Materializer

type Materializer[T any] func(commit session.CommitResult) T

Materializer turns a successful commit into the command result. It runs synchronously on the mutation line and must not perform effects.

type Models

Models is the provider collection used by the durable runtime. The runtime accepts the production collection and instrumented collections through the same request boundary. Ports packages/agent/src/harness/agent-harness.ts (AgentHarnessOptions.models).

type OperationCommand

type OperationCommand[T any] struct {
	Kind           CommandKind
	Writes         []session.Write
	Materialize    Materializer[T]
	Events         EventsForCommit
	OperationState session.OperationState
	Record         session.OperationResultRecord
	Lane           *LanePatch
	Result         T
}

OperationCommand is a durable operation transition (upstream OperationCommand). The Lane pairs the state write with projection publication:

  • commit: Writes, Materialize, optional Events, the next OperationState and an optional Lane patch;
  • finish: Writes, the terminal Record, optional Lane patch, Materialize and optional Events;
  • return: Result without writing.

type PendingMessage

type PendingMessage struct {
	EntryID string
	Message agent.AgentMessage
}

PendingMessage is a resolved pending entry and its message payload.

func ReadPendingMessages

func ReadPendingMessages(ctx context.Context, reader session.SessionReader, ids []string, description string) ([]PendingMessage, error)

ReadPendingMessages resolves message payloads in the requested ID order.

type ProcedureResult

type ProcedureResult struct {
	Kind    ProcedureResultKind
	Outcome agentharness.DriveOutcome
	Record  session.OperationResultRecord
}

ProcedureResult is one drive procedure step: continue driving, wait with Outcome, or settle with Record.

func CommitNavigation

func CommitNavigation(ctx harness.Context, lane *Lane, drive *Drive, navigation session.OperationState) (ProcedureResult, error)

CommitNavigation validates and atomically publishes unsummarized navigation and its terminal observation.

func FinishRunBoundary

func FinishRunBoundary(ctx harness.Context, lane *Lane, drive *Drive, capability session.OperationState, continuation session.Continuation, plannedEntryIDs []string, pendingEvents []agentharness.HarnessEvent) (ProcedureResult, error)

FinishRunBoundary replans after before_run_end, publishing renewed work or the terminal result on the same mutation line.

func PublishConfigurationFailure

func PublishConfigurationFailure(ctx harness.Context, lane *Lane, drive *Drive, capability session.OperationState, failure session.OperationError) (ProcedureResult, error)

PublishConfigurationFailure settles a non-retryable configuration failure without reserving response ids.

func PublishResponse

func PublishResponse(ctx harness.Context, lane *Lane, drive *Drive, intent session.OperationState, response *ai.AssistantMessage, recovery bool) (ProcedureResult, error)

PublishResponse classifies and atomically settles one assistant generation or deferred poll under its reserved ids.

func ReconcileOperation

func ReconcileOperation(ctx harness.Context, lane *Lane, drive *Drive) (ProcedureResult, error)

ReconcileOperation advances a cancelled durable leaf without admitting ordinary work.

func RecoverAssistantGeneration

func RecoverAssistantGeneration(ctx harness.Context, lane *Lane, drive *Drive, generation session.OperationState) (ProcedureResult, error)

RecoverAssistantGeneration settles an orphan from its committed frame prefix without another provider request.

func RecoverCancelledAssistantEffect

func RecoverCancelledAssistantEffect(ctx harness.Context, lane *Lane, drive *Drive, effect session.OperationState) (ProcedureResult, error)

RecoverCancelledAssistantEffect settles a cancelled orphan under its reserved response and usage ids.

func RecoverDeferredPoll

func RecoverDeferredPoll(ctx harness.Context, lane *Lane, drive *Drive, deferred session.OperationState) (ProcedureResult, error)

RecoverDeferredPoll replaces an unknown poll under fresh ids at the same poll number.

func RecoverStructuralGeneration

func RecoverStructuralGeneration(ctx harness.Context, lane *Lane, drive *Drive, effect session.OperationState) (ProcedureResult, error)

RecoverStructuralGeneration consumes an orphaned attempt without resuming its abandoned nested request.

func RunCheckpoint

func RunCheckpoint(ctx harness.Context, lane *Lane, drive *Drive, run session.OperationState) (ProcedureResult, error)

RunCheckpoint advances a durable run boundary with at most one commit.

func RunDeferred

func RunDeferred(ctx harness.Context, lane *Lane, drive *Drive, deferred session.OperationState) (ProcedureResult, error)

RunDeferred advances or reports the durable wait for a deferred operation.

func RunDeferredSuspended

func RunDeferredSuspended(ctx harness.Context, lane *Lane, drive *Drive, deferred session.OperationState) (ProcedureResult, error)

RunDeferredSuspended polls a suspended request only when this drive holds a permit.

func RunGeneration

func RunGeneration(ctx harness.Context, lane *Lane, drive *Drive, generation session.OperationState) (ProcedureResult, error)

RunGeneration executes one ready assistant request or advances its durable retry wait.

func RunRetryWait

func RunRetryWait(ctx harness.Context, lane *Lane, drive *Drive, generation session.OperationState) (ProcedureResult, error)

RunRetryWait either reports the durable deadline or admits a cancellable wait before publishing the next ready attempt.

func RunStructuralDecision

func RunStructuralDecision(ctx harness.Context, lane *Lane, drive *Drive, deciding session.OperationState) (ProcedureResult, error)

RunStructuralDecision consumes the durable preparation and its decision hook without publishing stale cancelled output.

func RunStructuralGeneration

func RunStructuralGeneration(ctx harness.Context, lane *Lane, drive *Drive, ready session.OperationState) (ProcedureResult, error)

RunStructuralGeneration performs one durable structural attempt, accounting for each nested provider request separately.

func RunStructuralRetryWait

func RunStructuralRetryWait(ctx harness.Context, lane *Lane, drive *Drive, retry session.OperationState) (ProcedureResult, error)

RunStructuralRetryWait consumes a retry wait without starting a provider request.

func RunTools

func RunTools(ctx harness.Context, lane *Lane, drive *Drive, run session.OperationState) (ProcedureResult, error)

RunTools executes, recovers, stages, and source-orders a complete durable tool batch.

func StartRun

func StartRun(ctx harness.Context, lane *Lane, drive *Drive, run session.OperationState) (ProcedureResult, error)

StartRun consumes before_run and commits its injected messages with the initial checkpoint.

type ProcedureResultKind

type ProcedureResultKind string

ProcedureResultKind discriminates ProcedureResult.

const (
	ProcedureContinue ProcedureResultKind = "continue"
	ProcedureWaiting  ProcedureResultKind = "waiting"
	ProcedureSettled  ProcedureResultKind = "settled"
)

Procedure result kinds.

type ProgressChannel

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

ProgressChannel serializes durable progress admission. Seal refuses subsequent writes; Drain returns the latest write's completion or admission error.

func OpenFrameProgress

func OpenFrameProgress(lane *Lane, drive *Drive, responseEntryID string) *ProgressChannel[ai.AssistantMessageFrame]

OpenFrameProgress appends frames only while the lane's authoritative phase owns this response.

func OpenToolProgress

func OpenToolProgress(lane *Lane, drive *Drive, turnID string, sourceIndex int, invocationID string) *ProgressChannel[harness.AgentToolResult]

OpenToolProgress replaces the checkpoint only while the authoritative tool batch owns the invocation.

func (*ProgressChannel[T]) Drain

func (progress *ProgressChannel[T]) Drain() error

Drain waits for the latest write and preserves its rejection. Session lifetime owns any earlier commit still in flight after a later admission failure.

func (*ProgressChannel[T]) Seal

func (progress *ProgressChannel[T]) Seal()

Seal closes admission without cancelling already queued updates.

func (*ProgressChannel[T]) Write

func (progress *ProgressChannel[T]) Write(item T)

Write admits an ordered progress update without waiting for storage. Drain owns completion of admitted updates.

type ProviderMessageConverter

type ProviderMessageConverter func(ctx harness.Context, messages []agent.AgentMessage) ([]ai.Message, error)

ProviderMessageConverter converts agent messages to provider messages (upstream AgentHarnessOptions.toProviderMessages).

type RestoredLane

type RestoredLane struct {
	Name  string
	State LaneState
}

RestoredLane is one name/state pair from restoreSession's ordered Map. A slice preserves its iteration order in Go.

func RestoreSession

func RestoreSession(ctx context.Context, opened session.Session) ([]RestoredLane, error)

RestoreSession restores every complete configured lane in one coherent Session read, in inventory order. Plain Branches are omitted. Restore does not write or start effects.

type SliceNotImplemented

type SliceNotImplemented struct {
	Operation string
}

SliceNotImplemented reports an AgentHarness operation that belongs to a later slice (upstream SliceNotImplemented).

func (*SliceNotImplemented) Error

func (err *SliceNotImplemented) Error() string

type StructuralPreparation

type StructuralPreparation struct {
	TaskID      string
	Preparation session.DurableStructuralPreparation
}

StructuralPreparation pairs a reserved task identity with its immutable preparation.

func PrepareOverflowCompaction

func PrepareOverflowCompaction(ctx harness.Context, lane *Lane, drive *Drive, generation session.OperationState) (*StructuralPreparation, error)

PrepareOverflowCompaction prepares one overflow recovery before settling the assistant response.

type SystemPromptFactory

type SystemPromptFactory func(ctx harness.Context, toolContext any) (string, error)

SystemPromptFactory builds the system prompt (upstream AgentHarnessOptions.systemPrompt; a static string is a factory returning it).

type ToolBatchSource

type ToolBatchSource struct {
	Assistant agent.AssistantMessage
	Calls     map[int]ai.ToolCall
}

ToolBatchSource binds planned source indexes to their immutable assistant tool calls.

func ReadToolBatchSource

func ReadToolBatchSource(ctx harness.Context, lane *Lane, drive *Drive, batch session.ToolBatch) (ToolBatchSource, error)

ReadToolBatchSource validates the batch's source assistant and tool-call indexes.

type ToolContextFactory

type ToolContextFactory func(ctx harness.Context) (any, error)

ToolContextFactory resolves the tool context for one invocation (upstream AgentHarnessOptions.toolContext; a static value is a factory returning it).

type ToolInvocationEnded

type ToolInvocationEnded struct{}

func (*ToolInvocationEnded) Error

func (*ToolInvocationEnded) Error() string

Jump to

Keyboard shortcuts

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