driver

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: 31 Imported by: 0

Documentation

Overview

Package driver holds the native Go effect executors of the Durable core (docs/plan/durable-core/ABI.md section 6, ADR-0001 D17). A sqlhost.Host starts them in owned goroutines under a context.Context; they post completions back to the Host's owner goroutine. The executors serve the model plane: model_context and deferred over a durable.Models, the same calls pi-ai's Models makes in the Cloudflare host (durable/core/host/cf/src/effects.ts).

Index

Constants

View Source
const RootConversationID durable.ConversationId = 1

RootConversationID is the reserved ID of the root conversation.

Variables

View Source
var ErrTxEnded = errors.New("Transaction has settled")

ErrTxEnded is returned by an operation on a transaction that ended.

View Source
var ErrUnsupported = errors.New("not supported by the Durable core session yet")

ErrUnsupported is the error of a public operation the native session does not serve yet (PROTOCOL.md, "Not supported").

Functions

func Open

Open opens a session over the core. In the default "harness" mode the result is the core's harness.Harness; in "session" mode it is also a durable.Session.

func OpenHarness

func OpenHarness(ctx context.Context, path string, options harness.HarnessOptions) (harness.Harness, error)

OpenHarness opens the Durable core as a native Harness over the SQLite store at path (":memory:" or a file; a file written by pi-durable opens as it is, CONTRACT section 3). A file at an older schema version is copied to <path>.schema-<N>.bak before the core upgrades it (D188). It is the D17 counterpart of harness.OpenHarness: the same options and the same harness.Harness, with one owner goroutine holding the core and the connection, and the store closed with the Harness. The registry may keep changing while the Harness runs.

Types

type Callback

type Callback func(ctx context.Context, payload json.RawMessage, tx *Tx) (any, error)

Callback is host code Pi runs inside an open commit callback: the core holds a transaction (tx) open and waits for the result. The payload is the callback's JSON input.

type Callbacks

type Callbacks struct {
	Client *Client
	// Named holds the callbacks the session installed, such as conversationCreated.
	Named map[string]Callback
}

Callbacks runs callback effects (ABI effect 13) by name.

func (*Callbacks) Handler

func (c *Callbacks) Handler() sqlhost.Handler

Handler returns the sqlhost handler of callback effects.

type Client

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

Client sends the requests of the host-to-core request plane: `api` requests (ABI section 8.1), inspect and abort requests that expect an answer, and the extension transaction channel (section 8). An answer is a notice delivered after the step that carried the request. Every request fails when the handle is discarded, with the host's error.

func NewClient

func NewClient(host *sqlhost.Host) *Client

NewClient returns a client of one host.

func (*Client) API

func (c *Client) API(ctx context.Context, op string, args map[string]any) (json.RawMessage, error)

API runs one api request and returns the `ok` JSON. A core error is a *CoreError.

func (*Client) Abort

func (c *Client) Abort(ctx context.Context, body map[string]any) (json.RawMessage, error)

Abort sends an abort that expects an answer (abortSubmission, abortTask).

func (*Client) Begin

func (c *Client) Begin(ctx context.Context, options map[string]any) (*Tx, error)

Begin opens a transaction. It returns at `ready`; a `waiting` answer only means the line is held and `ready` follows. Options are `invocation` and `conversationId`.

func (*Client) Bind

func (c *Client) Bind(txID uint32) *Tx

Bind returns the transaction a callback effect carries (ABI effect 13): the core already opened it.

func (*Client) Inspect

func (c *Client) Inspect(ctx context.Context, query map[string]any) (json.RawMessage, error)

Inspect runs an inspect query (ABI section 5, kind 16); the core echoes the request ID in an api_result notice.

func (*Client) Submit

func (c *Client) Submit(ctx context.Context, body map[string]any) (json.RawMessage, error)

Submit sends a submit event (ABI section 5, kind 3); the core answers with an api_result notice for the event's id, {ok: {id: submissionId}}, after the commit's published notice.

type CoreError

type CoreError struct {
	Name    string `json:"name"`
	Message string `json:"message"`
	// ConversationID is ConversationBusy's structured field (the wire body's conversationId); nil when the core sent none.
	ConversationID *int64 `json:"conversationId,omitempty"`
}

CoreError is an error the core answered with: Pi's `{name, message}` (ABI section 8).

func (*CoreError) As

func (e *CoreError) As(target any) bool

As lets errors.As find the typed Pi error a remote error names: Pi's Session throws ReadAfterWrite, StorageRequestError, SessionFailed and ConversationBusy instances and callers match them with instanceof (errors.ts), so a caller of the driver matches the same Go types the in-process Session returns. ConversationBusy carries its id in the structured conversationId field; ReadAfterWrite is message-only in Pi (errors.ts keeps no method property), so its method comes from the message.

func (*CoreError) Error

func (e *CoreError) Error() string

func (*CoreError) ErrorName

func (e *CoreError) ErrorName() string

ErrorName is the Pi error class name the core reported.

type Envs

type Envs struct {
	// Build is HarnessOptions.Env; nil means no environment.
	Build func(ctx context.Context, target harness.EnvTarget) (env.ExecutionEnv, error)
	// Reader returns the committed document reads an environment builder may use.
	Reader func() durable.DocumentReader
	// contains filtered or unexported fields
}

Envs builds and keeps the environments of tasks. The core asks for one with an env effect before a task's sections and tools run; the section executor reads it back by task.

func (*Envs) Get

func (e *Envs) Get(task durable.TaskId) env.ExecutionEnv

Get returns the environment built for a task; nil when none.

func (*Envs) Handler

func (e *Envs) Handler() sqlhost.Handler

Handler returns the sqlhost handler of env effects.

type Hooks

type Hooks struct {
	// Lookup returns what the handler index names: a *harness.GenerationHooks, *harness.ToolHooks,
	// *harness.CompactionHooks or a PrepareArguments. The index is the host's append-only handler table, so an index
	// never changes meaning.
	Lookup func(handler int) (any, bool)
	// API returns the reads and memos a hook of one task may use.
	API func(task durable.TaskId, conversation durable.ConversationId) harness.HookApi
	// Task returns the registered definition of a task kind, for the `migrate` hook the core asks when it reserves a record that an
	// older version stored (scheduler.ts #resolve).
	Task func(kind string) (durable.AnyTask, bool)
}

Hooks runs hook effects against the handlers an extension registered.

func (*Hooks) Handler

func (h *Hooks) Handler() sqlhost.Handler

Handler returns the sqlhost handler of hook effects.

type Models

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

Models runs model_context and deferred effects over a durable.Models.

func NewModels

func NewModels(models func() durable.Models, now func() float64, report func(error)) *Models

NewModels returns the executors. report receives failures that do not fail an effect; now stamps a synthesized error message.

func (*Models) Handlers

func (m *Models) Handlers() map[abi.EffectKind]sqlhost.Handler

Handlers returns the sqlhost handlers for the effect kinds this package serves.

type PhaseEffect

type PhaseEffect struct {
	TaskID     int64           `json:"taskId"`
	Kind       string          `json:"kind"`
	Phase      *string         `json:"phase"`
	Record     json.RawMessage `json:"record"`
	Invocation int64           `json:"invocation"`
	Abort      bool            `json:"abort"`
	// Handler is the registry table index of the task definition the core reserved the task under; nil when the core
	// names none (the registry's definition of Kind runs then).
	Handler *int `json:"handler"`
	// Extension is the extension that installed the definition the core reserved the task under (scheduler.ts installerOf);
	// empty for a built-in task.
	Extension string `json:"extension"`
	// EffectID is the ID of the effect that carries this phase; the core cancels it when the invocation ends.
	EffectID uint32 `json:"-"`
}

PhaseEffect is a phase effect (ABI effect 8): the core asks the host to run one phase of a custom task, or its abort handler when Abort is true. Record is the task's record as the core holds it and Invocation the task's invocation identity.

type Phases

type Phases struct {
	// Run executes one phase or abort handler and returns when it finishes. A returned error completes the effect as
	// thrown; the core settles the task from it.
	Run func(ctx context.Context, effect PhaseEffect) error
}

Phases runs the phases and abort handlers of custom tasks.

func (*Phases) Handler

func (p *Phases) Handler() sqlhost.Handler

Handler returns the sqlhost handler of phase effects.

type PrepareArguments

type PrepareArguments func(args any) (any, error)

PrepareArguments is a tool's argument repair (durable.ToolRegistration.PrepareArguments).

type SectionBackend

type SectionBackend interface {
	durable.DocumentReader
	// Agent is the conversation's agent as the task resolved it; its Sections are the effect's section indexes.
	Agent(ctx context.Context) (durable.Agent, error)
}

SectionBackend is what rendering a section reads from the session.

type Sections

type Sections struct {
	Backend func(task durable.TaskId, conversation durable.ConversationId) SectionBackend
	Envs    *Envs
}

Sections runs section effects.

func (*Sections) Handler

func (s *Sections) Handler() sqlhost.Handler

Handler returns the sqlhost handler of section effects.

type SessionConfig

type SessionConfig struct {
	// Core is the ABI session the owner goroutine drives; SQL is its sql_table.
	Core sqlhost.Stepper
	SQL  []string
	// DB is the store connection. The session owns it and closes it with the session.
	DB *sqlhost.DB
	// Harness carries the host code and policy: Models, Registry, Settings, Env, ConversationCreated, Now, OnReport.
	Harness harness.HarnessOptions
	// ModelsInUse are the catalogue entries the core may name.
	ModelsInUse []*ai.Model
	// Sidecar is the cold-open mode of ADR D6; default "index".
	Sidecar string
	// Mode is "harness" (default) or "session" (the tables-and-documents Session without the Harness).
	Mode string
	// Phases runs the phases and abort handlers of custom tasks; nil means the host has no custom task runtime.
	Phases func(ctx context.Context, effect PhaseEffect) error
	// OnCommitted observes every commit after the store applied it (trace capture).
	OnCommitted func(c abi.Commit, sql []string)
	// Monotonic is the clock a model request's duration is measured on (pi-ai: performance.now); nil uses Harness.Now.
	Monotonic func() float64
	// TimerLead and Settle are sqlhost.Options.TimerLead and Settle.
	TimerLead time.Duration
	Settle    func()
	// TimerFired is sqlhost.Options.TimerFired: a virtual Harness.Now clock moves to a timer's time as it fires.
	TimerFired func(at float64)
	// contains filtered or unexported fields
}

SessionConfig configures one native session on the core (ADR D17).

type SessionFailedError

type SessionFailedError struct{ *durable.SessionFailed }

SessionFailedError is what every call after a failed commit returns: Pi's SessionFailed (session.ts GuardedStorage), with the store's failure as its cause. It is a *durable.SessionFailed and also matches the core's session.ErrSessionFailed. The handle itself is discarded (ABI section 4.6); this is how the driver Session reports that to a caller.

func (*SessionFailedError) Is

func (e *SessionFailedError) Is(target error) bool

Is matches the core's ErrSessionFailed.

func (*SessionFailedError) Unwrap

func (e *SessionFailedError) Unwrap() error

Unwrap returns the *durable.SessionFailed, whose own cause is the store's failure.

type SnapshotJSON

type SnapshotJSON struct {
	Extensions []snapshotExtension `json:"extensions"`
}

SnapshotJSON is the registry snapshot the core receives (PROTOCOL.md, "Registry snapshot").

type ToolBackend

type ToolBackend interface {
	durable.DocumentObserver
	durable.DocumentReader
	Registry() durable.RegistrySnapshot
	Agent(ctx context.Context) (durable.Agent, error)
	// Models is HarnessOptions.models.
	Models() durable.Models
	// Env is the environment built for this call; nil without one.
	Env() env.ExecutionEnv
	// Now is the Harness clock.
	Now() float64
	Commit(ctx context.Context, change func(tx durable.Tx) (any, error)) (any, error)
	Memo(ctx context.Context, name string) (value durable.JsonValue, ok bool, err error)
	MemoCandidate(ctx context.Context, name string, candidate durable.JsonValue) (durable.JsonValue, error)
	CreateTaskErased(ctx context.Context, task durable.AnyTask, input durable.JsonValue, options durable.TaskOptions) (durable.TaskId, error)
	GetTask(ctx context.Context, id durable.TaskId) (*durable.TaskRecord[durable.JsonValue, durable.JsonValue, durable.JsonValue], error)
	WaitForTask(ctx context.Context, id durable.TaskId) (durable.SettledTask[durable.JsonValue], error)
	Conversation(ctx context.Context, id durable.ConversationId) (durable.ConversationHandle, error)
}

ToolBackend is the part of durable.ToolExecutionApi that reads or writes core state: the operations a tool call runs against the session. The session that owns the core supplies it per call; the executor supplies the rest (output, diagnostics, details, identity).

type ToolCall

type ToolCall struct {
	TaskID         durable.TaskId
	ConversationID durable.ConversationId
	CallID         string
	Name           string
}

ToolCall identifies one tool effect.

type Tools

type Tools struct {
	// Lookup returns the registration a tool call executes: the called tool among the conversation's resolved agent's tools (tool.ts call
	// phase), so a later same-name tool replaces an earlier one and wrappers apply. ok is false when the agent has no such tool.
	Lookup func(ctx context.Context, conversation durable.ConversationId, name string) (registration durable.ToolRegistration, ok bool, err error)
	// Backend returns the core-state operations for one call.
	Backend func(call ToolCall) ToolBackend
	// contains filtered or unexported fields
}

Tools runs tool effects: it finds the registration, gives it an api, and reports progress and the result to the core.

func (*Tools) Handler

func (t *Tools) Handler() sqlhost.Handler

Handler returns the sqlhost handler of tool effects.

type Tx

type Tx struct {

	// Current is the task record a transaction begun for an invocation read when it took the line (ready.current); nil
	// for a Session commit.
	Current json.RawMessage
	// contains filtered or unexported fields
}

Tx is one extension transaction: the Session line is held from Begin to End or Abort, across calls. Operations run one at a time.

func (*Tx) Abort

func (t *Tx) Abort(ctx context.Context, cause error) error

Abort rolls back: the callback failed with err.

func (*Tx) End

func (t *Tx) End(ctx context.Context, state any) error

End commits. state is the next task state that goes with the commit; nil sends none. It returns when the core answers {result: null}, at the end of the commit's job on the Session line (ABI section 5.3); a rejected step is Pi's rejection.

func (*Tx) Op

func (t *Tx) Op(ctx context.Context, op string, args map[string]any) (json.RawMessage, error)

Op runs one Tx operation and returns its `result`. A rejection is a *CoreError.

Jump to

Keyboard shortcuts

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