services

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 15 Imported by: 0

README

Experimental presentation services

This package ports the presentation controller, connection-source, Models facet, and server service-host logic from the pinned upstream files under packages/coding-agent/src/experimental/services/. It is an opt-in library. It does not change command dispatch, start a client, open a socket, select a model by default, or contact an external service.

Host boundaries

AgentController carries the pi.agent-controller command contract: prompt, steer, followUp, cancelQueued, abort, compact and waitForPrompt. CreateAgentController consumes the root conversation and its Harness through the consumer-owned AgentConversation and AgentHarness boundaries. A prompt is a durable submission whose decimal ID is the operation or entry ID; ConversationBusy becomes code busy and any other failure operation_failed. waitForPrompt returns the answer's text, or the reason a prompt settled unanswered.

CreateServerServiceSource and CreateSessionServiceSource consume a ServiceClient. Each source owns the bindings returned by ServiceSourceOptions.NewBinding. The caller supplies a Chord host binding implementation. The source does not own the client or its transport. ServiceClient owns catalogue request completion, cancellation, and shutdown draining. A catalogue request can outlive source disposal, as it does upstream.

The client invokes lifecycle listeners in event order after updating its current state. The binding starts Rebind synchronously in invocation order and invokes its completion exactly once. Ready synchronously registers a hydration/release waiter and completes inline when already settled. Both adapter methods return promptly. These callback boundaries retain the synchronous prefix of upstream's Promise operations. Starting blocking methods in independent goroutines can reorder detach and attach or change which immediately rejected readiness error reaches the caller.

Ready cancels only a waiter, not shared hydration or the underlying attachment. Source readiness starts waiters in binding insertion order, cancels and drains remaining waiters on the first failure, and preserves that failure rather than an induced cancellation. Already-settled failures follow invocation order; a later binding's asynchronous rejection does not wait for earlier pending bindings. Background server transitions run in order. Session transitions can overlap. Initial lifecycle publication precedes transition registration; a listener panic is reported and does not change transition work. Revision and full attachment identity prevent old completions from publishing current state. Disposal removes the listener, drains source-owned transitions, and attempts every remaining binding's disposal. It does not dispose the client.

SourceState exposes lifecycle snapshots and context-bearing hydration/update deliveries. It hydrates subscriptions synchronously, including reentrant subscriptions. It suppresses equal replacements and preserves publication order. Each subscription has its own queue (bounded at 100 deliveries; a full queue drops its older deliveries) and runs one callback at a time, so a callback that publishes sees the resulting deliveries after it returns. Removing a subscription drops its queued deliveries, including those of a publication that already snapshotted it, but does not stop its running callback (chord state.ts StateSubscriber). A subscriber does not replay publications at or before its hydration sequence. A callback panic, including one during hydration, never reaches the publisher and does not remove the subscription: it is reported through chord's reportErrorAsync analog, an uncaught panic on a new goroutine. Callbacks run outside source locks. Callbacks and error reporters must return promptly. The caller must not synchronously dispose a source from a callback whose transition that disposal would drain.

Concrete server and Models hosts

CreateModelsServiceFacet returns an internal/chord.Facet. Its setup provides pi.models with concrete replicated state. The Chord host connects bindings with a background context and activates the provider after setup, using the background context for lane reads. Method calls retain the caller's context. The Models contract registers both its guarded service view and its typed remote client. In-host consumers use Chord's loopback replica. Retained methods and state follow provider replacement, and retained views reject access after their consuming facet retires. The caller supplies the configuration lane, optional model catalogue runtime, and optional settings manager. Creating the facet does not read the lane or activate a provider.

CreateExperimentalServerServices reads the initial Session directory with the background context. Its Host.AttachClient creates a connection-scoped provider and endpoint for pi.session-directory, pi.session-management, and pi.presentation-plugins. Attachments share the directory and one FIFO mutation queue. Each attachment retains its own prepared package selection and owns its subscriptions. A nil selection request means defaults. An explicitly empty selection means no packages. Failed preparation or failed detachment retains the prior selection. Successful detachment clears only that attachment's selection.

Create and remove refresh the directory only after the application operation succeeds. Removal first awaits the presentation's attachment cleanup. A failed directory read retains the last published revision and snapshot, even when the preceding storage operation succeeded. The next mutation still runs after a failure. The queue does not check cancellation or substitute contexts. Each admitted callback receives its original context after preceding operations finish. Pass context.Background() to Refresh for upstream's omitted-context behavior.

Attachment release removes subscriptions immediately and rejects new calls. Server disposal releases current attachments before joining the queued mutations. It does not cancel admitted application operations. The mutation queue creates no background goroutines. It retains one completion channel per in-flight call and one settled tail. The caller owns admission and cancellation of external requests. An application callback must not wait on a mutation that it queues behind itself.

These factories exercise the concrete local Chord host, endpoint, operation stream, and replica. The package does not supply the durable Harness or a worker process host: AgentHarness, AgentConversation, AgentDocument, TranscriptConversation and TaskGraphActivity are the boundaries that its adapter implements, and internal/experimental/durabletest implements them in memory for the tests. The connection sources still require the client's binding adapter and routed transport.

Worker service composition

CreateSessionWorkerServices activates controller, Models, Transcript, and Session plugin-reload facets with a supplied facet loader. It returns only after activation finishes. Each server-connection/attachment pair owns an endpoint and its subscriptions. Reloads load and activate a candidate generation in admission order, cut over the Chord host, and then dispose the retired loaded set. A failed candidate is disposed without retiring the previous loaded set. Disposal removes subscriptions, waits for queued reloads, disposes the host, and attempts both loaded-set cleanups. This composes the local worker services; it does not spawn a Session worker or load JavaScript bundles.

Local slash-command contributions

CreateSlashCommandsRuntimeFacet provides the local SlashCommands service on a Chord host. SlashCommandRegistry preserves name insertion order and stages replacements until the preceding registration retires. Closing a staged replacement leaves the current command intact. Closing a registration twice publishes only once. Subscriptions hydrate immediately and publish synchronously. Call registry methods and listeners on the owning presentation executor. The service is local because contributions carry callbacks; it never appears in a remote service catalogue. This library does not enable commands in the stable CLI.

Go representations

Go uses one namespace for types and values, so AgentControllerID names upstream's service token. Contexts are leading parameters on controller methods. Nullable fields use pointers or nil slices without omitempty. The anonymous cancellation response has the Go name AgentCancelQueuedResponse.

The consumer-owned conversation contracts contain only consumed arguments and result fields. They do not declare a second durable harness runtime. ConversationView, LiveState, InboxState and EntryRecord in conversation_view.go are JSON-level stand-ins for the durable types of the Transcript value. The client and binding contracts contain only operations used by connection sources. They do not implement Chord wire encoding, keyed instance management, or client connection establishment.

Evidence

Run go test -race ./internal/experimental/services.

The tests exercise local controller and binding paths. TestUpstreamAgentController runs the three 1.0.0 controller cases over the in-memory Harness. TestConnectionMatchesPinnedSourceWithLocalBindings executes the exact pinned connection-source bodies with local client and Chord dependencies. The probe replaces imports only. It compares lifecycle states, catalogue retention, rebind order, and ownership cleanup. The changing wall clock is checked separately for ISO millisecond formatting.

The controller and connection lifecycle tests use barriers for delayed hydration, replacement, cancellation, and disposal. They also cover client-owned catalogue requests, early readiness failure, stale completion rejection, aggregate errors, inactive bindings, and subscription order. Those tests do not claim framed-transport, Chord-host, durable-AgentLane, or published-CLI integration coverage.

TestModelsFacetOnConcreteChordHost exercises activation with a cancelled host context, remote state publication, and configuration changes that arrive through the agent-document subscription. TestFacetHostReadinessUsesBackgroundContext in internal/chord checks upstream facets/host.ts's background-context connection rule independently of caller cancellation. TestModelsFacetConsumerRetainsGuardedServiceAcrossReload exercises every Models method through the concrete host's in-host loopback, caller cancellation and errors, retained state subscriptions across provider replacement, and access revocation after consumer retirement and host disposal. Both new regressions fail on the unmodified runtime; removing the guarded-view registration or returning an unguarded target also fails the Models consumer regression. TestServerServicesMatchPinnedUpstream compares the complete structured trace to the unmodified pinned server and Chord sources. Calls and publications cross the local provider, endpoint, JSON-copy transport, and replica. TestServerMutationsFIFOAndDisposeDrainFailure compares disposal ordering against an exact-source oracle and checks context retention separately. Compiling mutations demonstrate that the tests reject broken activation context, FIFO ordering, disposal draining, detach selection clearing, and removal preparation. Failure tests cover initial reads, storage mutations, refreshes, and retained snapshots. Concurrent tests exercise independent selections for 128 attachments. No test contacts a network service or claims durable-lane or CLI integration.

Run go test ./internal/experimental/services -run '^$' -bench 'Benchmark(SourceStatePublication|ConnectionLifecycle|ServerServiceLifecycle)' -benchmem to measure state publication, an eight-binding attach/detach/dispose lifecycle, and a server lifecycle with 16 subscribed attachments and 256 advertised Sessions. Every source-owned transition is drained. Catalogue tasks remain client-owned. No extension IPC runs on an input or render loop in this package.

Documentation

Overview

Package services contains the opt-in experimental presentation service contracts.

Ports packages/coding-agent/src/experimental/services/agent-controller.ts.

Package services defines opt-in experimental service contracts and local providers.

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

Ports packages/coding-agent/src/experimental/services/presentation-ui.ts.

Ports packages/coding-agent/src/experimental/services/slash-commands.ts.

Ports packages/coding-agent/src/experimental/services/slash-commands-provider.ts.

Ports packages/coding-agent/src/experimental/services/slash-commands-provider.ts.

Ports packages/coding-agent/src/experimental/services/worker.ts.

Index

Constants

View Source
const (
	AgentDocKind = "pi.agent"
	LiveDocKind  = "pi.live"
	InboxDocKind = "pi.inbox"
)

Document kinds of a ConversationView.

View Source
const AgentControllerID = "pi.agent-controller"

AgentControllerID identifies the remote service. Go's shared type/value namespace requires a separate name for the service token.

Variables

AgentControllerDefinition names the remote service token; Go shares type and value names.

View Source
var ModelsDefinition = chord.DefineService[Models]("pi.models")

ModelsDefinition is the pi.models token; Go types and values share a namespace.

View Source
var PresentationPluginsDefinition = chord.DefineService[PresentationPlugins]("pi.presentation-plugins")

PresentationPluginsDefinition is the pi.presentation-plugins token; Go types and values share a namespace.

View Source
var PresentationUIDefinition = chord.DefineServiceWithOptions[PresentationUI]("pi.local.presentation-ui", chord.ServiceOptions{Local: true})

PresentationUIDefinition names the local service; Go shares type and value names.

View Source
var SessionDirectoryDefinition = chord.DefineService[SessionDirectory]("pi.session-directory")

SessionDirectoryDefinition is the pi.session-directory token.

View Source
var SessionManagementDefinition = chord.DefineService[SessionManagement]("pi.session-management")

SessionManagementDefinition is the pi.session-management token.

View Source
var SessionPluginsDefinition = chord.DefineService[SessionPlugins]("pi.session-plugins")

SessionPluginsDefinition is the pi.session-plugins token.

View Source
var SlashCommandsDefinition = chord.DefineServiceWithOptions[SlashCommands]("pi.local.slash-commands", chord.ServiceOptions{Local: true})

SlashCommandsDefinition names the local service token; Go shares type and value names.

View Source
var TranscriptDefinition = chord.DefineService[Transcript]("pi.transcript")

Functions

func CreateBuiltInSlashCommandsFacet

func CreateBuiltInSlashCommandsFacet(options BuiltInSlashCommandsOptions) chord.Facet

CreateBuiltInSlashCommandsFacet installs model, thinking, compact and reload contributions, in that order. Activation and disposal run on the command registry's owner executor; command bodies may block and must run off the TUI input loop.

func CreateModelsServiceFacet

func CreateModelsServiceFacet(options ModelsServiceFacetOptions) chord.Facet

CreateModelsServiceFacet declares a Models provider on the Chord host. After setup it publishes the catalog with a background context and then follows the agent document, so configuration changes made by any client reach the replicated state.

func CreateSlashCommandsRuntimeFacet

func CreateSlashCommandsRuntimeFacet(registry *SlashCommandRegistry) chord.Facet

CreateSlashCommandsRuntimeFacet provides the local command registry without activating commands. A nil registry selects a new empty registry, as upstream's omitted argument does.

func CreateTranscriptServiceFacet

func CreateTranscriptServiceFacet(ctx context.Context, conversation TranscriptConversation) (chord.Facet, error)

CreateTranscriptServiceFacet serves the conversation's durable view state. The facet owns the attached state and disposes it with the host.

Types

type AgentCancelQueuedResponse

type AgentCancelQueuedResponse struct {
	Outcome string `json:"outcome"`
}

AgentCancelQueuedResponse reports "cancelled", "already_consumed", or "not_found".

type AgentCompactionRequest

type AgentCompactionRequest struct {
	CustomInstructions *string `json:"customInstructions"`
}

AgentCompactionRequest uses null to select the default instructions.

type AgentController

type AgentController interface {
	// Prompt starts a run; it is rejected with code "busy" while one is active.
	Prompt(context.Context, AgentPromptRequest) (AgentOperationResponse, error)
	// Steer steers the active run, or starts one when idle.
	Steer(context.Context, AgentPromptRequest) (AgentQueueResponse, error)
	// FollowUp queues input for after the active run, or starts one when idle.
	FollowUp(context.Context, AgentPromptRequest) (AgentQueueResponse, error)
	CancelQueued(context.Context, string) (AgentCancelQueuedResponse, error)
	// Abort withdraws queued input and aborts the active run and compaction.
	Abort(context.Context) error
	Compact(context.Context, AgentCompactionRequest) (AgentOperationResponse, error)
	// WaitForPrompt waits until the prompt with this operation ID is answered or settles unanswered.
	WaitForPrompt(context.Context, string) (AgentPromptResult, error)
}

AgentController is the presentation-safe command facade over the worker-owned root conversation. Calls wait for the conversation's result, propagate context cancellation, and return transport errors separately from admission responses.

type AgentControllerInitiator

AgentControllerInitiator separates the admitted Promise from its observer without changing the AgentController wire contract. Begin methods preserve the operation context; Wait uses a separate observer context. A selected local override must expose its own admission boundary.

type AgentControllerProvider

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

AgentControllerProvider adapts durable conversation outcomes without exposing worker-owned details.

func CreateAgentController

func CreateAgentController(harness AgentHarness, conversation AgentConversation) *AgentControllerProvider

CreateAgentController creates the presentation-safe facade for one root conversation.

func (*AgentControllerProvider) Abort

func (controller *AgentControllerProvider) Abort(ctx context.Context) error

func (*AgentControllerProvider) CancelQueued

func (controller *AgentControllerProvider) CancelQueued(ctx context.Context, entryID string) (AgentCancelQueuedResponse, error)

func (*AgentControllerProvider) Compact

func (*AgentControllerProvider) FollowUp

func (controller *AgentControllerProvider) FollowUp(ctx context.Context, request AgentPromptRequest) (AgentQueueResponse, error)

func (*AgentControllerProvider) Prompt

func (*AgentControllerProvider) Steer

func (*AgentControllerProvider) WaitForPrompt

func (controller *AgentControllerProvider) WaitForPrompt(ctx context.Context, operationID string) (AgentPromptResult, error)

type AgentConversation

type AgentConversation interface {
	ID() durable.ConversationId
	Submit(ctx context.Context, content ai.UserContent, whenBusy durable.WhenBusy) (durable.SubmissionId, error)
	Abort(context.Context) error
	Compact(ctx context.Context, customInstructions *string) (int64, error)
}

AgentConversation is the root durable conversation boundary the controller drives. Submit adds one input and returns its submission; Compact starts a compaction task and returns its task ID.

type AgentDocument

type AgentDocument interface {
	Value() *AgentState
	Subscribe(func(context.Context)) func()
	Dispose()
}

AgentDocument is the conversation's replicated pi.agent document: its configuration follows every change, also those made by other clients. Value is nil until the document exists. Subscribe returns its unsubscribe function. The facet that acquired the document disposes it.

type AgentHarness

type AgentHarness interface {
	AbortSubmission(ctx context.Context, id durable.SubmissionId, conversationID durable.ConversationId) (durable.SubmissionAbortResult, error)
	Submission(ctx context.Context, id durable.SubmissionId) (PromptSubmission, error)
	AgentDocument(ctx context.Context, conversationID durable.ConversationId) (AgentDocument, error)
}

AgentHarness is the durable Harness boundary the worker services consult: queued and settled submissions for the controller, and a conversation's pi.agent document for the Models service. Submission returns (nil, nil) for an unknown ID; AgentDocument returns (nil, nil) for a conversation without one.

type AgentOperationError

type AgentOperationError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

AgentOperationError is the presentation-safe code and message of a failure.

type AgentOperationResponse

type AgentOperationResponse struct {
	Accepted    bool                 `json:"accepted"`
	OperationID *string              `json:"operationId"`
	Error       *AgentOperationError `json:"error"`
}

AgentOperationResponse distinguishes admission from rejection. An accepted operation has an operation ID and no error; a rejected one has an error and no operation ID. OperationID identifies the durable submission of a prompt, or the task of a compaction.

type AgentPromptImage

type AgentPromptImage struct {
	Type     string `json:"type"`
	Data     string `json:"data"`
	MimeType string `json:"mimeType"`
}

AgentPromptImage carries an image in a presentation prompt. Type is "image".

type AgentPromptRequest

type AgentPromptRequest struct {
	Message string             `json:"message"`
	Images  []AgentPromptImage `json:"images"`
}

AgentPromptRequest preserves null images separately from an empty image list.

type AgentPromptResult

type AgentPromptResult struct {
	Status string  `json:"status"`
	Text   *string `json:"text"`
	Reason *string `json:"reason"`
}

AgentPromptResult is the settled outcome of a prompt: "done" with the answer's text, or "unanswered" with the reason it got none.

type AgentQueueResponse

type AgentQueueResponse struct {
	Accepted bool                 `json:"accepted"`
	EntryID  *string              `json:"entryId"`
	Error    *AgentOperationError `json:"error"`
}

AgentQueueResponse has an entry ID and no error when accepted, or an error and no entry ID when rejected. EntryID identifies the durable submission; CancelQueued withdraws it while it is still queued.

type AgentState

type AgentState struct {
	Model         *ModelRef
	ThinkingLevel ai.ThinkingLevel
}

AgentState is the part of the conversation's pi.agent document that the Models service follows. An empty ThinkingLevel is unset and reads as "off".

type AggregateError

type AggregateError = chord.AggregateError

AggregateError retains every failure while exposing the upstream aggregate message.

type BuiltInSlashCommandsOptions

type BuiltInSlashCommandsOptions struct {
	ReloadPresentationPlugins func(context.Context, chord.JsonValue) error
}

BuiltInSlashCommandsOptions supplies the presentation generation reload. It waits for replacement and retired-generation disposal before returning.

type ConversationConfiguration

type ConversationConfiguration struct {
	Model         *ModelRef
	ThinkingLevel *ai.ThinkingLevel
}

ConversationConfiguration selects the model and thinking level to apply together; a nil member keeps its current value.

type ConversationView

type ConversationView = harness.ConversationView

ConversationView is a durable conversation's active transcript and built-in documents: the raw active entries (the head marker, then the non-head entries from its head) and pi.agent, pi.live, pi.inbox and pi.usage by kind. It is the value of the Transcript service.

type ExperimentalServerServices

type ExperimentalServerServices struct {
	Host *RoutedServerServiceHost
}

ExperimentalServerServices owns a shared directory and one service endpoint per attached presentation. It has no listener or default CLI activation.

func CreateExperimentalServerServices

func CreateExperimentalServerServices(options ExperimentalServerServicesOptions) (*ExperimentalServerServices, error)

CreateExperimentalServerServices reads the initial directory in the background context. Application operations remain opt-in through the returned host.

func (*ExperimentalServerServices) Dispose

func (services *ExperimentalServerServices) Dispose() error

Dispose releases every current attachment before waiting for queued mutations. In-flight operations retain their application context and are not cancelled.

func (*ExperimentalServerServices) Refresh

func (services *ExperimentalServerServices) Refresh(ctx context.Context) error

Refresh queues a directory refresh after preceding mutations.

type ExperimentalServerServicesOptions

type ExperimentalServerServicesOptions struct {
	List                      func(context.Context) ([]SessionSummary, error)
	Create                    func(context.Context, SessionCreateOptions) (SessionSummary, error)
	Remove                    func(context.Context, string) error
	PrepareSessionPlugins     func(context.Context, string, []string) (PreparedSessionPlugins, error)
	ReloadPresentationPlugins func(context.Context, []string) (chord.JsonValue, error)
}

ExperimentalServerServicesOptions supplies application-owned Session storage and plugin selection. Nil package paths select defaults; an empty slice selects no packages.

type ModelRef

type ModelRef struct {
	Provider string `json:"provider"`
	ModelId  string `json:"modelId"`
}

ModelRef identifies a model within its provider.

type ModelSummary

type ModelSummary struct {
	ModelRef
	Name      string `json:"name"`
	Reasoning bool   `json:"reasoning"`
}

ModelSummary is the catalog metadata exposed to clients.

type Models

type Models interface {
	State() chord.ReplicatedStateOf[*ModelsState]
	CycleThinking(context.Context) error
	GetThinkingLevels(context.Context) ([]ai.ThinkingLevel, error)
	Refresh(context.Context) error
	Select(context.Context, ModelRef) error
	SelectThinking(context.Context, ai.ThinkingLevel) error
}

Models is the model-selection service. Each call waits for its publications and propagates errors to the caller.

type ModelsCatalog

type ModelsCatalog struct {
	Revision        int            `json:"revision"`
	AvailableModels []ModelSummary `json:"availableModels"`
}

ModelsCatalog preserves runtime order and includes an otherwise unavailable selected model.

type ModelsConfiguration

type ModelsConfiguration struct {
	Model         *ModelRef        `json:"model"`
	ThinkingLevel ai.ThinkingLevel `json:"thinkingLevel"`
}

ModelsConfiguration uses a nil Model for an unconfigured lane.

type ModelsRefresh

type ModelsRefresh struct {
	Status string            `json:"status"`
	Errors map[string]string `json:"errors,omitzero"`
}

ModelsRefresh reports idle, refreshing, done, or warning with provider errors.

type ModelsRefreshResult

type ModelsRefreshResult struct {
	Aborted bool
	Errors  map[string]error
}

ModelsRefreshResult carries refresh diagnostics. An aborted result is not itself a rejected operation.

type ModelsServiceConversation

type ModelsServiceConversation interface {
	Configure(context.Context, ConversationConfiguration) error
}

ModelsServiceConversation is the configuration boundary the Models service consumes from the root conversation.

type ModelsServiceFacetOptions

type ModelsServiceFacetOptions struct {
	Conversation    ModelsServiceConversation
	Agent           AgentDocument
	ModelRuntime    ModelsServiceModelRuntime
	SettingsManager ModelsServiceSettingsManager
}

ModelsServiceFacetOptions selects the conversation, its agent document and the optional runtime and settings collaborators. The facet owns Agent and disposes it with the host.

type ModelsServiceModelRuntime

type ModelsServiceModelRuntime interface {
	GetAvailableSnapshot() []*ai.Model
	GetModel(provider, modelId string) *ai.Model
	Refresh(context.Context) (ModelsRefreshResult, error)
}

ModelsServiceModelRuntime supplies snapshots and lookup without contacting a provider during reads. Refresh policy belongs to the supplied runtime.

type ModelsServiceRuntime

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

ModelsServiceRuntime binds one Models service to its activation operation and to configuration changes of the agent document.

func CreateModelsService

func CreateModelsService(conversation ModelsServiceConversation, agent AgentDocument, modelRuntime ModelsServiceModelRuntime, settingsManager ModelsServiceSettingsManager, createState func(*ModelsState) chord.MutableReplicatedStateOf[*ModelsState]) *ModelsServiceRuntime

CreateModelsService creates an inactive service over one conversation. Its configuration starts from the agent document and follows it after SyncConfiguration; state allocation and publication belong to the caller's Chord host.

func (*ModelsServiceRuntime) Activate

func (runtime *ModelsServiceRuntime) Activate(ctx context.Context) error

Activate reads the current catalog and publishes it with an idle refresh. Upstream reads and publishes in one synchronous turn (models-provider.ts:114-120), so catalog revisions publish in order; the read runs inside the change, which the state serializes, so concurrent calls keep that order.

func (*ModelsServiceRuntime) SyncConfiguration

func (runtime *ModelsServiceRuntime) SyncConfiguration(ctx context.Context) error

SyncConfiguration publishes the agent document's model and thinking level when they changed.

type ModelsServiceSettingsManager

type ModelsServiceSettingsManager interface {
	SetDefaultModelAndProvider(provider, model string) error
	Flush() error
}

ModelsServiceSettingsManager persists model selection before publication.

type ModelsState

type ModelsState struct {
	Catalog       ModelsCatalog       `json:"catalog"`
	Configuration ModelsConfiguration `json:"configuration"`
	Refresh       ModelsRefresh       `json:"refresh"`
}

ModelsState is the replicated model catalog, lane configuration, and refresh outcome.

type PrepareSessionPluginsRequest

type PrepareSessionPluginsRequest struct {
	SessionId    string   `json:"sessionId"`
	PackagePaths []string `json:"packagePaths"`
}

PrepareSessionPluginsRequest selects packages for a Session. Nil PackagePaths selects defaults; an empty slice selects no packages.

type PreparedSessionPlugins

type PreparedSessionPlugins struct {
	PackagePaths        []string
	PresentationPlugins chord.JsonValue
}

PreparedSessionPlugins contains the resolved package selection and its presentation artifacts.

type PresentationPlugins

type PresentationPlugins interface {
	PrepareSession(context.Context, PrepareSessionPluginsRequest) (chord.JsonValue, error)
	Reload(context.Context) (chord.JsonValue, error)
}

PresentationPlugins exposes server-built plugin generations to presentations. Calls wait for completion and propagate errors to the caller.

type PresentationSelectItem

type PresentationSelectItem struct {
	Value       string
	Label       string
	Description *string
}

PresentationSelectItem is a local selector choice. Nil Description preserves omission.

type PresentationUI

type PresentationUI interface {
	Select(context.Context, string, []PresentationSelectItem, *string) (*string, error)
	ShowStatus(context.Context, string) error
}

PresentationUI supplies process-local presentation capabilities. Select waits for selection or cancellation; nil means the selector was cancelled. ShowStatus completes after the owner loop applies the status.

type PromptSubmission

type PromptSubmission interface {
	// Wait returns once the submission is answered or settles unanswered.
	Wait(context.Context) (SettledPrompt, error)
}

PromptSubmission is one durable submission that a prompt created.

type RemoteServiceBinding

type RemoteServiceBinding interface {
	Use(Service) (any, error)
	Observe(Service, func(context.Context, any) error) (func(), error)
	Ready(context.Context, func(error))
	Rebind(context.Context, bool, func(error))
	Dispose(context.Context) error
}

RemoteServiceBinding is supplied by the Chord host. Rebind synchronously starts invalidation and calls its completion exactly once after hydration/release. Ready synchronously registers a waiter for current hydration/release and calls its completion exactly once, inline if already settled. Both methods return promptly; invocation order preserves the synchronous prefix of the upstream Promise API. Cancelling Ready releases only its waiter, and completion follows waiter cleanup. Implementations honor caller cancellation and make Dispose idempotent. Use and Observe retain the host's typed service handles and access checks.

type RemoteServiceBindingOptions

type RemoteServiceBindingOptions struct {
	ServiceBindingOptions
	GetTarget func() *ServiceTarget
	Bound     bool
}

RemoteServiceBindingOptions supplies the host with lazy routing and an initially unbound service set. GetTarget returns nil while detached.

type ReplicatedStateDelivery

type ReplicatedStateDelivery struct {
	Kind     string
	Sequence int
}

ReplicatedStateDelivery distinguishes initial hydration from ordered updates.

type RoutedServerPresentation

type RoutedServerPresentation interface {
	AttachSession(context.Context, string) error
	DetachSession(context.Context) error
	PrepareSessionRemoval(context.Context, string) error
}

RoutedServerPresentation supplies the presentation-scoped routing capabilities used by server management.

type RoutedServerServiceAttachment

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

RoutedServerServiceAttachment owns the provider and subscriptions for one presentation connection.

func (*RoutedServerServiceAttachment) InvokeService

InvokeService forwards a service call while the attachment is live. Release rejects new calls but does not abort admitted calls.

func (*RoutedServerServiceAttachment) Release

func (attachment *RoutedServerServiceAttachment) Release(context.Context) error

Release immediately removes subscriptions and the provider. It is idempotent and does not wait for application mutations.

type RoutedServerServiceHost

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

RoutedServerServiceHost serializes all application mutations across its presentation attachments.

func (*RoutedServerServiceHost) AttachClient

AttachClient creates the three server-scoped services with independent plugin selection and subscriptions. Only the directory state and mutation queue are shared.

type RoutedServiceBinding

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

RoutedServiceBinding activates a source-owned host binding on first Ready.

func (*RoutedServiceBinding) BeginReady

func (binding *RoutedServiceBinding) BeginReady(ctx context.Context) func() error

BeginReady starts first-activation fencing before returning its continuation. The caller runs that continuation exactly once and owns any goroutine used to await it.

func (*RoutedServiceBinding) Dispose

func (binding *RoutedServiceBinding) Dispose(ctx context.Context) error

func (*RoutedServiceBinding) Observe

func (binding *RoutedServiceBinding) Observe(service Service, handler func(context.Context, any) error) (func(), error)

func (*RoutedServiceBinding) Ready

func (binding *RoutedServiceBinding) Ready(ctx context.Context) error

func (*RoutedServiceBinding) Use

func (binding *RoutedServiceBinding) Use(service Service) (any, error)

type ServerConnectionState

type ServerConnectionState struct {
	Status  string
	Attempt int
	Since   string
	Reason  string
	RetryAt *string
}

ServerConnectionState is discriminated by Status: connecting has Attempt; connected has Since; disconnected has Since, Reason, and nullable RetryAt.

func (ServerConnectionState) MarshalJSON

func (state ServerConnectionState) MarshalJSON() ([]byte, error)

type ServerServiceSource

type ServerServiceSource struct {
	Connection *SourceState[ServerConnectionState]
	// contains filtered or unexported fields
}

ServerServiceSource owns server-scoped bindings and serializes reconnect transitions. It does not connect or close the client.

func CreateServerServiceSource

func CreateServerServiceSource(client ServiceClient, options ServiceSourceOptions) *ServerServiceSource

func (*ServerServiceSource) AcceptsUnavailableServices

func (*ServerServiceSource) AcceptsUnavailableServices() bool

func (*ServerServiceSource) Catalogue

func (source *ServerServiceSource) Catalogue(ctx context.Context) ([]ServiceCatalogueEntry, error)

func (*ServerServiceSource) Dispose

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

func (*ServerServiceSource) Open

type Service

type Service struct {
	ID    string
	Local bool
}

Service identifies a Chord service. Local services cannot cross a remote binding.

type ServiceBindingOptions

type ServiceBindingOptions struct {
	Services     []Service
	AssertAccess func() error
	OnError      func(error)
}

ServiceBindingOptions configures one source-owned remote binding.

type ServiceCatalogueEntry

type ServiceCatalogueEntry struct {
	ServiceID string `json:"serviceId"`
	Mode      string `json:"mode"`
}

ServiceCatalogueEntry describes an available singleton or keyed service.

type ServiceClient

type ServiceClient interface {
	ServerID() string
	ConnectionState() string
	Attachment() *SessionTarget
	ServiceCatalogue(context.Context, ServiceTarget, func([]ServiceCatalogueEntry, error))
	OnConnectionStateChange(func(string, error)) func()
	OnAttachmentChange(func(*SessionTarget)) func()
}

ServiceClient is the source's consumer-owned client boundary. Getters return snapshots. Event listeners run in event order and observe already-committed client state; removing a listener prevents new invocations. ServiceCatalogue starts a client-owned request and calls its completion exactly once. The client owns cancellation and shutdown draining, including requests that outlive a source.

type ServiceSourceOptions

type ServiceSourceOptions struct {
	OnError    func(error)
	NewBinding func(RemoteServiceBindingOptions) RemoteServiceBinding
}

ServiceSourceOptions supplies the external Chord binding implementation and asynchronous error sink. Sources own bindings, not the client or its transport. NewBinding must return an independent binding for every call.

type ServiceTarget

type ServiceTarget struct {
	ServerID     string  `json:"serverId"`
	SessionID    *string `json:"sessionId,omitempty"`
	AttachmentID *string `json:"attachmentId,omitempty"`
}

ServiceTarget routes either to the server or to an exact Session attachment.

type SessionAddress

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

SessionAddress identifies a Session on a server.

type SessionAttachmentState

type SessionAttachmentState struct {
	Status    string `json:"status"`
	SessionID string `json:"sessionId"`
}

SessionAttachmentState has a SessionID only while attaching, attached, or degraded.

func (SessionAttachmentState) MarshalJSON

func (state SessionAttachmentState) MarshalJSON() ([]byte, error)

type SessionCreateOptions

type SessionCreateOptions struct {
	Id *string `json:"id,omitempty"`
}

SessionCreateOptions distinguishes an omitted id from an explicitly empty id.

type SessionDirectory

type SessionDirectory interface {
	State() chord.ReplicatedStateOf[*SessionDirectoryState]
}

SessionDirectory exposes replicated Session discovery without mutation operations.

type SessionDirectoryState

type SessionDirectoryState struct {
	Revision int              `json:"revision"`
	Sessions []SessionSummary `json:"sessions"`
}

SessionDirectoryState is the ordered, revisioned set of Sessions advertised by a server.

type SessionManagement

type SessionManagement interface {
	Create(context.Context, SessionCreateOptions) (SessionSummary, error)
	Remove(context.Context, string) error
	Attach(context.Context, string) error
	Detach(context.Context) error
}

SessionManagement creates, removes, and selects Sessions. Calls wait for completion and return operation errors.

type SessionPlugins

type SessionPlugins interface {
	Reload(context.Context) error
}

SessionPlugins reloads plugin facets in the currently attached Session worker. Reload waits for completion and propagates errors to the caller.

type SessionServiceSource

type SessionServiceSource struct {
	Attachment *SourceState[SessionAttachmentState]
	// contains filtered or unexported fields
}

SessionServiceSource owns bindings for the selected attachment. Readiness is fenced by both the local revision and the server/Session/attachment identity.

func CreateSessionServiceSource

func CreateSessionServiceSource(client ServiceClient, options ServiceSourceOptions) *SessionServiceSource

func (*SessionServiceSource) AcceptsUnavailableServices

func (source *SessionServiceSource) AcceptsUnavailableServices() bool

func (*SessionServiceSource) Catalogue

func (source *SessionServiceSource) Catalogue(ctx context.Context) ([]ServiceCatalogueEntry, error)

func (*SessionServiceSource) Dispose

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

func (*SessionServiceSource) Open

func (*SessionServiceSource) WhenAttached

func (source *SessionServiceSource) WhenAttached(sessionID string, ctx context.Context) error

WhenAttached waits for the exact current attachment generation to finish hydrating. Cancelling the wait does not cancel shared binding work.

func (*SessionServiceSource) WhenDetached

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

WhenDetached waits for every binding to finish releasing the previous attachment.

type SessionSummary

type SessionSummary struct {
	SessionAddress
	CreatedAt float64 `json:"createdAt"`
}

SessionSummary adds the creation timestamp in milliseconds.

type SessionTarget

type SessionTarget struct {
	ServerID     string `json:"serverId"`
	SessionID    string `json:"sessionId"`
	AttachmentID string `json:"attachmentId"`
}

SessionTarget identifies one attachment generation, not just a Session.

type SessionWorkerConversation

type SessionWorkerConversation interface {
	AgentConversation
	ModelsServiceConversation
	TranscriptConversation
}

SessionWorkerConversation is the root conversation the worker services expose: the command, configuration and view capabilities their providers consume.

type SessionWorkerServices

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

SessionWorkerServices owns the worker's facet generations and attachment-scoped endpoints. Reload calls wait in admission order; Dispose drains that work before releasing both facet sets.

func CreateSessionWorkerServices

func CreateSessionWorkerServices(options SessionWorkerServicesOptions) (*SessionWorkerServices, error)

CreateSessionWorkerServices activates controller, plugin-reload, Models, Transcript, and supplied plugin facets. It returns only after activation finishes; initialization and reload use the background context as upstream's context-free calls do.

func (*SessionWorkerServices) Dispose

func (services *SessionWorkerServices) Dispose() error

Dispose removes subscriptions, waits for queued reloads, disposes the host, and releases every loaded set even after an earlier cleanup failure.

func (*SessionWorkerServices) Invoke

Invoke routes a service call through the endpoint belonging to scope, creating it on first use. It returns the original call's result or error.

func (*SessionWorkerServices) RemoveSubscriptions

func (services *SessionWorkerServices) RemoveSubscriptions(matches func(WorkerServiceScope) bool)

RemoveSubscriptions closes endpoints whose attachment scopes match, in their creation order.

type SessionWorkerServicesOptions

type SessionWorkerServicesOptions struct {
	Harness         AgentHarness
	Conversation    SessionWorkerConversation
	ModelRuntime    ModelsServiceModelRuntime
	SettingsManager ModelsServiceSettingsManager
	FacetLoader     chord.FacetLoader
	Publish         func(context.Context, WorkerServiceScope, string, chord.ServiceProviderUpdate) error
}

SessionWorkerServicesOptions selects a worker's built-in and plugin facets. Harness and Conversation are the Session's durable Harness and its root conversation. Publish sends a subscription update to its original attachment.

type SettledPrompt

type SettledPrompt struct {
	Unanswered bool
	Reason     string
	Answer     ai.Message
}

SettledPrompt is a prompt submission that finished: unanswered with a reason, or answered by Answer. Answer is the first model message of the answer entry; it is nil when the settled submission has no answer.

type SlashCommandCompletion

type SlashCommandCompletion struct {
	Value       string
	Label       string
	Description *string
}

SlashCommandCompletion is one argument completion. A nil description is omitted.

type SlashCommandContribution

type SlashCommandContribution struct {
	Name                   string
	Description            *string
	ArgumentHint           *string
	GetArgumentCompletions func(string) ([]SlashCommandCompletion, error)
	Run                    func(context.Context, string) (SlashCommandRunResult, error)
	// contains filtered or unexported fields
}

SlashCommandContribution supplies a command and its optional completion callback. Callbacks block until the upstream Promise settles and return its rejection as an error. Nil completions preserve the upstream null result.

func (SlashCommandContribution) Origin

func (command SlashCommandContribution) Origin() (SlashCommandOrigin, bool)

Origin returns the supplied runtime callback identity, if this contribution came from a bridge.

func (SlashCommandContribution) RegistrationIdentity

func (command SlashCommandContribution) RegistrationIdentity() *SlashCommandRegistrationIdentity

RegistrationIdentity remains stable across List snapshots and changes on every registration or replacement admission.

func (SlashCommandContribution) WithOrigin

WithOrigin returns a contribution carrying the bridge's owner/handle identity. The registry still assigns a fresh command-object identity when it admits the contribution.

type SlashCommandOrigin

type SlashCommandOrigin struct {
	Owner  string
	Handle string
}

SlashCommandOrigin identifies an originating callback object inside one isolated runtime, without exposing or comparing Go function pointers.

type SlashCommandRegistrationIdentity

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

SlashCommandRegistrationIdentity is the opaque identity of one frozen registry command object. Its nonzero size preserves distinct live Go pointer identities.

type SlashCommandRegistry

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

SlashCommandRegistry retains the first live registration for each name in insertion order. Methods and listeners run synchronously on the owning presentation executor; listeners may register, replace, or unsubscribe reentrantly.

func NewSlashCommandRegistry

func NewSlashCommandRegistry() *SlashCommandRegistry

NewSlashCommandRegistry creates an empty contribution registry.

func (*SlashCommandRegistry) List

List returns a detached snapshot of visible contributions in name insertion order.

func (*SlashCommandRegistry) Register

func (registry *SlashCommandRegistry) Register(command SlashCommandContribution) (func(), error)

Register rejects an invalid name or an existing registration, including a staged replacement.

func (*SlashCommandRegistry) Replace

func (registry *SlashCommandRegistry) Replace(command SlashCommandContribution) (func(), error)

Replace stages a same-name contribution until the preceding registration closes.

func (*SlashCommandRegistry) Subscribe

func (registry *SlashCommandRegistry) Subscribe(callback func([]SlashCommandContribution)) func()

Subscribe hydrates the listener immediately and returns an idempotent unsubscriber.

type SlashCommandRunResult

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

SlashCommandRunResult is an operation response, a queue response, or nil for no response.

type SlashCommands

type SlashCommands interface {
	Register(SlashCommandContribution) (func(), error)
	Replace(SlashCommandContribution) (func(), error)
	List() []SlashCommandContribution
	Subscribe(func([]SlashCommandContribution)) func()
}

SlashCommands owns ordered local contributions. Replace stages a generation until its predecessor retires. Listener hydration and publications are synchronous on the presentation's owner executor.

type SourceState

type SourceState[T comparable] struct {
	// contains filtered or unexported fields
}

SourceState is a read-only lifecycle snapshot with ordered, context-bearing subscriptions. Equal replacements do not publish. Subscribers must not mutate pointer fields. Callbacks run outside source locks and should return promptly.

Each subscription has its own queue of at most stateSubscriberQueueLimit deliveries and runs one callback at a time, so a callback that publishes sees its own later deliveries only after it returns. Unsubscribing drops the queued deliveries, even those of a publication that already snapshotted the subscription. A callback panic never reaches the publisher: it is reported and later deliveries continue. Go callbacks cannot return a Promise, so upstream's wait for one has no counterpart.

func (*SourceState[T]) Subscribe

func (state *SourceState[T]) Subscribe(listener func(T, context.Context, ReplicatedStateDelivery)) func()

Subscribe synchronously hydrates the listener and returns an idempotent removal function. Removal drops queued deliveries but does not stop a callback that is running. A callback that panics is reported and stays subscribed.

func (*SourceState[T]) Value

func (state *SourceState[T]) Value() T

type TaskGraphActivity

type TaskGraphActivity interface {
	Subscribe(func(active bool)) func()
	Dispose()
}

TaskGraphActivity reports whether the durable Harness has a live task. Subscribe delivers the current activity and then every change, and returns its unsubscribe function; Dispose detaches the observation.

type Transcript

type Transcript interface {
	State() chord.ReplicatedStateOf[ConversationView]
}

Transcript is the root conversation's durable view, replicated through Chord's operation stream: the active entries and its live, inbox, agent and usage documents.

type TranscriptConversation

type TranscriptConversation interface {
	ViewState(context.Context) (TranscriptViewState, error)
}

TranscriptConversation is the observation boundary the Transcript provider consumes from the root conversation.

type TranscriptViewState

type TranscriptViewState interface {
	chord.ReplicatedStateOf[ConversationView]
	Dispose()
}

TranscriptViewState is the conversation's attached durable view state. The durable Harness publishes exact operations per commit, so the worker keeps no reducer of its own. Dispose detaches it.

type WorkerServiceScope

type WorkerServiceScope struct {
	ServerConnectionId string
	AttachmentId       string
}

WorkerServiceScope binds one endpoint to an attachment on a server connection.

Jump to

Keyboard shortcuts

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