docs/internal/remote-destinations.md

Remote destination ownership

internal/remotedestination owns reusable outbound EzAgent client connections. It consumes config.ProviderConfig remote descriptors, but does not resolve LLM credentials, discover provider exports, cache catalogs, or change saved models. The agent's consumer runtime owns discovery, caching, and adapter resolution. Configurator integration is separate from the daemon's lifetime. Creating a manager performs no network I/O.

Lifetime and API

  • DialSSH(ctx context.Context, destination, socket string, opts Options) (net.Conn, error) opens a raw connection through a private SSH forward. It shares the manager's destination validation, SSH options, escaping, and bounded socket-readiness probes. Noninteractive startup defaults to ten seconds. With SSHAskpass, startup is cancellation-owned so human input has no elapsed deadline; callers can still cancel or provide their own context deadline. It sends no hello and installs no handlers; TUI callers supply their own protocol client. The context owns the entire connection lifetime, not just startup. Closing the result first closes the socket, then kills and reaps the exact SSH child and removes its private directory before returning. Context cancellation or unexpected SSH exit closes the same owner. Each call owns an independent forward, without manager caching, retry, or backoff.
  • ResolveSSHSocket(ctx context.Context, destination string, opts Options) (string, error) uses a separate, temporary SSH exec session to discover $XDG_RUNTIME_DIR/ez-agent/ez-agent.sock on the remote host. It runs only a fixed shell command with no interpolated caller input. It never starts a daemon, guesses a fallback, or checks whether the remote daemon is running. Stdout and stderr retention are bounded to 4 KiB each; only an absolute path without CR, LF, or NUL is accepted. This is best effort: the remote account must permit shell commands and expose a valid absolute XDG_RUNTIME_DIR. Restricted accounts, missing XDG, banners, and command failures require an explicit socket path. Auto discovery followed by DialSSH uses two SSH sessions and may prompt twice. Managers do not use Auto discovery implicitly.
  • New(ctx, Options) creates a lazy manager. Daemon runtime owns its manager until shutdown. Setup can create a separate temporary manager and close it after a bounded probe. Runtime must not borrow setup's process lifetime.
  • Get(ctx, host, descriptor) establishes or reuses one hello-complete Connection. Concurrent callers and aliases of the same endpoint share a single startup and connection. Each startup attempt publishes its readiness and immutable result together, so delayed waiters retain their attempt's result when another caller reconnects. Canceling one waiter does not cancel other callers or the manager-owned connection.
  • Retain(providers) retires removed or changed routes and joins their current owners. Model-selection-only changes do not interrupt transport. Call this when publishing configuration. After the first publication, Get rejects descriptors that do not match that publication, including stale run snapshots of removed destinations. Peek(host, descriptor) borrows a matching live connection without I/O for nonblocking metadata projections. Close cancels and joins every owner, including generations replaced by Get.
  • Connection.ListMacros(ctx) requests the unfiltered inventory with empty leaf and filter. Connection.MacroCall(ctx, "", name, row) uses the exact connection, never a local registry. Export-name, IFO, and catalog validation belong to discovery, not this transport package.
  • Connection.Dial(ctx, macro, init) opens a shared tunnelstream net.Conn. init starts with the tunnel type, followed by application target fields. The context owns the stream lifetime. Close each result after use. Opening and active streams share a 128-stream destination limit. Retiring a destination interrupts and joins its stream owners.

The manager's private connection sends an ordinary hello named ez-agent-service, with empty leaf and cwd, no handlers, and no announce. Without SSHAskpass, socket connection and hello have a shared startup deadline, ten seconds by default. Output is bounded to 1024 frames and 4 MiB. Disconnection fails current work rather than replaying it. Subsequent access lazily reconnects. Failed starts use exponential backoff from 100 ms to five seconds, returning unavailable during the backoff instead of blocking unrelated leaves. Startup errors distinguish ErrAccess from ErrHello; both wrap ErrUnavailable. Startup errors include bounded connection/hello details and the last 4 KiB of SSH stderr, without logging command lines or environment. Discovery must distinguish these from missing exports.

Automatic SSH

Direct descriptors dial AF_UNIX. SSH destinations are [user@]host[:port], with bracketed IPv6 for ports (user@[2001:db8::1]:2222); bare IPv6 without a port is accepted. Plain ssh_config aliases are preserved verbatim, and destinations without a port use OpenSSH defaults with no -p flag. Ports use a structured -p port argv element plus a single -- destination operand, with no shell, no inherited stdin, and no detached or multiplexed process. Each owner retains the exact child handle, waits for its exit, and kills and reaps only that child on retirement. It never runs an EzAgent helper against user state and never stops another daemon.

Each forward has a fresh 0700 directory beneath Options.RuntimeDir, defaulting to XDG_RUNTIME_DIR or the system temporary directory. Only that private directory and socket are cleaned up. OpenSSH forwarding-field escaping preserves literal colons, backslashes, and brackets in socket paths. Socket readiness is probed only during bounded startup; tunnel I/O is event driven.

SSH authentication, keys, ssh-agent and host trust belong to the administrator's normal SSH configuration. Without an askpass callback, EzAgent uses BatchMode and a bounded connect timeout. With a callback, it uses BatchMode=no and SSH_ASKPASS_REQUIRE=force, without an elapsed startup or connect timeout that could dismiss human input. Each local socket-dial probe is still bounded by StartupTimeout; interactive startup as a whole is owned by caller cancellation. EzAgent uses ExitOnForwardFailure. It disables multiplexing and authentication-time forking only to keep this forward in the exact child it owns. It does not override password methods, host-key policy, local commands or keepalive settings. The process inherits the admin's SSH configuration and agent environment. EzAgent adds no LLM credentials to the SSH command or environment.

Interactive askpass

Options.SSHAskpass func(context.Context, string) (string, error) supplies the caller-owned masked UI for password or key-passphrase entry. OpenSSH can also request textual host-key confirmation. The caller must not log or save answers and must return when the supplied context is canceled. Callback calls are serialized across SSH owners. Returning an error dismisses the prompt and stops the exact owned SSH child rather than leaving authentication retries running. No known-hosts or host-key policy is disabled.

Options.SSHAskpassCommand selects the helper executable, defaulting to os.Executable(). That executable must call HandleSSHAskpass(os.Args) (handled bool, err error) before normal startup and exit immediately when handled, using a nonzero status on error. Ordinary invocations without the dedicated EZ_AGENT_SSH_ASKPASS=1 marker are untouched. The helper also requires the private broker socket and random capability token from the child-only environment and the exact single-prompt argument shape. Only the successful answer is written to stdout for OpenSSH. Helper errors are generic and do not expose prompts, answers, tokens, or UI callback errors.

The broker lives in the forward's owned 0700 directory, with a 0600 Unix socket whose ownership and permissions are checked. Every request authenticates a random 256-bit capability before the UI is called. The local length-prefixed protocol is private to askpass, not EzAgent JSONL. Prompts and answers are capped at 16 KiB; answers cannot contain CR, LF, or NUL. No answer or capability is persisted. Socket reads before the UI and response writes are bounded; human input itself has no elapsed timeout. Helper disconnect cancels an open prompt. Owner cancellation and SSH exit cancel and join the broker and callback before private-file cleanup. The callback must honor cancellation for joining to finish. Askpass requires Unix ownership and permission checks; unsupported platforms fail closed.

Forward disconnection

SSH exit closes the associated client connection. Unexpected socket closure also joins the owned forward and retains its bounded failure details during backoff, even when the socket closes before the SSH child exits. Intentional retirement does not report an SSH failure. Next access can start another forward after backoff.

The forwarded socket grants full host daemon access. It is not a provider-only restricted socket. Forward it only into environments trusted with that access.