harness

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 32 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,
}

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 and its commit. Inputs 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"),
				"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 ReportInfo type.",
			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: 1,
		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 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 ActiveEntries

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

ActiveEntries returns the raw active entries within captured bounds, without deriving model context. The entries are the caller's own.

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

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

func BuiltinTasks

func BuiltinTasks() []durable.AnyTask

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

func ClearProgress

func ClearProgress(slot *delta.Object)

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

func Configure

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

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

func ConvertPartial

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

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

func CreateAgent

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

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

func CreateCompaction

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

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

func DefineExtension

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

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

func DefineTool

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

func DeriveContext

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

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

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

func EndRun

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

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

func EstimateContext

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

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

func 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 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(err error, info durable.ReportInfo)) 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 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, inputs []durable.SubmissionId) error

StartRun starts a run for inputs, placed input submissions: a new generation takes pi.live.run. The generation starts in its first input's trace and links to the others.

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): the schema's strict check, without conversion or coercion.

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

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); Conversation.Submit 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 with ConversationBusy. 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]
}

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

type AgentChangedEvent

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

func (AgentChangedEvent) EventType

func (AgentChangedEvent) EventType() string

func (AgentChangedEvent) MarshalJSON

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

type AgentEvent

type AgentEvent interface {
	EventType() string
}

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

func TranslateViewEvents

func TranslateViewEvents(conversationId durable.ConversationId, before, after ConversationView, ops []durable.Op, publication durable.CommitPublication, held map[durable.TaskId]bool) []AgentEvent

TranslateViewEvents returns every event one commit causes, in the order of spec §9.4: before and after are the view around the commit, ops its view operations, publication the records it wrote, and held the generations whose held outcome already ended their turn (updated here).

type AgentEventStream

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

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

func NewAgentEventStream

func NewAgentEventStream(snapshot SnapshotEvent, watch *session.CommittedWatch[[]AgentEvent]) *AgentEventStream

NewAgentEventStream is the stream of a snapshot and the committed watch of the event batches that follow it.

func WatchEvents

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

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

func (*AgentEventStream) Closed

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

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

func (*AgentEventStream) End

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

End returns the terminal result once Closed is closed.

func (*AgentEventStream) Start

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

Start installs the sole listener; it never runs inline.

func (*AgentEventStream) Stop

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

Stop idempotently stops the stream and returns its terminal result.

type AgentState

type AgentState struct {
	Model         *durable.ModelRef     `json:"model,omitempty"`
	ThinkingLevel ai.ModelThinkingLevel `json:"thinkingLevel,omitempty"`
	// Extensions: an exact list selects exactly these extensions, in order; an edit changes the host default selection.
	Extensions *ExtensionSelection `json:"extensions,omitempty"`
	// Tools filters the selected extensions' tools. An exact list offers exactly these, in order.
	Tools *ToolSelection `json:"tools,omitempty"`
	// 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"`
}

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

type AutoRetryEndEvent

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

func (AutoRetryEndEvent) EventType

func (AutoRetryEndEvent) EventType() string

func (AutoRetryEndEvent) MarshalJSON

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

type AutoRetryStartEvent

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

func (AutoRetryStartEvent) EventType

func (AutoRetryStartEvent) EventType() string

func (AutoRetryStartEvent) MarshalJSON

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

type BeforeToolResult

type BeforeToolResult struct {
	Arguments 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
	Restarts       int
	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
	Reset bool
}

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

func ApplyBoundary

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

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

type Change

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

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

func Cleared

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

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

func SetTo

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

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

type CompactionCheckpoint

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

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

func (CompactionCheckpoint) MarshalJSON

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

MarshalJSON writes the select phase without request members.

type CompactionDecision

type CompactionDecision struct {
	Decline bool
	Summary *string
}

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

type CompactionEndEvent

type CompactionEndEvent struct {
	TaskId durable.TaskId           `json:"taskId"`
	Reason durable.CompactionReason `json:"reason"`
	Error  *string                  `json:"error,omitempty"`
}

CompactionEndEvent: the task's receipt tells whether it produced a summary; the summary entry has its own events. Error is set when the compaction failed, faulted, or was orphaned, as in pi.live.compactionFailure.

func (CompactionEndEvent) EventType

func (CompactionEndEvent) EventType() string

func (CompactionEndEvent) MarshalJSON

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

type CompactionFailure

type CompactionFailure struct {
	TaskId durable.TaskId           `json:"taskId"`
	Reason durable.CompactionReason `json:"reason"`
	// 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 CompactionStartEvent

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

func (CompactionStartEvent) EventType

func (CompactionStartEvent) EventType() string

func (CompactionStartEvent) MarshalJSON

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

type CompactionStatus

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

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

type ContextBounds

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

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

func CaptureContextBounds

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

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

type Conversation

type Conversation interface {
	Id() durable.ConversationId
	// Agent resolves the agent with the current registry snapshot and settings.
	Agent(ctx context.Context) (durable.Agent, error)
	// Configure applies change in its own commit.
	Configure(ctx context.Context, change AgentChange) error
	// Submit durably admits user input or a passive entry write. A busy conversation, or one with queued items, queues it in pi.inbox; WhenBusy reject fails with ConversationBusy instead and writes nothing.
	Submit(ctx context.Context, submission durable.SubmissionDraft) (durable.Submission, error)
	// Reset admits a write of a pi.reset entry that starts a new context, carrying handoff as a user message when non-nil. It returns after admission; while busy, it is placed at the next boundary.
	Reset(ctx context.Context, handoff *string) error
	// Compact admits a manual compaction task and returns its ID (spec §8.7).
	Compact(ctx context.Context, instructions *string) (durable.TaskId, error)
	// Commit runs a Session commit whose tx.CreateTask defaults to this conversation.
	Commit(ctx context.Context, change func(tx durable.Tx) (any, error)) (any, error)
	// Context 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
	// ViewState returns the structural view (spec §9.3) as a disposable read-only Chord state.
	ViewState(ctx context.Context) (durable.AttachedReplicatedState[ConversationView], error)
	// Watch returns the structural view as a serialized exact-frame watch with bounded pending frames.
	Watch(ctx context.Context) (ConversationWatch, error)
}

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

type ConversationCreateOptions

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

ConversationCreateOptions are the options of creating or forking a conversation.

type ConversationInit

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

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

type ConversationView

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

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

type ConversationViews

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

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

func NewConversationViews

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

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

func (*ConversationViews) Attach

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

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

func (*ConversationViews) State

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

func (*ConversationViews) Watch

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

type ConversationWatch

type ConversationWatch = durable.WatchHandle[ConversationView]

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

type DeferredPollEvent

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

func (DeferredPollEvent) EventType

func (DeferredPollEvent) EventType() string

func (DeferredPollEvent) MarshalJSON

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

type DeferredStatus

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

DeferredStatus is a provider-side deferred response being polled.

type EntryAppendedEvent

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

func (EntryAppendedEvent) EventType

func (EntryAppendedEvent) EventType() string

func (EntryAppendedEvent) MarshalJSON

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

type EnvTarget

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

EnvTarget is what HarnessOptions.Env builds an environment for.

type ExtensionChange

type ExtensionChange struct {
	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"`
	Handle        *ai.DeferredHandle                 `json:"handle,omitempty"`
	PollAt        *float64                           `json:"pollAt,omitempty"`
	Assistant     *durable.EntryId                   `json:"assistant,omitempty"`
	Tools         []durable.TaskId                   `json:"tools,omitempty"`
	Pending       []string                           `json:"pending,omitempty"`
}

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

  • prepare: Attempt; Compacted is the blocking compaction this generation waited for, which starts no other compaction (spec §8.3); Overflow is the error text of the overflow that started Compacted, checked once when prepare resumes; 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.
  • poll: Attempt, Compacted, Model, Cutoff, Handle, PollAt.
  • tools: Assistant (the tool-calling answer), Tools (tool tasks created so far, in call order) and Pending (calls of a sequential round not started yet, in call order). The generation owns the tool tasks (spec §8.5).

func (GenerationCheckpoint) MarshalJSON

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

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

type GenerationHooks

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

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

type GenerationInput

type GenerationInput 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 GenerationRequest

type GenerationRequest struct {
	Messages []ai.Message
}

GenerationRequest is the request a beforeRequest hook may replace.

type GenerationResult

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

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

type Harness

type Harness interface {
	durable.Session
	// Resume enables task scheduling. It is idempotent and panics after close. Calls that ask for progress enable it too: Conversation.Submit, Compact, Abort, WaitForIdle, Submission.Wait, WaitForTask, and Harness.WaitForIdle. Read-only viewers never do.
	Resume()
	// 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)
	// RetryTask runs a task parked by settings.restartLimit again: it clears its restart count and enables scheduling. It
	// does nothing for a task that is not parked, and fails for an unknown one.
	RetryTask(ctx context.Context, id durable.TaskId) 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)
	// TaskGraph returns every live task with its owner edge, status, and owned conversations (spec §9.5), as a disposable Chord state.
	TaskGraph(ctx context.Context) (durable.AttachedReplicatedState[TaskGraph], error)
	// WatchTaskGraph returns the task graph as a serialized exact-frame watch with bounded pending frames.
	WatchTaskGraph(ctx context.Context) (TaskGraphWatch, error)
}

Harness is a durable agent harness over one Session.

func OpenHarness

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

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

type HarnessInspection

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

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

type HarnessOptions

type HarnessOptions struct {
	// 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 off the Session line, after the commit that changed
	// the value, 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. info says what happened: a host can tell a failed
	// Session (ReportSessionFailed, often a platform reset) from a faulted task (ReportTaskFaulted) or a parked one
	// (ReportTaskParked). A panic of its own is dropped.
	OnReport func(err error, info durable.ReportInfo)
	// 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 or document state 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) 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 is parked as blocked (restart_limit) instead of run again;
	// Harness.RetryTask runs it again. Nil selects the default, 5; +Inf never parks.
	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)
}

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

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 InboxUpdateEvent

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

func (InboxUpdateEvent) EventType

func (InboxUpdateEvent) EventType() string

func (InboxUpdateEvent) MarshalJSON

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

type InvocationBinding

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

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

type LiveGeneration

type LiveGeneration struct {
	Attempt int `json:"attempt"`
	// Message is the committed throttled partial of the in-flight response, as JSON.
	Message *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 []durable.SubmissionId `json:"inputs"`
}

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

type LiveState

type LiveState struct {
	// Run is present exactly while busy.
	Run        *LiveRun        `json:"run,omitempty"`
	Generation *LiveGeneration `json:"generation,omitempty"`
	// Tools is the current round in call order, from the tool-calling answer until the generation's tools phase ends
	// it; never empty while present.
	Tools []ToolSlot `json:"tools,omitempty"`
	// 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"`
}

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

type MessageChange

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

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

func (MessageChange) MarshalJSON

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

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

type MessageEndEvent

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

func (MessageEndEvent) EventType

func (MessageEndEvent) EventType() string

func (MessageEndEvent) MarshalJSON

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

type MessageStartEvent

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

func (MessageStartEvent) EventType

func (MessageStartEvent) EventType() string

func (MessageStartEvent) MarshalJSON

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

type MessageUpdateEvent

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

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

func (MessageUpdateEvent) EventType

func (MessageUpdateEvent) EventType() string

func (MessageUpdateEvent) MarshalJSON

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

type 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 ProgressPolicyPatch

type ProgressPolicyPatch struct {
	PartialIntervalMs *float64
	OutputIntervalMs  *float64
}

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

type ProviderState

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

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

type QueueModes

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

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

func QueueModesOf

func QueueModesOf(settings durable.Settings) QueueModes

QueueModesOf returns the queue modes of resolved settings.

type QueuedItem

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

QueuedItem is one queued inbox item as events report it.

type Registry

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

Registry is an application-owned registry of extensions.

func CreateRegistry

func CreateRegistry() Registry

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

type RegistryReader

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

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

type RetryPolicyPatch

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

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

type RetryStatus

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

RetryStatus is a durable backoff before the next attempt.

type RootOptions

type RootOptions struct {
	Agent *AgentChange
	Init  ConversationInit
}

RootOptions are the options of Harness.Root.

type RunEndEvent

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

func (RunEndEvent) EventType

func (RunEndEvent) EventType() string

func (RunEndEvent) MarshalJSON

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

type RunEvent

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

RunEvent carries the inputs of run_start and run_end.

type RunStartEvent

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

func (RunStartEvent) EventType

func (RunStartEvent) EventType() string

func (RunStartEvent) MarshalJSON

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

type SchedulerOutcome

type SchedulerOutcome = anyOutcome

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

type SectionOptions

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

SectionOptions are the options of Section.

type SnapshotEvent

type SnapshotEvent struct {
	Entries []durable.EntryRecord `json:"entries"`
	// Run is nil when idle.
	Run        *RunEvent           `json:"run,omitempty"`
	Generation *SnapshotGeneration `json:"generation,omitempty"`
	Tools      []ToolSlot          `json:"tools"`
	// NestedTools are pi.live.nestedTools: nested calls of running tool calls.
	NestedTools []NestedToolSlot `json:"nestedTools"`
	// Compactions are pi.live.compactions: live compactions with their attempt and retry backoff.
	Compactions []CompactionStatus `json:"compactions"`
	// CompactionFailure is pi.live.compactionFailure: the newest compaction failure since a compaction last produced a
	// summary.
	CompactionFailure *CompactionFailure `json:"compactionFailure,omitempty"`
	Inbox             []QueuedItem       `json:"inbox"`
	// Agent is pi.agent; empty when absent.
	Agent AgentState `json:"agent"`
	Usage UsageState `json:"usage"`
}

SnapshotEvent is the state of a conversation at attachment.

func ViewSnapshotEvent

func ViewSnapshotEvent(view ConversationView) SnapshotEvent

ViewSnapshotEvent is the snapshot event of a conversation view.

func (SnapshotEvent) EventType

func (SnapshotEvent) EventType() string

func (SnapshotEvent) MarshalJSON

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

type SnapshotGeneration

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

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

type SubmissionEvent

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

func (SubmissionEvent) EventType

func (SubmissionEvent) EventType() string

func (SubmissionEvent) MarshalJSON

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

type Submissions

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

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

func NewSubmissions

func NewSubmissions(line *session.SessionImpl, storage durable.Storage, now func() float64, queueModes func() QueueModes, resume func(), 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) Get

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

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

func (*Submissions) Status

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

Status returns the committed record of a submission.

func (*Submissions) Submit

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

Submit admits a submission in one commit; see AdmitSubmission.

func (*Submissions) Wait

Wait returns the settled record of a submission; cancelling ctx cancels only this wait, 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.

type SummaryRequest

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

SummaryRequest is the pinned summarization request.

type SystemDraft

type SystemDraft = durable.TypedEntryDraft[durable.Never]

SystemDraft is a planned pi.system entry.

func PlanSystemEntries

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

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

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

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

type TaskFailedEvent

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

func (TaskFailedEvent) EventType

func (TaskFailedEvent) EventType() string

func (TaskFailedEvent) MarshalJSON

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

type TaskGraph

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

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

type 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), or the restart limit parked it (restart_limit). 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, which are durable.

func NewTaskGraphView

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

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

func (*TaskGraphView) State

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

func (*TaskGraphView) Watch

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

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

type TaskGraphWatch

type TaskGraphWatch = durable.WatchHandle[TaskGraph]

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

type TaskInspection

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

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

type TaskInspectionKind

type TaskInspectionKind string

TaskInspectionKind is the kind of a TaskInspectionState.

const (
	TaskInspectionRunning    TaskInspectionKind = "running"
	TaskInspectionReady      TaskInspectionKind = "ready"
	TaskInspectionWaiting    TaskInspectionKind = "waiting"
	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); ready (the next scheduling pass reserves it; Migrates when its definition is newer and has a migration); waiting (on these live tasks: the live part of its on, or, when abort-marked, its live ordinary owned work); sleeping (until the Harness clock reaches Until); completing (outcome held until its ordinary owned work drains); blocked (no registered definition can take it, or the restart limit parked it, with Reason missing_task, task_too_old, migration_failed, or restart_limit 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 (missing_task, task_too_old, migration_failed) or the restart limit (restart_limit); 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) 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 that reaches the restart limit this way is parked and reported.

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.

func (*TaskScheduler) Retry

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

Retry runs a task parked by the restart limit again: it clears its restart count and enables scheduling. It does nothing for a task that is not parked, and fails for an unknown one.

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) 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 been entered, 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)
	// SettleOutcome is the Harness cleanup staged in the commit that makes an outcome the scheduler wrote itself
	// terminal.
	SettleOutcome func(tx durable.Tx, record anyTaskRecord, outcome SchedulerOutcome) error
	// WithdrawInputs withdraws a conversation's queued inputs, for conversation abort and abort cascades.
	WithdrawInputs func(tx durable.Tx, conversationId durable.ConversationId) error
	// Conversation returns an invocation-bound handle of an existing conversation, for task runtimes and tools.
	Conversation func(ctx context.Context, id durable.ConversationId, binding InvocationBinding) (durable.ConversationHandle, error)
	// Context is the context of scheduler commits and invocations; it carries no caller cancellation.
	Context context.Context
}

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

type ToolChange

type ToolChange struct {
	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 ToolEventCall

type ToolEventCall struct {
	ToolCallId       string          `json:"toolCallId"`
	ToolName         string          `json:"toolName"`
	TaskId           *durable.TaskId `json:"taskId,omitempty"`
	ParentToolCallId string          `json:"parentToolCallId,omitempty"`
	ParentTaskId     *durable.TaskId `json:"parentTaskId,omitempty"`
}

ToolEventCall says which call a tool event is about. ToolCallId is the call's ID in the transcript and in tool events: the provider's ID for a model-issued call, "<parent call ID>/<key>" for a nested one. TaskId is the call's tool task, nil for a call that never got one. A nested call also names the call that made it, by call ID and tool task.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolEventCall
	Entry  *durable.EntryRecord               `json:"entry,omitempty"`
	Result *durable.NestedToolExecutionResult `json:"result,omitempty"`
}

ToolExecutionEndEvent has a nil Entry when the tool task faulted or was orphaned; a nested call's end carries its Result, when its caller's document stored one, instead of an entry.

func (ToolExecutionEndEvent) EventType

func (ToolExecutionEndEvent) EventType() string

func (ToolExecutionEndEvent) MarshalJSON

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

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolEventCall
	Args durable.JsonObject `json:"args"`
}

func (ToolExecutionStartEvent) EventType

func (ToolExecutionStartEvent) EventType() string

func (ToolExecutionStartEvent) MarshalJSON

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

type ToolExecutionUpdateEvent

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

func (ToolExecutionUpdateEvent) EventType

func (ToolExecutionUpdateEvent) EventType() string

func (ToolExecutionUpdateEvent) MarshalJSON

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

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

type 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 ToolOutputChange

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

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

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

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

type ToolSlotStatus

type ToolSlotStatus string

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

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

type ToolTaskCheckpoint

type ToolTaskCheckpoint struct {
	Phase     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.

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"`
}

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 TurnEndEvent

type TurnEndEvent struct{}

func (TurnEndEvent) EventType

func (TurnEndEvent) EventType() string

func (TurnEndEvent) MarshalJSON

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

type TurnStartEvent

type TurnStartEvent struct{}

func (TurnStartEvent) EventType

func (TurnStartEvent) EventType() string

func (TurnStartEvent) MarshalJSON

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

type TypeError

type TypeError struct{ Message string }

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

func (*TypeError) Error

func (err *TypeError) Error() string

type UsageBucket

type UsageBucket string

UsageBucket names one bucket of the usage ledger.

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

type UsageChangedEvent

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

func (UsageChangedEvent) EventType

func (UsageChangedEvent) EventType() string

func (UsageChangedEvent) MarshalJSON

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

type UsageState

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

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

func NewUsageState

func NewUsageState() UsageState

NewUsageState returns an empty ledger.

type 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 func(ctx context.Context, value ConversationView, ops []durable.Op)
	// Publication receives every publication, after the mount took it; ops are the mount's, possibly none.
	Publication func(ctx context.Context, before, after ConversationView, ops []durable.Op, publication durable.CommitPublication)
	// CloseSession receives the Session's failure, nil when it closed.
	CloseSession func(failure error)
}

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

type Waiter

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

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

func (*Waiter[T]) Done

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

Done is closed once the waiter settles.

func (*Waiter[T]) Wait

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

Wait blocks until the waiter settles.

type Waiters

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

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

func (*Waiters[K, T]) Add

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

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

func (*Waiters[K, T]) Keys

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

Keys returns the keys with pending waits.

func (*Waiters[K, T]) RejectAll

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

RejectAll fails every pending wait with err.

func (*Waiters[K, T]) Resolve

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

Resolve settles every wait of key with value.

type 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