harness

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 40 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,
		CheckpointWhenRaw: func(durable.JsonObject, []durable.Op, durable.CheckpointInfo) bool { return true },

		Initial: func() AgentState { return AgentState{} },
	},
	DocumentSemantics: durable.NewRewindableConversationSemantics(durable.ForkAsOf).DocumentSemantics,
})

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 DefaultHarnessIdentity = ai.ClientIdentity{Attribution: new(ai.PiAttribution)}

DefaultHarnessIdentity is the request identity of a Harness's model requests: the ai package's defaults with provider attribution to PiG.

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

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 DurableTelemetrySchema = telemetry.DefineTelemetrySchema(&telemetry.TelemetrySchemaDefinition{
	Version: 1,
	Spans: map[string]telemetry.TelemetrySpanDefinition{
		"pi.durable.submit": {
			Description: "Public submission admission: with its commit for submit(draft, context); the admission only for submit(tx, draft), whose result is provisional (a later throw or storage failure of the caller's commit leaves no submission) and whose commit events go to the caller's commit context. Inputs and continues start root traces linked to their callers; writes are children. Internal admissions emit phase events only.",
			Parents:     telemetry.TelemetryParentDefinition{Kind: telemetry.TelemetryParentKindAny},
			StartAttributes: map[string]telemetry.TelemetryStartAttributeDefinition{
				"submission.type": attribute(attrString, true, "Submission type.", "input", "write", "continue"),
				"conversation.id": highCardinality(attribute(attrNumber, true, "Conversation ID.")),
			},
			EndAttributes: map[string]telemetry.TelemetryAttributeDefinition{
				"submission.id": endAttribute(highCardinality(attribute(attrNumber, false, "Admitted submission ID."))),
				"result":        endAttribute(attribute(attrString, false, "Admission result; stale writes report done.", "queued", "placed", "done")),
			},
			Events: map[string]telemetry.TelemetryEventDefinition{
				"pi.durable.entry":      durableEntryEvent,
				"pi.durable.submission": durableSubmissionEvent,
				"pi.durable.report":     durableReportEvent,
			},
			Status: telemetry.TelemetrySpanStatusDefinition{Default: telemetry.SpanStatusCodeOK, ErrorWhen: "Admission failed."},
		},
		"pi.durable.phase": {
			Description: "One task phase invocation, including its decision commit, never a wait or restart.",
			Parents:     telemetry.TelemetryParentDefinition{Kind: telemetry.TelemetryParentKindAny},
			StartAttributes: map[string]telemetry.TelemetryStartAttributeDefinition{
				"task.id":   highCardinality(attribute(attrNumber, true, "Task ID.")),
				"task.name": attribute(attrString, true, "Registered task name."),
				"phase":     attribute(attrString, true, "Invoked checkpoint phase."),
				"kind":      attribute(attrString, true, "Invocation kind.", "run", "abort"),
				"attempt":   attribute(attrNumber, false, "Checkpoint attempt, when present."),
				"resumed":   attribute(attrBoolean, true, "First invocation of a task loaded in this process."),
			},
			EndAttributes: map[string]telemetry.TelemetryAttributeDefinition{
				"outcome":      endAttribute(attribute(attrString, false, "next=<phase>, waiting, sleeping, done, faulted, or aborted.")),
				"tool.name":    endAttribute(attribute(attrString, false, "Called tool name.")),
				"tool.call_id": endAttribute(highCardinality(attribute(attrString, false, "Transcript tool call ID."))),
			},
			Events: map[string]telemetry.TelemetryEventDefinition{
				"pi.durable.entry":      durableEntryEvent,
				"pi.durable.submission": durableSubmissionEvent,
				"pi.durable.report":     durableReportEvent,
				"pi.durable.checkpoint": {
					Description: "The running checkpoint's phase changed while the invocation continued.",
					Attributes: map[string]telemetry.TelemetryEventAttributeDefinition{
						"phase": attribute(attrString, true, "Committed checkpoint phase."),
					},
				},
				"pi.durable.replay": {
					Description: "A nested tool call was answered from its stored result.",
					Attributes: map[string]telemetry.TelemetryEventAttributeDefinition{
						"tool.name": attribute(attrString, true, "Called tool name."),
					},
				},
			},
			Status: telemetry.TelemetrySpanStatusDefinition{
				Default:   telemetry.SpanStatusCodeOK,
				ErrorWhen: "Faulted, failed, and orphaned outcomes use task_faulted, task_failed, and task_orphaned with a diagnostic capped at 500 characters. Aborted outcomes keep status ok.",
			},
		},
	},
	Metrics: map[string]telemetry.TelemetryMetricDefinition{
		"pi.durable.reports": {
			Kind:        telemetry.TelemetryMetricKindCounter,
			Description: "Reports raised, grouped by their fixed kind.",
			Attributes:  map[string]telemetry.TelemetryMetricAttributeDefinition{"type": durableReportAttributes["type"]},
		},
		"pi.durable.phase.duration": {
			Kind:        telemetry.TelemetryMetricKindHistogram,
			Unit:        "ms",
			Description: "Duration of a phase invocation and its decision commit.",
			Attributes: map[string]telemetry.TelemetryMetricAttributeDefinition{
				"task":    attribute(attrString, true, "Registered task name."),
				"phase":   attribute(attrString, true, "Invoked checkpoint phase."),
				"outcome": attribute(attrString, true, "Phase outcome."),
			},
		},
		"pi.durable.tasks.active": {
			Kind:        telemetry.TelemetryMetricKindUpDownCounter,
			Description: "Live tasks held by this Harness; decremented at terminal settlement or close.",
			Attributes: map[string]telemetry.TelemetryMetricAttributeDefinition{
				"task": attribute(attrString, true, "Registered task name."),
			},
		},
	},
})

DurableTelemetrySchema is DURABLE_TELEMETRY_SCHEMA: Durable's content-free span, event, and metric vocabulary. IDs address durable records, never content.

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,
		CheckpointWhenRaw: func(value durable.JsonObject, _ []durable.Op, _ durable.CheckpointInfo) bool {
			items, _ := value.Get("items")
			list, _ := items.([]any)
			return len(list) == 0
		},

		Initial: func() InboxState { return InboxState{Items: []InboxItem{}} },
	},
	DocumentSemantics: durable.NewLatestConversationSemantics(durable.ForkInitial).DocumentSemantics,
})

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: 3,

		Migrate: func(value durable.JsonObject, _ int) (LiveState, error) {
			live := value.Clone()
			if run, ok := value.Get("run"); ok {
				migrated := run.(durable.JsonObject).Clone()
				if turns, _ := migrated.Get("turns"); !isJSONNumber(turns) {
					migrated.Set("turns", float64(0))
				}
				live.Set("run", migrated)
			}
			if list, ok := value.Get("compactions"); ok {
				statuses, _ := list.([]any)
				renamed := make([]any, len(statuses))
				for i, status := range statuses {
					renamed[i] = renameReason(status.(durable.JsonObject))
				}
				live.Set("compactions", renamed)
			}
			if failure, ok := value.Get("compactionFailure"); ok {
				live.Set("compactionFailure", renameReason(failure.(durable.JsonObject)))
			}
			return durable.FromJsonValue[LiveState](live)
		},
		CheckpointWhenRaw: func(value durable.JsonObject, _ []durable.Op, _ durable.CheckpointInfo) bool {
			if generation, _ := value.Get("generation"); generation != nil {
				return false
			}
			for _, key := range [...]string{"tools", "nestedTools"} {
				list, _ := value.Get(key)
				slots, _ := list.([]any)
				for _, entry := range slots {
					if slot, ok := entry.(*delta.JsonObject); ok {
						if status, _ := slot.Get("status"); status == string(ToolSlotRunning) {
							return false
						}
					}
				}
			}
			return true
		},

		Initial: func() LiveState { return LiveState{} },
	},
	DocumentSemantics: durable.NewLatestConversationSemantics(durable.ForkInitial).DocumentSemantics,
})

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 NestedCallDoc = durable.DefineDocFamily(durable.DocFamilyDefinition[NestedCallState, any]{
	Kind:              nestedCallKind,
	Version:           1,
	DocumentSemantics: durable.DocumentSemantics{Scope: durable.ScopeTask},
	Family:            true,
	Initial:           func(any) NestedCallState { return NestedCallState{} },

	CheckpointWhen: func(NestedCallState, []durable.Op, durable.CheckpointInfo) bool { return false },
})

NestedCallDoc is the built-in pi.tool.nested-call family of a calling task, keyed by the nested call's key: so a rerun finds the calls it already made, and the caller reads each result. Created with the nested task; the nested call's terminal commit adds its result. One document per call, so no commit rewrites the others. It retires with the caller.

View Source
var ProgressCommit = durable.CommitOptions{Persistence: &durable.CommitPersistence{Kind: durable.CommitDeferred}}

ProgressCommit is how the progress throttles commit a partial answer and running tool output into pi.live: deferred, so storage gets them together, at the next commit that reads or writes pi.live or after Settings.Progress.PersistWithinMs. Every commit that consumes or clears streamed fields reads pi.live, so it stores them with its own changes (spec §8.2).

View Source
var ProviderDoc = durable.DefineDoc(durable.DocDefinition[ProviderState]{
	CommonDocDefinition: durable.CommonDocDefinition[ProviderState]{
		Kind:    "pi.provider",
		Version: 1,
		CheckpointWhenRaw: func(durable.JsonObject, []durable.Op, durable.CheckpointInfo) bool {
			return true
		},

		Initial: newProviderState,
	},
	DocumentSemantics: durable.NewLatestConversationSemantics(durable.ForkInitial).DocumentSemantics,
})

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,
		CheckpointWhenRaw: func(durable.JsonObject, []durable.Op, durable.CheckpointInfo) bool {
			return true
		},

		Initial: NewUsageState,
	},
	DocumentSemantics: durable.NewLatestConversationSemantics(durable.ForkInitial).DocumentSemantics,
})

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

Functions

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 to tools and modelTools, so the next request offers the tools: an exact list gets each name it lacks appended, and {remove} loses the names. An unset tools already enables every tool, so nothing is written for it. An unset or filter modelTools also gets each name appended to its add, which loads deferred tools and has no effect for others. By name, without the registry: a tool that is not registered now, such as one of an MCP server that is reconnecting, is offered once it is again.

Ports packages/durable/src/harness/agent.ts (addTools).

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 AppendToolResult

func AppendToolResult(tx durable.Tx, conversationId durable.ConversationId, call ai.ToolCall, result durable.ToolExecutionResult, timestamp float64, durationMs *int64) (*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, plan *AssignPlan) 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. That append costs a compare of the whole string, though; where plan says what a string member grew by, and the committed string plus that text has the new string's length, the text is appended with AppendText instead.

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 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 CutOffCount

func CutOffCount(restarts int) string

CutOffCount says how often a task was cut off, for a message: "once", or "3 times in a row".

func CutOffTooOften

func CutOffTooOften(restarts int, runtime settingsOf) bool

CutOffTooOften reports whether a task was cut off settings.restartLimit times in a row, so its phase ends it instead of running. The settings are read only for a task that was cut off at all, so the normal path resolves nothing more.

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. The view is the caller's own.

func EndRun

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

EndRun ends the run owned by taskId: it settles each of its inputs, removes run, and, without an answer, records runFailure. A run that answered already, and runs only its afterRun tasks, records no failure, however it ends. It always removes generation, tools, and nestedTools, whose presentation belongs to the ending run.

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 FailCompactionStatus

func FailCompactionStatus(live *delta.Object, taskId durable.TaskId, message string) error

FailCompactionStatus removes the status of compaction task taskId and records that it failed with 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, model-issued in the current round or nested, or nil when pi.live no longer lists it. Nested slots are found by binary search: a tool may make thousands of nested calls, each of which looks up its slot in several commits. Their task IDs ascend: each slot is appended in the commit that creates its task, task IDs ascend in commit order, and removal keeps the order.

func FinishSlot

func FinishSlot(slot *delta.Object) error

FinishSlot marks a slot done and clears its running output (live.ts:197-204 finishSlot); the caller sets a model-issued call's result entry, or a nested call's summary. Neither is set when the task faulted or was orphaned.

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 HasQueuedReset

func HasQueuedReset(items []InboxItem) bool

HasQueuedReset reports whether a reset (a head "self" write) is queued; entries appended before it leave the active range when it lands (inbox.ts hasQueuedReset).

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 HookEntry

func HookEntry[D any](ctx context.Context, api HookApi, token durable.Entry[D], id durable.EntryId) (*durable.TypedEntry[D], error)

HookEntry is the typed overload of HookApi.entry (harness/types.ts:953): the committed entry visible from the task's conversation when it is present and has the token's kind, nil otherwise. A method cannot take the token's type parameter, so the read is a function, as durable.TaskEntry is for a task's runtime.

func IsDisplayOnly

func IsDisplayOnly(entry durable.EntryDraft) bool

IsDisplayOnly reports whether a write is display-only: it has no model, head or edits (a present one counts, even if empty), so it changes nothing the model sees and needs no boundary (inbox.ts isDisplayOnly).

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. The view is the caller's own.

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 RemoveNestedSlots

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

RemoveNestedSlots removes the nested slots below tool task taskId, transitively; the list holds parents before their children.

func ResolveAgent

func ResolveAgent(state *AgentState, snapshot durable.RegistrySnapshot, settings durable.Settings, report func(err error, extension string)) 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 SafeNow

func SafeNow(now func() float64, report func(err error, info durable.ReportInfo)) func() float64

SafeNow is the host clock, falling back to the wall clock when it panics: a broken clock must not stop commits. The first failure is reported; the clock is read in every task change, so later ones are not. Ports harness.ts safeNow; the Harness over the core wraps its Now with it too.

func SafeReport

func SafeReport(onReport func(report durable.Report)) func(err error, info durable.ReportInfo)

SafeReport is onReport that cannot fail: it is the last place an error goes, so its own panic is dropped. Ports harness.ts safeReport; the Harness over the core wraps its OnReport with it too.

func Salvageable

func Salvageable(restarts int, runtime settingsOf) bool

Salvageable reports whether a task at the limit may still do the cleanup it does when it ends, such as converting a partial: only at the limit. Past it, that cleanup may be what cut the task off, so the task ends without it.

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 SectionExtension

func SectionExtension(agent durable.Agent, key string) string

SectionExtension is the extension whose code a section of agent runs: the last selected one that provides or wraps it; empty when there is none.

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, and so is thinking: providers return summaries of the real reasoning, and replayed thinking is often not part of the live context, so including it can make the request larger than the context it summarizes (compaction.ts serializeConversation).

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 and its failure recorded. 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, run RunStart, options *StartRunOptions) error

StartRun starts a run for run.Inputs, placed input submissions, whose first entry is run.First (LiveRun.First): a new generation takes pi.live.run. It removes runFailure unless options.KeepFailure: a run started in the commit that ended the failed one keeps its failure.

func StructuredOutputError

func StructuredOutputError(tool *durable.ToolRegistration, result durable.ToolExecutionResult) string

StructuredOutputError is why a result's structuredOutput breaks the tool's contract, or "" when it keeps it (tool.ts structuredOutputError): pi-schema's check of the schema, without conversion or coercion. The path is the first error's JSON Pointer with its escapes undone and its segments joined by dots, "root" for the value itself.

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 ToolExtension

func ToolExtension(agent durable.Agent, name string) string

ToolExtension is the extension whose code a tool of agent runs: the last selected one that provides or wraps it; empty when there is none.

func ToolOutputLimits

func ToolOutputLimits(tool *durable.ToolRegistration) output.OutputLimits

ToolOutputLimits is the bound a tool's retained output keeps: the tool's own limits over the defaults (tool.ts outputLimits); all defaults when the tool did not resolve (nil).

func WithdrawQueuedInputs

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

WithdrawQueuedInputs is WithdrawQueuedInputsFor with reason aborted, as Conversation.Abort and abort cascades withdraw.

func WithdrawQueuedInputsFor

func WithdrawQueuedInputsFor(tx durable.Tx, conversationId durable.ConversationId, reason string) error

WithdrawQueuedInputs withdraws every queued input of a conversation, as Conversation.Abort and abort cascades do: each settles unanswered with reason (Conversation.Abort uses 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 Admission

type Admission struct {
	Id     durable.SubmissionId
	Status string
}

Admission is what AdmitSubmission reports: the submission and how it was admitted ("queued", "placed", or "done"; a stale write reports done).

func AdmitSubmission

func AdmitSubmission(tx durable.Tx, conversationId durable.ConversationId, draft durable.SubmissionDraft, now float64, queueModes QueueModes, span telemetry.TelemetrySpan) (Admission, error)

AdmitSubmission admits a submission inside a commit (spec §6, submissions.ts:136-207); both Conversation.Submit forms and conversation-owned compactions share it. A known request ID returns its existing submission without writing. A display-only write (only kind and data) is appended and settled done at once, busy or not, as it changes nothing the model sees; only behind a queued reset it queues, so it lands after the reset instead of before it in the context the reset ends. A busy conversation queues anything else in pi.inbox, or rejects whenBusy reject input and any continue with ConversationBusy; an idle one rejects whenIdle reject input with ConversationIdle. An idle continue places queued items and starts a run with them and itself, placing no entry of its own. An idle conversation with queued items queues it behind them and runs a final boundary. Otherwise idle input places its entry (pi.user, or the input's own) and starts a run, and an idle write appends its entry and settles done, or stale when its head reaches before the active range.

type AgentChange

type AgentChange struct {
	Model         Change[durable.ModelRef]
	ThinkingLevel Change[ai.ModelThinkingLevel]
	Extensions    Change[ExtensionChange]
	Tools         Change[ToolChange]
	ModelTools    Change[ToolChange]
	Instructions  Change[string]
	Cwd           Change[string]
	// MaxTurns is validated by Configure: it must be an integer 1 or more (or cleared), else an error (upstream's RangeError).
	MaxTurns Change[float64]
}

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 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"`
	// ModelTools filters the enabled tools the model may call (Callers includes the model): the tools offered to it. It never
	// widens: other tools can still call the ones it leaves out.
	//   - Unset: every such tool except deferred ones.
	//   - An exact list: exactly these, in order, deferred ones too.
	//   - A filter: every such tool except deferred ones and those in Remove, in registry order, followed by the deferred tools
	//     in Add that are not in Remove, in Add order. Names of tools that are not deferred or not registered have no effect in Add.
	ModelTools *ToolSelection `json:"modelTools,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"`
	// MaxTurns is the tool rounds one run takes at most (pi.live.run.turns): the round that reaches it runs its tools, then the run
	// ends unanswered with turn_limit. An integer, 1 or more; unset, no limit. Task-owned children and forks inherit it.
	MaxTurns *int `json:"maxTurns,omitempty"`
}

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

type AssignPlan

type AssignPlan struct {
	Kind   planKind
	Text   string
	Fields map[any]*AssignPlan
}

AssignPlan says how AssignJson writes one value instead of assigning it leaf by leaf.

type BeforeToolResult

type BeforeToolResult struct {
	Arguments map[string]any
	Block     *string
}

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

type BlockedSubject

type BlockedSubject struct {
	Id             durable.TaskId
	Kind           string
	Version        int
	AbortRequested bool
	AbortReason    durable.TaskAbortReason
	Status         durable.TaskStatus
}

BlockedSubject is what BlockedReason reads of a task: the task graph keeps only this of each record.

func BlockedSubjectOf

func BlockedSubjectOf(record anyTaskRecord) BlockedSubject

BlockedSubjectOf is the part of a record BlockedReason reads.

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
	First *durable.EntryId
	Reset bool
}

BoundaryResult holds the selected user items, in ID order, the first entry the boundary placed, a write's or a user item's (a run it starts begins there, LiveRun.First), 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 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 CompactionFailure

type CompactionFailure struct {
	TaskId durable.TaskId `json:"taskId"`
	// Trigger is what started the compaction that failed.
	Trigger durable.CompactionReason `json:"trigger"`
	// Error is the failed or faulted outcome's error message, or why the scheduler orphaned the task.
	Error string `json:"error"`
}

CompactionFailure is the newest compaction that failed since a compaction last produced a summary (spec §8.7, live.ts:74-79).

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
	// ModelOverrides is keyed by exact "provider/modelId"; each field an entry sets replaces the Harness-wide one for that
	// model, so small- and large-window models can share a Harness (types.ts CompactionSettings, Pi c4cf7957).
	ModelOverrides map[string]durable.CompactionPolicyOverride
}

CompactionPolicyPatch is CompactionSettings: Partial<CompactionPolicy>, nil fields keep the defaults, plus ModelOverrides.

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 CompactionStatus

type CompactionStatus struct {
	TaskId durable.TaskId `json:"taskId"`
	// Trigger is what started it: compact(), a threshold, or a context overflow.
	Trigger durable.CompactionReason `json:"trigger"`
	// 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, session lineReader, storage durable.Storage, conversationId durable.ConversationId, at *durable.EntryId, visible bool) (*ContextBounds, error)

CaptureContextBounds captures the bounds of the current context, or of the context cut off at the visible entry at; nil when the conversation has no entry. The newest entry and head marker are known from the Session's commits, so the current bounds usually cost no Storage read. Run it on the Session line, with its gated storage; entries at or below the tail are immutable, so DeriveContext can then scan them off the line. visible is set when at is known to be visible, as an entry of a range of the conversation is.

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, a passive entry write, or a continue. A busy conversation, or one with queued items, queues input and writes that affect model context in pi.inbox; WhenBusy reject rejects input with ConversationBusy instead and writes nothing. An idle conversation rejects WhenIdle reject input with ConversationIdle and writes nothing. A write of only Kind and Data (no Model, Head, or Edits) is appended at once, even mid-run, as it changes nothing the model sees. A continue starts a run on the context as it is, after placing queued items; a busy conversation rejects it with ConversationBusy, as it never queues.
	Submit(ctx context.Context, submission durable.SubmissionDraft) (durable.Submission, error)
	// SubmitIn admits a submission inside the caller's commit tx (Harness.Commit, Conversation.Commit, a task's runtime Commit), with the same rules, and returns its ID: the admission is stored with that commit, or not at all when the callback fails later or the commit fails. Call it before the commit's first table write (AppendEntry, CreateTask, CreateSubmission, another admission): otherwise it fails with ReadAfterWrite, on every path. Documents may be read and written before and after it. A rejection (ConversationBusy, ConversationIdle) fails before any write, so the callback may handle it. Do not call Submission or other Harness reads inside the callback: they wait for the commit holding the line. Its pi.durable.submit span covers the admission only, so its result is provisional. Fails for a transaction of another Session.
	SubmitIn(tx durable.Tx, submission durable.SubmissionDraft) (durable.SubmissionId, 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; options are as for Session.Commit.
	Commit(ctx context.Context, change func(tx durable.Tx) (any, error), options ...durable.CommitOptions) (any, error)
	// Context returns the committed raw active transcript and model context. With options.At, it returns the context as
	// of that visible entry: the same view Fork(at) would start with, without creating a conversation.
	Context(ctx context.Context, options *durable.ContextOptions) (durable.ContextView, error)
	// Entries returns the fork-aware history of this conversation, newest first unless query.Order is ScanAscending;
	// 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
	// Watch returns the structural view (spec §9.3) as a serialized watch; commits made while its listener runs arrive folded.
	// Its Entries are a window over the transcript, as window says: the newest 50 by default, then appends, dropping the
	// oldest past 100. A nil window takes the defaults. It is built on the same mount as Harness.ObserveConversation.
	Watch(ctx context.Context, window *ConversationWindow) (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 ConversationTranscript

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

ConversationTranscript is what a client has of one conversation: every entry it got from a view or fetched, and the gaps between (spec §9.3). A layer over any ConversationView, wherever it comes from: call Merge with every value of the view; it returns the view with the client's whole transcript as Items instead of the window. Entries never change once committed, so the transcript only grows; a window that dropped its oldest entries keeps them here.

A window whose Before lies past the newest entry the client has does not continue it, after a stall, an overflow, or a reconnect: the entries in between become a gap. Nothing counts entries or computes ranges from entry IDs, which have holes; only exclusive bounds are turned into the inclusive bounds of EntryQuery. After a drop, a new watch with Resume as its window continues the transcript.

A merge costs O(items) and never re-sorts or re-fetches; a merge, LoadEarlier, or FillGap that adds nothing returns the previous view, whose Items are the previous items. Concurrent calls of LoadEarlier, or of FillGap for the same gap, share one load, so a placeholder that stays visible does not fetch twice. It is safe for concurrent use.

func NewConversationTranscript

func NewConversationTranscript(load EntryLoader, options *ConversationTranscriptOptions) (*ConversationTranscript, error)

NewConversationTranscript returns an empty transcript that loads through load; it fails for a page size below 1.

func (*ConversationTranscript) FillGap

func (transcript *ConversationTranscript) FillGap(ctx context.Context, gap TranscriptGap) (*TranscriptView, error)

FillGap loads the next page of gap, a gap item of the view's Items, shrinking it from its start, or removing it once nothing is missing. A gap that has shrunk since loads the gap it became; one that is no longer there returns the current view.

func (*ConversationTranscript) LoadEarlier

func (transcript *ConversationTranscript) LoadEarlier(ctx context.Context) (*TranscriptView, error)

LoadEarlier loads the page before the oldest entry held. Without anything earlier, it returns the current view.

func (*ConversationTranscript) Merge

func (transcript *ConversationTranscript) Merge(view ConversationView) *TranscriptView

Merge takes one value of the view: its window's entries join the transcript.

func (*ConversationTranscript) Newest

func (transcript *ConversationTranscript) Newest() (durable.EntryId, bool)

Newest is the ID the transcript reaches: its newest entry, or the Before of a later window that was empty. It reports false before the first merge and for an empty transcript.

func (*ConversationTranscript) Resume

func (transcript *ConversationTranscript) Resume() *ConversationWindow

Resume is the window that resumes this transcript after a drop: From right after Newest, so a new watch returns only what was missed when it fits its window, otherwise its newest entries and a gap; an empty window for an empty transcript; nil before the first merge. conversation.Watch(ctx, transcript.Resume()).

type ConversationTranscriptOptions

type ConversationTranscriptOptions struct {
	// PageSize is the number of entries LoadEarlier and FillGap load per call; default 50.
	PageSize *int
}

ConversationTranscriptOptions are the options of NewConversationTranscript.

type ConversationView

type ConversationView struct {
	Conversation durable.ConversationRecord `json:"conversation"`
	// Entries are a window over the transcript, its fork-aware history (Conversation.Entries), in entry ID order. Head markers
	// such as compaction summaries sit where they were written; their Head tells where the entries they summarize end.
	Entries []durable.EntryRecord `json:"entries"`
	// Before is the ID of the entry just before the window; nil when the window starts the transcript.
	Before *durable.EntryId `json:"before,omitempty"`
	// Docs holds the built-in conversation documents keyed by kind; absent documents are absent.
	Docs ViewDocs `json:"docs"`
}

ConversationView is the structural view of one conversation: a window over its transcript and its 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, and hands each observer the next revision of its own window.

func NewConversationViews

func NewConversationViews(sessionImpl *session.SessionImpl) *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, window *ConversationWindow, create func(value ConversationView, release func()) *ViewObserver) (*ViewObserver, func(), error)

Attach registers an observer created from its window's first revision, atomically on the Session line: it sees every later publication and nothing earlier. The returned detach drops the observer, and the mount with its last observer.

func (*ConversationViews) Observe

Observe attaches a synchronous observer of the view (Harness.ObserveConversation), behind session.GuardObserver; ctx governs only the attachment.

func (*ConversationViews) Watch

Watch returns a serialized watch of the view, an observer of its mount; aborting ctx ends it aborted.

type ConversationWatch

type ConversationWatch = durable.WatchHandle[ConversationView]

ConversationWatch is a serialized watch of the structural view.

type ConversationWindow

type ConversationWindow struct {
	// From is where the first value's window starts, inclusive, such as right after the newest entry a client has
	// (ConversationTranscript.Resume). It selects only that first value: every entry committed after the attachment is
	// appended, whatever its ID. A From past the newest entry starts the window empty, with Before the newest entry.
	From *durable.EntryId
	// Min defaults to 50; an integer, at least 1.
	Min *int
	// Max defaults to 2 * Min; an integer, at least Min.
	Max *int
}

ConversationWindow says which entries a view's window holds (spec §9.3). The window holds between Min and Max entries: it starts with the newest Min entries, takes appends, and once it would hold more than Max, drops its oldest in one splice down to Min. With From, it starts at From instead when at most Max entries are at or after it. Every field is optional; a nil *ConversationWindow takes every default.

type DeferredStatus

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

DeferredStatus is a provider-side deferred response being polled.

type EntryLoader

type EntryLoader func(ctx context.Context, query durable.EntryQuery, limit int) (durable.Page[durable.EntryRecord, durable.Cursor], error)

EntryLoader pages a conversation's entries, as Conversation.Entries does without a cursor; query.ConversationId is ignored.

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 {
	List []*durable.Extension
	Edit *ExtensionEdit
}

ExtensionChange is Pi's `Extension[] | { add?, remove? }`: List is the array form, a non-nil list (empty included) that replaces the selection, and Edit is the object form that edits the host default selection. Go has no sum of a list and an object, so exactly one of the two fields is set; neither set is the empty object `{}`.

type ExtensionEdit

type ExtensionEdit struct {
	Add    []*durable.Extension
	Remove []*durable.Extension
}

ExtensionEdit is the `{ add?, remove? }` form of an extension change; 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         GenerationPhase                    `json:"phase"`
	Attempt       int                                `json:"attempt,omitempty"`
	Compacted     *durable.TaskId                    `json:"compacted,omitempty"`
	Overflow      *string                            `json:"overflow,omitempty"`
	Threshold     bool                               `json:"threshold,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"`
	Poll          *GenerationPoll                    `json:"poll,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"`
	Run           *RunSummary                        `json:"run,omitempty"`
	Answer        *durable.EntryId                   `json:"answer,omitempty"`
	Tasks         []durable.TaskId                   `json:"tasks,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; Threshold is set when the blocking threshold started Compacted, whose outcome is 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, and Poll, the deferred response a poll was fetching when the host died: the next attempt polls it again instead of sending another request, so the provider's job is neither lost nor paid twice.
  • poll: Attempt, Compacted, Model, ThinkingLevel (absent in checkpoints of earlier versions), 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).
  • finish: Run, the run that answered: its answer is committed and its inputs settled, and it keeps pi.live.run while afterRun hooks are asked for tasks (spec §8.3). A crash here asks them again: nothing was created yet.
  • drain: Answer and Tasks: waiting on the tasks afterRun hooks asked for, which the generation owns; then the run ends.

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)
	// BeforeProviderRequest runs after pi-ai builds the provider request body, before it is sent; a non-nil result replaces
	// the body for that request only. pi-ai calls it once per request, before it retries the provider request, so the hook does
	// not run again for a retry.
	// The body is in the provider API's own format (request.Model.ProviderMeta.API), so a hook checks the API before changing it.
	BeforeProviderRequest func(ctx context.Context, request ProviderRequest, api HookApi) (*ProviderPayload, 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
	// AfterRun runs after a run answered, its answer committed and its inputs settled done: a final answer, or a
	// terminate round; not when an onYield continuation is taken, and never after a failure or an abort. The requested
	// tasks of every hook are created together as children of the generation, which keeps the run, and the conversation
	// busy, until they are terminal; then queued items are placed and the run ends (spec §8.3). A crash before they are
	// created asks again; once created, never again for this run.
	AfterRun func(ctx context.Context, run RunSummary, api HookApi) (*RunEndTasks, 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 map[string]struct{}

GenerationInput is the input of the built-in generation task, Pi's Record<string, never> (generation.ts:49): an object with no members, created as {} (generation.ts:675). The run's inputs live in pi.live.run.

type GenerationPhase

type GenerationPhase string

GenerationPhase names a phase of the generation task (generation.ts:49-90).

type GenerationPoll

type GenerationPoll struct {
	Model         durable.ModelRef      `json:"model"`
	ThinkingLevel ai.ModelThinkingLevel `json:"thinkingLevel,omitempty"`
	Cutoff        durable.EntryId       `json:"cutoff"`
	Handle        ai.DeferredHandle     `json:"handle"`
}

GenerationPoll is the deferred response a retry polls again: what the poll checkpoint it came from held.

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; it panics after close, and with *durable.ReadOnlySession on a read-only Harness. 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()
	// Wake is when this Session next needs a running process, from the scheduler's memory: Active while some task can run
	// now or is running, At for the earliest sleep. Answers also while scheduling is paused. A host that wakes the
	// process itself, such as a Durable Object alarm, arms from it and calls Resume when woken; see HarnessOptions.OnWake.
	Wake() Wake
	// 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. A conversation-owned task nothing waits for commits in
	// an order set by goroutine scheduling against its conversation's generation, so its record can still be live when the answer settles
	// (D181); wait for it, or for WaitForIdle, before reading its state.
	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)
	// WatchTaskGraph returns every live task with its owner edge, status, and owned conversations (spec §9.5), as a
	// serialized watch; commits made while its listener runs arrive folded.
	WatchTaskGraph(ctx context.Context) (TaskGraphWatch, error)
	// ObserveConversation attaches a synchronous Observer to a conversation's structural view (spec §9.3), atomically on
	// the Session line, for adapters: Advance gets each next revision with its operations as memory adopts the commit,
	// inside Storage's adopt for a stored one and before it is stored for a deferred one, so it only records it. window is as
	// for Conversation.Watch; each observer has its own. ctx governs only the attachment.
	ObserveConversation(ctx context.Context, id durable.ConversationId, observer durable.Observer[ConversationView], window *ConversationWindow) (durable.Observation[ConversationView], error)
	// ObserveTaskGraph attaches a synchronous Observer to the task graph (spec §9.5), as ObserveConversation does to a view. A
	// blocked reason that changes without a commit (a registry change, a failed migration) advances it on the Session line
	// outside any commit and adopt, with the background context.
	ObserveTaskGraph(ctx context.Context, observer durable.Observer[TaskGraph]) (durable.Observation[TaskGraph], 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 {
	// Telemetry is the host-owned adapter, HarnessOptions.telemetry, for content-free admission and phase telemetry
	// (DurableTelemetrySchema). Its Propagation() and Metrics() capabilities are optional (nil is absent); a nil
	// Telemetry is the omitted option, the no-op context.
	Telemetry telemetry.TelemetryContext
	// Models is the pi-ai model access used by generation, compaction, hooks and tools: a Model Runtime or a pi-ai
	// collection. ModelsFunc, when set, replaces it: it returns the current one and is called at each use, so a host can
	// replace its model configuration without reopening the Harness (HarnessOptions.models as a function, Pi 7ec1f648).
	Models     durable.Models
	ModelsFunc func() durable.Models
	// Identity is how model requests identify the app to providers, merged field by field over DefaultHarnessIdentity (attribution to PiG). It applies to every request through the Harness's models, including hooks and tools, and overrides the identity the models were created with; a request's own Identity overrides it. Pass an identity with AttributionNull to send no attribution headers (HarnessOptions.identity).
	Identity *ai.ClientIdentity

	Registry RegistryReader
	// Settings returns the current settings at every resolution; nil uses the defaults. Upstream reads a settings object whose fields may be getters.
	// It is called from the Harness's own goroutines (the Session line, the scheduler, task runtimes, graph views), concurrently with the host and
	// with itself, and the returned value is read after the call returns. It must be safe for concurrent use and the value must not be written once
	// returned. Publish a change by returning a new value, for example from an atomic.Pointer.
	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, epoch milliseconds; nil uses the wall clock. Sleeping tasks store deadlines on it, so
	// every process that opens the same storage must use the same clock.
	Now func() float64
	// SetTimer arms the timers of the Session, the scheduler, and its tasks: pacing progress commits, freeing idle
	// memory (background), and, without OnWake, resuming sleeping tasks; and the timers of TaskRuntime.SetTimer. The
	// Node.js environment, file watcher, and image worker keep their own timers. Nil uses Go timers. Tests can pass fake
	// timers; a host can keep timers off a process that should hibernate.
	SetTimer durable.SetTimer
	// OnWake wakes the process for sleeping tasks instead of a SetTimer timer. Without it, while scheduling runs, a timer
	// that keeps the process alive resumes sleeping tasks when they are due. With it, the Harness arms no timer for
	// them: it calls OnWake after open and whenever Harness.Wake() changes, and the host arms its own wakeup, such as a
	// Durable Object alarm, and calls Resume() when it fires. Called in a goroutine the Session line never waits for,
	// after the commit that changed the value was adopted, so a host arms a recovery wakeup before calls that can start
	// work. It may call Wake and Resume, and must not block. A panic is reported, and the value is offered again at the
	// next change.
	OnWake func(wake Wake)
	// OnReport receives failures that do not fail the calling operation, such as a panicking hook or listener, a task
	// that faulted, and the error that fails the Session, once: one durable.Report, the Error and what happened (Kind and
	// the fields of its ReportInfo). A host can tell a failed Session (ReportStorageFailed, often a platform reset) from a
	// faulted task (ReportTaskFaulted). A panic of its own is dropped.
	OnReport func(report durable.Report)
	// ReadOnly opens for reading only, as a viewer of a session that another process drives, for example a synced copy on a
	// device that only shows it. Open recovers nothing: a running task stays as committed. Every commit with writes fails
	// with *durable.ReadOnlySession before it reaches Storage, and so does Resume (a panic, as it throws upstream) and every
	// call that enables scheduling; the Harness stays usable for reads and watches. Wake is always inactive, and OnWake is
	// never called. Reopen without it to write.
	ReadOnly bool
	// contains filtered or unexported fields
}

HarnessOptions are the options of OpenHarness.

func (HarnessOptions) CurrentModels

func (options HarnessOptions) CurrentModels() durable.Models

CurrentModels is HarnessOptions.models at this use, with Identity applied over DefaultHarnessIdentity: ModelsFunc's answer when set, else Models (harness.ts currentModels). Nil models stay nil.

func (HarnessOptions) WithModelsView

func (options HarnessOptions) WithModelsView() HarnessOptions

WithModelsView returns the options with a plain Models wrapped once with Identity applied over DefaultHarnessIdentity, so every CurrentModels returns the same view (harness.ts currentModels: "A plain Models is wrapped once; a function's result is wrapped at each call").

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
	// ContextRetentionMs is how long an idle conversation keeps its last context read in memory, so its next run reads
	// only newer entries. Busy conversations always keep it; 0 drops it once the conversation is idle. Nil selects the
	// default, ten minutes.
	ContextRetentionMs *float64
	// DocumentRetentionMs is how long a loaded document that no watch observes stays in memory after
	// its last read or write; the next access loads it from Storage. Observed documents always stay. Nil selects the
	// default, ten minutes; 0 drops one right after use; +Inf keeps them. Anything else that is not a number of
	// milliseconds, 0 or more, means the default.
	DocumentRetentionMs *float64
	// AfterFailedRun is what a run that fails (model_error, no_model, interrupted, restart_limit, nothing_to_answer,
	// turn_limit) does with the inputs queued behind it: keep leaves
	// them queued until the next input or queued write, continue starts the next run with them, as an answer would, and
	// withdraw settles them unanswered with reason run_failed. Empty selects keep.
	AfterFailedRun durable.AfterFailedRun
	// RestartLimit is how many times in a row a task may be cut off by a crash, eviction, or reset (a close does not
	// count) without changing its state before it ends instead of running again: a tool call with an error result, a
	// compaction failed into pi.live.compactionFailure, a run with pi.live.runFailure reason restart_limit, any other task
	// faulted with detail {reason: "restart_limit"}. A generation's request or poll the host died during is a failed
	// attempt under retry first; the limit bounds it only when charging that attempt keeps being cut off. Nil selects the
	// default, 5; +Inf never ends a task for it.
	RestartLimit *float64
}

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
	// Models is HarnessOptions.models.
	Models() durable.Models
	// 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)
	// Entry is a committed entry visible from the task's conversation, as TaskRuntime.Entry; nil when the entry is
	// absent or not visible. A typed read is HookEntry.
	Entry(ctx context.Context, id durable.EntryId) (*durable.EntryRecord, error)
	// Entries is the committed raw history of the task's conversation, as TaskRuntime.Entries.
	Entries(ctx context.Context, query durable.EntryQuery, limit int, cursor durable.Cursor) (durable.Page[durable.EntryRecord, durable.Cursor], error)
}

HookApi is what a hook may use: committed reads and the asking task's memos, which hooks and the task share. Hooks run off the Session line, so reads see what is committed when they run; a hook rerun after a crash may see more.

type HookHandlers

type HookHandlers struct {
	Extension string
	Handlers  any
}

HookHandlers is the handlers of one extension's hook, with the extension's name.

func AgentHooks

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

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

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 of a write, or of the InputEntry of an input placed as an
	// application entry; nil for an input placed as pi.user.
	Entry durable.JsonObject `json:"entry,omitempty"`
}

InboxItem is a queued submission: user input for a run, with Content and, when it is not placed as pi.user, Entry, an InputEntry stored as plain JSON; or a passive entry write, with Entry, an EntryDraft stored as plain JSON (inbox.ts:8-16).

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 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 *ai.AssistantMessage `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 are the run's placed inputs, settled when it ends; empty once it answered and runs only its afterRun tasks.
	Inputs []durable.SubmissionId `json:"inputs"`
	// Turns are the tool rounds so far, which AgentState.MaxTurns bounds; an onYield continuation starts the count over.
	Turns int `json:"turns"`
	// First is the run's first entry: the first one the boundary that started it placed, a continue's the failed run's it
	// continues; otherwise its first tool-calling answer. A run started before it was recorded may lack it; afterRun
	// hooks then get the answer as the first entry.
	First *durable.EntryId `json:"first,omitempty"`
	// AfterRun is present once the run answered and its generation waits for the tasks afterRun hooks asked for, listed
	// once created: queued items stay queued until they are terminal, and the run then ends without a failure.
	AfterRun *LiveRunAfterRun `json:"afterRun,omitempty"`
}

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

type LiveRunAfterRun

type LiveRunAfterRun struct {
	Tasks []durable.TaskId `json:"tasks,omitempty"`
}

LiveRunAfterRun is LiveRun.AfterRun: the tasks afterRun hooks asked for.

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"`
	// NestedTools are the nested calls of running tool calls, in creation order, so a parent precedes its children and
	// task IDs ascend. A call's nested slots are removed when the call settles.
	NestedTools []NestedToolSlot `json:"nestedTools,omitempty"`
	// Compactions lists live compaction tasks in task ID order; never empty while present.
	Compactions []CompactionStatus `json:"compactions,omitempty"`
	// CompactionFailure is the newest compaction failure, so a client can show it after the task ended. A compaction
	// that produces a summary removes it; one that is aborted or finds nothing to compact leaves it.
	CompactionFailure *CompactionFailure `json:"compactionFailure,omitempty"`
	// RunFailure is why the newest run ended without an answer, so a client can show it after the run ended. It is set in the
	// commit that ends the run and removed when a later commit starts a run. A run started in the same commit, by
	// AfterFailedRunContinue or after a reset, keeps it.
	RunFailure *RunFailure `json:"runFailure,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 NestedCallState

type NestedCallState struct {
	// TaskId is absent only inside the commit that creates the call; a creation that fails leaves no member.
	TaskId *durable.TaskId `json:"taskId,omitempty"`
	// Result is exactly what ExecuteTool returns; absent while running, and for a call the scheduler faulted or orphaned.
	Result *durable.NestedToolExecutionResult `json:"result,omitempty"`
}

NestedCallState is one nested call of a running tool: its task, and once it ended, its result.

type NestedCaller

type NestedCaller interface {
	durable.DocumentReader
	TaskId() durable.TaskId
	ConversationId() durable.ConversationId
	// CommitFenced runs change in one commit that fails once the calling task is aborted or settled.
	CommitFenced(ctx context.Context, change func(tx durable.Tx) error) error
	WaitForTask(ctx context.Context, id durable.TaskId) (durable.SettledTask[durable.JsonValue], error)
	// MemoCandidate stores a memo of the calling task unless one exists.
	MemoCandidate(ctx context.Context, name string, candidate durable.JsonValue) (durable.JsonValue, error)
}

NestedCaller is what a running tool call lends nested-call admission: its identity, reads, waiting for a task, and commits fenced to the call.

type NestedCalls

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

NestedCalls is the nested-call state of one running tool call: the default key sequence and the admissions its cleanup awaits. A call's admissions are awaited at cleanup, and none starts after it.

func NewNestedCalls

func NewNestedCalls(callId string, resumes bool) *NestedCalls

NewNestedCalls returns the nested-call state of tool call callId. resumes is whether the tool can rerun after a restart, so its caller reattaches to the nested calls it made; any other caller never resumes, so its nested calls are abandoned.

func (*NestedCalls) End

func (n *NestedCalls) End()

End refuses further admissions and lets those underway commit, so settlement aborts and lists their calls.

func (*NestedCalls) Execute

Execute calls another tool as a nested call (tool.ts executeTool).

type NestedToolSlot

type NestedToolSlot struct {
	CallId       string         `json:"callId"`
	ParentCallId string         `json:"parentCallId"`
	ParentTaskId durable.TaskId `json:"parentTaskId"`
	Name         string         `json:"name"`
	TaskId       durable.TaskId `json:"taskId"`
	// Arguments are what the call was made with, replaced by the arguments it runs with, after repair, beforeTool, and
	// coercion, once it starts executing. Always a JSON object; a JsonValue so that it keeps the member order of the
	// caller's arguments object, as Pi's slot does (tool.ts:724).
	Arguments    durable.JsonValue        `json:"arguments"`
	Status       ToolSlotStatus           `json:"status"`
	Output       *string                  `json:"output,omitempty"`
	DroppedBytes *int                     `json:"droppedBytes,omitempty"`
	DroppedLines *int                     `json:"droppedLines,omitempty"`
	Details      *durable.JsonValue       `json:"details,omitempty"`
	Diagnostics  []durable.ToolDiagnostic `json:"diagnostics,omitempty"`
	// Summary is how the call ended, for a status line, once done; the result itself is in the caller's NestedResultDoc.
	Summary *NestedToolSummary `json:"summary,omitempty"`
}

NestedToolSlot is the presentation of one nested call: a call a running tool made through ExecuteTool (live.ts NestedToolSlot). CallId is "<parentCallId>/<key>", the call's ID in tool events and unique because keys contain no "/". The Harness relates slots by task ID: TaskId is the call's tool task, ParentTaskId the calling one, model-issued or nested. The members are in the order startNestedCall writes them (tool.ts:685-693), which a stored pi.live keeps.

type NestedToolSummary

type NestedToolSummary struct {
	IsError    bool      `json:"isError"`
	DurationMs *int64    `json:"durationMs,omitempty"`
	Usage      *ai.Usage `json:"usage,omitempty"`
	Error      string    `json:"error,omitempty"`
}

NestedToolSummary is how a nested call ended: an error flag, its execution time, its spend, and up to 500 characters of error text.

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(err error, section *durable.PromptSection)) (*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 PartialChanges

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

PartialChanges collects, from a response's events, what changed in its partial message since the last commit, so the commit appends new text instead of reassigning growing strings. Reassigning makes Chord compare the old and new string, which costs the length of the string per commit.

  • Text and thinking: the text_delta and thinking_delta events. The commit appends them where the committed string plus the deltas has the new string's length, and compares otherwise. A block's end event drops them, because providers may replace the text when a block ends.
  • Tool-call arguments: a StreamingJSONParser per call, fed with the raw argument text of each toolcall_delta, reports what each piece changed. The commit applies those changes to the committed arguments in order and leaves the arguments out of the message assignment, so the committed arguments are exactly the parsed text so far. toolcall_end ends the tracking; the call's last commit assigns its final arguments.

The event consumer and the commit run on different goroutines, so the state is under a mutex. The changes describe the partial message of the last event observed, and a commit writes the partial it is given, so the caller keeps the two paired: it observes an event and records that event's partial in one step, and cuts the changes and takes the recorded partial in one step (Cut, Bind).

func NewPartialChanges

func NewPartialChanges() *PartialChanges

NewPartialChanges returns a collector with nothing tracked.

func (*PartialChanges) BindPartial

func (changes *PartialChanges) BindPartial(cut *PartialCut, partial *ai.AssistantMessage) (durable.JsonObject, *PartialCommit, error)

BindPartial binds cut to partial, the partial message it describes, for a commit: it returns the JSON object of partial, whose tracked tool calls have no arguments, because the commit writes them from the changes, and what the commit takes. It builds the object without encoding and decoding the text and thinking of the blocks or the arguments of the tracked calls, which grow with the stream: every commit would otherwise cost the length of the message. Call Restore if the commit fails.

func (*PartialChanges) Commit

func (changes *PartialChanges) Commit(generation *delta.Object, message durable.JsonObject, taken *PartialCommit) error

Commit writes message with what taken took into generation.message: the message leaf by leaf with the plan, then the argument changes. A tracked call whose block is new here gets its arguments from its changes, which then start at its first piece; when the committed message lost a call whose changes were already committed (another writer reset it), the call falls back to its snapshot from now on.

func (*PartialChanges) Cut

func (changes *PartialChanges) Cut() *PartialCut

Cut takes what the events observed so far changed since the last cut. It describes the partial message of the last event observed, not of any later one: bind it to a copy of exactly that partial with Bind. A cut is only as good as that pairing, since a string that grew by as much as the changes did is appended their characters, not its own, so a partial one event behind or ahead of the changes would commit text no stream produced.

func (*PartialChanges) Observe

func (changes *PartialChanges) Observe(event ai.AssistantMessageEvent)

Observe records what event changed.

func (*PartialChanges) Restore

func (changes *PartialChanges) Restore(taken *PartialCommit)

Restore puts back what a failed commit took, so the next commit applies it first.

func (*PartialChanges) Uncut

func (changes *PartialChanges) Uncut(cut *PartialCut)

Uncut puts back what cut took, when no commit is made of it: the argument changes wait for the next cut, and the appended text is dropped, so the next commit of that text compares it.

type PartialCommit

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

PartialCommit is what one partial commit writes besides the partial message itself; from PartialChanges.Bind.

type PartialCut

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

PartialCut is what the events observed up to one moment changed since the last cut, before it is bound to the partial message of that moment; from PartialChanges.Cut.

type ProgressPolicyPatch

type ProgressPolicyPatch struct {
	PartialIntervalMs *float64
	OutputIntervalMs  *float64
	// PersistWithinMs is how long deferred commits may stay in memory before they are stored; a value that is not a number
	// of milliseconds, 0 or more, means the default, 1,000.
	PersistWithinMs *float64
}

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

type ProviderPayload

type ProviderPayload struct {
	Payload any
}

ProviderPayload is the beforeProviderRequest result that replaces the provider request body.

type ProviderRequest

type ProviderRequest struct {
	Model   *ai.Model
	Payload any
}

ProviderRequest is what a beforeProviderRequest hook sees: the model of the request and its provider request body, in the format of the model's API (Model.ProviderMeta.API).

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

func NewRegistryReader

NewRegistryReader is registryReader: a RegistryReader over a Chord registry value whose composition is a registry snapshot. Snapshot reads the current composition (the last good one while Compose fails), as the reader's observer recorded it. Subscribe observes its compositions; the listener runs synchronously inside the Chord batch that composed, so it only wakes the scheduler (a Chord call there fails with invalid/reentrant). ctx is the observation's: cancelling it detaches every listener. The name differs from Pi's because Go names the interface RegistryReader. Subscribe panics with the error Observe returns, where Pi's observe throws: the value has no composition to start at.

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 RunEnd

type RunEnd struct {
	// Status is SubmissionDone with Answer, or SubmissionUnanswered with Reason and Detail.
	Status durable.SubmissionStatus
	Answer durable.EntryId
	Reason RunFailureReason
	Detail *string
	// Settlement is the inputs' settlement of an unanswered end; nil settles them unanswered with Reason and Detail.
	Settlement *durable.SubmissionSettlement
}

RunEnd is how a run ends: with an answer, or without one, settling its inputs unanswered and recording why.

type RunEndReason

type RunEndReason string

RunEndReason is how a run ended, for afterRun hooks.

const (
	// RunEndAnswer is a final answer.
	RunEndAnswer RunEndReason = "answer"
	// RunEndTerminate is a tool round whose every call asked to terminate.
	RunEndTerminate RunEndReason = "terminate"
)

type RunEndTask

type RunEndTask struct {
	Task  durable.AnyTask
	Input durable.JsonValue
}

RunEndTask is a task an afterRun hook asks for, built by RunEndTaskOf. Input is JSON.

func RunEndTaskOf

func RunEndTaskOf[I, S, R, H any](task durable.Task[I, S, R, H], input I) RunEndTask

RunEndTaskOf is a task an afterRun hook asks for, its input typed by the task (spec §8.3). The input is checked and copied as JSON when the generation prepares the request, so a broken one is rejected there, against the hook's extension.

type RunEndTasks

type RunEndTasks struct {
	Tasks []RunEndTask
}

RunEndTasks is what an afterRun hook asks for: the tasks to create and wait for.

type RunFailure

type RunFailure struct {
	// TaskId is the task that ended the run: the run's task at its end.
	TaskId durable.TaskId `json:"taskId"`
	// Inputs are the run's inputs, settled unanswered.
	Inputs []durable.SubmissionId `json:"inputs"`
	Reason RunFailureReason       `json:"reason"`
	// Detail is, for model_error, the error text; no_model, which model is missing; faulted, the error message; orphaned, why
	// the task could not run (missing_task, task_too_old, migration_failed); interrupted and restart_limit: what was cut off,
	// and how often; turn_limit: the tool rounds the run took, "1 turn" or "N turns".
	Detail *string `json:"detail,omitempty"`
	// First is the failed run's run.first, so a continue's afterRun hooks see its history too.
	First *durable.EntryId `json:"first,omitempty"`
}

RunFailure is the newest run that ended without an answer (spec §8.2).

type RunFailureReason

type RunFailureReason string

RunFailureReason is why a run ended without an answer:

  • RunModelError: the model's response failed, after any retries, or the compaction a request needed failed;
  • RunNoModel: no model is configured, or the configured one is not available;
  • RunAborted: the run was aborted (Conversation.Abort, Harness.AbortTask); Detail says when its abort handler was cut off settings.restartLimit times and did not finish;
  • RunReset: a queued reset started a new context at the post-tools boundary, before an answer (a tool's handoff continues the run);
  • RunFaulted: the run's task threw where it cannot recover, or storage rejected its commit;
  • RunOrphaned: the run's task was aborted while no registered definition could take it;
  • RunInterrupted: the host stopped while the model was answering, more often than settings.retry retries;
  • RunRestartLimit: the run's generation was cut off settings.restartLimit times in a row; a request or poll it was cut off during counts as a failed attempt first, so this ends one whose charge itself keeps failing;
  • RunNothingToAnswer: the context did not end in a user message or tool results (empty, or ending in an answer), so no request was sent, as for a continue after an answer;
  • RunTurnLimit: a tool round reached the conversation's MaxTurns; a continue resumes on its results.
const (
	RunModelError RunFailureReason = "model_error"
	RunNoModel    RunFailureReason = "no_model"
	RunAborted    RunFailureReason = "aborted"
	RunReset      RunFailureReason = "reset"
	RunFaulted    RunFailureReason = "faulted"
	RunOrphaned   RunFailureReason = "orphaned"
	// RunInterrupted and RunRestartLimit end a run the host's crashes cut off.
	RunInterrupted     RunFailureReason = "interrupted"
	RunRestartLimit    RunFailureReason = "restart_limit"
	RunNothingToAnswer RunFailureReason = "nothing_to_answer"
	RunTurnLimit       RunFailureReason = "turn_limit"
)

type RunStart

type RunStart struct {
	Inputs []durable.SubmissionId
	First  *durable.EntryId
}

RunStart is what a run starts for: its placed inputs, and its first entry (LiveRun.First).

type RunSummary

type RunSummary struct {
	Reason RunEndReason `json:"reason"`
	// First is the run's first entry (LiveRun.First): the first one the boundary that started it placed, for a continue
	// the failed run's it continues, otherwise its first tool-calling answer; the answer itself for a run that has none
	// of these.
	First durable.EntryId `json:"first"`
	// Answer is the answer, or the terminating round's tool-calling answer, whose results follow it.
	Answer durable.EntryId `json:"answer"`
	// Last is the run's last entry: the answer; for a terminate round its newest result, or the reset of its handoff.
	Last durable.EntryId `json:"last"`
}

RunSummary is how a run ended, for afterRun hooks. Read the run's history with api.Entries(durable.EntryQuery{MinEntryId: &first, MaxEntryId: &last}, ...).

func (RunSummary) MarshalJSON

func (run RunSummary) MarshalJSON() ([]byte, error)

MarshalJSON writes the members in the order Pi stores them in a generation's finish checkpoint: the held end, then first.

type SchedulerIdleState

type SchedulerIdleState struct {
	Contexts       int
	IdleContexts   int
	IdleMismatches int
	FullIdleChecks int
}

SchedulerIdleState is the kept contexts' idle state, for tests: how many are kept and how many are idle, how many disagree with a full recompute, and how many idle checks covered every scope.

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 StartRunOptions

type StartRunOptions struct {
	// KeepFailure keeps runFailure: a run started in the commit that ended the failed one keeps its failure.
	KeepFailure bool
}

StartRunOptions are the options of StartRun.

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, now func() float64, queueModes func() QueueModes, resume func() error, root telemetry.TelemetryContext) *Submissions

NewSubmissions subscribes to the Session's commits and close. telemetry is the Harness's root adapter, the parent of input admissions; nil is the no-op context.

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) Admit

func (submissions *Submissions) Admit(tx durable.Tx, conversationId durable.ConversationId, draft durable.SubmissionDraft) (durable.SubmissionId, error)

Admit admits a submission inside the caller's commit tx, with the rules of Submit. The admission is stored or lost with that commit. It must come before the commit's first table write, another admission's included.

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) SubmitUnlessCancelled

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

SubmitUnlessCancelled is Submit for a caller whose cancellation applies only until the job starts (session.ts commit: `context.abortSignal?.throwIfAborted()` as the job begins): ctx carries the commit, so it should not be cancellable, and startCheck, when non-nil, runs as the job starts and rejects it, storing nothing, with the error it returns.

func (*Submissions) Wait

Wait returns the settled record of a submission; cancelling ctx cancels only this wait, including its wait for the listeners of the batches committed before it to enter (their synchronous part ran, or they went on to a wait of the Session), which it resumes its caller after as upstream's drain microtask runs before the code that awaited the promise.

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 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 TaskGraphBlocking

type TaskGraphBlocking struct {
	Blocked          func(record BlockedSubject) durable.BlockedReason
	SubscribeBlocked func(listener func()) func()
}

TaskGraphBlocking is what the graph asks the scheduler: a task's blocked reason, and when reasons may change without a commit.

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"`
	// Blocked is why it cannot run here, when it cannot: no registered definition takes it (missing_task, task_too_old,
	// migration_failed). Follows registry changes. Empty when it can.
	Blocked durable.BlockedReason `json:"blocked,omitempty"`
}

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"`
	// Until is the time a sleeping task wakes at.
	Until float64 `json:"until,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, sleeping with Phase and Until, 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 as memory adopts them.

func NewTaskGraphView

func NewTaskGraphView(sessionImpl *session.SessionImpl, blocking TaskGraphBlocking) *TaskGraphView

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

func (*TaskGraphView) Observe

Observe attaches a synchronous observer of the graph (Harness.ObserveTaskGraph), behind session.GuardObserver; ctx governs only the attachment.

func (*TaskGraphView) Watch

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

Watch returns a serialized watch of the graph, an observer of its mount; cancelling ctx stops it.

type TaskGraphWatch

type TaskGraphWatch = durable.WatchHandle[TaskGraph]

TaskGraphWatch is a serialized 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"
	TaskInspectionPending    TaskInspectionKind = "pending"
	TaskInspectionWaiting    TaskInspectionKind = "waiting"
	TaskInspectionSleeping   TaskInspectionKind = "sleeping"
	TaskInspectionCompleting TaskInspectionKind = "completing"
	TaskInspectionBlocked    TaskInspectionKind = "blocked"
)

type TaskInspectionState

type TaskInspectionState struct {
	Kind     TaskInspectionKind
	Migrates bool
	On       []durable.TaskId
	// Until is the time a sleeping task wakes at.
	Until  float64
	Reason string
	Error  error
}

TaskInspectionState is what the scheduler would do with a live task: running (an invocation is active); pending (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); sleeping (until the Harness clock reaches Until); 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, sleeping, 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, keepRestart bool) (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:269-296). A request replaces a restart mark, so a task abandoned after a restart that waits for its definition is orphaned; with keepRestart, as for an owner's own cleanup, such a task keeps its mark and waits on.

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) BlockedReason

func (s *TaskScheduler) BlockedReason(record BlockedSubject) durable.BlockedReason

BlockedReason is why a live task cannot run here, if it cannot: its definition is missing (missing_task), too old (task_too_old), or failed to migrate (migration_failed); empty when it can. A running task, an abort-marked one, and one holding its outcome are never blocked.

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 signals every invocation and waits for them, and for scheduler passes in flight. It writes nothing. Close calls it after every close listener has run, so waits, watches, and streams a task holds end with the Session's reason, not as cancelled by its signal (scheduler.ts join).

func (*TaskScheduler) MembershipKeys

func (s *TaskScheduler) MembershipKeys(tx *session.Transaction) ([]string, error)

MembershipKeys is the ownership memberships a commit's task and conversation changes write (group commit §4.2), at its admission on the line: for each task created or made terminal, every node from its parent up to and including the nearest live task, or the root conversation, and then the roots too, conservatively, as a pending end may unlist the root a creation finds listed; for each conversation created under a task, that task; and the intent set when a change sets, upgrades, or clears a mark or a held or ended outcome other than completed. It loads the chains it walks; the nodes it installs stay until the commit is published.

func (*TaskScheduler) Open

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

Open loads live tasks and changes surviving running tasks back to pending, counting the restart. It dispatches nothing; a task cut off settings.restartLimit times ends when it is next reserved. Read-only, it only loads them: a running task stays as committed, running in another process.

func (*TaskScheduler) Resume

func (s *TaskScheduler) Resume()

Resume enables scheduling, and makes sleeping tasks that are due runnable: a host wakeup, such as an alarm, calls this. It is idempotent; the kick does nothing once closing. It panics with *durable.ReadOnlySession on a read-only Harness, as scheduler.ts resume() throws.

func (*TaskScheduler) SubscribeBlocked

func (s *TaskScheduler) SubscribeBlocked(listener func()) func()

SubscribeBlocked calls listener when blocked reasons may have changed without a commit: a registry change or a failed migration. The listener runs off the Session line and the scheduler's lock. The result unsubscribes.

func (*TaskScheduler) TryResume

func (s *TaskScheduler) TryResume() error

TryResume is Resume for the callers that are async upstream, where the throw is a rejection: it returns the *durable.ReadOnlySession instead of panicking.

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. Like WaitForTask it resumes its caller after the listeners of the batches committed before it have entered (their synchronous part ran, or they went on to a wait of the Session), and cancelling ctx cancels that wait too.

func (*TaskScheduler) WaitForTask

WaitForTask returns the terminal receipt of a task; cancelling ctx cancels only this wait, including its wait for the listeners of the batches committed before it to be entered, which it resumes its caller after as upstream's drain microtask runs before the code that awaited the promise.

func (*TaskScheduler) Wake

func (s *TaskScheduler) Wake() Wake

Wake is when the Session next needs a process: Active while some task can run now or is running, At for the earliest sleep not yet due. Synchronous, from memory; a task whose chain is not loaded yet counts as it would alone.

type TaskSchedulerOptions

type TaskSchedulerOptions struct {
	// Telemetry is HarnessOptions.telemetry: the root of phase spans and the source of the metrics; nil is the no-op context.
	Telemetry telemetry.TelemetryContext
	Session   *session.SessionImpl
	Storage   durable.Storage
	Registry  RegistryReader
	// Models returns the host's current model access (HarnessOptions.models); read at each access.
	Models func() 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
	// OnWake is HarnessOptions.OnWake: it replaces the timer for sleeping tasks.
	OnWake func(wake Wake)
	// Timers are the host's timers (HarnessOptions.SetTimer).
	Timers durable.Timers
	// WriteAtClose writes what the callback returns straight to Storage, on the line, after the commits admitted before
	// the seal have settled (BeforeClose of the Session).
	WriteAtClose func(writes func() []durable.StorageWrite) error
	Report       func(ctx context.Context, err error, info durable.ReportInfo)
	// LimitsRestarts reports the task kinds whose run phases end the task themselves once it was cut off
	// settings.restartLimit times (the built-in tasks, from TaskRecord.Restarts); the scheduler ends a task of any other
	// kind faulted instead.
	LimitsRestarts func(kind string) bool
	// 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
	// ReadOnly is HarnessOptions.ReadOnly: Open loads live tasks as committed, running ones included, and the scheduler
	// never commits, runs anything, or asks for a wakeup.
	ReadOnly bool
}

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

type ToolChange

type ToolChange struct {
	List []*durable.ToolRegistration
	Edit *ToolEdit
}

ToolChange is Pi's `ToolRegistration[] | { remove, add }`: List is the array form, a non-nil list (empty included) that replaces the filter, and Edit is the `{ remove, add }` form; neither set is `{ remove: [] }`.

type ToolEdit

type ToolEdit struct {
	Remove []*durable.ToolRegistration
	Add    []*durable.ToolRegistration
}

ToolEdit is the `{ remove, add }` form of a tool change: a nil list is absent, and the tools filter takes Remove only.

type ToolHookCall

type ToolHookCall struct {
	// Type is "toolCall": the discriminator of pi-ai's ToolCall, which Go carries as the type of the call.
	Type string
	ai.ToolCall
	Parent *ToolParent
}

ToolHookCall is a call as tool hooks see it; Parent is set for a nested call, one a running tool made through ExecuteTool (types.ts ToolHookCall).

func NewToolHookCall

func NewToolHookCall(call ai.ToolCall, parent *ToolParent) ToolHookCall

NewToolHookCall is the ToolHookCall for call, with parent set for a nested call.

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 ToolHookCall, 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 ToolHookCall, 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 ToolParent

type ToolParent struct {
	TaskId durable.TaskId
	CallId string
}

ToolParent is the calling task and call ID of a nested call.

type ToolSelection

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

ToolSelection is the stored tools field of AgentState: an exact list (Exact), or a filter with an optional Remove list and, for modelTools, an optional Add list of the deferred tools loaded so far. A nil Remove or Add is absent.

func (ToolSelection) MarshalJSON

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

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

func (*ToolSelection) UnmarshalJSON

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

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

type ToolSlot

type ToolSlot struct {
	CallId string `json:"callId"`
	Name   string `json:"name"`
	// TaskId is nil for a call not started yet (sequential round).
	TaskId *durable.TaskId `json:"taskId,omitempty"`
	Status ToolSlotStatus  `json:"status"`
	// Unoffered is a call to a tool its request did not offer: its task settles tool_unavailable without running anything.
	Unoffered bool `json:"unoffered,omitempty"`
	// 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     ToolTaskPhase      `json:"phase"`
	Arguments map[string]any     `json:"arguments"`
	Replay    durable.ToolReplay `json:"replay"`
	// contains filtered or unexported fields
}

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.

func (*ToolTaskCheckpoint) UnmarshalJSON

func (checkpoint *ToolTaskCheckpoint) UnmarshalJSON(data []byte) error

UnmarshalJSON reads the checkpoint and keeps the arguments' text, so the rerun of a safe tool shows them in the member order the intent stored, as the parsed object keeps it upstream (tool.ts:202-217).

type ToolTaskInput

type ToolTaskInput struct {
	Kind         ToolTaskKind    `json:"kind"`
	Assistant    durable.EntryId `json:"assistant,omitempty"`
	CallId       string          `json:"callId,omitempty"`
	Parent       durable.TaskId  `json:"parent,omitempty"`
	ParentCallId string          `json:"parentCallId,omitempty"`
	Key          string          `json:"key,omitempty"`
	Call         *ai.ToolCall    `json:"call,omitempty"`
	// Progress false commits no running output, details, or diagnostics to the slot; the result still gets them.
	Progress *bool `json:"progress,omitempty"`
	// Unoffered is a call to a tool its request did not offer: it settles tool_unavailable without resolving the name (Kind "model").
	Unoffered bool `json:"unoffered,omitempty"`
}

ToolTaskInput is the input of the built-in tool task (tool.ts ToolTaskInput): a model-issued call, read from its assistant entry (Kind "model": Assistant, CallId), or a nested call a running tool made through executeTool(), whose call the input carries because no entry holds it (Kind "nested": Parent, ParentCallId, Key, Call, Progress).

type ToolTaskKind

type ToolTaskKind string

ToolTaskKind is the `kind` of a ToolTaskInput and a ToolTaskResult (tool.ts): "model" for a call the model issued, "nested" for one a running tool made through executeTool().

const (
	// ToolTaskModel is a call the model issued.
	ToolTaskModel ToolTaskKind = "model"
	// ToolTaskNested is a call a running tool made through executeTool().
	ToolTaskNested ToolTaskKind = "nested"
)

type ToolTaskPhase

type ToolTaskPhase string

ToolTaskPhase names a phase of the tool task (tool.ts:36-38).

type ToolTaskResult

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

ToolTaskResult is the result of the built-in tool task (tool.ts ToolTaskResult): a model-issued call's result is its transcript entry and the controls it requested (Kind "model"); a nested call's result is in its caller's NestedResultDoc, so the receipt is only {kind: "nested"}. A version 1 task that was already holding its outcome as `completing` when the Harness upgraded finishes with a version 1 result, `{entryId, control?}` without kind: a result without a kind is a model-issued call's.

type TranscriptEarlier

type TranscriptEarlier struct{}

TranscriptEarlier says the transcript continues above: render "load earlier" and call LoadEarlier. It is always the first item.

func (TranscriptEarlier) Kind

func (TranscriptEarlier) Kind() string

Kind is "earlier".

func (TranscriptEarlier) MarshalJSON

func (item TranscriptEarlier) MarshalJSON() ([]byte, error)

MarshalJSON writes Pi's { kind: "earlier" }.

type TranscriptEntry

type TranscriptEntry struct{ Entry durable.EntryRecord }

TranscriptEntry is an entry the client has.

func (TranscriptEntry) Kind

func (TranscriptEntry) Kind() string

Kind is "entry".

func (TranscriptEntry) MarshalJSON

func (item TranscriptEntry) MarshalJSON() ([]byte, error)

MarshalJSON writes Pi's { kind: "entry", entry }.

type TranscriptGap

type TranscriptGap struct{ After, UpTo durable.EntryId }

TranscriptGap says the entries strictly between After and UpTo are missing: render "load more" and call FillGap.

func (TranscriptGap) Kind

func (TranscriptGap) Kind() string

Kind is "gap".

func (TranscriptGap) MarshalJSON

func (item TranscriptGap) MarshalJSON() ([]byte, error)

MarshalJSON writes Pi's { kind: "gap", after, upTo }.

type TranscriptItem

type TranscriptItem interface {
	Kind() string
	// contains filtered or unexported methods
}

TranscriptItem is one row of a client's transcript: a TranscriptEntry, a TranscriptGap, or a TranscriptEarlier. Kind is the discriminator of Pi's TranscriptItem union ("entry", "gap" or "earlier"), which each variant also writes as its JSON "kind".

type TranscriptView

type TranscriptView struct {
	Conversation durable.ConversationRecord `json:"conversation"`
	Docs         ViewDocs                   `json:"docs"`
	Items        []TranscriptItem           `json:"items"`
}

TranscriptView is the conversation view as a renderer sees it: Items, the client's whole transcript, instead of the window.

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 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 ViewDocs

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

ViewDocs is a view's read-only record of documents keyed by kind (Pi Readonly<Record<string, JsonObject>>). Its keys keep Pi's object order (view.ts:161-166): mounted documents in mount order, then documents set later in the order they arrive.

func ViewDocsOf

func ViewDocsOf(docs ViewDocs, kind string, document durable.JsonObject) ViewDocs

ViewDocsOf returns docs with document set at kind, last when kind is new; docs itself is unchanged.

func ViewDocsWithout

func ViewDocsWithout(docs ViewDocs, kind string) ViewDocs

ViewDocsWithout returns docs without kind; docs itself is unchanged.

func (ViewDocs) All

func (docs ViewDocs) All() iter.Seq2[string, durable.JsonObject]

All iterates the kinds and documents in order.

func (ViewDocs) Get

func (docs ViewDocs) Get(kind string) (durable.JsonObject, bool)

Get returns the document of kind and whether it is present.

func (ViewDocs) Has

func (docs ViewDocs) Has(kind string) bool

Has reports whether a document of kind is present.

func (ViewDocs) Keys

func (docs ViewDocs) Keys() []string

Keys returns the kinds in order.

func (ViewDocs) Len

func (docs ViewDocs) Len() int

Len returns the number of documents.

func (ViewDocs) MarshalJSON

func (docs ViewDocs) MarshalJSON() ([]byte, error)

MarshalJSON writes the documents as one JSON object in order.

func (*ViewDocs) UnmarshalJSON

func (docs *ViewDocs) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a JSON object of JSON objects, keeping the text's key order.

type ViewObserver

type ViewObserver struct {
	// Advance receives each next revision.
	Advance func(ctx context.Context, change chord.WatchCall[ConversationView])
	// End receives the Session's close (failed with session.ErrSessionClosedEnd, as an adapter following the Session reads it as
	// a reason to follow the next one), or its failure (failed).
	End func(end chord.WatchEnd)
	// contains filtered or unexported fields
}

ViewObserver receives each next revision of one observer's window, and the Session's close.

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]) Park

func (waiter *Waiter[T]) Park()

Park registers the wait with the Session. Wait does it when it was not done; a caller that must be registered before it releases a lock the settle needs calls it first. It must not be called inside a Session line job: that job's outcome is delivered after the publication that waits for the registered wait to resume.

func (*Waiter[T]) Wait

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

Wait blocks until the waiter settles, then acknowledges the wait to the Session: the goroutine runs again.

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, line *session.SessionImpl, key K) *Waiter[T]

Add registers a wait for key, which the caller then blocks in through Wait; line is the Session whose publications resume it in order. 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.

func (*Waiters[K, T]) Settle

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

Settle takes the waits of key out of the pending set and fixes their result to value, as resolving a promise does, and returns the function that wakes them. Until it is called the waits are settled but their goroutines still sleep: a RejectAll or a cancelled context in between no longer reaches them, so a close that seals before the wake cannot turn the result into an error.

type Wake

type Wake struct {
	Active bool
	// At is the earliest sleep not yet due; nil when there is none.
	At *float64
}

Wake is when a Session next needs a running process (Harness.Wake). Active: some task can run now or is running, so a process that dies must be woken again soon, for example by a recovery alarm. At: the earliest sleep not yet due, when there is one. Neither: nothing needs a process until new work is submitted. Tasks blocked on a missing or unmigratable definition, completing tasks, and waits on live tasks do not count; the work they wait for does. Active is also set while a reconcile pass, such as the recovery of Open, has not landed yet: it may finalize held outcomes and mark cascades.

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