app

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 35 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package app coordinates ChannelTerm application use cases.

It composes configuration, transports, and Session ownership without adding protocol behavior to the Session Core or presentation behavior to adapters.

Index

Constants

View Source
const (
	// FileTransferChunkSize bounds how long Ctrl+C must wait for an already
	// active raw-terminal block. At 115200 baud, 8 KiB is normally below one
	// second while still amortizing the shell acknowledgement round trip.
	FileTransferChunkSize = 8 * 1024
)
View Source
const (
	// MaxSessionWriteBytes is the largest payload accepted by one application
	// write operation, including writes authorized by a Session lease.
	MaxSessionWriteBytes = 1 * 1024 * 1024
)
View Source
const (
	// MaxTerminalCommandBytes bounds one terminal_exec shell command before any
	// remote wrapper is allocated or written.
	MaxTerminalCommandBytes = 64 * 1024
)

Variables

View Source
var (
	// ErrNilApplicationManager is returned when Application cannot provide
	// Session use cases because no Session Manager was supplied.
	ErrNilApplicationManager = errors.New("application session manager must not be nil")
	// ErrNilDeviceRegistry is returned when a device use case is requested
	// without the optional discovery dependency configured.
	ErrNilDeviceRegistry = errors.New("application device registry must not be nil")
	// ErrSessionNotFound is returned when a Session use case receives no active
	// Session ID or short reference owned by the Application's Manager.
	ErrSessionNotFound = errors.New("application session not found")
	// ErrWritePayloadTooLarge is returned before a Session write when its payload
	// exceeds MaxSessionWriteBytes.
	ErrWritePayloadTooLarge = errors.New("session write payload exceeds maximum size")
)
View Source
var (
	// ErrDirectoryTarUnavailable is returned when the POSIX target has no tar
	// command. ChannelTerm does not install target-side software automatically.
	ErrDirectoryTarUnavailable = errors.New("Remote tar command is unavailable.\nDirectory transfer is not supported on this target.")
	// ErrUnsupportedDirectoryEntry is returned for local filesystem entries
	// that the first directory-transfer version deliberately does not preserve.
	ErrUnsupportedDirectoryEntry = errors.New("directory transfer supports only regular files and directories")
	// ErrUnsafeTarPath is returned when a remote tar member could escape the
	// caller-owned extraction directory.
	ErrUnsafeTarPath = errors.New("unsafe tar entry path")
)
View Source
var (
	// ErrFileTransferProtocol is returned when the remote shell emits an invalid
	// or unexpected ChannelTerm file-transfer control marker.
	ErrFileTransferProtocol = errors.New("invalid file transfer protocol response")
	// ErrFileTransferSizeMismatch is returned when the verified byte count does
	// not match the announced or locally supplied file size.
	ErrFileTransferSizeMismatch = errors.New("file transfer size mismatch")
	// ErrFileTransferChecksumMismatch is returned when SHA-256 verification
	// differs between the sending and receiving endpoints.
	ErrFileTransferChecksumMismatch = errors.New("file transfer SHA-256 mismatch")
)
View Source
var (
	// ErrInvalidLeaseOwner is returned when a lease request has no owner token.
	ErrInvalidLeaseOwner = errors.New("lease owner is required")
	// ErrInvalidLeaseType is returned when a lease request uses an unsupported type.
	ErrInvalidLeaseType = errors.New("lease type is invalid")
	// ErrSessionBusy is returned when a writer does not own a Session's active lease.
	ErrSessionBusy = errors.New("session is busy")
	// ErrLeaseNotOwned is returned when a caller attempts to release a lease held by another owner.
	ErrLeaseNotOwned = errors.New("session lease is not owned by caller")
	// ErrFileTransferCancelPending is returned when another attachment already
	// owns the confirmation prompt for the active file transfer.
	ErrFileTransferCancelPending = errors.New("file transfer cancellation confirmation is already pending")
	// ErrFileTransferCancelRequest is returned for a stale or unknown request ID.
	ErrFileTransferCancelRequest = errors.New("file transfer cancellation request is invalid")
	// ErrFileTransferIDMismatch is returned when file-transfer status does not
	// identify the transfer owned by the active file-transfer lease.
	ErrFileTransferIDMismatch = errors.New("file transfer ID does not match the active lease")
)
View Source
var (
	// ErrTerminalCommandRequired is returned when terminal_exec has no command.
	ErrTerminalCommandRequired = errors.New("terminal command is required")
	// ErrTerminalCommandTooLarge is returned before acquiring a lease when one
	// command exceeds MaxTerminalCommandBytes.
	ErrTerminalCommandTooLarge = errors.New("terminal command exceeds maximum size")
	// ErrTerminalCommandControlCharacter prevents multiline input and terminal
	// control bytes from escaping the structured Agent presentation boundary.
	ErrTerminalCommandControlCharacter = errors.New("terminal command must be one printable line")
	// ErrTerminalCommandInputPending prevents an isolated command bootstrap from
	// being appended to bytes already waiting in the interactive line editor.
	ErrTerminalCommandInputPending = errors.New("terminal has unsubmitted interactive input")
	// ErrTerminalCommandRequiresBash reports that zero-history execution cannot
	// be guaranteed for the active interactive shell.
	ErrTerminalCommandRequiresBash = errors.New("zero-history terminal commands require an interactive Bash shell")
	// ErrTerminalCommandProtocol identifies a missing or malformed target-side
	// command marker.
	ErrTerminalCommandProtocol = errors.New("invalid terminal command protocol response")
)
View Source
var (
	// ErrNilSessionManager is returned when a SerialService has no Session owner.
	ErrNilSessionManager = errors.New("session manager must not be nil")
)
View Source
var ErrSessionIDExhausted = errors.New("could not allocate a unique session ID")

ErrSessionIDExhausted is returned only when generated Session IDs collide repeatedly.

Functions

func ConnectRSPBridge added in v0.3.0

func ConnectRSPBridge(ctx context.Context, info debugger.BridgeConnection) (io.ReadWriteCloser, error)

ConnectRSPBridge connects a byte-stream adapter and its independent control heartbeat without starting or controlling GDB. ctx bounds dialing/authentication; after return the caller owns both sockets through the stream's Close method. Secret descriptors must remain private.

func PlanDirectory

func PlanDirectory(source string) (int64, error)

PlanDirectory validates source and calculates the exact bytes emitted by Go's archive/tar writer without materializing an archive in memory or on disk. It is exported so callers can reject unsupported local sources before acquiring a shared Session lease.

func WithFileTransferShell

func WithFileTransferShell(ctx context.Context, terminal FileTransferSession, operation func(FileTransferSession) error) (err error)

WithFileTransferShell runs operation inside one non-interactive target-side shell. An interactive Bash parent deletes the bootstrap from its in-memory history while other shells still receive one recognizable entry instead of one command per bounded payload chunk. Nested calls reuse the active shell.

Types

type Application

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

Application is the UI-independent entry point for ChannelTerm use cases.

It delegates each concern to the existing SerialService, Session Manager, Device Registry, and Connection Policy packages. Application intentionally owns managed debug operations but no terminal presentation, protocol schema, host stdin/stdout, or Host process lifetime. The Composition Root owns the supplied Manager and Registry.

func New

func New(dependencies Dependencies) (*Application, error)

New creates an Application from Core runtime dependencies.

New does not start or close the supplied Device Registry and does not close Manager. The caller that assembled those long-lived resources retains their lifecycle ownership, allowing one Application to serve multiple adapters.

func (*Application) AcquireLease

func (a *Application) AcquireLease(identifier, owner string, typ LeaseType) (SessionLease, error)

AcquireLease creates one exclusive application-level lease for an active Session. Readers and raw output are unaffected. An expired debug lease closes the Session because restoring its terminal state cannot be assumed.

func (*Application) AttachSession

func (a *Application) AttachSession(identifier, actor string) error

AttachSession records one adapter attachment to an active Session. It does not acquire writer ownership or alter Session lifecycle; it only publishes observer-visible metadata on the separate Session event stream.

func (*Application) BeginFileTransferCancel

func (a *Application) BeginFileTransferCancel(identifier string) (FileTransferCancelRequest, error)

BeginFileTransferCancel atomically opens a confirmation request only when identifier currently has an active file-transfer lease. Ordinary terminal input can therefore preserve its existing Ctrl+C byte semantics.

func (*Application) CloseRSPBridge added in v0.3.0

func (a *Application) CloseRSPBridge(id, owner string) (BridgeStatus, error)

CloseRSPBridge idempotently closes both the bridge and its serial Session. It never sends RSP commands or claims shell recovery. Use RestoreRSPBridge after externally ending RSP to preserve a verified terminal Session instead.

func (*Application) CloseSession

func (a *Application) CloseSession(identifier string) (session.SessionInfo, error)

CloseSession removes and closes a managed Session identified by its opaque ID or short reference. It returns the pre-close SessionInfo so adapters can report stable metadata without retaining the Session object.

func (*Application) ConnectionDecision

func (a *Application) ConnectionDecision(ctx context.Context, transport, endpoint string) (ConnectionDecision, error)

ConnectionDecision returns the policy action for one discovered endpoint. It never opens a Transport, creates a Session, or prompts a user.

func (*Application) DebugCommand added in v0.3.0

func (a *Application) DebugCommand(ctx context.Context, q DebugCommandRequest) (debugger.Record, error)

DebugCommand executes an allow-listed action with token correlation and retry deduplication. A timeout with uncertain execution fails the operation closed. Completed GDB errors remain retryable with a new request ID.

func (*Application) DetachSession

func (a *Application) DetachSession(identifier, actor string) error

DetachSession records one adapter detachment from an active Session. It does not close the shared Session or affect any other attachment.

func (*Application) ExecuteTerminalCommand

func (a *Application) ExecuteTerminalCommand(ctx context.Context, identifier, command string) (result TerminalCommandResult, err error)

ExecuteTerminalCommand runs command in a non-interactive child shell of an idle interactive Bash prompt. The parent Bash removes the bootstrap from its current in-memory history before disabling terminal echo. A terminal lease excludes concurrent ChannelTerm writers for the operation, and Application renews that lease until completion or bounded cancellation recovery.

ctx cancellation sends Ctrl+C through the owned lease and waits briefly for the wrapper to restore terminal echo. If recovery cannot be confirmed, the Session is closed rather than releasing a possibly corrupted terminal.

func (*Application) FileTransferCheckpoint

func (a *Application) FileTransferCheckpoint(ctx context.Context, identifier, owner string) (FileTransferControlAction, error)

FileTransferCheckpoint blocks a lease owner at a safe protocol boundary while a user confirmation is pending, then returns continue or cancel.

func (*Application) LeaseStatus

func (a *Application) LeaseStatus(identifier string) (SessionLease, bool, error)

LeaseStatus reports identifier's current exclusive lease, if any.

func (*Application) ListDevices

func (a *Application) ListDevices(ctx context.Context) ([]device.Device, error)

ListDevices returns the current Device Registry snapshot without opening an endpoint or creating a Session.

func (*Application) ListRSPBridges added in v0.3.0

func (a *Application) ListRSPBridges(ctx context.Context) ([]BridgeSummary, error)

ListRSPBridges returns all unfinished external bridges in this Application, ordered by port, address, then bridge ID. Disconnected and recovering bridges remain included until finalization; closed, failed, and restored runs are excluded. Snapshots may change immediately after reading; this is not an OS-wide port scan. It neither renews leases nor sends target bytes. Cancellation stops collection without affecting bridges. Adapters must enforce Host access policy; observation does not require a per-bridge owner capability.

func (*Application) ListSerialPorts

func (a *Application) ListSerialPorts(ctx context.Context) ([]serialtransport.Port, error)

ListSerialPorts returns operating-system-reported ports without opening a Transport, creating a Session, or changing device discovery state.

func (*Application) ListSerialProfiles

func (a *Application) ListSerialProfiles(ctx context.Context, configuredPath string) ([]SerialProfileInfo, error)

ListSerialProfiles loads an existing configuration file and returns named Serial profiles after inheritance resolution. An absent file is treated as an empty profile list so read-only discovery never creates configuration.

func (*Application) ListSessions

func (a *Application) ListSessions() []session.SessionInfo

ListSessions returns a point-in-time snapshot of Application-managed Sessions without exposing their Transport implementations.

func (*Application) OpenSSH added in v0.2.0

func (a *Application) OpenSSH(ctx context.Context, request OpenSSHRequest) (OpenSSHResult, error)

OpenSSH opens or reuses a Session for the exact SSH user, host, and port. ctx cancels connection setup and duplicate-open waiting. Reuse retains the original credentials, PTY settings, and label; it does not reauthenticate. Manager owns successful Sessions, and closes them through existing lifecycle handling. No SSH configuration file or discovery state is created.

func (*Application) OpenSerial

func (a *Application) OpenSerial(ctx context.Context, request OpenSerialRequest) (OpenSerialResult, error)

OpenSerial resolves a profile and explicit overrides, opens or reuses a serial Session, and returns structured Manager-owned Session metadata.

ctx cancels configuration access and connection setup. A wake byte is sent only when the resolved profile enables it, preserving the existing explicit opt-in behavior.

func (*Application) RSPBridgeStatus added in v0.3.0

func (a *Application) RSPBridgeStatus(id, owner string) (BridgeStatus, error)

RSPBridgeStatus reads lifecycle state without renewing the management TTL.

func (*Application) ReadDebugEvents added in v0.3.0

func (a *Application) ReadDebugEvents(ctx context.Context, id, owner string, cursor uint64) (DebugEvents, error)

ReadDebugEvents waits up to the caller's deadline for events after cursor. Reads renew the client heartbeat but not ownership after a terminal failure.

func (*Application) ReadDeviceEvents

func (a *Application) ReadDeviceEvents(ctx context.Context, cursor *device.Cursor, maxEvents int) (device.EventChunk, error)

ReadDeviceEvents returns retained device transitions or waits after cursor. A nil cursor reads recent retained events without waiting.

func (*Application) ReadSession

func (a *Application) ReadSession(ctx context.Context, identifier string, cursor *session.OutputCursor, maxBytes int) (session.OutputChunk, error)

ReadSession returns retained terminal output or waits for output after the supplied cursor. A nil cursor reads recent output without waiting.

ctx controls only cursor waits. The returned OutputChunk is raw terminal data and is never converted to CLI or protocol presentation text.

func (*Application) ReadSessionActivity

func (a *Application) ReadSessionActivity(ctx context.Context, identifier string, cursor *session.ActivityCursor, maxEvents int) (session.ActivityChunk, error)

ReadSessionActivity returns retained operation activity or waits after the supplied cursor. A nil cursor reads the most recent retained events.

ctx controls only cursor waits. Activity remains separate from terminal output so adapters cannot accidentally interpret local metadata as device bytes.

func (*Application) ReadSessionEvents

func (a *Application) ReadSessionEvents(ctx context.Context, identifier string, cursor *session.EventCursor, maxEvents int) (session.EventChunk, error)

ReadSessionEvents returns retained structured Session events or waits after the supplied cursor. A nil cursor reads the newest retained events. Events are separate from raw output and activity, so each observer has an independent cursor and cannot consume terminal data for another client.

func (*Application) ReleaseLease

func (a *Application) ReleaseLease(identifier, owner string) error

ReleaseLease releases identifier's lease only when owner matches its owner capability. Releasing an already absent lease is successful and idempotent. Managed debug leases must end through their MI or RSP bridge lifecycle to verify terminal restoration or close the Session.

func (*Application) RenewLease

func (a *Application) RenewLease(identifier, owner string) (SessionLease, error)

RenewLease extends an active lease only when owner matches its opaque capability. Callers must renew before ExpiresAt to retain writer ownership.

func (*Application) RenewRSPBridge added in v0.3.0

func (a *Application) RenewRSPBridge(id, owner string) (BridgeStatus, error)

RenewRSPBridge renews the internal lease before extending the 60-second management TTL, capped by the absolute lifetime. An expired or ended operation cannot be resurrected, even if the timer has not run yet.

func (*Application) ReportFileTransferEvent

func (a *Application) ReportFileTransferEvent(identifier, owner, transferID string, typ session.EventType, actor string, metadata map[string]any) error

ReportFileTransferEvent publishes one validated file-transfer transition on the Session event stream. owner and transferID must match the active file-transfer lease. Metadata is presentation data only and must not include transfer payload bytes or lease owner capabilities.

func (*Application) ReportRSPBridge added in v0.3.0

ReportRSPBridge publishes Codex-reported text through the Session event stream. It never writes target bytes, runs GDB, changes target state, or renews leases. Failure/cancellation affects only reporting. The latest identical report may be retried without duplication; older/conflicting sequences are rejected. Only bounded UTF-8 text is accepted, with known bridge capabilities rejected. Callers remain responsible for omitting other secrets and raw RSP traffic.

func (*Application) ResizeSession added in v0.2.0

func (a *Application) ResizeSession(identifier string, cols, rows uint16) error

ResizeSession forwards character dimensions to a managed Session's optional Channel capability. It returns the existing lookup, lifecycle, or unsupported errors unchanged. Callers own resize authority; this method does not grant a lease or expose resizing through any network adapter. Closing the Session interrupts an in-flight resize when the underlying transport supports it.

func (*Application) ResolveFileTransferCancel

func (a *Application) ResolveFileTransferCancel(ctx context.Context, identifier, requestID string, cancel bool) (FileTransferCancelResolution, error)

ResolveFileTransferCancel answers a Host-owned confirmation. A negative answer resumes immediately. A positive answer waits until the transfer owner restores protocol state and releases its lease.

func (*Application) ResolveSerialTarget

func (a *Application) ResolveSerialTarget(ctx context.Context, target string) (string, error)

ResolveSerialTarget verifies that an operating-system serial endpoint is currently present and returns the exact name reported by discovery. It never opens a Transport or creates a Session. See "Identifiers and References" (docs/reference/identifiers.md) for the target and Session identifier boundary.

func (*Application) RestoreRSPBridge added in v0.3.0

func (a *Application) RestoreRSPBridge(id, owner, ttyState string, confirmShellReady bool) (BridgeStatus, error)

RestoreRSPBridge requires explicit confirmation that the target has returned to its shell and the exact stty -g value saved before target preparation. It refuses an active client. A fresh split-token probe applies and reads back that TTY state; only success releases the lease. Recovery has an independent ten-second deadline; uncertainty closes the Session. No RSP detach is injected.

func (*Application) StartDebug added in v0.3.0

func (a *Application) StartDebug(ctx context.Context, request DebugStartRequest) (DebugStatus, error)

StartDebug takes over a Session, starts gdbserver and GDB/MI, and returns only after remote connection is established. Setup is bounded to 30 seconds. Cancellation after terminal mutation closes the Session unless recovery can be proven; a duplicate request returns the original operation, never launches another inferior. At most 128 operations are retained per Application.

func (*Application) StartRSPBridge added in v0.3.0

StartRSPBridge exposes one prepared serial Session through authenticated TLS over TCP. It checks open state and pending input under an exclusive lease, but does not send an RSP probe or infer readiness from silence/history. Output begins at the current cursor, never by replaying terminal history. Setup errors release the lease without mutating target bytes. Retention is bounded to 128.

func (*Application) StopDebug added in v0.3.0

func (a *Application) StopDebug(ctx context.Context, id, owner string, terminate bool) (DebugStatus, error)

StopDebug idempotently detaches by default. terminate is permitted only for an inferior launched by this operation. Recovery uses its own bounded context so a cancelled MCP request cannot release an unverified terminal.

func (*Application) WriteSession

func (a *Application) WriteSession(ctx context.Context, identifier string, request session.WriteRequest) (int, error)

WriteSession writes one complete payload to a managed Session. It rejects writes while another operation owns an exclusive lease.

ctx is checked before the operation and between short-write retries. The Session retains responsibility for serializing concurrent writers and for recording the supplied Actor; Application never changes request.Data. A request larger than MaxSessionWriteBytes returns ErrWritePayloadTooLarge without looking up or writing to a Session.

func (*Application) WriteSessionWithLease

func (a *Application) WriteSessionWithLease(ctx context.Context, identifier, owner string, request session.WriteRequest) (int, error)

WriteSessionWithLease writes one complete payload using owner as the capability for an active lease on identifier. owner must match the active lease exactly; ordinary writes must continue to use WriteSession. It applies the same MaxSessionWriteBytes limit as WriteSession.

type BridgeReportRequest added in v0.3.0

type BridgeReportRequest struct {
	BridgeID string `json:"bridge_id"`
	Owner    string `json:"owner"`
	Sequence uint64 `json:"sequence"`
	Kind     string `json:"kind"`
	Text     string `json:"text"`
}

BridgeReportRequest is a caller-selected account of external GDB activity. Kind is command, result, or state; Text must omit protocol bytes and secrets. Sequence increases per bridge; gaps are allowed so failed reporting cannot hold up debugging. This is not an execution request or a complete GDB audit.

type BridgeReportResult added in v0.3.0

type BridgeReportResult struct {
	BridgeID string `json:"bridge_id"`
	Sequence uint64 `json:"sequence"`
}

BridgeReportResult acknowledges event publication, not GDB command execution.

type BridgeStartRequest added in v0.3.0

type BridgeStartRequest struct {
	SessionID                   string `json:"session_id"`
	Owner                       string `json:"owner"`
	RequestID                   string `json:"request_id"`
	ListenAddress               string `json:"listen_address,omitempty"`
	AllowedPeer                 string `json:"allowed_peer,omitempty"`
	StrictPortPool              bool   `json:"strict_port_pool,omitempty"`
	AcknowledgeUnverifiedTarget bool   `json:"acknowledge_unverified_target"`
}

BridgeStartRequest leases an already prepared serial Session without sending target commands. Owner authenticates management calls; RequestID deduplicates exact retries. AcknowledgeUnverifiedTarget confirms out-of-band preparation, not protocol detection. No GDB or gdbserver is started or controlled.

type BridgeStartResult added in v0.3.0

type BridgeStartResult struct {
	Status     BridgeStatus               `json:"status"`
	Connection *debugger.BridgeConnection `json:"connection,omitempty"`
}

BridgeStartResult includes secret connection material only in the authorized start response. Store Connection privately for the external rsp-client helper.

type BridgeStatus added in v0.3.0

type BridgeStatus struct {
	BridgeID      string    `json:"bridge_id"`
	SessionID     string    `json:"session_id"`
	State         string    `json:"state"`
	Address       string    `json:"address"`
	ExpiresAt     time.Time `json:"expires_at"`
	MaxExpiresAt  time.Time `json:"max_expires_at"`
	AutoKeepalive bool      `json:"auto_keepalive"`
	TargetState   string    `json:"target_state"`
	Warning       string    `json:"warning,omitempty"`
	Error         string    `json:"error,omitempty"`
}

BridgeStatus separates transport lifecycle from target and shell state. Disconnected retains the lease; restored alone proves a fresh shell probe and exact caller-supplied TTY-state readback. Closed/failed close the Session. AutoKeepalive reflects recent control evidence. MaxExpiresAt is the absolute lifetime bound, independent of manual or automatic management renewal.

type BridgeSummary added in v0.3.0

type BridgeSummary struct {
	BridgeID      string    `json:"bridge_id"`
	SessionID     string    `json:"session_id"`
	SessionRef    string    `json:"session_ref"`
	Target        string    `json:"target"`
	Address       string    `json:"address"`
	Port          uint16    `json:"port"`
	State         string    `json:"state"`
	ExpiresAt     time.Time `json:"expires_at"`
	AutoKeepalive bool      `json:"auto_keepalive"`
}

BridgeSummary is a non-secret snapshot of an unfinished external RSP bridge. Address and Port identify the Host endpoint, not an unauthenticated GDB target. SessionRef and Target are empty if the Session was removed during finalization. No management capability or connection descriptor is included.

type ConnectedSession

type ConnectedSession interface {
	session.Session
	// Connect establishes the candidate's Transport and starts its Session I/O.
	//
	// ctx controls cancellation and deadlines for protocol-specific connection
	// work. The opening service retains ownership after success until Manager
	// registration, and remains responsible for closing the candidate on error.
	Connect(context.Context) error
}

ConnectedSession is an unregistered Session candidate that can establish its Transport. A Transport-specific open service retains ownership until a successful candidate is transferred to the shared Manager.

type ConnectionDecision

type ConnectionDecision struct {
	Transport        string
	Endpoint         string
	Present          bool
	Connected        bool
	Policy           connectionpolicy.Policy
	Action           connectionpolicy.Action
	SessionID        string
	SessionReference string
}

ConnectionDecision is the structured result of evaluating a discovered endpoint against the current Device Registry, Session snapshot, and policy.

type DebugCommandRequest added in v0.3.0

type DebugCommandRequest struct {
	DebugID   string `json:"debug_id"`
	Owner     string `json:"owner"`
	RequestID string `json:"request_id"`
	Action    string `json:"action"`
	Argument  string `json:"argument,omitempty"`
}

DebugCommandRequest selects one supported MI action. RequestID makes retrying a mutation safe. Argument is one MI-quoted value, never a raw MI command. Multi-inferior and non-stop commands are deliberately absent.

type DebugEvent added in v0.3.0

type DebugEvent struct {
	Sequence uint64          `json:"sequence"`
	Record   debugger.Record `json:"record"`
}

DebugEvent is an ordered MI record or a lifecycle transition.

type DebugEvents added in v0.3.0

type DebugEvents struct {
	Status DebugStatus  `json:"status"`
	Events []DebugEvent `json:"events"`
	Next   uint64       `json:"next"`
}

DebugEvents is a bounded event page. A stale cursor returns an explicit error; callers must never treat lost stop events as an unchanged inferior state.

type DebugStartRequest added in v0.3.0

type DebugStartRequest struct {
	SessionID string   `json:"session_id"`
	Owner     string   `json:"owner"`
	RequestID string   `json:"request_id"`
	ELF       string   `json:"elf"`
	Args      []string `json:"args,omitempty"`
	PID       int      `json:"pid,omitempty"`
	GDB       string   `json:"gdb,omitempty"`
	GDBServer string   `json:"gdbserver,omitempty"`
}

DebugStartRequest starts one Linux all-stop inferior on an idle Bash Session. Owner is a caller-generated secret capability (at least 32 characters). RequestID must be reused unchanged after a lost response; conflicting reuse is rejected. GDB, GDBServer and ELF are absolute local paths. PID zero launches ELF; a positive PID attaches only after local terminal-isolation checks.

type DebugStatus added in v0.3.0

type DebugStatus struct {
	DebugID   string    `json:"debug_id"`
	SessionID string    `json:"session_id"`
	State     string    `json:"state"`
	Next      uint64    `json:"next"`
	ExpiresAt time.Time `json:"expires_at"`
	Error     string    `json:"error,omitempty"`
}

DebugStatus describes a debug operation without disclosing owner capabilities. Closed means the shell probe succeeded and its lease was released; failed means the Session was closed and must be reopened explicitly.

type Dependencies

type Dependencies struct {
	Manager         *session.Manager
	Devices         *device.Registry
	Policy          connectionpolicy.Policy
	Serial          SerialDependencies
	ListSerialPorts func() ([]serialtransport.Port, error)
}

Dependencies supplies the Core capabilities assembled into an Application.

Manager is required because Application always provides Session and Serial use cases. Devices is optional for callers that only open local sessions; device-list and connection-decision use cases return ErrNilDeviceRegistry until a Registry is supplied. Policy defaults to connectionpolicy.Default. Serial and ListSerialPorts are test seams; nil values select production configuration, Serial Transport construction, and port enumeration.

type DirectoryTransferResult

type DirectoryTransferResult struct {
	Size       int64
	SHA256     string
	RemotePath string
}

DirectoryTransferResult reports the tar stream byte count and selected remote destination for a directory transfer. Size counts tar stream bytes, not the sum of local file sizes.

func ReceiveDirectory

func ReceiveDirectory(ctx context.Context, terminal FileTransferSession, remotePath, destination string, progress FileTransferProgress) (DirectoryTransferResult, error)

ReceiveDirectory streams a target-side tar archive into destination, which must be an empty staging directory owned by the caller. Go's tar extractor rejects paths and entry types outside the supported first-version contract.

func SendDirectory

func SendDirectory(ctx context.Context, terminal FileTransferSession, source, remotePath string, progress FileTransferProgress) (DirectoryTransferResult, error)

SendDirectory creates a standard tar stream directly from source, writes it to a remote temporary archive in bounded blocks, and extracts it into a same-directory staging path. The final rename happens only after the archive is complete and tar exits successfully.

type FileTransferCancelRequest

type FileTransferCancelRequest struct {
	Active    bool
	RequestID string
	State     string
}

FileTransferCancelRequest describes a Host-owned cancellation confirmation. RequestID prevents a delayed answer from affecting a later transfer.

type FileTransferCancelRequested

type FileTransferCancelRequested func() bool

FileTransferCancelRequested reports whether a local caller has requested a safe stop. SendFileWithCancellation and ReceiveFileWithCancellation observe it only at protocol chunk boundaries, never by interrupting an active raw terminal block.

type FileTransferCancelResolution

type FileTransferCancelResolution struct {
	State       string
	Transferred int64
	Total       int64
	Percent     float64
}

FileTransferCancelResolution describes the result of answering a pending confirmation. A confirmed cancellation returns only after lease release.

type FileTransferControlAction

type FileTransferControlAction string

FileTransferControlAction tells the lease owner whether its next safe protocol boundary may continue or must stop as a user cancellation.

const (
	// FileTransferContinue allows the next file-transfer block to start.
	FileTransferContinue FileTransferControlAction = "continue"
	// FileTransferCancel stops the transfer after its current safe boundary.
	FileTransferCancel FileTransferControlAction = "cancel"
)

type FileTransferProgress

type FileTransferProgress func(transferred, total int64) error

FileTransferProgress receives transfer byte counts and the total size. A receive operation first invokes it with zero bytes after remote metadata is known and before payload transfer starts; later calls report confirmed bytes. Returning an error stops the transfer and propagates the presentation or I/O failure to the caller.

type FileTransferResult

type FileTransferResult struct {
	Size int64
	// SHA256 is the verified lowercase hexadecimal digest.
	SHA256 string
	// RemotePath is the actual POSIX destination selected for a send transfer.
	RemotePath string
}

FileTransferResult reports the verified file metadata after transfer.

func ReceiveFile

func ReceiveFile(ctx context.Context, terminal FileTransferSession, destination io.Writer, remotePath string, progress FileTransferProgress) (FileTransferResult, error)

ReceiveFile streams remotePath from an idle Linux shell into destination.

Metadata is collected before streaming. Each dd invocation emits at most one fixed-size block while the remote TTY is raw, after which its saved settings are restored. destination is caller-owned and is not closed by ReceiveFile.

func ReceiveFileWithCancellation

func ReceiveFileWithCancellation(ctx context.Context, terminal FileTransferSession, destination io.Writer, remotePath string, cancelRequested FileTransferCancelRequested, progress FileTransferProgress) (FileTransferResult, error)

ReceiveFileWithCancellation receives a file while observing cancelRequested at safe protocol boundaries. A non-nil request never truncates an active raw block emitted by the remote terminal.

func SendFile

func SendFile(ctx context.Context, terminal FileTransferSession, source io.Reader, size int64, remotePath string, progress FileTransferProgress) (FileTransferResult, error)

SendFile streams size bytes from source through terminal into remotePath.

The remote endpoint must be an idle POSIX-compatible Linux shell providing stty, dd with iflag=fullblock, wc, sha256sum, and sleep. Each payload chunk is sent through Session.Write and acknowledged only after dd appends it. The final byte count and SHA-256 digest are independently computed by the remote shell.

func SendFileWithCancellation

func SendFileWithCancellation(ctx context.Context, terminal FileTransferSession, source io.Reader, size int64, remotePath string, cancelRequested FileTransferCancelRequested, progress FileTransferProgress) (FileTransferResult, error)

SendFileWithCancellation streams a file while observing cancelRequested at safe protocol boundaries. A non-nil request never truncates a raw block that has already started on the remote terminal.

type FileTransferSession

type FileTransferSession interface {
	ReadRecent(context.Context, int) (session.OutputChunk, error)
	ReadOutput(context.Context, session.OutputCursor, int) (session.OutputChunk, error)
	Write(session.WriteRequest) (int, error)
}

FileTransferSession is the cursor-based Session view required by file transfer. Implementations may be local Session adapters or remote CLI attachments, but must ultimately read and write through one Session.

type LeaseType

type LeaseType string

LeaseType identifies the exclusive operation currently using a Session.

const (
	// LeaseTypeTerminal reserves a Session for a terminal-oriented operation.
	LeaseTypeTerminal LeaseType = "terminal"
	// LeaseTypeFileTransfer reserves a Session for a multi-chunk file transfer.
	LeaseTypeFileTransfer LeaseType = "file-transfer"
	// LeaseTypeDebug reserves a Session for an exclusive debugging operation.
	LeaseTypeDebug LeaseType = "debug"
)

func (LeaseType) Valid

func (typ LeaseType) Valid() bool

Valid reports whether typ is a supported lease type.

type OpenSSHRequest added in v0.2.0

type OpenSSHRequest struct {
	Config sshtransport.Config
	Label  string
}

OpenSSHRequest supplies explicit SSH connection settings and display-only metadata. Config contains ordinary settings and file paths, not SSH-library objects. Authentication stays inside Transport and never enters SessionInfo.

type OpenSSHResult added in v0.2.0

type OpenSSHResult struct {
	Info   session.SessionInfo
	Reused bool
}

OpenSSHResult identifies a Manager-owned SSH PTY shell Session.

type OpenSerialRequest

type OpenSerialRequest struct {
	Profile    string
	ConfigPath string
	Overrides  config.SerialOverrides
	Save       string
	Label      string
}

OpenSerialRequest describes a caller's serial connection intent.

Overrides must contain only explicitly supplied values, preserving profile inheritance. Label is display metadata and is never used as an identifier.

type OpenSerialResult

type OpenSerialResult struct {
	Info    session.SessionInfo
	Profile config.SerialProfile
	Reused  bool
}

OpenSerialResult reports the Manager-owned Session created or reused by OpenSerial.

type RemotePathKind

type RemotePathKind string

RemotePathKind identifies the supported kind of a target-side source.

const (
	// RemotePathFile is a regular remote file.
	RemotePathFile RemotePathKind = "file"
	// RemotePathDirectory is a remote directory.
	RemotePathDirectory RemotePathKind = "directory"
	// RemotePathMissing does not exist on the target.
	RemotePathMissing RemotePathKind = "missing"
	// RemotePathUnsupported is a symlink or other unsupported special entry.
	RemotePathUnsupported RemotePathKind = "unsupported"
)

func DetectRemotePath

func DetectRemotePath(ctx context.Context, terminal FileTransferSession, remotePath string) (RemotePathKind, error)

DetectRemotePath determines whether remotePath is a regular file, a directory, absent, or unsupported without following symlinks.

type SSHFileVerification added in v0.2.0

type SSHFileVerification struct {
	Name              string
	SourceSHA256      string
	DestinationSHA256 string
}

SSHFileVerification reports per-file checksum work. Matching hashes confirm content, not successful replacement; Files is updated only after completion.

type SSHFilesRequest added in v0.2.0

type SSHFilesRequest struct {
	Config    sshtransport.Config
	Protocol  string
	Operation string
	Local     string
	Remote    string
	Target    string
	Recursive bool
	Overwrite bool
	// SafeReplace stages each SFTP file beside its destination, then renames
	// it after a complete copy. It requires Overwrite and never makes a whole
	// directory transactional. Remote upload requires POSIX rename support.
	SafeReplace bool
	Progress    func(name string, transferred, total int64) error
	// Verify accepts "none" (also the empty default) or "sha256" for put/get.
	// Verification reports a start event with empty hashes, then matching hashes.
	// Returning an error aborts the operation, including before a safe rename.
	Verify       string
	Verification func(SSHFileVerification) error
}

SSHFilesRequest describes one dedicated SSH file operation. Local/Remote are source/destination paths for put/get; Target is the new remote name for rename. Recursive enables directory transfer, not recursive deletion. Overwrite must be explicitly enabled for replacement. Progress is per file and may cancel by returning an error. Passwords are supplied through Config callbacks only. Each regular file reports (name, 0, size) before payload, including empty files.

type SSHFilesResult added in v0.2.0

type SSHFilesResult struct {
	Entries       []sshtransport.FileInfo `json:"entries,omitempty"`
	Files         int64                   `json:"files"`
	Bytes         int64                   `json:"bytes"`
	VerifiedFiles int64                   `json:"verified_files,omitempty"`
}

SSHFilesResult returns remote entries or successfully copied file/byte counts. Files includes requested verification and replacement; Bytes includes partial payloads but excludes checksum readback. VerifiedFiles counts completed files with matching SHA-256 digests. No credentials or Session identifiers are returned.

func RunSSHFiles added in v0.2.0

func RunSSHFiles(ctx context.Context, request SSHFilesRequest) (result SSHFilesResult, err error)

RunSSHFiles owns one operation's dedicated connection and local file handles. Cancellation interrupts the SSH connection. Direct copies can leave partial destinations; SafeReplace instead attempts to remove uncommitted staging files. Neither mode is a transactional tree copy. It does not acquire a terminal lease or register a Session and is reusable by non-CLI adapters.

type SerialDependencies

type SerialDependencies struct {
	ConfigPath   configPathResolver
	LoadConfig   configLoader
	SaveConfig   configSaver
	UpdateConfig configUpdater
	NewSession   SerialSessionFactory
	NewSessionID sessionIDGenerator
}

SerialDependencies supplies replaceable boundaries for SerialService tests and for presentation adapters that need an in-memory terminal implementation. Nil values use the normal production implementation.

type SerialProfileInfo

type SerialProfileInfo struct {
	Name    string
	Profile config.SerialProfile
}

SerialProfileInfo is one named, fully resolved Serial connection profile. Name identifies the configuration entry; Profile contains inherited values after resolution and is never rendered for a particular Adapter.

type SerialService

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

SerialService owns serial connection use cases over one shared Session Manager.

The service resolves a profile, creates the Serial Transport and Session, connects it, and registers fixed Session metadata as one operation. It does not own the Manager itself; the embedding application closes that owner at process shutdown.

func NewSerialService

func NewSerialService(manager *session.Manager) (*SerialService, error)

NewSerialService creates the normal production serial application service.

func NewSerialServiceWithDependencies

func NewSerialServiceWithDependencies(manager *session.Manager, dependencies SerialDependencies) (*SerialService, error)

NewSerialServiceWithDependencies creates a serial application service with explicitly replaceable construction dependencies.

It is intended for adapters and unit tests that must avoid opening physical serial hardware. Production callers should use NewSerialService.

func (*SerialService) OpenSerial

func (s *SerialService) OpenSerial(ctx context.Context, request OpenSerialRequest) (OpenSerialResult, error)

OpenSerial resolves configuration and opens or reuses one Manager-owned serial Session.

ctx cancels profile opening, connection, and duplicate-open waiting. A wake carriage return is sent only when the final resolved profile explicitly enables it. A reused Session keeps the metadata and connection settings from its original open operation.

type SerialSessionFactory

type SerialSessionFactory func(string, serialtransport.Config) (ConnectedSession, error)

SerialSessionFactory creates one unconnected serial Session for an ID.

type SessionBusyError

type SessionBusyError struct {
	SessionID string
	Lease     SessionLease
}

SessionBusyError identifies the active lease preventing a write. It unwraps ErrSessionBusy so callers can handle all contention errors consistently.

func (*SessionBusyError) Error

func (e *SessionBusyError) Error() string

Error returns a concise, user-facing reason without exposing the owner token.

func (*SessionBusyError) Unwrap

func (*SessionBusyError) Unwrap() error

Unwrap makes SessionBusyError comparable with ErrSessionBusy.

type SessionLease

type SessionLease struct {
	SessionID string
	Owner     string
	Type      LeaseType
	// TransferID identifies one file-transfer lease across its structured events.
	// It is empty for leases whose Type is not LeaseTypeFileTransfer.
	TransferID string
	CreatedAt  time.Time
	// ExpiresAt is the deadline by which the owner must renew the lease.
	ExpiresAt time.Time
	State     string
}

SessionLease is a point-in-time description of an exclusive Session lease. Owner is an opaque caller-selected capability and must not be presented as a human identity.

type TerminalCommandResult

type TerminalCommandResult struct {
	SessionID   string
	CommandID   string
	ExitCode    int
	OutputStart session.OutputCursor
	OutputEnd   session.OutputCursor
}

TerminalCommandResult describes one completed isolated Agent command. OutputStart and OutputEnd delimit only command output in the raw Session stream; each observer retains its own independent output cursor.

Jump to

Keyboard shortcuts

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