experimental

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 67 Imported by: 0

README

Experimental server, worker and client

This package ports Pi's src/experimental application: the coordinator, server, Session worker, client runtime, client TUI and command parser. Only the unshipped pig_experimental build of cmd/pig (see cmd/pig-experimental/README.md) dispatches it. The stable CLI never does.

Experimental Radius composition is designed out (D64). The server and client use native Unix sockets only. The explicit-gateway Radius relay library from experimental/radius-auth.ts and experimental/radius-relay.ts remains in this package with its ported tests; no application path selects it.

On Windows, EnsurePrivateServerDirectory and the client Unix transport reject startup as Pi does (no POSIX user ID; Unix transport is not supported on Windows). The coordinator itself uses AF_UNIX socket files on every platform.

Radius relay library

Selection and authentication

Supply the gateway explicitly to NewRadiusRelayAuthResolver. Supply either a token, a token file, or a lazy CreateRuntime callback. Configure that runtime without model-network refresh and with OAuth refresh directed to the selected gateway. Do not use the built-in Earendil Radius runtime as a substitute for a PiG-owned gateway (D64). The existing RequestAuthRuntime supports an explicit radius provider configuration with oauth: "radius" and the selected baseUrl. TestRadiusAuthRefreshesFiveMinuteCredentialAtLocalGateway exercises that composition against a local gateway.

The resolver checks context cancellation before PI_OFFLINE presence. Offline mode performs no token-file or runtime access. The resolver trims explicit tokens using JavaScript whitespace semantics and reads a token file anew for every attempt. The resolver creates a stored-auth runtime once and resolves credentials anew for every attempt. Stored OAuth requires five minutes of remaining validity, including after refresh.

Ownership and async contract

RadiusRelayHost.Start owns one reconnect loop. RadiusRelayHost.Close cancels and joins opening, serving, pending writes, and retry waits. The host accepts independent virtual connections in arrival order. Pong and unknown or rejected connection-close replies reserve their order and bytes immediately without waiting for socket writes. One owned writer drains control and data submissions in that order while the reader continues delivering inbound data, closes, and opens. Control-write failures close the socket with the transport-error code and report the failure on the reader. Shutdown rejects queued writes and joins the active write and all completion callbacks. A local virtual close writes its non-nil final chunk before its close control. A remote close or host failure reports one terminal callback per active connection in insertion order.

CreateRadiusClientTransportFactory awaits authentication and the WebSocket handshake. The returned transport delivers raw binary messages without the host multiplexing envelope. Send copies each submission and awaits its ordered write. Pending submissions share the upstream four-frame byte budget. Native socket writes provide backpressure instead of browser bufferedAmount polling. Close initiates local shutdown without synthesizing a remote callback. Wait on Done to join transport cleanup.

Callbacks execute on the transport reader, not the TUI loop. Do not wait for that reader's shutdown from its own callback. Marshal any UI mutation through the UI owner's executor.

RadiusClientReconnect observes an established client. It retries after one second, doubles failed-attempt delays to thirty seconds, and restores the last selected Session after reconnect succeeds. A disconnected attachment reset preserves the selection. An explicit detach while connected clears it. A failed reattachment disconnects the client and retries. Dispose removes listeners, cancels pending work, disconnects, and joins the retry loop.

Server selection

ResolveServerDirectory resolves an explicit value, then the selected environment override, then the server directory beside the agent tree. Default mode uses PIG_SERVER_DIR and the PiG configuration root's server directory. PIG_USE_PI_DIRS=1 uses PI_SERVER_DIR and ~/.pi/server instead (D2). The logical ID follows PIG_SERVER_ID or PI_SERVER_ID in the same selected namespace. Explicit empty values are retained; directory resolution and existing profile validation own their meaning.

RunServerProcess validates internal arguments and model JSON before startup, selects automatic lifetime policy, and waits for server closure. It registers one handler per termination signal after startup and joins shutdown before returning. The executable owns internal-role validation and consumption; this function does not consume the role marker. Parser failures preserve the fixed diagnostic and their syntax cause separately.

Plugin package selections

RestoreServerPluginPackageProfile persists normalized package selections for later server generations. A nil selection restores the saved value. An explicit empty selection removes the server profile. Session profiles distinguish an absent selection from an explicitly empty selection and bind the stored paths to the exact Session path. Profile files use Pi's existing version-1 JSON shape and mode 0600. These APIs only manage selections; they do not build or load JavaScript facet bundles or activate experimental command routing.

Automatic native activation

StartServer composes the native coordinator, worker manager, meta.json Session catalog, plugin selection/builds and Unix backend. RunningServer.Closed observes backend/catalog closure; Close also joins worker and coordinator cleanup. StartForegroundServer serializes that startup with automatic activation. No relay is opened (D64).

ActivateServer acquires the server profile and activation lock, connects to an existing endpoint, or spawns the internal server role and waits for its native handshake. Failed activation terminates and joins its child before releasing the lock. Worker manager/process APIs preserve model-option presence, generation demand, operation ownership and joined shutdown. RunSessionWorkerProcess runs the coding-Harness factory. The worker closes its resources on retirement, shutdown, disconnection, SIGTERM or SIGINT, and leaves its control socket to process exit, so the coordinator reports the disconnection only when the worker is exiting.

Command parsing

Cli.Parse parses the experimental server/client command group without reading configuration, opening a connection, or dispatching a process. Cli.Execute awaits the selected CliContext callback and returns its error on the same call. Unknown options stop the prefix parser and remain available to the command builder. Radius addresses and relay credential options are unsupported (D64).

Client application composition

OpenClientRuntime validates selection, discovers or activates local routes, and owns the real client and server/Session namespaces. Non-Unix routes are rejected before discovery (D64). Dispose marks the runtime disposed before joining source and client cleanup phases. A repeated or reentrant call returns immediately, matching Pi's disposed flag.

RunClient lists, creates or attaches Sessions through those services. A one-shot prompt returns the text that AgentController.WaitForPrompt settles with; a rejected prompt and an unanswered prompt are errors. Result variants are values: ClientListResult, ClientAttachedResult and ClientPromptedResult, with Kind() and the corresponding JSON fields.

Client service namespaces

NewClientServerServiceSource and NewClientSessionServiceSource adapt the real framed Client to the same structural Chord source contracts used by loopback presentations. An optional TransportClient decorator changes request/subscription behavior without fabricating connection or attachment state. Bindings use BeginReady and BeginRebind to preserve the synchronous admission/fencing prefix; each source owns and drains its continuation work.

ActivateBuiltinClientServices acquires Session directory/management/plugins and Models/controller/Transcript facades and waits for both namespaces. Management attach/detach/remove operations wait for the matching attachment hydration transition before returning. These APIs do not open or discover servers by themselves.

A selected AgentController view also exposes AgentControllerInitiator. Its Begin* methods resolve the current facet override and return only after that implementation admits the operation. Typed operations expose Wait(waitContext), with the same result decoding as an awaited call. Cancelling this observer does not replace or cancel the operation's original context. The nine upstream wire methods remain unchanged. An in-host provision reaches the view through the host's loopback binding; the provider forwards admission to an implementation that implements chord.ServiceMemberInitiator. A blocking local override without that boundary reports chord.ErrInvocationAdmissionUnavailable; the client TUI then awaits its blocking method as Pi awaits the returned Promise.

Server-owned facet builds

BundleFacets builds caller-selected opaque entries into a caller-selected output directory. Entries is an ordered []FacetEntrySource, not a Go map, because upstream record enumeration determines validation order. Repeated names retain their first position and last value. Integer property names enumerate first. Compilation then uses upstream's locale-sorted entry order. An omitted plugin version stays omitted. Direct builds default to no source maps.

BundleFacetPackage applies package metadata and caller-supplied DefaultFacets before invoking the same compiler. It returns the manifest paths and canonical package directory/package.json paths. It does not inject session or TUI conventions. Package source maps default to true and can be disabled in chord.sourceMap. The direct options currently expose the node22.19 default compiler configuration; optional minify, define, platform and target selection are not implemented.

CreateServerPluginPackage returns a serialized builder with ManifestPath and Build(ctx). It reads package metadata, applies the conventional src/session.ts and src/tui.ts entries, validates lexical and canonical package containment, and preserves configured overrides/disables. Builds use esbuild 0.28.2, the same Go compiler behind the pinned Pi JavaScript API. They emit content-addressed CommonJS entries, SHA-256 integrity, declared external imports, and source maps selected by package metadata. A successful build replaces the server-owned cache directory transactionally. The result contains the transportable TUI artifact, or an empty list when the package has no TUI entry.

Build waits for admitted compiler and filesystem work; Pi's builder has no AbortSignal. It does not evaluate JavaScript. Facet execution belongs to the separately selected Node extension host. These APIs do not enable experimental routing in the stable CLI.

Evidence

Run go test -race -count=3 ./internal/experimental. The suite includes the relevant pinned upstream relay cases, malformed controls and envelopes, token rotation, local OAuth refresh, a native WebSocket echo gateway, ordered bidirectional backpressure, reconnect selection, and cancellation/cleanup tests. TestPinnedUpstreamRadiusSource executes the actual pinned TypeScript modules with local dependency adapters and rejects implicit endpoints or live sockets. The compiler adapter uses the repository's existing TypeScript installation and installs nothing.

Run go test ./internal/experimental -run '^$' -bench 'Benchmark(RelayDataFrame|RadiusClientSend|RadiusHostControl)$' -benchmem to measure framing, client-send, and host-control allocation costs. These benchmarks do not claim a speedup or complete CLI/server parity. The server's accept adapter and the established client's reconnect adapter remain caller-owned library boundaries.

Documentation

Overview

Ports packages/coding-agent/src/experimental/client-tui.ts.

Ports packages/coding-agent/src/experimental/client-tui-chat.ts.

Ports packages/coding-agent/src/experimental/client-tui.ts.

Ports packages/coding-agent/src/experimental/plugins/package.ts.

Package experimental implements the opt-in local process transport used by Pi's experimental server.

Package experimental provides opt-in transports for the experimental Session runtime. It does not register CLI commands or select network endpoints.

Index

Constants

View Source
const (
	FacetBundleFormat                = "chord.facet-bundle"
	FacetBundleFormatVersion         = 2
	FacetBundleManifestFile          = "chord-facets.json"
	FacetBundleArtifactFormat        = "chord.facet-bundle-artifact"
	FacetBundleArtifactFormatVersion = 2
)

These format discriminators belong to the pinned upstream Chord schema.

View Source
const (
	EnvServerDir = "PIG_SERVER_DIR"
	EnvServerID  = "PIG_SERVER_ID"
)
View Source
const (
	SessionWorkerControlAddressEnv     = "PI_SESSION_WORKER_CONTROL_ADDRESS"
	SessionWorkerControlTokenEnv       = "PI_SESSION_WORKER_CONTROL_TOKEN"
	SessionWorkerSessionKeyEnv         = "PI_SESSION_WORKER_SESSION_KEY_BASE64"
	SessionWorkerPeerIDEnv             = "PI_SESSION_WORKER_PEER_ID"
	SessionWorkerInitialDemandGraceEnv = "__PI_SESSION_WORKER_INITIAL_DEMAND_GRACE_MS"
	SessionWorkerOrphanDemandGraceEnv  = "__PI_SESSION_WORKER_ORPHAN_DEMAND_GRACE_MS"
)
View Source
const CoordinatorProtocolVersion = 3

CoordinatorProtocolVersion is the exact upstream-owned coordinator wire version.

View Source
const EnvRadiusGateway = codingagent.EnvRadiusGateway

EnvRadiusGateway is the upstream experimental gateway override.

View Source
const InternalProcessEnv = "__PI_INTERNAL_SPAWN"
View Source
const MaxControlLineBytes = 128 * 1024 * 1024
View Source
const RadiusRelayClientSubprotocol = "pi-session-relay.client.v1"

RadiusRelayClientSubprotocol is the upstream raw client WebSocket protocol.

View Source
const RadiusRelayHostSubprotocol = "pi-session-relay.host.v1"

RadiusRelayHostSubprotocol is the upstream multiplexed host WebSocket protocol.

Variables

View Source
var Cli = createCli()

Cli parses the development-only server/client group without consulting the stable CLI or environment.

Functions

func AcquireServerActivation

func AcquireServerActivation(ctx context.Context, directory, serverID string) (func() error, error)

AcquireServerActivation serializes cold activators independently of the launcher's profile lock.

func CreateFacetBundleArtifactLoader

func CreateFacetBundleArtifactLoader(options FacetBundleArtifactLoaderOptions) (chord.FacetLoader, error)

CreateFacetBundleArtifactLoader validates transported metadata and source integrity before creating an isolated loader.

func CreateFacetBundleLoader

func CreateFacetBundleLoader(options FacetBundleLoaderOptions) (chord.FacetLoader, error)

CreateFacetBundleLoader creates a reusable isolated loader. Each Load rereads the manifest and evaluates a fresh CommonJS generation inside the existing Node host.

func CreatePresentationFacetData

func CreatePresentationFacetData(artifacts []FacetBundleArtifact) chord.JsonValue

CreatePresentationFacetData preserves artifact order in the server-selected presentation payload. It does not build, load, or activate plugin code.

func CreatePresentationFacetLoaders

func CreatePresentationFacetLoaders(data chord.JsonValue) ([]chord.FacetLoader, error)

CreatePresentationFacetLoaders creates local loaders only for artifacts selected by the connected server. Validation completes before any plugin code is evaluated.

func CreateSessionPluginFacetLoader

func CreateSessionPluginFacetLoader(manifestPaths []string) (chord.FacetLoader, error)

CreateSessionPluginFacetLoader preserves manifest order and returns nil for an empty selection. A selected package without a session entry contributes an empty loaded set.

func DeleteSession

func DeleteSession(metadata SessionCatalogMetadata) error

DeleteSession deletes a Session directory. Its worker must be closed first.

func EncodeControlLine

func EncodeControlLine(message any) (string, error)

EncodeControlLine encodes one value with JSON.stringify number, string and object-key semantics and a newline, enforcing Pi's UTF-8 byte limit including the delimiter.

func EncodeRelayDataFrame

func EncodeRelayDataFrame(connectionID string, payload []byte) ([]byte, error)

EncodeRelayDataFrame copies payload into the Radius version/type/UUID envelope.

func EnsurePrivateServerDirectory

func EnsurePrivateServerDirectory(directory string) error

EnsurePrivateServerDirectory rejects symlinks and foreign ownership before setting the Unix socket directory's private mode.

func IsSessionID

func IsSessionID(id string) bool

IsSessionID reports whether id is a valid Session ID and so a safe directory name.

func LiveOf

LiveOf is the pi.live document of a view: the active run, the streaming answer, and running tools. An absent document is an empty one.

func NormalizePluginPackagePaths

func NormalizePluginPackagePaths(packagePaths []string) ([]string, error)

NormalizePluginPackagePaths resolves paths against the current working directory, preserves order, and rejects empty or duplicate paths.

func ReadSessionPluginPackageProfile

func ReadSessionPluginPackageProfile(directory, serverId, sessionPath string) ([]string, error)

ReadSessionPluginPackageProfile reads the selection for one durable Session. Nil means the profile does not exist; an empty slice means an explicitly empty selection.

func RemoveSessionPluginPackageProfile

func RemoveSessionPluginPackageProfile(directory, serverId, sessionPath string) error

RemoveSessionPluginPackageProfile removes a deleted Session's selection. A missing file is already removed.

func ResolveServerDirectory

func ResolveServerDirectory(directory *string) (string, error)

ResolveServerDirectory resolves an explicit path, the selected server-directory override, or the server directory beside the selected agent tree. Explicit empty paths resolve to the current directory.

func ResolveSessionDirectory

func ResolveSessionDirectory(sessionDir *string) (string, error)

ResolveSessionDirectory uses the experimental storage directory under the selected agent directory by default. Explicit paths retain Pi's cwd-relative, tilde, and file-URL resolution.

func RestoreServerPluginPackageProfile

func RestoreServerPluginPackageProfile(directory, serverId string, configuredPackagePaths []string) ([]string, error)

RestoreServerPluginPackageProfile persists an explicit package selection or restores it for a later server generation. Nil means omitted; a non-nil empty slice deletes the server selection file and rejects a directory at that path.

func RunClientTui

func RunClientTui(ctx context.Context, command ClientCommand, options RunClientTuiOptions) (err error)

RunClientTui opens the native experimental runtime and its shared fullscreen presentation. The terminal pump, UI executor, selected facets, source bindings and ResourceLoader all have joined shutdown ownership.

func RunCoordinatorEntry

func RunCoordinatorEntry(ctx context.Context, args []string) error

RunCoordinatorEntry validates and consumes the internal role before starting the coordinator. An opt-in executable calls this entry explicitly; importing the package never changes CLI dispatch.

func RunCoordinatorProcess

func RunCoordinatorProcess(ctx context.Context, args []string) error

RunCoordinatorProcess serves the stable endpoint until shutdown, cancellation or the empty grace period. Unlike Node's process-owned event loop, Go explicitly joins the owned socket work before returning.

func RunDurableTui

func RunDurableTui(ctx context.Context, source durableagent.DurableViewSource, controller durableagent.DurableController, settings *codingagent.SettingsManager) (err error)

RunDurableTui shows source's view and sends the user's input to controller until the user exits. The theme is pi's: the theme setting, also light and dark pairs, resolved against the terminal's colors.

func RunServerProcess

func RunServerProcess(ctx context.Context, args []string) (err error)

RunServerProcess runs an automatically activated server until its lifetime ends, a termination signal arrives, or the caller cancels. The executable owns internal-role validation; this function owns startup and joined shutdown.

func RunSessionWorkerProcess

func RunSessionWorkerProcess(ctx context.Context, args []string) error

RunSessionWorkerProcess runs the real coding Harness factory through the worker's owned control and resource lifetime. The executable validates and consumes the internal role before calling it.

func RunSessionWorkerWithHarness

func RunSessionWorkerWithHarness(ctx context.Context, args []string, createHarness CreateSessionWorkerHarness) (result error)

RunSessionWorkerWithHarness owns the child-process event loop until retirement, shutdown, disconnection, or cancellation. It joins the worker's resources before returning and leaves the control socket to process exit; call it only from a process entry that exits after it returns.

func SessionStoragePath

func SessionStoragePath(metadata SessionCatalogMetadata) string

SessionStoragePath is the durable storage file of a Session. Only the Session's worker opens it.

func TerminateInternalProcess

func TerminateInternalProcess(child *InternalProcess) error

TerminateInternalProcess forces a child to exit and waits until it can no longer take ownership. A nonzero exit status is expected after a kill and is available separately through Wait.

func WriteSessionPluginPackageProfile

func WriteSessionPluginPackageProfile(directory, serverId, sessionPath string, packagePaths []string) error

WriteSessionPluginPackageProfile persists normalized package paths for one Session, including an explicitly empty selection.

Types

type ActivateServerOptions

type ActivateServerOptions struct {
	Directory         string
	RequestedServerId *string
	SessionDir        string
	Provider          *string
	Model             *string
}

ActivateServerOptions selects a logical server and startup-only worker model. Nil requested identity uses the directory's persisted default identity.

type ActivatedClientRuntimeServer

type ActivatedClientRuntimeServer struct {
	*ClientRuntimeServer
	Directory  services.SessionDirectory
	Management services.SessionManagement
	Plugins    services.PresentationPlugins
	Models     services.Models
	Agent      services.AgentController
	Transcript services.Transcript
}

ActivatedClientRuntimeServer holds the built-in service views used by a non-interactive presentation.

func ActivateBuiltinClientServices

func ActivateBuiltinClientServices(_ context.Context, server *ClientRuntimeServer) (*ActivatedClientRuntimeServer, error)

ActivateBuiltinClientServices acquires the actual remote service facades and waits for both namespaces to hydrate. As upstream's context-free activation does, initial readiness uses the background context; subsequent operations retain their caller context.

type ActivatedServer

type ActivatedServer struct {
	Client *client.Client
	Route  client.UnixServerRoute
}

ActivatedServer owns a connected client and the stable logical server route it reached.

func ActivateServer

func ActivateServer(ctx context.Context, options ActivateServerOptions) (activated *ActivatedServer, err error)

ActivateServer serializes cold activation with other activators and foreground startup. It returns only after a real client handshake; failed activation terminates and joins its child.

type AuthInput

type AuthInput struct {
	Type  string
	Token string
	Path  string
}

AuthInput selects an explicit token or a token file. Nil selects stored credentials.

type BundleFacetPackageOptions

type BundleFacetPackageOptions struct {
	PackagePath   string
	Outdir        string
	DefaultFacets []FacetEntrySource
}

BundleFacetPackageOptions selects a directory or package.json and application-provided conventional entries. Nil defaults select no conventional entries.

type BundleFacetPackageResult

type BundleFacetPackageResult struct {
	BundleFacetsResult
	PackageDirectory string
	PackageJsonPath  string
}

BundleFacetPackageResult includes the canonical package paths used to read metadata and resolve entries.

func BundleFacetPackage

func BundleFacetPackage(ctx context.Context, options BundleFacetPackageOptions) (BundleFacetPackageResult, error)

BundleFacetPackage applies metadata and caller conventions before invoking the shared compiler. Package source maps default to true unless chord.sourceMap disables them. The call waits for all compiler/filesystem work; upstream supplies no cancellation signal.

type BundleFacetsOptions

type BundleFacetsOptions struct {
	Plugin           FacetBundlePlugin
	Entries          []FacetEntrySource
	Outdir           string
	WorkingDirectory *string
	External         []string
	SourceMap        bool
}

BundleFacetsOptions selects independent entries and their output directory. A nil plugin version stays omitted; SourceMap defaults to false. WorkingDirectory defaults to the current directory.

type BundleFacetsResult

type BundleFacetsResult struct {
	Manifest     FacetBundleManifest
	ManifestPath string
}

BundleFacetsResult owns the manifest data and the absolute path of its installed manifest file.

func BundleFacets

func BundleFacets(_ context.Context, options BundleFacetsOptions) (result BundleFacetsResult, err error)

BundleFacets builds opaque entries with the same compiler and transactional output replacement used by server packages. It waits for completion even if ctx is cancelled because upstream has no cancellation signal.

type CliContext

type CliContext struct {
	RunServer func(context.Context, ServerCommand) error
	RunClient func(context.Context, ClientCommand) error
}

CliContext supplies the two awaited experimental command actions. Each action owns its work until it returns.

type ClientAttachedResult

type ClientAttachedResult struct {
	ServerId  string `json:"serverId"`
	SessionId string `json:"sessionId"`
}

func (ClientAttachedResult) Kind

func (ClientAttachedResult) MarshalJSON

func (result ClientAttachedResult) MarshalJSON() ([]byte, error)

type ClientCommand

type ClientCommand struct {
	Command        string
	Connect        *TransportAddress
	SessionId      *string
	Continue       *bool
	Resume         *bool
	Provider       *string
	Model          *string
	PluginPackages []string
	Prompt         *string
}

ClientCommand preserves absent selections as nil, including absent versus explicitly empty PluginPackages.

type ClientListResult

type ClientListResult struct {
	Sessions []services.SessionAddress `json:"sessions"`
}

func (ClientListResult) Kind

func (ClientListResult) Kind() string

func (ClientListResult) MarshalJSON

func (result ClientListResult) MarshalJSON() ([]byte, error)

type ClientPromptedResult

type ClientPromptedResult struct {
	ServerId  string `json:"serverId"`
	SessionId string `json:"sessionId"`
	Text      string `json:"text"`
}

func (ClientPromptedResult) Kind

func (ClientPromptedResult) MarshalJSON

func (result ClientPromptedResult) MarshalJSON() ([]byte, error)

type ClientResult

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

ClientResult is the closed list/attached/prompted result union. Go names the upstream anonymous variants so callers cannot confuse absent fields with zero values.

func RunClient

func RunClient(ctx context.Context, command ClientCommand, options RunClientOptions) (result ClientResult, err error)

RunClient discovers servers, then lists, attaches or creates a Session and runs a one-shot prompt. ctx owns initial opening; service operations retain upstream's Background Context. A prompt returns the answer's text once AgentController.WaitForPrompt settles.

type ClientRuntime

type ClientRuntime struct {
	Servers []*ClientRuntimeServer
	// contains filtered or unexported fields
}

ClientRuntime owns the live Unix client and service namespaces for one presentation. Dispose joins sources before transport lifetimes.

func OpenClientRuntime

func OpenClientRuntime(ctx context.Context, command ClientCommand, options OpenClientRuntimeOptions) (_ *ClientRuntime, err error)

OpenClientRuntime validates selection, discovers or activates local servers, and opens real server/Session sources. Startup failures close all previously acquired resources before returning.

func (*ClientRuntime) Dispose

func (runtime *ClientRuntime) Dispose() error

Dispose marks the runtime disposed before starting cleanup. The first caller joins every cleanup phase; subsequent or reentrant callers return immediately, as upstream's disposed flag does.

type ClientRuntimeRoute

type ClientRuntimeRoute struct {
	Transport string  `json:"transport"`
	ServerId  string  `json:"serverId"`
	Path      *string `json:"path,omitempty"`
}

ClientRuntimeRoute is a selected Unix route with its socket path and logical server ID.

type ClientRuntimeServer

type ClientRuntimeServer struct {
	Route   ClientRuntimeRoute
	Client  *client.Client
	Server  ServerServiceSource
	Session SessionServiceSource
}

ClientRuntimeServer owns one connected client and its server/Session service namespaces.

type ClientServerServiceSource

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

ClientServerServiceSource adapts the real client to the structural source consumed by presentations and FacetHost.

func NewClientServerServiceSource

func NewClientServerServiceSource(peer *client.Client, options ClientServiceSourceOptions) (result *ClientServerServiceSource, err error)

func (*ClientServerServiceSource) AcceptsUnavailableServices

func (source *ClientServerServiceSource) AcceptsUnavailableServices() bool

func (*ClientServerServiceSource) Catalogue

func (*ClientServerServiceSource) Connection

func (*ClientServerServiceSource) Dispose

func (source *ClientServerServiceSource) Dispose(ctx context.Context) error

func (*ClientServerServiceSource) Open

type ClientServiceSourceOptions

type ClientServiceSourceOptions struct {
	OnError         func(error)
	TransportClient client.ServiceTransportClient
}

ClientServiceSourceOptions selects an error sink and an optional request/subscription decorator. Lifecycle state always belongs to the original client.

type ClientSessionServiceSource

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

ClientSessionServiceSource retains attachment generation fencing while adapting the real client to a structural Chord source.

func NewClientSessionServiceSource

func NewClientSessionServiceSource(peer *client.Client, options ClientServiceSourceOptions) (result *ClientSessionServiceSource, err error)

func (*ClientSessionServiceSource) AcceptsUnavailableServices

func (source *ClientSessionServiceSource) AcceptsUnavailableServices() bool

func (*ClientSessionServiceSource) Attachment

func (*ClientSessionServiceSource) Catalogue

func (*ClientSessionServiceSource) Dispose

func (source *ClientSessionServiceSource) Dispose(ctx context.Context) error

func (*ClientSessionServiceSource) Open

func (*ClientSessionServiceSource) WhenAttached

func (source *ClientSessionServiceSource) WhenAttached(ctx context.Context, id string) error

func (*ClientSessionServiceSource) WhenDetached

func (source *ClientSessionServiceSource) WhenDetached(ctx context.Context) error

type ClientTuiExecutor

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

ClientTuiExecutor serializes input, render and UI mutations for one experimental presentation. Operations admitted by RunOnMain finish before it returns. RPC and plugin operations run outside this executor. Close runs off-loop after the component has closed.

func NewClientTuiExecutor

func NewClientTuiExecutor() *ClientTuiExecutor

NewClientTuiExecutor starts the presentation's owner loop. The caller owns Close; the loop stays alive during component cleanup.

func (*ClientTuiExecutor) Close

func (executor *ClientTuiExecutor) Close()

Close stops accepting UI mutations and joins the owner loop. Repeated calls wait for the same completion. Call Close only after component cleanup has released all UI work.

func (*ClientTuiExecutor) QueueMicrotask

func (executor *ClientTuiExecutor) QueueMicrotask(ctx context.Context, apply func()) error

QueueMicrotask appends a fast owner-loop continuation to the current turn's FIFO checkpoint. Nested enqueue joins the same checkpoint. Remote work must be started off-loop; its completion posts another turn.

func (*ClientTuiExecutor) RunOnMain

func (executor *ClientTuiExecutor) RunOnMain(ctx context.Context, apply func()) error

RunOnMain waits for a mutation and its FIFO microtask checkpoint to finish on the owner loop. A call made on the owner executes inline without draining microtasks. Cancellation before admission does not execute the mutation; an admitted callback completes before returning.

type ClientTuiServer

type ClientTuiServer struct {
	ServerId string
	Radius   bool
	Server   ServerServiceSource
	Session  SessionServiceSource
}

ClientTuiServer identifies a server and its independently scoped service sources. Radius enables connection recovery presentation.

type Command

type Command struct {
	Name string
	// contains filtered or unexported fields
}

Command composes options, a builder, an awaited action, and subcommands. Configuration completes before concurrent parsing or execution.

func NewCommand

func NewCommand(name string) *Command

func (*Command) Action

func (*Command) Build

func (c *Command) Build(builder func(ParsedCommandInput) CommandParseResult) *Command

func (*Command) Command

func (c *Command) Command(command *Command) error

func (*Command) Execute

func (c *Command) Execute(ctx context.Context, argv []string, commandContext CliContext) (CommandExecutionResult, error)

Execute waits for the selected action and returns its errors on the same operation. Invalid input never invokes an action.

func (*Command) Option

func (c *Command) Option(option CommandOption) error

func (*Command) Parse

func (c *Command) Parse(argv []string) (CommandParseResult, error)

type CommandExecutionResult

type CommandExecutionResult = CommandParseResult

CommandExecutionResult has the same shape as a parse result; Execute returns only after the selected action completes.

type CommandOption

type CommandOption struct {
	Name       string
	Flag       bool
	Repeatable bool
	Parse      func(string) (any, error)
}

CommandOption describes a flag or a value option. Parse returns a CLI diagnostic on invalid input.

func FlagOption

func FlagOption(name string) CommandOption

func StringOption

func StringOption(name string, repeatable bool) CommandOption

func ValueOption

func ValueOption(name string, parse func(string) (any, error), repeatable bool) CommandOption

type CommandParseResult

type CommandParseResult struct {
	Ok      bool
	Command NamedCommandInvocation
	Errors  []string
}

CommandParseResult distinguishes CLI diagnostics from successful invocations. Go errors carry upstream exceptions, not option diagnostics.

type ConfiguredServerPluginPackage

type ConfiguredServerPluginPackage struct {
	ManifestPath string
	Build        func(context.Context) ([]FacetBundleArtifact, error)
}

ConfiguredServerPluginPackage is one serialized server-owned builder. Build waits for the complete compiler/filesystem operation, as upstream's context-free Promise does. It never evaluates plugin JavaScript.

func CreateServerPluginPackage

func CreateServerPluginPackage(directory, serverId, packagePath string) (*ConfiguredServerPluginPackage, error)

CreateServerPluginPackage derives the server-owned cache path without building or loading the package.

type CoordinatorConnection

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

CoordinatorConnection is the server-side endpoint of the coordinator's opaque message router. Event callbacks run in receive order, outside the state lock. They may send, close or unsubscribe.

func NewCoordinatorConnection

func NewCoordinatorConnection(options CoordinatorConnectionOptions) *CoordinatorConnection

NewCoordinatorConnection creates an unconnected server generation with a random ID when none is supplied.

func (*CoordinatorConnection) Broadcast

func (c *CoordinatorConnection) Broadcast(payload any) error

Broadcast writes a payload to every connected peer after registration.

func (*CoordinatorConnection) Close

func (c *CoordinatorConnection) Close()

Close destroys the socket and clears membership without marking an intentional close as replacement.

func (*CoordinatorConnection) Connect

func (c *CoordinatorConnection) Connect(ctx context.Context) error

Connect waits for a validated registration. Cancellation closes the pending connection.

func (*CoordinatorConnection) ControlPath

func (c *CoordinatorConnection) ControlPath() string

func (*CoordinatorConnection) OnEvent

func (c *CoordinatorConnection) OnEvent(listener *CoordinatorConnectionListener) func()

OnEvent adds a listener reference once, in insertion order. Each cleanup removes that reference, including any later re-registration.

func (*CoordinatorConnection) PeerIDs

func (c *CoordinatorConnection) PeerIDs() []string

PeerIDs returns a detached snapshot in the coordinator's insertion order.

func (*CoordinatorConnection) Replaced

func (c *CoordinatorConnection) Replaced() <-chan struct{}

Replaced closes once on replacement or an unexpected disconnect, but not on an explicit Close.

func (*CoordinatorConnection) Send

func (c *CoordinatorConnection) Send(peerID string, payload any) error

Send writes a payload to a named peer after registration and waits for the socket write.

func (*CoordinatorConnection) ServerConnectionID

func (c *CoordinatorConnection) ServerConnectionID() string

func (*CoordinatorConnection) WasReplaced

func (c *CoordinatorConnection) WasReplaced() bool

type CoordinatorConnectionEvent

type CoordinatorConnectionEvent struct {
	Type    string
	PeerID  string
	From    string
	Payload json.RawMessage
}

CoordinatorConnectionEvent carries peer membership changes or an opaque routed payload. A nil Payload means absent; json.RawMessage("null") is an explicit JSON null.

type CoordinatorConnectionListener

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

CoordinatorConnectionListener is a callback with stable reference identity. Go functions cannot be compared; OnEvent identifies listeners by this pointer instead.

func NewCoordinatorConnectionListener

func NewCoordinatorConnectionListener(listener func(CoordinatorConnectionEvent)) *CoordinatorConnectionListener

NewCoordinatorConnectionListener creates a listener reference. Reuse it to register the same callback again.

type CoordinatorConnectionOptions

type CoordinatorConnectionOptions struct {
	ControlPath        string
	Endpoint           string
	ServerConnectionID *string
}

CoordinatorConnectionOptions identifies this server generation and its private forwarding endpoint.

type CoordinatorStartupLease

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

CoordinatorStartupLease keeps an unregistered control connection alive while a server starts.

func EnsureCoordinator

func EnsureCoordinator(ctx context.Context, publicPath, controlPath string, options ...InternalProcessSpawnOptions) (*CoordinatorStartupLease, error)

EnsureCoordinator connects to an existing router or launches one and waits for its control endpoint. The optional native spawn options select an explicit opt-in entry executable, without changing Stock CLI dispatch.

func (*CoordinatorStartupLease) Close

func (lease *CoordinatorStartupLease) Close()

Close releases startup demand. It does not stop a coordinator that has other demand.

type CreateSessionOptions

type CreateSessionOptions struct {
	ID  *string
	Cwd string
}

CreateSessionOptions selects the new Session's ID, which defaults to a random UUID, and its working directory.

type CreateSessionWorkerHarness

type CreateSessionWorkerHarness func(ctx context.Context, databasePath string, options SessionWorkerOptions) (SessionWorkerRuntime, error)

CreateSessionWorkerHarness opens the Session's Harness over databasePath and returns it with its root conversation. It runs while the worker holds the Session lock; on failure it closes whatever it opened.

type ExperimentalChatView

type ExperimentalChatView struct {
	Transcript      *tui.Container
	PendingMessages *tui.Container
	Status          *tui.Container
	// contains filtered or unexported fields
}

ExperimentalChatView renders the root conversation's durable view for the service-only experimental presentation. Apply and RefreshTheme run on the presentation owner loop. After detaching the view from that loop, Dispose cancels and joins its timers, image conversions and tool-renderer work.

func NewExperimentalChatView

func NewExperimentalChatView(ctx context.Context, cwd string, requestRender func(), runOnMain func(context.Context, func()) error) *ExperimentalChatView

NewExperimentalChatView creates the native message and tool containers without reading Session history.

func (*ExperimentalChatView) Apply

func (view *ExperimentalChatView) Apply(conversation services.ConversationView) error

Apply appends new entries, reuses streaming assistant/tool components, replaces the queue, and tracks the status line. Only a changed entry-ID prefix, or a streaming answer whose partial disappeared, rebuilds the retained transcript.

func (*ExperimentalChatView) Dispose

func (view *ExperimentalChatView) Dispose() error

Dispose joins background work after the caller has detached all view callbacks and rendering. Repeated calls return the same result.

func (*ExperimentalChatView) RefreshTheme

func (view *ExperimentalChatView) RefreshTheme(conversation services.ConversationView) error

RefreshTheme replaces themed components while retaining the supplied view as the single source of transcript state.

type ExperimentalClientTui

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

ExperimentalClientTui presents one attached Session through Chord services. UI methods run on the supplied owner executor; admitted transport operations and facet lifecycle operations are owned background work joined by Close, while a selected service call without an admission boundary keeps running on the background Context after Close, as in Pi.

func CreateExperimentalClientTui

func CreateExperimentalClientTui(ctx context.Context, options ExperimentalClientTuiOptions) (*ExperimentalClientTui, error)

CreateExperimentalClientTui prepares/attaches the selected Session, loads shared and selected facets, and opens the replicated transcript before returning. Command service calls retain context.Background; ctx owns facet startup and UI observation. Startup failure closes every acquired presentation resource.

func (*ExperimentalClientTui) Close

func (component *ExperimentalClientTui) Close() error

Close marks the UI closed, cancels pending selection and UI observation, joins recovery/reload/workers, detaches the lane and disposes facets. The owner executor must remain alive until this off-loop call returns.

func (*ExperimentalClientTui) HandleInput

func (component *ExperimentalClientTui) HandleInput(data string)

func (*ExperimentalClientTui) Invalidate

func (component *ExperimentalClientTui) Invalidate()

func (*ExperimentalClientTui) LayoutRoot

func (component *ExperimentalClientTui) LayoutRoot() tui.Component

LayoutRoot supplies the shared fullscreen transcript/dock layout.

func (*ExperimentalClientTui) RefreshTheme

func (component *ExperimentalClientTui) RefreshTheme()

func (*ExperimentalClientTui) Render

func (component *ExperimentalClientTui) Render(width int) []string

func (*ExperimentalClientTui) ShowError

func (component *ExperimentalClientTui) ShowError(message string)

type ExperimentalClientTuiOptions

type ExperimentalClientTuiOptions struct {
	Command        ClientCommand
	UI             tui.Renderer
	Servers        []ClientTuiServer
	FacetLoader    chord.FacetLoader
	RequestRender  func()
	Finish         func()
	RunOnMain      func(context.Context, func()) error
	QueueMicrotask func(context.Context, func()) error
}

ExperimentalClientTuiOptions supplies presentation services and one UI owner executor. RunOnMain completes a top-level turn after its FIFO QueueMicrotask checkpoint; owner reentry executes inline without draining. Create and Close run off-loop; Render and HandleInput run on-loop. Keep the executor alive until Close completes.

type FacetBundleArtifact

type FacetBundleArtifact struct {
	Format            string            `json:"format"`
	FormatVersion     int               `json:"formatVersion"`
	Plugin            FacetBundlePlugin `json:"plugin"`
	EntryName         string            `json:"entryName"`
	Entry             FacetBundleEntry  `json:"entry"`
	Source            string            `json:"source"`
	SourceMapContents *string           `json:"sourceMapContents,omitempty"`
}

FacetBundleArtifact is one self-contained entry transported to a Node host. Optional string pointers preserve omission separately from an explicit empty string.

func ReadFacetBundleArtifact

func ReadFacetBundleArtifact(options FacetBundleArtifactReadOptions) (FacetBundleArtifact, error)

ReadFacetBundleArtifact reads one transportable entry and verifies its SHA-256 integrity before returning it. Integrity covers the UTF-8 encoding of the decoded source, as in Node; an optional source map is read as text but is not itself hashed.

type FacetBundleArtifactLoaderOptions

type FacetBundleArtifactLoaderOptions struct {
	Artifact           chord.JsonValue
	TemporaryDirectory string
	ResolveExternal    FacetBundleExternalResolver
}

FacetBundleArtifactLoaderOptions selects a transported entry and its optional materialization parent.

type FacetBundleArtifactReadOptions

type FacetBundleArtifactReadOptions struct {
	ManifestPath string
	Entry        string
}

FacetBundleArtifactReadOptions selects one opaque entry from a manifest on disk.

type FacetBundleEntry

type FacetBundleEntry struct {
	File            string   `json:"file"`
	Integrity       string   `json:"integrity"`
	ExternalImports []string `json:"externalImports"`
	SourceMap       *string  `json:"sourceMap,omitempty"`
}

FacetBundleEntry names one content-addressed CommonJS entry and its declared external imports.

type FacetBundleExternalResolver

type FacetBundleExternalResolver func(string) (string, bool, error)

FacetBundleExternalResolver resolves one declared external import. A false result leaves resolution to the pinned Node loader; errors propagate before evaluation.

type FacetBundleLoaderOptions

type FacetBundleLoaderOptions struct {
	ManifestPath    string
	Entry           string
	VerifyIntegrity *bool
	ResolveExternal FacetBundleExternalResolver
}

FacetBundleLoaderOptions selects an opaque bundle entry. ResolveExternal maps selected external imports to host module paths or file URLs. Nil VerifyIntegrity verifies the source.

type FacetBundleManifest

type FacetBundleManifest struct {
	Format        string                      `json:"format"`
	FormatVersion int                         `json:"formatVersion"`
	Plugin        FacetBundlePlugin           `json:"plugin"`
	Entries       map[string]FacetBundleEntry `json:"entries"`
}

FacetBundleManifest describes the server-owned bundle entries. The builder owns entry ordering in the manifest file.

func ReadFacetBundleManifest

func ReadFacetBundleManifest(path string) (FacetBundleManifest, error)

ReadFacetBundleManifest reads and validates the pinned Chord manifest shape without evaluating its entries. Relative paths resolve against the working directory; read and JSON syntax failures retain their cause. Optional null fields are invalid rather than absent.

type FacetBundlePlugin

type FacetBundlePlugin struct {
	Id      string  `json:"id"`
	Version *string `json:"version,omitempty"`
}

FacetBundlePlugin identifies the selected plugin content.

func (FacetBundlePlugin) MarshalJSON

func (plugin FacetBundlePlugin) MarshalJSON() ([]byte, error)

MarshalJSON preserves the JavaScript identity strings, including lone UTF-16 units, until the receiving wire codec validates them.

type FacetEntrySource

type FacetEntrySource struct {
	Name   string
	Source string
}

FacetEntrySource retains the order of an upstream string-valued record. Repeated names overwrite their value without moving the first property; integer names enumerate before other names, as in Object.entries.

type InternalProcess

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

InternalProcess owns the child's exit observation and reaps it exactly once. A detached child may outlive its launcher. Done closes only after Wait has reaped it.

func SpawnInternalProcess

func SpawnInternalProcess(role InternalProcessRole, args []string, options InternalProcessSpawnOptions) (*InternalProcess, error)

SpawnInternalProcess starts a detached native role with ignored stdio and the current working directory. The caller must select an executable that explicitly dispatches internal roles. Stock CLI dispatch is unchanged.

func (*InternalProcess) Done

func (p *InternalProcess) Done() <-chan struct{}

Done closes when the child can no longer take ownership of a socket or session.

func (*InternalProcess) PID

func (p *InternalProcess) PID() int

PID returns the spawned process ID.

func (*InternalProcess) ProcessState

func (p *InternalProcess) ProcessState() *os.ProcessState

ProcessState returns nil while the process runs and its final state after it exits.

func (*InternalProcess) Wait

func (p *InternalProcess) Wait() error

Wait joins exit observation and returns the child's exit error, if any.

type InternalProcessRole

type InternalProcessRole string

InternalProcessRole selects an internal entrypoint, not a public CLI command.

func ConsumeInternalProcessRole

func ConsumeInternalProcessRole() (InternalProcessRole, error)

ConsumeInternalProcessRole validates before removing the role so descendants cannot inherit it.

func GetInternalProcessRole

func GetInternalProcessRole() (InternalProcessRole, error)

GetInternalProcessRole reads and validates the role without consuming it.

type InternalProcessSpawnOptions

type InternalProcessSpawnOptions struct {
	EntryPath string
	Env       map[string]string
}

InternalProcessSpawnOptions supplies an optional native entry executable and environment overrides. EntryPath is the native counterpart of a source module URL; an empty path re-executes this executable.

type NamedCommandInvocation

type NamedCommandInvocation interface {
	// contains filtered or unexported methods
}

NamedCommandInvocation is the closed union of experimental CLI invocations.

type OpenClientRuntimeOptions

type OpenClientRuntimeOptions struct {
	Directory *string
}

OpenClientRuntimeOptions preserves an omitted search directory separately from an explicitly empty path.

type ParsedCommandInput

type ParsedCommandInput struct {
	RemainingArgs []string
	// contains filtered or unexported fields
}

ParsedCommandInput retains the first unrecognized argument and every argument after it, including a -- separator.

func (ParsedCommandInput) Value

func (p ParsedCommandInput) Value(option CommandOption) any

func (ParsedCommandInput) Values

func (p ParsedCommandInput) Values(option CommandOption) []any

type RadiusClientAttachment

type RadiusClientAttachment struct{ SessionID string }

RadiusClientAttachment identifies the currently selected Session.

type RadiusClientByteTransport

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

RadiusClientByteTransport carries raw binary messages and reports one remote terminal event. Close initiates local shutdown; Done joins reads, writes, and cancellation cleanup.

func (*RadiusClientByteTransport) Close

func (t *RadiusClientByteTransport) Close()

Close initiates shutdown without emitting a remote terminal callback. It is safe in a data callback.

func (*RadiusClientByteTransport) Done

func (t *RadiusClientByteTransport) Done() <-chan struct{}

Done closes when every operation owned by this transport has finished.

func (*RadiusClientByteTransport) Send

func (t *RadiusClientByteTransport) Send(chunk []byte) error

Send copies and writes a chunk, in submission order, with bounded pending bytes.

type RadiusClientReconnect

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

RadiusClientReconnect reconnects an established client and restores its last selected Session. Dispose removes listeners, cancels, disconnects, and joins the retry loop.

func NewRadiusClientReconnect

func NewRadiusClientReconnect(ctx context.Context, client RadiusReconnectClient, reattach func(context.Context, string) error) *RadiusClientReconnect

NewRadiusClientReconnect observes an already established client; it does not initiate a connection until a disconnection event.

func (*RadiusClientReconnect) Dispose

func (r *RadiusClientReconnect) Dispose()

Dispose is idempotent and joins all retry and reattachment work.

type RadiusClientTransportFactory

type RadiusClientTransportFactory func(context.Context, RelayByteConnectionHandler) (*RadiusClientByteTransport, error)

RadiusClientTransportFactory resolves fresh credentials and connects one client byte stream. The context owns the resulting transport until Close.

func CreateRadiusClientTransportFactory

func CreateRadiusClientTransportFactory(options RadiusClientTransportOptions) RadiusClientTransportFactory

CreateRadiusClientTransportFactory creates an inert connection factory.

type RadiusClientTransportOptions

type RadiusClientTransportOptions struct {
	ServerID         string
	Auth             *RadiusRelayAuthResolver
	WebSocketFactory RadiusRelayWebSocketFactory
}

RadiusClientTransportOptions selects one authenticated raw client relay.

type RadiusReconnectClient

type RadiusReconnectClient interface {
	Attachment() *RadiusClientAttachment
	Connected() bool
	ConnectionState() string
	Disconnect(reason string)
	OnAttachmentChange(func(*RadiusClientAttachment)) func()
	OnConnectionStateChange(func(string)) func()
	Reconnect(context.Context) error
}

RadiusReconnectClient is the established-client contract used by the reconnect owner. Listener removers must be safe during notification; methods and listeners may run concurrently.

type RadiusRelayAuth

type RadiusRelayAuth struct {
	Gateway string
	Token   string
}

RadiusRelayAuth is one connection attempt's resolved credential.

type RadiusRelayAuthOptions

type RadiusRelayAuthOptions struct {
	Input         *AuthInput
	Gateway       string
	CreateRuntime func() (*codingagent.RequestAuthRuntime, error)
}

RadiusRelayAuthOptions requires an explicit gateway. CreateRuntime supplies the stored-auth runtime without model-network refresh; it is called once, lazily, only without Input. Its owner must configure OAuth refresh for its selected gateway.

type RadiusRelayAuthResolver

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

RadiusRelayAuthResolver rereads explicit or stored credentials for every connection attempt.

func NewRadiusRelayAuthResolver

func NewRadiusRelayAuthResolver(options RadiusRelayAuthOptions) (*RadiusRelayAuthResolver, error)

NewRadiusRelayAuthResolver creates an inert resolver. Gateway and the stored-auth runtime are caller-owned so construction cannot select a hosted service.

func (*RadiusRelayAuthResolver) Gateway

func (r *RadiusRelayAuthResolver) Gateway() string

Gateway returns the normalized gateway selected by the caller.

func (*RadiusRelayAuthResolver) Resolve

func (r *RadiusRelayAuthResolver) Resolve(ctx context.Context, required bool) (*RadiusRelayAuth, error)

Resolve checks cancellation, then PI_OFFLINE presence, before reading credentials. Required turns missing auth into an actionable error. Stored OAuth must have at least five minutes of validity.

type RadiusRelayHost

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

RadiusRelayHost owns a reconnecting, multiplexed host connection. Incoming controls enqueue ordered replies without waiting for socket writes. Close cancels and joins every owned operation.

func NewRadiusRelayHost

func NewRadiusRelayHost(options RadiusRelayHostOptions) (*RadiusRelayHost, error)

NewRadiusRelayHost validates the collaborators without starting work.

func (*RadiusRelayHost) Close

func (h *RadiusRelayHost) Close()

Close is idempotent and joins shutdown, including a pending authentication or opening attempt.

func (*RadiusRelayHost) Start

func (h *RadiusRelayHost) Start(ctx context.Context)

Start begins the owned reconnect loop once. The context owns its lifetime.

type RadiusRelayHostOptions

type RadiusRelayHostOptions struct {
	ServerID         string
	Accept           func(*RelayServerByteConnection) RelayByteConnectionHandler
	Auth             *RadiusRelayAuthResolver
	WebSocketFactory RadiusRelayWebSocketFactory
	OnStatus         func(RadiusRelayHostStatus)
}

RadiusRelayHostOptions binds the relay to a server's accept operation. No command or default endpoint is activated by construction.

type RadiusRelayHostStatus

type RadiusRelayHostStatus struct {
	Status string
	Error  string
}

RadiusRelayHostStatus reports authentication, connection, and retry transitions.

type RadiusRelayWebSocket

type RadiusRelayWebSocket interface {
	Protocol() string
	Read() (binary bool, data []byte, err error)
	Send(binary bool, data []byte) error
	Close(code int, reason string) error
}

RadiusRelayWebSocket is a connected transport. Read has one owner; Send is serialized by the relay. Close must unblock both and may run concurrently with them.

type RadiusRelayWebSocketFactory

type RadiusRelayWebSocketFactory func(context.Context, RadiusRelayWebSocketOptions) (RadiusRelayWebSocket, error)

RadiusRelayWebSocketFactory completes the opening handshake or returns its error. The context owns cancellation of the opening attempt.

type RadiusRelayWebSocketOptions

type RadiusRelayWebSocketOptions struct {
	URL           string
	Protocol      string
	Authorization string
}

RadiusRelayWebSocketOptions carries the exact URL, subprotocol, and bearer header for an attempt.

type RelayByteConnectionHandler

type RelayByteConnectionHandler struct {
	OnData  func([]byte)
	OnClose func()
	OnError func(error)
}

RelayByteConnectionHandler receives ordered data and exactly one terminal callback. Callbacks run on the host's reader, not the TUI loop; they must not wait for host shutdown.

type RelayDataFrame

type RelayDataFrame struct {
	ConnectionID string
	Payload      []byte
}

RelayDataFrame contains a validated lowercase UUIDv4 and an independently owned payload.

func ParseRelayDataFrame

func ParseRelayDataFrame(frame []byte) (RelayDataFrame, bool)

ParseRelayDataFrame validates the envelope and returns a copied payload, or false for malformed frames.

type RelayServerByteConnection

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

RelayServerByteConnection is one server-side virtual byte stream. Send and Close await ordered writes; a final chunk precedes its close control.

func (*RelayServerByteConnection) Close

func (c *RelayServerByteConnection) Close(finalChunk []byte) error

Close removes the connection once, then sends a non-nil final chunk before the close control. It does not synthesize a remote-close callback.

func (*RelayServerByteConnection) Closed

func (c *RelayServerByteConnection) Closed() bool

Closed reports local or remote terminal state.

func (*RelayServerByteConnection) Send

func (c *RelayServerByteConnection) Send(chunk []byte) error

Send sends one copied payload on this connection.

type RoutedSessionAttachment

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

RoutedSessionAttachment fences all service invocations to one server generation and acknowledged client attachment.

func (*RoutedSessionAttachment) InvokeService

func (*RoutedSessionAttachment) Release

func (a *RoutedSessionAttachment) Release(ctx context.Context) error

type RoutedSessionHandle

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

RoutedSessionHandle retains the worker generation selected by OpenSession.

func (*RoutedSessionHandle) AttachClient

func (*RoutedSessionHandle) Close

func (h *RoutedSessionHandle) Close(ctx context.Context) error

func (*RoutedSessionHandle) TerminalError

func (h *RoutedSessionHandle) TerminalError() error

func (*RoutedSessionHandle) Terminated

func (h *RoutedSessionHandle) Terminated() <-chan struct{}

type RunClientOptions

type RunClientOptions struct {
	Directory *string
}

RunClientOptions selects discovery. Directory defaults to PI_SERVER_DIR or ~/.pi/server.

type RunClientTuiOptions

type RunClientTuiOptions struct {
	OpenClientRuntimeOptions
	FacetLoader chord.FacetLoader
	// ThemePaths are the resolved theme resources of a DefaultResourceLoader without extensions, skills, prompt templates or context files, in precedence order.
	ThemePaths []string
}

RunClientTuiOptions selects discovery and optional shared presentation facets.

type RunningServer

type RunningServer struct {
	ServerId   string
	SocketPath string
	SessionDir string
	Server     *routing.Server
	// contains filtered or unexported fields
}

RunningServer owns one replaceable Unix server generation. Closed observes backend/catalog closure; Close also joins worker shutdown and coordinator cleanup.

func StartForegroundServer

func StartForegroundServer(ctx context.Context, options StartServerOptions) (runtime *RunningServer, err error)

StartForegroundServer holds an operator-owned generation while serializing with automatic cold activation.

func StartServer

func StartServer(ctx context.Context, options StartServerOptions) (runtime *RunningServer, err error)

StartServer starts a replaceable Unix server behind its stable coordinator endpoint. Startup owns its profile lock until service discovery and lifetime observation finish. No hosted relay is opened (D64).

func (*RunningServer) Close

func (server *RunningServer) Close() error

Close stops lifetime timers and joins the generation's cleanup once. Replaced generations detach without stopping workers adopted by their replacement.

func (*RunningServer) Closed

func (server *RunningServer) Closed() <-chan struct{}

func (*RunningServer) ClosedError

func (server *RunningServer) ClosedError() error

func (*RunningServer) WorkerPids

func (server *RunningServer) WorkerPids() map[string]int

type ServerCommand

type ServerCommand struct {
	Command        string
	Provider       *string
	Model          *string
	PluginPackages []string
	ServerId       *string
	SessionDir     *string
}

ServerCommand contains the server options before runtime defaults are applied.

type ServerLifetime

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

ServerLifetime reconciles operator, startup, client, and worker holds for one server generation. The idle timer commits retirement (the lifetime stops) atomically with its eligibility check. The retire callback then runs outside the state lock and may stop the lifetime again.

func NewServerLifetime

func NewServerLifetime(keepAlive bool) *ServerLifetime

func (*ServerLifetime) SetConnectionCount

func (l *ServerLifetime) SetConnectionCount(count int)

func (*ServerLifetime) SetWorkerCount

func (l *ServerLifetime) SetWorkerCount(count int)

func (*ServerLifetime) SetWorkerCountSource

func (l *ServerLifetime) SetWorkerCountSource(source func() int)

SetWorkerCountSource names the live worker registry. The retirement check reads it under the lifetime lock. Upstream runs a worker-count change and the idle timer callback on one event loop, so a registered worker is never invisible to the check (server.ts:303-317, session-worker-manager.ts:699-703,810-812). Go delivers SetWorkerCount from other goroutines; a delayed delivery must not let the timer retire a generation that already has a worker.

func (*ServerLifetime) Start

func (l *ServerLifetime) Start(retire func())

func (*ServerLifetime) Stop

func (l *ServerLifetime) Stop()

type ServerProfile

type ServerProfile struct {
	ServerID string
	// contains filtered or unexported fields
}

ServerProfile owns the launcher lock for one persistent logical server identity.

func AcquireServerProfile

func AcquireServerProfile(ctx context.Context, directory string, requestedServerID *string) (*ServerProfile, error)

AcquireServerProfile serializes launchers of the same ID. Nil requestedServerID selects or atomically creates the directory's default identity.

func (*ServerProfile) Release

func (p *ServerProfile) Release() error

Release releases the launcher lock once; a second call fails like proper-lockfile's release.

type ServerServiceSource

type ServerServiceSource interface {
	chord.RemoteServiceSource
	Connection() chord.ReplicatedStateOf[*services.ServerConnectionState]
	Dispose(context.Context) error
}

ServerServiceSource supplies server services and their replicated connection state. Both network and loopback presentations use this contract.

type SessionCatalogMetadata

type SessionCatalogMetadata struct {
	ID        string  `json:"id"`
	CreatedAt float64 `json:"createdAt"`
	Cwd       string  `json:"cwd"`
	Path      string  `json:"path"`
}

SessionCatalogMetadata identifies one server-hosted Session: a directory holding meta.json and the worker-owned session.sqlite. It is also the StrictObject SessionWorkerMetadataSchema (session-worker.ts:69-74) that the manager sends in launch options and the worker echoes in worker_ready. CreatedAt is a JavaScript number, so any finite JSON number is valid. Cwd is the working directory the Session's agent runs in; Path is the Session directory, which workers lock and whose storage they own. upstream: packages/coding-agent/src/experimental/session-catalog.ts:SessionCatalogMetadata

func CreateSession

func CreateSession(sessionDir string, options CreateSessionOptions) (SessionCatalogMetadata, error)

CreateSession creates an empty Session. Its worker creates the storage on first open. A Session that already exists is an error.

func ListSessions

func ListSessions(sessionDir string) ([]SessionCatalogMetadata, error)

ListSessions returns every Session in the directory. An absent directory has none, and an entry without valid metadata is skipped.

func ReadSession

func ReadSession(sessionDir, id string) *SessionCatalogMetadata

ReadSession returns one Session by ID, or nil when its ID or its meta.json is invalid or absent. A metadata file that cannot be read or parsed is the same as an absent one, as in Pi.

func (SessionCatalogMetadata) SessionID

func (metadata SessionCatalogMetadata) SessionID() string

SessionID is the Session's ID, as routing's SessionMetadata requires.

type SessionPluginSelectionConflictError

type SessionPluginSelectionConflictError struct{ Message string }

SessionPluginSelectionConflictError rejects changing the plugin selection of a running or starting Session.

func (*SessionPluginSelectionConflictError) Error

type SessionServiceSource

type SessionServiceSource interface {
	chord.RemoteServiceSource
	Attachment() chord.ReplicatedStateOf[*services.SessionAttachmentState]
	WhenAttached(context.Context, string) error
	WhenDetached(context.Context) error
	Dispose(context.Context) error
}

SessionServiceSource supplies the selected attachment's services. Readiness waits are fenced to the requested Session generation by the source implementation.

type SessionWorkerCoordinator

type SessionWorkerCoordinator interface {
	ControlPath() string
	ServerConnectionID() string
	WasReplaced() bool
	OnEvent(*CoordinatorConnectionListener) func()
	Send(string, any) error
	Broadcast(any) error
}

SessionWorkerCoordinator is the coordinator boundary consumed by one replaceable server's worker manager.

type SessionWorkerHarness

type SessionWorkerHarness interface {
	services.AgentHarness
	Close(context.Context) error
	// TaskGraph observes the Harness's live tasks.
	TaskGraph(context.Context) (services.TaskGraphActivity, error)
	// Resume continues work an interrupted turn left behind.
	Resume()
}

SessionWorkerHarness is the Session's durable Harness as the worker owns it: the submission and agent-document boundary of the services, its task activity, and recovery of interrupted work. Close releases the storage.

type SessionWorkerManager

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

SessionWorkerManager owns process bookkeeping, generation-fenced requests, and attachment demand for one server generation. Blocking methods preserve awaited operations; Detach forgets workers without stopping their processes.

func NewSessionWorkerManager

func NewSessionWorkerManager(coordinator SessionWorkerCoordinator, sessionDir string, model *SessionWorkerModel, onWorkerCountChanged func(int)) *SessionWorkerManager

func (*SessionWorkerManager) AssertSessionPluginManifestPaths

func (m *SessionWorkerManager) AssertSessionPluginManifestPaths(metadata SessionCatalogMetadata, paths []string) error

func (*SessionWorkerManager) CloseSession

func (m *SessionWorkerManager) CloseSession(ctx context.Context, metadata SessionCatalogMetadata) error

func (*SessionWorkerManager) Detach

func (m *SessionWorkerManager) Detach()

Detach rejects pending calls and removes manager state without sending shutdown to surviving workers.

func (*SessionWorkerManager) Discover

func (m *SessionWorkerManager) Discover(peerIDs []string) error

func (*SessionWorkerManager) OpenSession

func (m *SessionWorkerManager) OpenSession(ctx context.Context, metadata SessionCatalogMetadata, pluginManifestPaths []string) (*RoutedSessionHandle, error)

func (*SessionWorkerManager) Shutdown

func (m *SessionWorkerManager) Shutdown() error

func (*SessionWorkerManager) TrackedSessions

func (m *SessionWorkerManager) TrackedSessions() []SessionCatalogMetadata

func (*SessionWorkerManager) WorkerCount

func (m *SessionWorkerManager) WorkerCount() int

WorkerCount is the registered plus launching worker count that notifyWorkerCountChanged delivers (session-worker-manager.ts:810-812).

func (*SessionWorkerManager) WorkerPids

func (m *SessionWorkerManager) WorkerPids() map[string]int

type SessionWorkerModel

type SessionWorkerModel struct {
	Provider *string `json:"provider,omitempty"`
	Model    string  `json:"model"`
}

SessionWorkerModel preserves a present model override even when empty. A nil Provider is omitted; a non-nil empty Provider reaches worker validation instead of selecting a default.

type SessionWorkerOptions

type SessionWorkerOptions struct {
	SessionDir          string                 `json:"sessionDir"`
	Metadata            SessionCatalogMetadata `json:"metadata"`
	Provider            string                 `json:"provider,omitempty"`
	Model               string                 `json:"model,omitempty"`
	PluginManifestPaths []string               `json:"pluginManifestPaths"`
}

SessionWorkerOptions describes the durable Session and selected plugins of one worker process.

type SessionWorkerRuntime

type SessionWorkerRuntime struct {
	Harness         SessionWorkerHarness
	Conversation    services.SessionWorkerConversation
	ModelRuntime    services.ModelsServiceModelRuntime
	SettingsManager services.ModelsServiceSettingsManager
	FacetLoader     chord.FacetLoader
	Cleanup         func(context.Context) error
}

SessionWorkerRuntime is a Session's opened Harness with its root conversation and the optional collaborators of the services. Cleanup releases resources the Harness does not own, such as execution environments, after it closed.

type StartServerOptions

type StartServerOptions struct {
	Directory      *string
	ServerId       *string
	SessionDir     *string
	Provider       *string
	Model          *string
	KeepAlive      *bool
	PluginPackages []string
}

StartServerOptions preserves omitted paths, identity, model selection, lifetime policy, and plugin selection separately from explicit empty values.

type TransportAddress

type TransportAddress struct {
	Transport string
	Path      string
}

TransportAddress is a parsed Unix address. Experimental Radius addresses are designed out (D64).

type WorkerLifecycle

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

WorkerLifecycle reconciles generation-scoped attachment demand with Harness activity. OnRetire runs inside the critical section that commits retirement, as upstream's synchronous #reconcile does, so it must be brief and must not call back into the lifecycle.

func NewWorkerLifecycle

func NewWorkerLifecycle(options WorkerLifecycleOptions) *WorkerLifecycle

func (*WorkerLifecycle) BeginRequest

func (l *WorkerLifecycle) BeginRequest(serverConnectionID, attachmentID string) (func(), error)

func (*WorkerLifecycle) Close

func (l *WorkerLifecycle) Close()

func (*WorkerLifecycle) HoldRetirement

func (l *WorkerLifecycle) HoldRetirement() func()

func (*WorkerLifecycle) ServerConnected

func (l *WorkerLifecycle) ServerConnected(serverConnectionID string)

func (*WorkerLifecycle) ServerDisconnected

func (l *WorkerLifecycle) ServerDisconnected(serverConnectionID string)

func (*WorkerLifecycle) SetDemand

func (l *WorkerLifecycle) SetDemand(serverConnectionID, attachmentID string, attached bool) error

func (*WorkerLifecycle) SetHarnessActive

func (l *WorkerLifecycle) SetHarnessActive(active bool)

SetHarnessActive records whether live Harness work, such as a run or a compaction, holds the worker. Only an inactive update reconciles, so repeated active updates never retire the worker.

type WorkerLifecycleOptions

type WorkerLifecycleOptions struct {
	InitialServerConnectionID *string
	InitialDemandGraceMs      int
	OrphanDemandGraceMs       int
	// OnRetire runs once, under the lifecycle lock, when retirement commits.
	OnRetire func()
}

WorkerLifecycleOptions selects the initial generation and the initial/orphan demand grace periods in milliseconds.

type WorkerOperationRequest

type WorkerOperationRequest struct {
	Type      string               `json:"type"`
	RequestID string               `json:"requestId"`
	Scope     WorkerOperationScope `json:"scope"`
	Call      chord.ServiceCall    `json:"call"`
}

type WorkerOperationScope

type WorkerOperationScope struct {
	ServerConnectionID string `json:"serverConnectionId"`
	AttachmentID       string `json:"attachmentId"`
}

Directories

Path Synopsis
Package client implements the experimental Pi client over ordered byte transports.
Package client implements the experimental Pi client over ordered byte transports.
Package durableadapter adapts the pi-durable Harness (durable/harness) to the consumer-owned boundaries of the experimental worker services.
Package durableadapter adapts the pi-durable Harness (durable/harness) to the consumer-owned boundaries of the experimental worker services.
Package durableagent holds the pi setup of a coding agent over the pi-durable Harness: the coding registry, the Harness settings, the execution environments, the HTTP setup and the initial model.
Package durableagent holds the pi setup of a coding agent over the pi-durable Harness: the coding registry, the Harness settings, the execution environments, the HTTP setup and the initial model.
main command
Command main runs the durable coding agent: pi's coding tools on the pi-durable Harness, with its own TUI.
Command main runs the durable coding agent: pi's coding tools on the pi-durable Harness, with its own TUI.
Package durabletest opens pi-durable Harnesses for the experimental tests: an in-memory one over the faux provider (packages/coding-agent/test/experimental-durable-support.ts openFauxConversation), and a file-backed SQLite one for worker processes.
Package durabletest opens pi-durable Harnesses for the experimental tests: an in-memory one over the faux provider (packages/coding-agent/test/experimental-durable-support.ts openFauxConversation), and a file-backed SQLite one for worker processes.
Package protocol implements the framed experimental Pi wire contract.
Package protocol implements the framed experimental Pi wire contract.
Package routing hosts contract-agnostic experimental server and client routing.
Package routing hosts contract-agnostic experimental server and client routing.
routingtest
Package routingtest ports the server package's testing subpath (packages/server/src/testing): a scripted Session host, a protocol test client, and an unstarted test server for transport and routing conformance tests.
Package routingtest ports the server package's testing subpath (packages/server/src/testing): a scripted Session host, a protocol test client, and an unstarted test server for transport and routing conformance tests.
Package services contains the opt-in experimental presentation service contracts.
Package services contains the opt-in experimental presentation service contracts.
Package vacation is a durable vacation planning agent on the pi-durable Harness: the coding agent of internal/experimental/durableagent with the coding tools and pi's coding prompt replaced by a vacation planner.
Package vacation is a durable vacation planning agent on the pi-durable Harness: the coding agent of internal/experimental/durableagent with the coding tools and pi's coding prompt replaced by a vacation planner.
main command
Command main runs the durable vacation planner: a research subagent that reports back, on the pi-durable Harness, with the durable agent's TUI.
Command main runs the durable vacation planner: a research subagent that reports back, on the pi-durable Harness, with the durable agent's TUI.

Jump to

Keyboard shortcuts

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