shared

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2026 License: MIT Imports: 17 Imported by: 0

README

Mini shared transport

This opt-in internal library ports Pi's experimental/mini/shared contracts. It does not add a command or contact a remote service.

JsonConnection owns a readable/writable pair. SocketTransport listens and connects over a local Unix socket. ChildConnection takes an already spawned child's stdin, stdout, and kill callback. The process owner still starts and waits for that child. ParentConnection uses the child's standard input/output and leaves stdout owned by the process.

Register close handlers before the first message handler. The first OnMessage starts delivery. Message handlers execute in registration order on one reader goroutine and must return promptly. Send serializes and queues a complete frame without waiting for the remote reader. Like Pi's writable stream, the output queue has no application-level cap; the owner must close an unresponsive connection. Close interrupts IO and notifies close handlers once. Each explicit Close invokes the supplied cleanup callback, including repeated calls, as Pi does. Wait joins the IO pumps; call it from the owner, not a message or close callback.

Framing splits only on LF. Empty lines are ignored. CRLF works because CR is JSON whitespace. An unterminated final line is discarded, unlike the separate published RPC mode's JSONL reader. Malformed JSON terminates this connection and is available through Err; this is Go's error boundary for Pi's uncaught parser exception. The serializer preserves literal HTML characters and U+2028/U+2029. A literal backslash followed by u2028 is not converted into a separator.

The service API structs contain function fields. Context arguments and error returns represent process-local cancellation and Promise rejection; they are not wire arguments. Service tokens attach those API shapes and event types to the exact upstream service names. SessionSnapshot.Lane, LaneEvent.Event, and auth notices carry lossless json.RawMessage because this transport routes harness/auth-owned data without interpreting it. The owner decodes the payload into its domain types. No replacement harness types or default snapshots are fabricated here.

RPC peer

CreatePeer(connection, PeerOptions{}) creates a bidirectional peer. Provide(peer, Worker, implementation) registers a typed function-field API. Use(peer, Worker, CallOptions{}) returns the same API shape with remote functions. These two operations are package functions because Go does not support generic methods. peer.Provide also accepts a Service map of context-aware handlers. peer.Use provides an untyped Remote.Call for routers and dynamically named services.

Call and CallWith block until one result or error arrives. A context cancelled before sending consumes an ID but emits no frame. Cancellation during a call sends cancel and rejects locally with Call cancelled. A configured TimeoutMs sends the same cancellation frame and includes the method and timeout in the error. The receiving handler gets a context whose cause is Cancelled by caller. Closing a connection rejects all pending calls and cancels all in-flight handlers with Connection closed. Late results and unknown response IDs are ignored. As in Pi, sends on an already closed connection are no-ops: a call begun after close still waits for its own context cancellation or timeout. Owners must bound such calls or avoid starting them after shutdown.

Handlers enter in frame order. Pi invokes an async handler synchronously through its first await; the Go reader likewise waits for a handler's synchronous prefix to finish. A handler must call Yield(ctx) immediately before a non-RPC blocking wait. Call, CallWith, and typed remote calls yield automatically after sending when passed the handler context. Preserve that context (or a derived context) through nested calls. Do not yield before the upstream synchronous effects have run. After yielding, the handler may complete concurrently with later calls, events, and replies. Yield releases frame delivery, not ownership: Wait still joins the entire handler. Calling Yield repeatedly or outside a handler is harmless.

The handler context is not a wire argument. A nil result becomes JSON null. Returned errors and recovered handler panics become error replies. The forward callback handles only absent services; a missing method on a local service is an error, not a forwarding request. Its Go context carries the same dispatch turn so forwarding can yield or make a nested call. It has no cancellation signal from this hop, matching Pi; its owner must arrange downstream lifetime management.

Service announcements retain insertion order and replace the remote inventory. Re-registering a service replaces its implementation without moving its name. OnEvent observes every event, including its optional destination. On filters by service name. Event callbacks run in registration order on the reader goroutine. A router republishes with EmitRaw, preserving the difference between an absent destination and an empty destination.

Liveness uses Pi's default silence interval and ping cadence. Any frame refreshes it. Set DeadMs to a pointer to zero to disable it. Close stops the watchdog, cancels handlers, and closes the connection. Wait joins the watchdog and handlers. Call it from the owner after closing, never from a handler. Context-cooperative handlers drain; a forward callback or handler that ignores shutdown still belongs to its owner and can keep Wait blocked. Protocol and asynchronous send failures are available through Err.

Verification

Tests import the exact pinned upstream source through Node for the framing and handler-order oracles. The handler-order test sends adjacent calls and a service-replacement event through the production Go JSON reader and compares the invocation trace to Pi's createPeer. Dynamic, typed, and forwarding handlers must enter before the following event. The RPC integration test spawns the real Pi peer over child pipes and checks concurrent reverse calls, service errors, undefined-to-null results, forwarding, addressed events, cancellation causes, and late results. Other tests drive the Go implementation through in-memory duplex streams and an isolated filesystem socket. go test -race ./internal/experimental/mini/shared requires the repository's Node and Go toolchains but no package installation, model credentials, or external service.

BenchmarkRpcRoundTrip measures a typed worker call through two peers and the complete local JSON framing path. It reports allocations. Profile this benchmark before changing dispatch or serialization for performance; no speedup is claimed by this port.

Documentation

Overview

Package shared implements mini's local service protocol and transports.

Index

Constants

This section is empty.

Variables

View Source
var (
	Lane     = DefineService[LaneServiceApi, LaneEvent]("lane")
	Models   = DefineService[ModelsServiceApi, ModelsEvent]("models")
	Worker   = DefineService[WorkerServiceApi, struct{}]("worker")
	Sessions = DefineService[SessionsServiceApi, struct{}]("sessions")
)

Functions

func On

func On[API, Event any](peer *RpcPeer, token ServiceToken[API, Event], handler func(Event))

func Provide

func Provide[API, Event any](peer *RpcPeer, token ServiceToken[API, Event], implementation API) error

func Use

func Use[API, Event any](peer *RpcPeer, token ServiceToken[API, Event], options CallOptions) (API, error)

Use binds each API function field to the same named remote method. Go has no generic methods or dynamic property proxy, so the typed form is a package function.

func Yield

func Yield(ctx context.Context)

Yield ends an incoming handler's synchronous prefix so the reader can deliver subsequent frames. Call it immediately before a blocking wait corresponding to an upstream await. Call and CallWith yield automatically after sending. Yield does not detach work: the peer owns the entire handler until it returns. It is a no-op outside a handler or after the first yield.

Types

type AuthEventPayload

type AuthEventPayload struct {
	Type      string             `json:"type"`
	RequestID *string            `json:"requestId,omitempty"`
	Request   *AuthPromptRequest `json:"request,omitempty"`
	Notice    json.RawMessage    `json:"notice,omitempty"`
}

AuthEventPayload is the prompt/notice half of the models event channel.

type AuthPromptOption

type AuthPromptOption struct {
	ID          string  `json:"id"`
	Label       string  `json:"label"`
	Description *string `json:"description,omitempty"`
}

type AuthPromptRequest

type AuthPromptRequest struct {
	Type        string              `json:"type"`
	Message     string              `json:"message"`
	Placeholder *string             `json:"placeholder,omitempty"`
	Options     *[]AuthPromptOption `json:"options,omitempty"`
}

AuthPromptRequest carries the prompt without its process-local cancellation signal.

type CallOptions

type CallOptions struct {
	// TimeoutMs bounds the call only when present. The context passed to CallWith supplies cancellation.
	TimeoutMs *float64
}

type CommandResult

type CommandResult struct {
	OK    bool    `json:"ok"`
	Error *string `json:"error,omitempty"`
}

CommandResult reports command failure as data rather than an RPC error.

type Connection

type Connection interface {
	Send(any) error
	OnMessage(func(json.RawMessage))
	OnClose(func())
	Close() error
}

Connection carries ordered JSON messages. Callbacks run serially on the reader; they must return promptly. Send queues a frame without waiting for the remote reader.

type Forward

type Forward func(ctx context.Context, method string, args []json.RawMessage) (any, error)

Forward routes calls for services not provided by this peer. Its context carries the dispatch turn for Yield and nested calls, but no cancellation signal from this hop.

type Handler

type Handler func(context.Context, []json.RawMessage) (any, error)

Handler receives wire arguments and the process-local cancellation signal. Its synchronous prefix runs before the next frame. Before blocking, it must call Yield or an RPC Call with this context; completion may then overlap later handlers.

type JSONConnection

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

JSONConnection owns its reader, writer, and their shutdown. Wait joins both pumps after Close. Incomplete final lines are not messages.

func ChildConnection

func ChildConnection(stdin io.WriteCloser, stdout io.ReadCloser, kill func() error) (*JSONConnection, error)

ChildConnection connects the parent's view of a spawned child's pipes. The caller owns starting and waiting for the process; closing this connection also invokes kill.

func JsonConnection

func JsonConnection(input io.ReadCloser, output io.WriteCloser, closeConnection func() error) *JSONConnection

JsonConnection frames JSON over an existing duplex pair. The first OnMessage registration starts delivery, allowing the owner to install its callbacks before any frame arrives.

func ParentConnection

func ParentConnection() *JSONConnection

ParentConnection connects a child's standard input/output. Closing stops reading from the parent.

func (*JSONConnection) Close

func (c *JSONConnection) Close() error

func (*JSONConnection) Err

func (c *JSONConnection) Err() error

Err reports a fatal framing or IO failure. An orderly EOF or explicit close has no error.

func (*JSONConnection) OnClose

func (c *JSONConnection) OnClose(handler func())

func (*JSONConnection) OnMessage

func (c *JSONConnection) OnMessage(handler func(json.RawMessage))

func (*JSONConnection) Send

func (c *JSONConnection) Send(message any) error

func (*JSONConnection) Wait

func (c *JSONConnection) Wait()

type LaneEvent

type LaneEvent struct {
	SubscriptionID string `json:"subscriptionId"`
	// Event is the harness-owned event, forwarded without decoding or losing fields.
	Event json.RawMessage `json:"event"`
}

type LaneServiceApi

type LaneServiceApi struct {
	Watch    func(context.Context, string) (LaneSubscription, error)
	Start    func(context.Context, string) error
	Unwatch  func(context.Context, string) error
	Prompt   func(context.Context, string) (CommandResult, error)
	Steer    func(context.Context, string) (CommandResult, error)
	FollowUp func(context.Context, string) (CommandResult, error)
	Compact  func(context.Context) (CommandResult, error)
	Abort    func(context.Context) (CommandResult, error)
	SetModel func(context.Context, ModelRef) (CommandResult, error)
}

Service APIs use function fields so the same shape can describe local implementations and remote calls. Context is process-local and never enters the wire args.

type LaneSubscription

type LaneSubscription struct {
	SubscriptionID string          `json:"subscriptionId"`
	Snapshot       SessionSnapshot `json:"snapshot"`
}

type Listener

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

Listener stops accepting on Close and waits for existing connections to close, as node:net Server.close does.

func (*Listener) Close

func (l *Listener) Close() error

type ModelRef

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

type ModelSummary

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

type ModelsEvent

type ModelsEvent struct {
	Type      string             `json:"type"`
	State     *ModelsState       `json:"state,omitempty"`
	RequestID *string            `json:"requestId,omitempty"`
	Request   *AuthPromptRequest `json:"request,omitempty"`
	Notice    json.RawMessage    `json:"notice,omitempty"`
}

ModelsEvent is state, prompt, or notice; only the corresponding payload is present.

type ModelsServiceApi

type ModelsServiceApi struct {
	Refresh   func(context.Context) (CommandResult, error)
	Login     func(context.Context, string, string) (CommandResult, error)
	AuthReply func(context.Context, string, *string) error
}

type ModelsState

type ModelsState struct {
	Models     []ModelSummary    `json:"models"`
	Accounts   []ProviderAccount `json:"accounts"`
	Refreshing bool              `json:"refreshing"`
}

type PeerOptions

type PeerOptions struct {
	Forward Forward
	// DeadMs defaults to 15000; zero disables liveness.
	DeadMs *float64
}

type ProviderAccount

type ProviderAccount struct {
	ID          string  `json:"id"`
	Name        string  `json:"name"`
	AuthType    string  `json:"authType"`
	Configured  bool    `json:"configured"`
	Source      *string `json:"source,omitempty"`
	Interactive bool    `json:"interactive"`
	MethodName  *string `json:"methodName,omitempty"`
}

type Remote

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

Remote addresses one service without a compile-time API shape.

func (*Remote) Call

func (r *Remote) Call(ctx context.Context, method string, args ...any) (json.RawMessage, error)

type RpcPeer

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

RpcPeer is a bidirectional peer. Call blocks until the answer, cancellation, timeout, or connection close. Incoming handlers enter in frame order and may complete concurrently after Yield; Wait joins them after Close. Handlers must respect their contexts to permit shutdown to finish.

func CreatePeer

func CreatePeer(connection Connection, options PeerOptions) *RpcPeer

func (*RpcPeer) Announced

func (p *RpcPeer) Announced() []string

func (*RpcPeer) Call

func (p *RpcPeer) Call(ctx context.Context, method string, args ...any) (json.RawMessage, error)

func (*RpcPeer) CallWith

func (p *RpcPeer) CallWith(ctx context.Context, options CallOptions, method string, args ...any) (json.RawMessage, error)

func (*RpcPeer) Close

func (p *RpcPeer) Close() error

func (*RpcPeer) Emit

func (p *RpcPeer) Emit(token Token, event any) error

func (*RpcPeer) EmitRaw

func (p *RpcPeer) EmitRaw(service string, payload any, to *string) error

func (*RpcPeer) EmitTo

func (p *RpcPeer) EmitTo(token Token, event any, to string) error

func (*RpcPeer) Err

func (p *RpcPeer) Err() error

Err returns a fatal protocol or send error. Remote method errors belong to their Call result instead.

func (*RpcPeer) On

func (p *RpcPeer) On(token Token, handler func(json.RawMessage))

func (*RpcPeer) OnClose

func (p *RpcPeer) OnClose(handler func())

func (*RpcPeer) OnEvent

func (p *RpcPeer) OnEvent(handler func(service string, payload json.RawMessage, to *string))

func (*RpcPeer) Provide

func (p *RpcPeer) Provide(token Token, implementation any) error

Provide accepts a Service map or a struct of API function fields. Replacing an implementation preserves its announcement order.

func (*RpcPeer) Provided

func (p *RpcPeer) Provided() []string

func (*RpcPeer) Use

func (p *RpcPeer) Use(token Token, options CallOptions) *Remote

func (*RpcPeer) Wait

func (p *RpcPeer) Wait()

type Service

type Service map[string]Handler

type ServiceToken

type ServiceToken[API, Event any] struct{ Name string }

ServiceToken attaches a service's call and event types to its globally unique name.

func DefineService

func DefineService[API, Event any](name string) ServiceToken[API, Event]

func (ServiceToken[API, Event]) ServiceName

func (t ServiceToken[API, Event]) ServiceName() string

type SessionSnapshot

type SessionSnapshot struct {
	SessionID   string `json:"sessionId"`
	Cwd         string `json:"cwd"`
	SessionPath string `json:"sessionPath"`
	// Lane is the harness-owned snapshot, forwarded without decoding or losing fields.
	Lane   json.RawMessage `json:"lane"`
	Models ModelsState     `json:"models"`
}

type SessionSummary

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

type SessionsServiceApi

type SessionsServiceApi struct {
	List   func(context.Context) ([]SessionSummary, error)
	Attach func(context.Context, *string, string, string) (string, error)
}

type Token

type Token interface{ ServiceName() string }

Token is the name-bearing half of a service token used by the RPC router.

type UnixTransport

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

UnixTransport negotiates local connections at a filesystem socket path.

func SocketTransport

func SocketTransport(path string) *UnixTransport

func (*UnixTransport) Connect

func (t *UnixTransport) Connect(ctx context.Context) (*JSONConnection, error)

func (*UnixTransport) Listen

func (t *UnixTransport) Listen(onConnection func(*JSONConnection)) (*Listener, error)

Listen removes a stale file or socket, but never a directory, before binding the local endpoint.

type WorkerDescription

type WorkerDescription struct {
	SessionID string `json:"sessionId"`
}

type WorkerServiceApi

type WorkerServiceApi struct {
	Describe func(context.Context) (WorkerDescription, error)
}

Jump to

Keyboard shortcuts

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