turn

package
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package turn is the agent turn: the built-in pi.generation and pi.tool tasks (spec §8.3-8.6) as session.TaskImpl definitions. Generation phases prepare, request, retry, poll and tools; tool phases call and execute; sequential and parallel rounds; the usage ledger; streaming partials committed with pi-durable main's fixed-interval throttle (generation.ts streamResponse) and tool output with the size-paced Progress (output.ts); retries, backoff and deferred polls as durable timers; recovery of an interrupted turn at any commit (CONTRACT section 3.8); the model request as a spliced model_context effect (context plane), and the wire plane behind the wireplane build tag.

Owner: dcore-history (taking dcore-loop). Depends on session (Runtime, Scheduler), history, rec, jv, abi.

Index

Constants

View Source
const (
	KindGeneration = "pi.generation"
	KindTool       = "pi.tool"
	KindCompaction = "pi.compaction"
)

Task kinds of the built-in tasks.

View Source
const (
	KindUser       = "pi.user"
	KindAssistant  = "pi.assistant"
	KindToolResult = "pi.tool-result"
	KindReset      = "pi.reset"
)

Entry kinds of the built-in entries (entries.ts).

View Source
const (
	UsageModels = "models"
	UsageTools  = "tools"
)

Ledger buckets of the pi.usage document: assistant entries and summarization attempts by provider/modelId, and tool results by tool name.

View Source
const KindSystem = "pi.system"

KindSystem is the kind of the system entry.

View Source
const ProgressBytesPerSecond = 100 * 1024

ProgressBytesPerSecond is the pace each progress commit buys: a pause proportional to what it wrote.

Variables

View Source
var CompactionDef = &session.TaskDef{
	Name:    KindCompaction,
	Version: 1,
	Initial: func(any) any { return jobj("phase", "select") },
}

CompactionDef is the pi.compaction definition: first checkpoint {phase: "select"} (compaction.ts). Read-only: assigned once at initialization.

View Source
var GenerationDef = &session.TaskDef{
	Name:    KindGeneration,
	Version: 1,
	Initial: func(any) any { return jobj("phase", phasePrepare, "attempt", 1.0) },
}

GenerationDef is the pi.generation definition: first checkpoint {phase: "prepare", attempt: 1}. Read-only: assigned once at initialization.

View Source
var LiveDef = &session.DocDef{
	Kind:    "pi.live",
	Version: 1,
	Scope:   session.ScopeConversation,
	History: session.HistoryLatest,
	Fork:    session.ForkInitial,
	Initial: func(any) *jv.Object { return jv.NewObject() },
	CheckpointWhen: func(value *jv.Object, _ []delta.Op, _ int) bool {
		if _, ok := value.Get("generation"); ok {
			return false
		}
		return !anySlotRunning(value)
	},
}

LiveDef is LiveDoc. A complete base is stored whenever nothing runs (spec section 8.2): no generation and no running tool slot. That holds while idle, in the commit handing a generation over to its tool round, and between tools, so the delta chain spans at most one generation or the overlapping execution of one round's tools. A slot holds output only while running, so every base is small. There is deliberately no delta-count bound. Read-only: assigned once at initialization.

View Source
var NestedCallDef = &session.DocDef{
	Kind:    "pi.tool.nested-call",
	Version: 1,
	Scope:   session.ScopeTask,
	Family:  true,
	Initial: func(any) *jv.Object { return jv.NewObject() },
}

NestedCallDef is the 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. Read-only: assigned once at initialization.

View Source
var ProviderDef = &session.DocDef{
	Kind:           "pi.provider",
	Version:        1,
	Scope:          session.ScopeConversation,
	History:        session.HistoryLatest,
	Fork:           session.ForkInitial,
	Initial:        func(any) *jv.Object { return jobj("sessionId", "") },
	CheckpointWhen: func(*jv.Object, []delta.Op, int) bool { return true },
}

ProviderDef is ProviderDoc: the provider-facing identity of one conversation; every fork starts with a fresh one. Read-only: assigned once at initialization.

View Source
var ToolDef = &session.TaskDef{
	Name:    KindTool,
	Version: 2,
	Initial: func(any) any {
		o := jv.NewObject()
		o.Set("phase", "call")
		return o
	},
}

ToolDef is the pi.tool task definition (tool.ts ToolTask, version 2): input {kind: "model", assistant, callId}, first checkpoint {phase: "call"}. Version 1 had only model-issued calls and no kind (migrateToolTask). Read-only: assigned once at initialization.

View Source
var UsageDef = &session.DocDef{
	Kind:           "pi.usage",
	Version:        1,
	Scope:          session.ScopeConversation,
	History:        session.HistoryLatest,
	Fork:           session.ForkInitial,
	Initial:        func(any) *jv.Object { return UsageInitial() },
	CheckpointWhen: func(*jv.Object, []delta.Op, int) bool { return true },
}

UsageDef is UsageDoc: the conversation's own spend, kept as a complete base on every change. Read-only: assigned once at initialization.

Functions

func AddCompactionStatus

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

AddCompactionStatus is addCompactionStatus: statuses stay in task ID order because a created task has the newest ID.

func AddUsage

func AddUsage(total, usage *jv.Object)

AddUsage adds every counter of usage to total; optional counters are added once either side reports them.

func AddUsageState

func AddUsageState(sum, state *jv.Object)

AddUsageState adds every bucket of state into sum.

func AppendToolResult

func AppendToolResult(tx *session.Tx, conversation ID, call, result *jv.Object, timestamp float64, durationMs *float64) (*jv.Object, error)

AppendToolResult is appendToolResult: it appends a pi.tool-result entry whose content ends with the rendered diagnostics, so the stored message is what the model sees, and adds the result's usage to pi.usage in the same commit. durationMs is nil when unknown. call is the tool call content block ({id, name, …}).

func ClearProgress

func ClearProgress(slot *delta.Obj)

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

func CompactionStatusOf

func CompactionStatusOf(live *delta.Obj, taskID session.ID) *delta.Obj

CompactionStatusOf is compactionStatus: the status of compaction task taskID, or nil.

func CurrentTools

func CurrentTools(messages []*jv.Object) []*jv.Object

CurrentTools is getCurrentTools: the tools available after applying every system message's toolsRemoved and toolsAdded in order, in first-declaration order (a re-added tool keeps its place).

func DeclarationsEqual

func DeclarationsEqual(left, right *jv.Object) bool

DeclarationsEqual is declarationsEqual: both tools go through ToolDeclaration, then their JSON text is compared.

func EndRun

func EndRun(tx *session.Tx, live *delta.Obj, taskID session.ID, settlement *jv.Object) error

EndRun is endRun: it settles each input of the run owned by taskID with settlement and removes `run`, and always removes `generation` and `tools`, whose presentation belongs to the ending run.

func FailCompactionStatus

func FailCompactionStatus(live *delta.Obj, taskID session.ID, message string) error

FailCompactionStatus is failCompactionStatus: it removes the status of compaction task taskID and records that it failed with message (pi.live.compactionFailure).

func FinishSlot

func FinishSlot(slot *delta.Obj) error

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

func HarnessError

func HarnessError(code, message string) *jv.Object

HarnessError is harnessError: an error result the Harness writes itself, with no content and one error diagnostic.

func IsContextOverflow

func IsContextOverflow(message *jv.Object) bool

IsContextOverflow is isContextOverflow(message) without a context window: an error message that matches an overflow pattern and no non-overflow pattern, or the Cerebras bodyless 400/413.

func IsNestedSlot

func IsNestedSlot(slot *delta.Obj) bool

IsNestedSlot is whether a slot names its parent task, which only a nested call's does.

func IsRetryableAssistantError

func IsRetryableAssistantError(message *jv.Object) bool

IsRetryableAssistantError is isRetryableAssistantError: a failed message whose error looks like a transient provider or transport error, and not like quota or billing exhaustion.

func Machines

func Machines(h *Host) []*session.TaskImpl

Machines returns the executable definitions of the built-in tasks over a Host, in registration order, for the registry snapshot of the Scheduler. Runs{} implements inbox.Runs for admission.

func PlanSystemEntries

func PlanSystemEntries(view PromptView, desired *Sections, tools []*jv.Object, timestamp float64) []*jv.Object

PlanSystemEntries is planSystemEntries. It returns entry drafts (`{model: [message]}`, with `edits` on a baseline that omits retained system entries). desired are the rendered sections in order and tools the registered tool schemas.

  • A head marker with no later system entry in context: one complete baseline that omits every retained earlier 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 null removals, or nothing.

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

func RecordUsage

func RecordUsage(ledger *jv.Object, bucket, key string, usage *jv.Object)

RecordUsage adds usage to the bucket entry key of ledger, in the commit that records the response: the first usage of a key is copied, with absent optional counters left out; later ones are added. Own keys only (a tool may be called `toString`), which an ordered object is by construction.

func RemoveCompactionStatus

func RemoveCompactionStatus(live *delta.Obj, taskID session.ID) error

RemoveCompactionStatus is removeCompactionStatus: it removes the status of compaction task taskID, and the list once empty.

func RemoveNestedSlots

func RemoveNestedSlots(live *delta.Obj, taskID session.ID) error

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

func RetryDelayMs

func RetryDelayMs(baseDelayMs float64, maxAgentDelayMs *float64, attempt float64) float64

RetryDelayMs is retryDelayMs: baseDelayMs * 2^(attempt-1), capped at maxAgentDelayMs (60 seconds when absent).

func SanitizeOutput

func SanitizeOutput(text string) string

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

func SettleSchedulerOutcome

func SettleSchedulerOutcome(tx *session.Tx, record, outcome *jv.Object) error

SettleSchedulerOutcome is settleSchedulerOutcome (harness/live.ts): the Harness side of a task the scheduler settled with an outcome it wrote itself (faulted or orphaned), in the settling transaction. A tool task finishes its slot; a compaction task drops its status; the generation that holds `run` converts its partial, and its inputs settle unanswered with the reason (faulted carries the error message as detail).

func ToolDeclaration

func ToolDeclaration(tool *jv.Object) *jv.Object

ToolDeclaration is toToolDeclaration: name, description, the parameters as a JSON round trip and constrainedSampling when defined.

func ToolSlotOf

func ToolSlotOf(live *delta.Obj, taskID session.ID) *delta.Obj

ToolSlotOf is toolSlot: the slot of tool task taskID, model-issued in the current round or nested, or nil. 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, and removal keeps the order.

func UsageInitial

func UsageInitial() *jv.Object

UsageInitial is the initial value of the pi.usage document: {models: {}, tools: {}}.

Types

type Agent

type Agent struct {
	Model         *ModelRef
	ThinkingLevel string
	// Sections are the extension sections, then the agent's instructions, in render order.
	Sections []Section
	Tools    []Tool
	// Callable are the tools a running tool's nested calls (executeTool) resolve among: enabled and callable by tools.
	Callable []Tool
	// Instructions and Cwd are the agent's optional base instructions and working directory (the render input).
	Instructions, Cwd string
	// HookHandlers are the hook handler tables of the selected extensions in extension order: hook name to handler index
	// (agent.ts agentHooks).
	HookHandlers []map[string]int
	// HookExtensions names the extension of each table of HookHandlers.
	HookExtensions []string
}

Agent is the resolved agent of a conversation (agent.ts resolution): its model, thinking level, prompt sections and tools.

func (*Agent) Declarations

func (a *Agent) Declarations() []*jv.Object

Declarations returns the tool declarations in order.

type BoundedOutput

type BoundedOutput struct {
	Text         string
	DroppedBytes int
	DroppedLines int
}

BoundedOutput is retained output and what the limits dropped.

type CompactionTask

type CompactionTask struct{ Host *Host }

CompactionTask implements the pi.compaction task over a Host.

func (*CompactionTask) Impl

func (g *CompactionTask) Impl() *session.TaskImpl

Impl returns the executable definition registered in the registry.

type CompleteRequest

type CompleteRequest struct {
	Model ModelRef
	// Context is the pi-ai Context ({messages}); Options the request options without the signal.
	Context, Options *jv.Object
}

CompleteRequest is a non-streaming model request (completeSimple): the compaction summarizer.

type Generation

type Generation struct{ Host *Host }

Generation implements the pi.generation task over a Host.

func (*Generation) Impl

func (g *Generation) Impl() *session.TaskImpl

Impl returns the executable definition registered in the registry.

type Host

type Host struct {
	Now      func() float64
	Settings func() Settings
	// Agent resolves the agent of a conversation (runtime.agent: the host resolves it and may call extension code, so it is
	// asynchronous). The resolution is fixed for the phase that asked.
	Agent func(conversation ID, cancel *session.Cancel, then func(*Agent, error))
	// ContextWindow returns the context window of a model; ok is false when the model is not available.
	ContextWindow func(model ModelRef) (window float64, ok bool)
	// KeptRange is the range the scheduler keeps for the conversation (scheduler.ts #contexts), read when runtime.context is
	// called: readContextFrom receives it as an argument, so a keep that lands later does not change that read.
	KeptRange func(conversation ID) KeptRange
	// Context derives the committed context of a conversation as of entry at (0: the tail), given the range KeptRange
	// returned when the read was called. It runs inside the bounds job on the Session line and returns the hops from the end of
	// that job until the caller resumes (a scan off the line and its return, or the return alone when the kept range serves the
	// read: context.ts readContextFrom :75-102) and keep, which the caller runs once the scan has
	// finished, before the read resolves: the scheduler keeps the range only after readContextFrom returns
	// (scheduler.ts:1231-1252), so a read whose bounds job runs while another's scan is in flight scans too. keep takes
	// whether the invocation has ended and may be nil.
	Context func(conversation, at ID, kept KeptRange) (view *history.View, scan int, keep func(ended bool) error, err error)
	// RequestContext is Context for a model request: the context the request is prepared from, which the Host may take from
	// the host that stores it instead of deriving it (compaction and overflow handling still need the view). It has the
	// hops, keep and kept-range contract of Context.
	RequestContext func(conversation, at ID, kept KeptRange) (ctx RequestContext, scan int, keep func(ended bool) error, err error)
	// Render renders the agent's prompt sections in order for one request preparation (renderSections, with the
	// environment). shown are the sections the context currently shows; a section that throws keeps its shown text.
	// task is the generation task, whose environment the sections see (runtime.env, built before the first section).
	Render func(conversation, task ID, agent *Agent, shown *Sections, cancel *session.Cancel, then func(desired *Sections, err error))
	// Stream runs the model request. onPartial receives the text of each partial assistant message, a JSON object, which the
	// request parses only when it commits it; then receives the terminal message.
	Stream func(req *StreamRequest, onPartial func(partial jv.Raw), cancel *session.Cancel, then func(message *jv.Object, err error))
	// PrepareArguments applies the tool's prepareArguments to the call's arguments: the repaired arguments, any JSON value
	// (harness/tool.ts prepare casts the result, it does not check it), or errText when the repair throws.
	PrepareArguments func(tool string, args *jv.Object, then func(args any, errText string, err error))
	// ValidateArguments validates and coerces arguments, any JSON value, against the tool's schema (validateToolArguments):
	// the coerced arguments, or errText describing why they are invalid.
	ValidateArguments func(tool string, call *jv.Object, args any, then func(args *jv.Object, errText string, err error))
	// CheckStructuredOutput asks the host whether a settled result's structured output keeps the tool's contract
	// (structuredOutputError): errText is why it does not, empty when it does. The schema lives in the host's registration.
	CheckStructuredOutput func(tool string, result *jv.Object, then func(errText string, err error))
	// RunTool builds the call's environment and runs the tool's execute: the tool effect. then receives the tool's result
	// object ({content?, details?, isError?, diagnostics?, usage?, control?}), or the error execute (or the environment) threw.
	RunTool func(run *ToolRun, io *ToolIO, cancel *session.Cancel, then func(result *jv.Object, err error))
	// MaxTokens is the model's own output token limit (0: none); ok is false when the model is not available.
	MaxTokens func(model ModelRef) float64
	// Complete runs one non-streaming model request and delivers the terminal assistant message.
	Complete func(req *CompleteRequest, cancel *session.Cancel, then func(message *jv.Object, err error))
	// Hooks returns the number of handlers the conversation's agent selects for a generation, tool or compaction hook.
	Hooks func(name string, conversation ID) int
	// HookExtension is the name of the extension of handler index of the hook name (agent.ts agentHooks).
	HookExtension func(name string, index int, conversation ID) string
	// Hook calls handler index of the hook name. The payload is the hook's first argument; the result is its return value (nil for none).
	Hook func(name string, index int, conversation, task ID, payload *jv.Object, then func(result any, err error))
	// FetchDeferred polls a provider-side deferred response; CancelDeferred abandons it.
	FetchDeferred  func(model ModelRef, handle *jv.Object, cancel *session.Cancel, then func(message *jv.Object, err error))
	CancelDeferred func(model ModelRef, handle *jv.Object, cancel *session.Cancel, then func(err error))
	// Snapshot reads the committed value of a conversation document, or nil when it does not exist.
	Snapshot func(def *session.DocDef, conversation ID) (*jv.Object, error)
	// SnapshotLoaded reports whether Snapshot is a cache hit: Pi's Session.snapshot takes a line job only on a miss.
	SnapshotLoaded func(def *session.DocDef, conversation ID) bool
	// Entry reads one committed entry record, or nil.
	Entry func(id ID) (*jv.Object, error)
	// AddTools adds tools to the agent's loadout in this commit (agent.ts addTools), for a tool result's addTools control.
	AddTools func(tx *session.Tx, conversation ID, added []any) error
	// After arms a volatile timer; the returned function cancels it.
	After func(ms float64, fire func()) (cancel func())
	// NewSessionID returns a fresh provider session ID (uuidv7).
	NewSessionID func() string
	// Hops runs then after n microtask hops of the shared host/core queue (ABI section 5.3, a hops effect), so a Pi await
	// chain of n hops lets host work queued meanwhile run first. n <= 0 runs then as the next microtask.
	Hops func(n int, then func())

	// ScanHops is Hops for the wait on a context range scan (context.ts scanRange awaits Storage.scanEntries): n is the scan's ticks
	// with the return to the caller, and a Host whose Storage queues statements runs the scan's statements through that queue.
	// A Host without it waits with Hops.
	ScanHops func(n int, then func())
}

Host is what the built-in tasks need of the surrounding Harness: the clock, settings, agent and model resolution, committed context, and the effects a task starts (model request, prompt sections, hooks, deferred responses, timers). The Session handler implements it by emitting ABI effects and resolving the continuations when their completions arrive; tests implement it with a script. Every continuation runs on the session Loop's turn, never re-entrantly.

type ID

type ID = session.ID

ID is a record ID.

func CreateCompaction

func CreateCompaction(tx *session.Tx, conv ID, input *jv.Object, owner ID) (ID, error)

CreateCompaction is compaction.ts createCompaction for an input {reason, instructions?}: Conversation.compact uses it with reason "manual".

type KeptRange

type KeptRange struct {
	Head, Tail ID
	Ok         bool
}

KeptRange is the head marker entry (0: none) and newest entry of a kept context range; Ok is false when none is kept.

type ModelRef

type ModelRef struct{ Provider, ModelID string }

ModelRef names a model: {provider, modelId}.

type OutputBuffer

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

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

func NewOutputBuffer

func NewOutputBuffer(limits OutputLimits) *OutputBuffer

NewOutputBuffer returns an empty buffer.

func (*OutputBuffer) End

func (b *OutputBuffer) End()

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

func (*OutputBuffer) PushBytes

func (b *OutputBuffer) PushBytes(chunk []byte, skipped *Skip) bool

PushBytes accepts a byte chunk, decoded as a stream.

func (*OutputBuffer) PushString

func (b *OutputBuffer) PushString(chunk string, skipped *Skip) bool

PushString accepts a string chunk; it reports whether anything was accepted. skipped is output omitted right before the chunk; only tail retention accepts it.

func (*OutputBuffer) Snapshot

func (b *OutputBuffer) Snapshot() BoundedOutput

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

func (*OutputBuffer) StoredBytes

func (b *OutputBuffer) StoredBytes() int

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

type OutputLimits

type OutputLimits struct {
	MaxBytes int
	MaxLines int
	// Retain is "head" or "tail".
	Retain string
}

OutputLimits are the retention limits of one tool's output.

type OutputSlice

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

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

func BoundOutput

func BoundOutput(text string, limits OutputLimits) OutputSlice

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

type PromptEntry

type PromptEntry struct {
	ID   int64
	Kind string
}

PromptEntry is an entry of the context view that planning inspects.

type PromptView

type PromptView struct {
	HasHead  bool
	HeadID   int64
	Entries  []PromptEntry
	Messages []*jv.Object
}

PromptView is the part of a ContextView that planSystemEntries reads: the head marker, the entries and the messages.

type RequestContext

type RequestContext interface {
	// PromptView is what planning reads: the head marker, the active entries when there is a marker, the system messages.
	PromptView() PromptView
	// SystemMessages are the context's system messages, in order.
	SystemMessages() []*jv.Object
	// Messages are the model messages; the beforeRequest hooks read them. A host that cannot answer fails the handle.
	Messages() []*jv.Object
	// Bounds are the head marker entry (0: none) and the newest entry that fix the context: what a model request names.
	Bounds() (head, tail int64)
	// Threshold is generation.ts thresholdCompaction over the context followed by the planned messages.
	Threshold(planned [][]byte, window float64, p history.Policy) history.Threshold
}

RequestContext is the committed context a model request is prepared from: what generation.ts reads of runtime.context before it sends a request. The Host gives one either from the core's own derivation (ViewContext) or from the context the host derived (Host.RequestContext), so a request never needs the whole transcript in the core.

type ResultFault

type ResultFault struct{ Text string }

ResultFault is the error RunTool answers with when the tool returned a value the host could not hand over as strict JSON. The call faults: there is no result to record.

func (*ResultFault) Error

func (e *ResultFault) Error() string

type Runs

type Runs struct{}

Runs implements inbox.Runs: the conversation's pi.live document and the start of a run for placed inputs.

func (Runs) Live

func (Runs) Live(tx *session.Tx, conv ID) (*delta.Obj, error)

Live returns the pi.live draft of a conversation.

func (Runs) Start

func (Runs) Start(tx *session.Tx, conv ID, live *delta.Obj, inputs []ID) error

Start is startRun.

type Section

type Section struct {
	Key     string
	Tag     bool
	Handler int
	// Extension is the last selected extension that provides or wraps the section (agent.ts sectionExtension); empty when
	// the agent's instructions render it.
	Extension string
}

Section is a resolved prompt section of the agent: its key, whether its text is wrapped as <key>…</key>, and the index of its render handler in the registry snapshot.

type Sections

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

Sections is an insertion-ordered string map (a JavaScript Map<string, string>): setting an existing key keeps its place, deleting then setting again appends.

func ReplaySections

func ReplaySections(messages []*jv.Object) *Sections

ReplaySections is replaySections: the sections in effect after replaying system messages in order. A message's `sections` object is read in ECMAScript property order; a null value deletes.

func (*Sections) Delete

func (s *Sections) Delete(key string)

Delete removes a key.

func (*Sections) Get

func (s *Sections) Get(key string) (string, bool)

Get returns a value.

func (*Sections) Has

func (s *Sections) Has(key string) bool

Has reports whether key is present.

func (*Sections) Keys

func (s *Sections) Keys() []string

Keys returns the keys in order. The slice is the map's own; do not modify it.

func (*Sections) Set

func (s *Sections) Set(key, value string)

Set stores a value; an existing key keeps its position.

type Settings

type Settings struct {
	RetryEnabled    bool
	MaxRetries      float64
	BaseDelayMs     float64
	MaxAgentDelayMs *float64

	Compaction history.Policy
	// CompactionOverrides is compaction.modelOverrides, keyed by exact "provider/modelId" (Pi c4cf7957); CompactionFor
	// applies it.
	CompactionOverrides map[string]history.PolicyOverride

	// PartialIntervalMs is progress.partialIntervalMs: the throttle of streamed partials committed into pi.live.
	PartialIntervalMs float64
	// OutputIntervalMs is progress.outputIntervalMs: the pace of tool output commits.
	OutputIntervalMs float64

	// Stream is the settings' request options (a JSON object), pinned into the request checkpoint.
	Stream *jv.Object
	// ToolExecution is "parallel" or "sequential".
	ToolExecution string
	Queue         inbox.QueueModes
	// AfterFailedRun is settings.afterFailedRun: "keep", "continue" or "withdraw".
	AfterFailedRun string
}

Settings are the resolved Harness settings the built-in tasks read (src/harness/types.ts HarnessSettings after defaults).

func (Settings) CompactionFor

func (s Settings) CompactionFor(model ModelRef) history.Policy

CompactionFor is compaction.ts compactionPolicy: the model's modelOverrides entry over the Harness-wide policy, field by field.

type Skip

type Skip struct {
	Bytes           int
	Newlines        int
	EndsWithNewline bool
}

Skip is output omitted right before a chunk (ShellOutputSkip): its size, newlines and whether it ended with one.

type StreamRequest

type StreamRequest struct {
	// Conversation is the conversation the request runs in: the host keeps its newest message list for the delta form.
	Conversation ID
	Model        ModelRef
	Context      RequestContext
	Replaced     []*jv.Object
	// Options are the request options without the signal: the pinned stream options, the provider session ID and the reasoning level.
	Options *jv.Object
}

StreamRequest is one model request: the model_context effect (ABI section 6). Context is the committed context through the cutoff; Replaced, when non-nil, replaces the context's messages after a beforeRequest hook.

type Tool

type Tool struct {
	Declaration *jv.Object
	// ExecutionMode is "sequential", "parallel" or "" (the settings decide).
	ExecutionMode string
	// Handler is the index of the tool's execute handler in the registry snapshot.
	Handler int
	// Replay is "safe" or "unsafe"; empty means unsafe.
	Replay string
	// Raw is the host's tool JSON, kept for the tool effect.
	Raw *jv.Object
	// Extension is the last selected extension that provides or wraps the tool (agent.ts toolExtension).
	Extension string
	// Limits are the tool's outputLimits; nil fields default to 50 KiB, 2000 lines and head retention.
	Limits ToolLimits
	// StructuredOutput is whether the tool declares a structured output schema.
	StructuredOutput bool
}

Tool is a registered tool of the resolved agent: its transcript declaration, execution mode, replay policy and output limits.

type ToolIO

type ToolIO struct {
	// Output reports a chunk (text when isString, bytes otherwise) and the output omitted right before it, if any.
	Output     func(chunk []byte, isString bool, skipped *Skip) error
	Diagnostic func(diagnostic *jv.Object) error
	Details    func(value any, then func(error))
}

ToolIO is what a running tool reports through its api (tool_progress events). Each function fails once the call has settled. Details calls then after the progress commit that includes the value.

type ToolLimits

type ToolLimits struct {
	MaxBytes, MaxLines *int
	Retain             string
}

ToolLimits are the optional output limits of a tool registration.

type ToolRun

type ToolRun struct {
	Task, Conversation ID
	CallID, Name       string
	Arguments          *jv.Object
	// OutputWindow is the retained window for tail retention ({maxBytes, maxLines, minIntervalMs, bytesPerSecond}), else nil.
	OutputWindow *jv.Object
}

ToolRun is one tool execution request: the tool effect (ABI section 6).

type ToolTask

type ToolTask struct{ Host *Host }

ToolTask implements the pi.tool task over a Host.

func (*ToolTask) Impl

func (g *ToolTask) Impl() *session.TaskImpl

Impl returns the executable definition registered in the registry.

type ViewContext

type ViewContext struct{ View *history.View }

ViewContext is the context the core derived itself.

func (ViewContext) Bounds

func (c ViewContext) Bounds() (head, tail int64)

Bounds implements RequestContext.

func (ViewContext) Messages

func (c ViewContext) Messages() []*jv.Object

Messages implements RequestContext.

func (ViewContext) PromptView

func (c ViewContext) PromptView() PromptView

PromptView implements RequestContext.

func (ViewContext) SystemMessages

func (c ViewContext) SystemMessages() []*jv.Object

SystemMessages implements RequestContext.

func (ViewContext) Threshold

func (c ViewContext) Threshold(planned [][]byte, window float64, p history.Policy) history.Threshold

Threshold implements RequestContext.

Jump to

Keyboard shortcuts

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