egg

package
v0.149.5 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LaunchPass  = "PASS"
	LaunchFail  = "FAIL"
	LaunchUnrun = "REQUIRED-UNRUN"
)
View Source
const MaxSessionPromptBytes = 64 << 10
View Source
const SessionTitleFile = "session.title"

SessionTitleFile holds the latest title the agent set for its terminal.

Variables

This section is empty.

Functions

func ApplyPreviewClaudeOSContext added in v0.148.0

func ApplyPreviewClaudeOSContext(env map[string]string, dataHome string) (string, error)

ApplyPreviewClaudeOSContext is used after the data-home mounts and native hook paths have been fixed. Never use OSHome as the history/sandbox home.

func AttachmentInfo added in v0.148.0

func AttachmentInfo(stream pb.Egg_SessionClient) *pb.AttachmentInfo

AttachmentInfo returns a copy of the immutable snapshot acknowledgment. AttachmentToken is private to this authenticated writer stream and must never be included in public status, relay messages, or logs.

func CaptureSessionHistory added in v0.122.0

func CaptureSessionHistory(agent, cwd, eggDir, home string, startedAfter time.Time, exactSessionID ...string) error

CaptureSessionHistory copies the agent's native session history (e.g. Claude's JSONL) into the egg directory as chat.jsonl.gz + chat.meta. Callers may choose to treat capture failures as best-effort, but this function reports them.

func ClaudeLifecycleArgs added in v0.148.0

func ClaudeLifecycleArgs(args []string, home, sessionID, providerID string) ([]string, error)

ClaudeLifecycleArgs adds observational native hooks to this invocation only. It preserves supplied settings and leaves disableAllHooks effective. The spool is inside the provider's existing writable directory; no permissions change.

func CleanSessionTitle added in v0.148.4

func CleanSessionTitle(raw string) string

CleanSessionTitle turns an OSC terminal title into a display label: it drops the leading spinner or status glyph (Claude uses ✳, ◐ and ◑), keeps letters, digits and plain punctuation only, and returns "" for generic program names.

func CodexLifecycleArgs added in v0.148.0

func CodexLifecycleArgs(args []string, home, sessionID string) ([]string, error)

CodexLifecycleArgs installs observational hooks in the session-flags layer. Only the exact generated definitions are trusted. Neither CODEX_HOME nor its config, notify, existing hook sources, or global trust policy is changed.

func CodexLifecycleVersionSupported added in v0.149.4

func CodexLifecycleVersionSupported(output string) bool

CodexLifecycleVersionSupported applies the runtime compatibility rule to saved version evidence. It does not execute the provider or establish live readiness.

func CodexNativeCommandPlan added in v0.148.0

func CodexNativeCommandPlan(binary, home, socket, providerID string) (server, tui []string, err error)

CodexNativeCommandPlan describes argv only; it never starts a provider. Both commands MUST execute inside the same existing egg sandbox. A private provider home is an input, not a request to copy authentication or grant access.

func CodexNativeThreadResult added in v0.148.0

func CodexNativeThreadResult(wire []byte, expectedID string) (string, error)

CodexNativeThreadResult reads only the exact thread returned by a caller's thread/start or thread/resume RPC. It never selects from an inventory/path. The caller must associate the response with its outstanding RPC request ID.

func CodexRunArgs added in v0.149.0

func CodexRunArgs(args []string, home, sessionID string) ([]string, bool, error)

CodexRunArgs keeps Codex's TUI and embedded runtime in the egg's process group. Native notifications publish atomically through a short-lived shell callback owned by Codex; no daemon, provider restart or rollout search exists.

func CodexVersionFromSavedOutput added in v0.149.4

func CodexVersionFromSavedOutput(output string) (string, bool)

CodexVersionFromSavedOutput returns only the parsed numeric version, never arbitrary saved output that could contain a prompt or credential.

func DefaultCacheDirs added in v0.22.0

func DefaultCacheDirs() []string

DefaultCacheDirs returns OS-standard cache directories that build tools need. Go, npm, pip, cargo, etc. all write to these. No secrets live here.

func DefaultDenyPaths added in v0.20.0

func DefaultDenyPaths() []string

DefaultDenyPaths returns paths that should be blocked by default in sandboxed sessions.

func FindLiveSessionFile added in v0.127.0

func FindLiveSessionFile(agent, cwd, home string) (string, error)

FindLiveSessionFile locates the live agent JSONL file for an active session. Returns the file path and agent name, or empty strings if not found.

func GuardPreviewClaudeMounts added in v0.148.0

func GuardPreviewClaudeMounts(mounts []sandbox.Mount, osHome string) ([]string, error)

GuardPreviewClaudeMounts prevents a more-specific caller mount from reopening the host provider configuration hidden by the native sandbox. Broader mounts retain their existing authority with these narrower denies applied last.

func HasRetainedSessionData added in v0.148.0

func HasRetainedSessionData(dir string) bool

HasRetainedSessionData keeps ownership and provider identity alongside native journals and retry reservations. An unreadable artifact is never absence.

func InferLocalPorts added in v0.144.0

func InferLocalPorts(cfg *EggConfig, agent, providerURL string) []int

InferLocalPorts returns the host loopback ports that must be forwarded into the jail's network namespace.

Retaining CLONE_NEWNET means the jail's 127.0.0.1 is not the host's, so every local model provider breaks unless its port is forwarded. Existing configs declare loopback intent with domain literals rather than ports, so the ports are inferred from the agent profile and the provider URL. Explicit network.local_ports entries are always honored.

func IsLaunchOption added in v0.149.4

func IsLaunchOption(flag string) bool

IsLaunchOption recognizes the same option syntax for assessment and display.

func LaunchCommandPreview added in v0.149.4

func LaunchCommandPreview(agentName, cwd, home, versionOutput string, unattended bool) (args []string, nativeRun bool, err error)

LaunchCommandPreview runs real preparation in disposable mirrored state, without writing the selected HOME or starting a PTY or process. Identity is a disposable planning identity; no prompt, resume ID, passthrough argv, or environment values are accepted.

func LaunchEnvironment added in v0.149.4

func LaunchEnvironment(rc RunConfig, selected map[string]string, inherited []string) map[string]string

LaunchEnvironment applies the runtime's profile reinjection to an explicit caller-selected environment and host snapshot. It never reads ambient values.

func NativePromptReady added in v0.148.0

func NativePromptReady(view SessionView) bool

NativePromptReady requires a living exact-provider session and native foreground idle/completion evidence; it does not certify a visible composer.

func NativeTerminalReset added in v0.149.4

func NativeTerminalReset() []byte

Native selection uses the terminal emulator's selection modifier (usually Shift or Option) while the provider has mouse tracking enabled. No keybindings, approval input or clipboard operations are installed by the attachment.

func ObserveToolController added in v0.148.4

func ObserveToolController(sockPath, userID string)

ObserveToolController routes a host-verified input claim to its live listener. Sessions without tools have no listener; reclaimed listeners already refuse Context authority. Call this before routing any input for the verified user.

func OpenRecordedSessionHistory added in v0.148.4

func OpenRecordedSessionHistory(agent, cwd, eggDir, home, expectedID string) (*os.File, error)

OpenRecordedSessionHistory pins the exact current native transcript beneath the caller's provider home, refusing symlinks at every path component.

func ParseChatMeta added in v0.122.0

func ParseChatMeta(data string) map[string]string

ParseChatMeta parses a simple key=value metadata file.

func ParseFSRules added in v0.20.0

func ParseFSRules(fs []string, home string) ([]sandbox.Mount, []string, []string)

ParseFSRules splits fs entries into mounts, deny paths, and deny-write paths. Entries are "mode:path" where mode is rw, ro, deny, deny-write, or deny-rename.

func PolicyDenialSources added in v0.149.4

func PolicyDenialSources(prefix, deny string, rules []PolicyRuleSource, cwd, home string) string

PolicyDenialSources attributes a resolved denial using the shared path expansion.

func PreviewClaudeOSContext added in v0.148.0

func PreviewClaudeOSContext(dataHome string) (osHome, configDir string, err error)

PreviewClaudeOSContext separates macOS user/Keychain lookup from Claude's explicit per-account config directory. It reads account metadata only. Absent data directories are supported so setup-guide remains output-only.

func ProjectLaunchFailure added in v0.149.4

func ProjectLaunchFailure(err error, policy *LaunchPolicySelection, prepared PreparedLaunch, stage, reason string) error

ProjectLaunchFailure consumes the existing preparation checks without a second assessor, filesystem discovery, provider probe, or raw error parsing.

func ProviderDestination added in v0.149.4

func ProviderDestination(agent, providerURL string) (string, error)

ProviderDestination identifies the declared or default destination without opening provider config or credentials. Empty means no default is declared.

func ReadSessionTitle added in v0.148.4

func ReadSessionTitle(dir string) string

ReadSessionTitle returns the saved title, cleaned again on the way out.

func RecordSessionProcessEvent added in v0.148.0

func RecordSessionProcessEvent(dir, eventType, state, reason string) error

RecordSessionProcessEvent persists termination even when the transcript is absent. A killed/crashed provider is never reported as a completed turn.

func RegisterRunTurnRPC added in v0.149.0

func RegisterRunTurnRPC(server *grpc.Server, handler RunTurnRPCServer)

func RequiresSandbox added in v0.144.0

func RequiresSandbox(cfg *EggConfig, agentName string) bool

RequiresSandbox reports whether cfg asks the runtime to enforce any policy. Trusted-host compatibility is intentionally recognized only when every relevant boundary is wide open. In particular, a wildcard network policy by itself must not silently disable filesystem, syscall, and resource isolation. Keep this predicate aligned with the explicit OuterBoundary marker passed to the egg subprocess by spawnEgg.

func ResolveLaunchConfig added in v0.149.4

func ResolveLaunchConfig(path, basesDir, home string) (*EggConfig, []PolicyRuleSource, error)

ResolveLaunchConfig is an explicit, read-only alternative to discovery. Empty path means built-in defaults; named bases require basesDir. It never reads a wing, HOME, environment variables, or credential contents. Parsing and merging use the same resolver as runtime discovery. The home argument is the merge-time host HOME, independently of execution HOME.

func ResolveRecordedProviderSessionID added in v0.148.4

func ResolveRecordedProviderSessionID(eggDir, agent, providerHome, expectedID string) (string, error)

ResolveRecordedProviderSessionID follows SessionStart bindings in this egg's journal and own hook spool. An expected ID must already belong to the egg. An empty providerHome reads only the bindings already persisted in the journal.

func RestoreSessionHistory added in v0.122.0

func RestoreSessionHistory(agent, cwd, eggDir, home string) (agentSessionID string, err error)

RestoreSessionHistory decompresses chat.jsonl.gz and places it in the agent's native session directory so the agent can resume the conversation. Returns the agent session ID for use with resume flags.

func ValidatePreviewClaudeBoundary added in v0.148.0

func ValidatePreviewClaudeBoundary(agent string, command []string, outerBoundary bool) error

func ValidateProtectedWriteTargetBoundary added in v0.148.0

func ValidateProtectedWriteTargetBoundary(targets []string, hasSandbox bool) error

ValidateProtectedWriteTargetBoundary refuses a protected set that no sandbox policy will enforce. It is an early, typed refusal only; overlap enforcement happens against the final emitted policy in sandbox.New.

func ValidateSocketPath added in v0.148.0

func ValidateSocketPath(path string) error

ValidateSocketPath checks the address passed to net.Listen("unix", path) without changing files. Go's syscall SockaddrUnix reserves a terminating NUL for filesystem sockets: Darwin has 104 path bytes and Linux has 108.

func WriteSessionTitle added in v0.148.4

func WriteSessionTitle(dir, title string) error

WriteSessionTitle replaces the egg's title file atomically; "" removes it.

Types

type AgentProfile added in v0.9.8

type AgentProfile struct {
	StateHomeEnv  string            // provider-supported state directory override variable
	ProviderHost  string            // default destination when no explicit provider URL is selected
	Domains       []string          // network domains needed (empty = no network)
	EnvVars       []string          // required env var names (merged from host)
	SetEnv        map[string]string // env vars forced to a default (host/config still wins)
	PlatformEnv   []string          // platform-specific env vars (e.g. macOS Keychain access)
	WriteDirs     []string          // relative to $HOME, need write access
	WriteRegex    []string          // dirs needing UseRegex (e.g. ".claude" covers .claude.json)
	SettingsFile  string            // agent config file relative to HOME (e.g. ".claude/settings.json")
	SessionDir    string            // agent session storage relative to $HOME (e.g. ".claude/projects")
	ResumeFlag    string            // CLI flag for resuming (e.g. "--resume")
	SessionIDFlag string            // CLI flag for controlling session ID (e.g. "--session-id")
}

AgentProfile declares what an agent needs from the host system. The sandbox merges these into the egg config automatically so users don't need to know agent internals (e.g. where Claude stores config).

func Profile added in v0.9.8

func Profile(agent string) AgentProfile

Profile returns the agent profile for the given agent name. Unknown agents get a restrictive default (no network, no extra dirs). Platform-specific env vars are injected based on runtime.GOOS.

type AttachOptions added in v0.148.0

type AttachOptions struct {
	// NativeTerminal requests canonical mouse modes after explicit discovery.
	// While tracking is active, selection uses the emulator's selection modifier.
	NativeTerminal bool
	ReadOnly       bool
	Takeover       bool
	Claim          bool
	Owner          string
	Rows           uint32
	Cols           uint32
}

type BaseField added in v0.23.0

type BaseField struct {
	Name    string `yaml:"name,omitempty"`
	FS      string `yaml:"fs,omitempty"`
	Network string `yaml:"network,omitempty"`
	Env     string `yaml:"env,omitempty"`
}

BaseField handles the `base` key in egg configs. It can be a scalar string (backward compat: "none", "strict", etc.) or an object with per-section masks.

func (BaseField) HasMasks added in v0.23.0

func (b BaseField) HasMasks() bool

func (BaseField) IsZero added in v0.23.0

func (b BaseField) IsZero() bool

func (BaseField) MarshalYAML added in v0.23.0

func (b BaseField) MarshalYAML() (interface{}, error)

func (*BaseField) UnmarshalYAML added in v0.23.0

func (b *BaseField) UnmarshalYAML(value *yaml.Node) error

type Client

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

Client wraps the generated gRPC client for a single egg process.

func Dial

func Dial(socketPath, tokenPath string) (*Client, error)

Dial connects to an egg's Unix socket and reads its auth token.

func (*Client) AttachSession

func (c *Client) AttachSession(ctx context.Context, sessionID string) (pb.Egg_SessionClient, error)

AttachSession opens a bidirectional stream for PTY I/O.

func (*Client) AttachSessionWithOptions added in v0.148.0

func (c *Client) AttachSessionWithOptions(ctx context.Context, sessionID string, options AttachOptions) (pb.Egg_SessionClient, error)

AttachSessionWithOptions confirms the initial snapshot before returning. An eager writer claim therefore fails before any prompt/input is submitted.

func (*Client) Close

func (c *Client) Close() error

Close closes the gRPC connection.

func (*Client) Kill

func (c *Client) Kill(ctx context.Context, sessionID string) error

Kill terminates the session.

func (*Client) ReadRunTurnResult added in v0.149.0

func (c *Client) ReadRunTurnResult(ctx context.Context, id string) (RunTurnResult, error)

func (*Client) ReserveRunTurn added in v0.149.0

func (c *Client) ReserveRunTurn(ctx context.Context, request RunTurnRequest) (RunTurnResult, error)

func (*Client) Resize

func (c *Client) Resize(ctx context.Context, sessionID string, rows, cols uint32) error

Resize changes terminal dimensions.

func (*Client) ResizeForAttachment added in v0.148.0

func (c *Client) ResizeForAttachment(ctx context.Context, sessionID string, rows, cols uint32, lease *pb.AttachmentInfo) error

ResizeForAttachment binds a resize to a specific stream's confirmed lease. Adapters sharing a client must retain this value rather than adopting a newer stream's token when the old connection sends a late resize.

func (*Client) RunTurnStatus added in v0.149.0

func (c *Client) RunTurnStatus(ctx context.Context, id string) (RunTurnResult, error)

func (*Client) Status added in v0.19.0

func (c *Client) Status(ctx context.Context) (*pb.StatusResponse, error)

Status returns debug stats from the egg session.

func (*Client) StopRunTurn added in v0.149.0

func (c *Client) StopRunTurn(ctx context.Context, id string) (RunTurnResult, error)

func (*Client) SubmitRunTurn added in v0.149.0

func (c *Client) SubmitRunTurn(ctx context.Context, request RunTurnRequest) (RunTurnResult, error)

func (*Client) WaitRunTurn added in v0.149.0

func (c *Client) WaitRunTurn(ctx context.Context, id string) (RunTurnResult, error)

type CodexCapability added in v0.149.4

type CodexCapability interface{ Supported(binary string) bool }

CodexCapability isolates the installed --version probe. Dry preparation uses digest-bound saved output through the same production version parser.

type CodexNativeEvent added in v0.148.0

type CodexNativeEvent struct {
	Event             SessionEvent    `json:"event"`
	TurnID            string          `json:"turn_id,omitempty"`
	ItemID            string          `json:"item_id,omitempty"`
	ProviderRequestID json.RawMessage `json:"provider_request_id,omitempty"`
}

CodexNativeEvent retains native correlation independently of Wingthing's delivery sequence. Event.Raw also retains these IDs when journaled today.

func ParseCodexNativeEvent added in v0.148.0

func ParseCodexNativeEvent(providerID string, wire []byte) (CodexNativeEvent, bool, error)

ParseCodexNativeEvent accepts the v2 app-server wire protocol for one exact thread. Foreign threads and unsupported methods are ignored. It emits no decisions/replies; every server request remains under the approval owner's control. Native runtime idle does not alone prove interactive TUI readiness.

func RecordCodexNativeEvent added in v0.148.0

func RecordCodexNativeEvent(eggDir, providerID string, wire []byte) (CodexNativeEvent, bool, error)

RecordCodexNativeEvent lets a future in-sandbox protocol consumer persist an already bound thread's event. Source keys deduplicate final turn/item replay; stream deltas are deliberately unsupported because they have no replay cursor.

type ConfigSnapshot added in v0.20.0

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

ConfigSnapshot holds copies of agent config files taken before a session.

func SnapshotAgentConfig added in v0.20.0

func SnapshotAgentConfig(agent, isolatedHome string, policies ...*sandbox.Config) *ConfigSnapshot

SnapshotAgentConfig pins critical config files inside the provider home. A sandbox caller must supply its compiled policy before any host-side read.

func (*ConfigSnapshot) Close added in v0.148.5

func (s *ConfigSnapshot) Close()

func (*ConfigSnapshot) Restore added in v0.20.0

func (s *ConfigSnapshot) Restore()

Restore publishes fresh inodes through no-follow parent descriptors. It never follows a substituted leaf or parent, and releases the pinned home afterward.

type DrilledHole added in v0.144.0

type DrilledHole struct {
	Kind   string // "domain" | "write_dir" | "env" | "local_port"
	Value  string
	Agent  string
	Reason string
}

DrilledHole records one capability the system added on the agent's behalf that the user did not ask for. The sandbox is egg.yaml plus auto-drilled agent holes; without attribution those holes are invisible and the policy cannot be reviewed by the person relying on it.

type EffectivePolicy added in v0.144.0

type EffectivePolicy struct {
	Agent       string
	Mounts      []sandbox.Mount
	Deny        []string
	DenyWrite   []string
	NetworkNeed sandbox.NetworkNeed
	Domains     []string
	LocalPorts  []int
	Mode        string
	Drilled     []DrilledHole
	Derived     []DrilledHole
	Suppressed  []DrilledHole
	// contains filtered or unexported fields
}

EffectivePolicy is the fully resolved sandbox policy for a session: what the user declared, plus what the agent profile required, with every addition attributable. This is what `wt egg explain` renders.

func ResolvePolicy added in v0.144.0

func ResolvePolicy(cfg *EggConfig, agent, home string) EffectivePolicy

ResolvePolicy merges an egg config with the named agent's profile and reports the result along with the provenance of every automatic addition. An empty agent name (a plain shell or command session) drills nothing.

func ResolvePolicyWithProvider added in v0.144.0

func ResolvePolicyWithProvider(cfg *EggConfig, agent, home, providerURL string) (EffectivePolicy, error)

ResolvePolicyWithProvider resolves the effective policy while treating an explicit provider URL as authoritative routing metadata. The derived exact host replaces the profile's static vendor domains and remains visible as a distinct source in explain output.

type EggConfig added in v0.8.0

type EggConfig struct {
	LaunchPolicy               *LaunchPolicySelection `yaml:"-"` // captured at resolution, never rediscovered for diagnostics
	Base                       BaseField              `yaml:"base,omitempty"`
	FS                         []string               `yaml:"fs"`
	RoostPolicyPaths           []string               `yaml:"-"` // runtime-only configured root policy files
	Network                    NetworkField           `yaml:"network"`
	Env                        EnvField               `yaml:"env,omitempty"`
	Resources                  EggResources           `yaml:"resources"`
	Shell                      string                 `yaml:"shell"`
	DangerouslySkipPermissions bool                   `yaml:"dangerously_skip_permissions"`
	Audit                      bool                   `yaml:"audit"`
	Trace                      bool                   `yaml:"trace"`
	AgentSettings              map[string]string      `yaml:"agent_settings,omitempty"` // agent name -> settings file path
}

EggConfig holds the sandbox and environment configuration for egg sessions.

func DefaultEggConfig added in v0.8.0

func DefaultEggConfig() *EggConfig

DefaultEggConfig returns the restrictive default config used when no egg.yaml exists. CWD is writable, home is read-only except agent-drilled holes. Sensitive dirs are denied. OS-standard cache dirs are writable so build tools (go, npm, cargo, pip) work out of the box. egg.yaml itself is deny-write so agents can read but not modify their sandbox config.

func DiscoverEggConfig added in v0.8.0

func DiscoverEggConfig(cwd string, wingDefault *EggConfig) *EggConfig

DiscoverEggConfig looks for egg.yaml in the given directory, falls back to the wing default, then to built-in defaults. Project configs are resolved through the base chain (additive inheritance) before being returned.

func LoadEggConfig added in v0.8.0

func LoadEggConfig(path string) (*EggConfig, error)

LoadEggConfig reads and parses an egg.yaml file.

func LoadEggConfigFromYAML added in v0.8.0

func LoadEggConfigFromYAML(yamlStr string) (*EggConfig, error)

LoadEggConfigFromYAML parses an egg config from a YAML string.

func LoadTaskEggConfigFromYAML added in v0.148.5

func LoadTaskEggConfigFromYAML(yamlStr string) (*EggConfig, error)

LoadTaskEggConfigFromYAML parses a task record written by TaskYAML.

func MergeEggConfig added in v0.21.0

func MergeEggConfig(parent, child *EggConfig) *EggConfig

MergeEggConfig merges a child config on top of a parent config. - fs: append child to parent; child ro/rw overrides parent deny for same path - network: union (dedup); "*" in either -> ["*"] - env: union (dedup); "*" in either -> ["*"] - resources: child wins per-field (non-zero overrides parent) - shell: child wins if non-empty - dangerously_skip_permissions: OR

func RebaseLaunchConfig added in v0.149.4

func RebaseLaunchConfig(cfg *EggConfig, policyBase string) *EggConfig

RebaseLaunchConfig anchors relative FS grants and denials at the selected configured root. It does not change the caller's config or expand execution HOME.

func ResolveEggConfig added in v0.21.0

func ResolveEggConfig(path string) (*EggConfig, error)

ResolveEggConfig loads an egg.yaml and resolves its base chain, returning a fully merged config. If base is empty, merges on top of DefaultEggConfig. If base is "none", returns the config as-is (empty slate).

func RuntimeEggConfig added in v0.148.4

func RuntimeEggConfig(wingDefault *EggConfig) *EggConfig

RuntimeEggConfig copies the administrator's captured session policy without consulting caller-writable workspace or global configuration files.

func UnsandboxedEggConfig added in v0.144.0

func UnsandboxedEggConfig() *EggConfig

UnsandboxedEggConfig returns the explicit trusted-host policy used when an outer VM or container is the security boundary. It passes the full environment and network through and declares no filesystem or resource restrictions, which causes the egg runtime to keep PTY persistence while skipping the OS sandbox entirely.

func WithLaunchPolicyBase added in v0.149.4

func WithLaunchPolicyBase(cfg *EggConfig, base string) *EggConfig

func (*EggConfig) BuildEnv added in v0.8.0

func (c *EggConfig) BuildEnv(home string) []string

BuildEnv filters the host environment based on the config. SSH_AUTH_SOCK is stripped when ~/.ssh is denied — otherwise the agent can still make outbound SSH connections via the forwarded socket despite the filesystem deny, causing unexpected host-key prompts inside the egg. If home is non-empty it is used to expand ~ in FS rules; otherwise os.UserHomeDir().

func (*EggConfig) BuildEnvMap added in v0.8.0

func (c *EggConfig) BuildEnvMap(home string) map[string]string

BuildEnvMap returns the environment as a map for proto SpawnRequest. If home is non-empty it is used to expand ~ in FS rules; otherwise os.UserHomeDir().

func (*EggConfig) IsAllEnv added in v0.20.0

func (c *EggConfig) IsAllEnv() bool

IsAllEnv returns true if the env config passes all environment variables.

func (*EggConfig) NetworkSummary added in v0.20.0

func (c *EggConfig) NetworkSummary() string

NetworkSummary returns a short description of the network config for logging.

func (*EggConfig) SSHAgentSocketDenyPaths added in v0.145.0

func (c *EggConfig) SSHAgentSocketDenyPaths(home string, force bool) []string

SSHAgentSocketDenyPaths returns the live SSH agent endpoint that must be masked alongside ~/.ssh. Removing SSH_AUTH_SOCK from the child environment is not sufficient: an agent can discover common socket paths under /tmp or the user runtime directory and connect to them directly.

Listing SSH_AUTH_SOCK explicitly (rather than via env: ["*"]) is a deliberate opt-in to agent-backed SSH without exposing raw key files. Shared-host callers pass force=true because they never forward host authentication agents.

func (*EggConfig) SelectEnv added in v0.149.4

func (c *EggConfig) SelectEnv(home string, inherited []string) []string

SelectEnv applies the launch environment selection to an explicit snapshot. Diagnostics can use it without inspecting ambient variable values.

func (*EggConfig) TaskYAML added in v0.148.5

func (c *EggConfig) TaskYAML() (string, error)

TaskYAML renders the config frozen into a host-written task record.

func (*EggConfig) ToSandboxConfig added in v0.8.0

func (c *EggConfig) ToSandboxConfig(home string) sandbox.Config

ToSandboxConfig converts the egg config to a sandbox.Config. If home is non-empty it is used to expand ~ in FS rules; otherwise os.UserHomeDir().

func (*EggConfig) YAML added in v0.8.0

func (c *EggConfig) YAML() (string, error)

YAML returns the config serialized as YAML.

type EggResources added in v0.8.0

type EggResources struct {
	CPU     string `yaml:"cpu"`    // duration: "300s"
	Memory  string `yaml:"memory"` // size: "2GB"
	MaxFDs  uint32 `yaml:"max_fds"`
	MaxPids uint32 `yaml:"max_pids"` // cgroup pids.max (Linux only)
}

EggResources configures resource limits for sandboxed processes.

func (*EggResources) CPUDuration added in v0.8.0

func (r *EggResources) CPUDuration() time.Duration

CPUDuration parses the CPU field as a duration.

func (*EggResources) MemBytes added in v0.8.0

func (r *EggResources) MemBytes() uint64

MemBytes parses the Memory field as bytes (supports GB, MB suffixes).

type EnvField added in v0.20.0

type EnvField []string

EnvField handles YAML unmarshaling of env: string | []string. "*" → ["*"], list → as-is.

func (*EnvField) UnmarshalYAML added in v0.20.0

func (e *EnvField) UnmarshalYAML(value *yaml.Node) error

type InstalledCodexCapability added in v0.149.4

type InstalledCodexCapability struct{}

func (InstalledCodexCapability) Supported added in v0.149.4

func (InstalledCodexCapability) Supported(binary string) bool

type LaunchCapabilities added in v0.149.4

type LaunchCapabilities struct {
	OS                   string     `json:"os"`
	Network              string     `json:"network"` // unknown, none, proxy-only, full
	WorkspaceWritable    LaunchFact `json:"workspace_writable"`
	ProviderHomeWritable LaunchFact `json:"provider_home_writable"`
	NativeSandbox        LaunchFact `json:"native_sandbox"`
	ParentSandbox        string     `json:"parent_sandbox"` // unknown, none, sandboxed, scoped
	UserBus              LaunchFact `json:"user_bus"`
	RequiresUserBus      bool       `json:"requires_user_bus"`
	ElanHome             string     `json:"elan_home,omitempty"` // explicit inherited path only
	ElanHomeWritable     LaunchFact `json:"elan_home_writable"`
	RawSocketsRequired   bool       `json:"raw_sockets_required"`
}

func (LaunchCapabilities) Validate added in v0.149.4

func (c LaunchCapabilities) Validate() error

type LaunchCheck added in v0.149.4

type LaunchCheck struct {
	Code       string `json:"code"`
	Status     string `json:"status"`
	Reason     string `json:"reason"`
	Source     string `json:"source"`
	Correction string `json:"correction,omitempty"`
}

type LaunchFact added in v0.149.4

type LaunchFact string

LaunchFact states are declarations from a captured input, never native probes. Empty/unknown stays unknown, even when every other fixture is green.

const (
	FactUnknown     LaunchFact = "unknown"
	FactSupported   LaunchFact = "supported"
	FactUnsupported LaunchFact = "unsupported"
)

type LaunchPolicySelection added in v0.149.4

type LaunchPolicySelection struct {
	Origin string             `json:"origin"`
	Path   string             `json:"path,omitempty"`
	Base   string             `json:"base,omitempty"`
	Rules  []PolicyRuleSource `json:"rules,omitempty"`
}

LaunchPolicySelection travels with the selected config, including inherited rule sources. It is private preparation input, not a diagnostic export.

func CaptureLaunchPolicy added in v0.149.4

func CaptureLaunchPolicy(cfg *EggConfig, path, base string) *LaunchPolicySelection

type LaunchPreparationOptions added in v0.149.4

type LaunchPreparationOptions struct {
	Binary, Home, HostHome, EggDir                                    string
	ProviderURL, BrowserRequestsPath, ToolBinary, PreviewClaudeOSHome string
	Environment                                                       map[string]string
	CodexCapability                                                   CodexCapability
	// A different saved platform can describe capabilities, but this process
	// cannot execute that platform's final policy builder.
	Platform string
	// EnvironmentConfig selects from an explicit snapshot when the caller has
	// not already selected Environment. Production can pass its selected map.
	EnvironmentConfig    *EggConfig
	InheritedEnvironment []string
	Requirements         *LaunchRequirements
}

type LaunchProviderEvidence added in v0.149.4

type LaunchProviderEvidence struct {
	BinarySHA256  string `json:"binary_sha256"`
	VersionOutput string `json:"version_output"`
	HelpOutput    string `json:"help_output"`
	CompleteHelp  bool   `json:"complete_help"`
}

LaunchProviderEvidence is saved version/help output from the selected executable. A digest binds it to today's executable, but still does not prove authentication, hooks, a provider tool call, or OS confinement. Help is never exported.

type LaunchRequirements added in v0.149.4

type LaunchRequirements struct {
	Route, AllowedHomeRoot, ProviderStateDir   string
	CredentialPaths                            []string
	Capabilities                               *LaunchCapabilities
	CapabilitySource, PolicySource, PolicyBase string
	Rules                                      []PolicyRuleSource
	Evidence                                   *LaunchProviderEvidence
	EvidenceBound, VersionKnown                bool
	// contains filtered or unexported fields
}

LaunchRequirements carries explicit caller constraints and captured host facts. Nil means facts were not supplied, never permission to probe the host. Preparation returns these diagnoses on both native and mirrored state.

type LaunchState added in v0.149.4

type LaunchState interface {
	MkdirAll(string) error
	// DirectoryLayout checks supplemental write requirements without creating
	// paths in selected state. Both effects use the same metadata mirror.
	DirectoryLayout(string) error
	ProviderSpool(home, relative string) error
	ClaudeSettings(args []string, home, eggDir, providerID, cwd string, policy *sandbox.Config) (argv []string, deferred bool, err error)
}

LaunchState isolates preparation's filesystem effects. Dry preparation runs the same MkdirAll and pinned provider-directory opens in a disposable mirror. It copies directory-entry metadata only, never provider files or credentials.

func NativeLaunchState added in v0.149.4

func NativeLaunchState() LaunchState

func NewDryLaunchState added in v0.149.4

func NewDryLaunchState(root string) (LaunchState, error)

NewDryLaunchState owns a fresh, empty root supplied by the caller. All absolute symlink destinations are rebased into it, including dangling ones. Relative links are also rebased: even a link containing many .. components cannot write outside the mirror. The caller removes the root after preparation.

type NetworkField added in v0.20.0

type NetworkField struct {
	Domains      []string `yaml:"domains,omitempty"`
	LocalPorts   []int    `yaml:"local_ports,omitempty"`
	Mode         string   `yaml:"mode,omitempty"`          // "" (default) | "observe" | "enforce"
	Log          *bool    `yaml:"log,omitempty"`           // legacy compatibility; policy-decision auditing is always on
	AgentDomains string   `yaml:"agent_domains,omitempty"` // ""/"merge" (default) | "none"
}

NetworkField handles YAML unmarshaling of network: string | []string | mapping. The scalar and list forms are a frozen contract: "none"/"" → no network, "*" → unrestricted, list → domain allowlist. The mapping form is additive and carries the loopback forwarding, enforcement mode, and legacy egress-logging option described in docs/sandbox-enhancement-design.md. Log is retained as a frozen config contract; policy decisions are audited independently of it.

func (NetworkField) IsZero added in v0.144.0

func (n NetworkField) IsZero() bool

IsZero lets yaml omitempty treat an unset network block as absent.

func (NetworkField) MarshalYAML added in v0.144.0

func (n NetworkField) MarshalYAML() (interface{}, error)

MarshalYAML re-emits the legacy scalar and list shapes whenever no mapping-only option is set, so rendered configs stay byte-stable for existing users.

func (*NetworkField) UnmarshalYAML added in v0.20.0

func (n *NetworkField) UnmarshalYAML(value *yaml.Node) error

type PolicyRuleSource added in v0.149.4

type PolicyRuleSource struct {
	Section string `json:"section"`
	Rule    string `json:"rule"`
	Source  string `json:"source"`
}

PolicyRuleSource describes effective declared rules, including inherited denials. Automatic provider holes are attributed separately by ResolvePolicy. Source retains the cleaned input filename for display; canonical filenames are used separately for file access and cycle detection.

type PreparedLaunch added in v0.149.4

type PreparedLaunch struct {
	Args                  []string
	CodexRun, NativeRun   bool
	Sandboxed             bool
	Policy                EffectivePolicy
	Sandbox               sandbox.Config
	ProfileDirs           []string
	LifecycleSettingsPath string
	Deferred              []string
	ProviderHost          string
	NetworkFailure        string
	Transport             string
	Checks                []LaunchCheck
	Environment           map[string]string
	FailureReason         string // fixed classifier for a failed preparation step
}

func PrepareLaunch added in v0.149.4

func PrepareLaunch(rc RunConfig, opts LaunchPreparationOptions, state LaunchState) (out PreparedLaunch, err error)

PrepareLaunch is the production preparation boundary, shared by Server.RunSession and doctor. It resolves policy, builds the sandbox specification, calls the actual provider builders, and validates their spools. No proxy, native sandbox, snapshot, control endpoint, PTY or provider process starts here.

type PromptDelivery added in v0.148.0

type PromptDelivery struct {
	BytesEnqueued int
	// NoInputAttempted is explicit sender evidence, never inferred from a
	// zero byte count or an error. Clear it before the first input Send.
	NoInputAttempted bool
	Release          func()
	Lost             <-chan error
}

PromptDelivery is transport evidence only. Release holds the input stream (and its writer lease when supported) until receipt observation finishes.

type RunConfig added in v0.9.0

type RunConfig struct {
	LaunchPolicy *LaunchPolicySelection
	Agent        string
	Kind         string
	// Command replaces the agent entirely; AgentArgs extends the agent's own
	// invocation and keeps the session an agent session. They are alternatives.
	Command      []string
	AgentArgs    []string
	InitialRun   *RunTurnRequest // host-admitted Codex prompt, reserved before launch
	CWD          string
	Shell        string
	FS           []string // "rw:./", "deny:~/.ssh"
	Network      []string // domain list
	LocalPorts   []int    // host loopback ports forwarded into the network namespace
	NetworkMode  string   // ""/"enforce" or "observe"
	AgentDomains string   // ""/"merge" or "none"
	Env          map[string]string
	Rows         uint32
	Cols         uint32

	DangerouslySkipPermissions bool
	CPULimit                   time.Duration
	MemLimit                   uint64
	MaxFDs                     uint32
	PidLimit                   uint32
	Debug                      bool
	Audit                      bool
	Trace                      bool          // wrap sandbox command with strace (Linux only)
	VTE                        bool          // use VTerm snapshot for reconnect instead of replay buffer
	RenderedConfig             string        // effective egg config as YAML (after merge/resolve)
	UserHome                   string        // per-user home directory (relay sessions only)
	SkipHostAgentEnv           bool          // shared hosts keep provider credentials in UserHome
	IdleTimeout                time.Duration // 0 = disabled; self-terminate after this much idle
	ResumeSessionID            string        // agent session ID to resume (from chat.meta)
	ProviderSessionID          string        // exact native session ID used for capture
	ToolNames                  []string      // names of privileged tools (for shim generation)
	ToolSocketPath             string        // path to tool.sock (set by wing, empty = no tools)
	OuterBoundary              bool          // explicit trusted-host marker from the parent process
	ProtectedWriteTargets      []string      // host-owned paths the final sandbox policy must keep unwritable (empty = no contract)
	RoostPolicyPaths           []string      // administrator-configured root policy files
	OmitBrowserBridge          bool          // no browser request file, shim, BROWSER/WT_SESSION_DIR env, PATH entry or mount
}

RunConfig holds everything needed to start a single egg session.

type RunDescendant added in v0.149.0

type RunDescendant struct {
	PID            int `json:"pid"`
	ParentPID      int `json:"parent_pid"`
	ProcessGroupID int `json:"process_group_id"`
}

Descendant reports identity only, never command arguments or diagnostics.

type RunTurnRPCServer added in v0.149.0

type RunTurnRPCServer interface {
	HandleRunTurn(context.Context, string, RunTurnRequest) (RunTurnResult, error)
}

Struct envelopes keep this additive control service independent of the PTY protobuf contract. Existing egg socket authentication covers every method.

type RunTurnRequest added in v0.149.0

type RunTurnRequest struct {
	RunID    string    `json:"run_id"`
	Prompt   string    `json:"prompt"`
	Deadline time.Time `json:"deadline"`
}

RunTurnRequest binds one prompt to an optional egg-owned absolute execution deadline. A zero deadline runs until completion, stop, or provider/egg exit.

type RunTurnResult added in v0.149.0

type RunTurnResult struct {
	RunID                string          `json:"run_id"`
	SessionID            string          `json:"session_id"`
	Status               string          `json:"status"`
	Text                 string          `json:"text"`
	ProviderSessionID    string          `json:"provider_session_id,omitempty"`
	TurnID               string          `json:"turn_id,omitempty"`
	StartedAt            time.Time       `json:"started_at"`
	EndedAt              time.Time       `json:"ended_at,omitempty"`
	Deadline             time.Time       `json:"deadline"`
	FailureKind          agent.ErrorKind `json:"failure_kind,omitempty"`
	Error                string          `json:"error,omitempty"`
	SurvivingDescendants []RunDescendant `json:"surviving_descendants,omitempty"`
	ContainmentError     string          `json:"containment_error,omitempty"`
}

func ReadRunTurnResult added in v0.149.0

func ReadRunTurnResult(dir, runID string) (RunTurnResult, error)

ReadRunTurnResult also works after the egg exits. Nonterminal artifacts are evidence of admission only, never proof that an absent provider succeeded.

func (RunTurnResult) Terminal added in v0.149.0

func (r RunTurnResult) Terminal() bool

type SavedCodexCapability added in v0.149.4

type SavedCodexCapability string

func (SavedCodexCapability) Supported added in v0.149.4

func (s SavedCodexCapability) Supported(string) bool

type Server

type Server struct {
	pb.UnimplementedEggServer
	// contains filtered or unexported fields
}

Server implements the Egg gRPC service — wraps a SINGLE process. Each egg is its own child process with its own socket/PID/token in ~/.wingthing/eggs/<session-id>/.

func NewServer

func NewServer(dir string) (*Server, error)

NewServer creates a new per-session egg server. dir is the session directory: ~/.wingthing/eggs/<session-id>/

func (*Server) HandleRunTurn added in v0.149.0

func (s *Server) HandleRunTurn(ctx context.Context, method string, request RunTurnRequest) (RunTurnResult, error)

func (*Server) Kill

func (s *Server) Kill(ctx context.Context, req *pb.KillRequest) (*pb.KillResponse, error)

Kill terminates the session.

func (*Server) Resize

func (s *Server) Resize(ctx context.Context, req *pb.ResizeRequest) (*pb.ResizeResponse, error)

Resize changes the terminal dimensions.

func (*Server) RunSession added in v0.9.0

func (s *Server) RunSession(ctx context.Context, rc RunConfig) (runErr error)

RunSession is the core lifecycle: create sandbox, start agent in PTY, serve gRPC, exit when done.

func (*Server) Session

func (s *Server) Session(stream pb.Egg_SessionServer) error

Session implements the bidirectional PTY I/O stream.

func (*Server) Status added in v0.19.0

func (s *Server) Status(ctx context.Context, req *pb.StatusRequest) (*pb.StatusResponse, error)

type Session

type Session struct {
	ID  string
	PID int

	Agent          string
	Kind           string
	Command        []string
	CWD            string
	Network        string // summary: "none", "*", or comma-separated domains
	RenderedConfig string // effective egg config as YAML (after merge/resolve)
	Cols           uint32
	Rows           uint32
	StartedAt      time.Time
	// contains filtered or unexported fields
}

Session holds a single PTY process and its state.

type SessionEvent added in v0.148.0

type SessionEvent struct {
	Sequence          int64           `json:"sequence"`
	Type              string          `json:"type"`
	Source            string          `json:"source"`
	State             string          `json:"state,omitempty"`
	Role              string          `json:"role,omitempty"`
	Text              string          `json:"text,omitempty"`
	Raw               json.RawMessage `json:"raw,omitempty"`
	ProviderSessionID string          `json:"provider_session_id,omitempty"`
	Timestamp         string          `json:"timestamp,omitempty"`
	Reason            string          `json:"reason,omitempty"`
	Truncated         bool            `json:"truncated,omitempty"`
	// Native record length, or serialized event length for legacy journal rows.
	OriginalBytes int64 `json:"original_bytes,omitempty"`
	ExitCode      *int  `json:"exit_code,omitempty"`
	// Import positions are persisted with each event in the same transaction.
	// This prevents duplicates if the reader or wing exits between imports.
	SourceKey    string `json:"source_key,omitempty"`
	SourceOffset int64  `json:"source_offset,omitempty"`
}

type SessionPromptOptions added in v0.148.0

type SessionPromptOptions struct {
	RequestID string
	Input     string
	Timeout   time.Duration
	Read      func(context.Context, int64, int) (SessionView, error)
	Send      func(context.Context, string) (PromptDelivery, error)
}

type SessionPromptResult added in v0.148.0

type SessionPromptResult struct {
	SessionID                   string `json:"session_id"`
	RequestID                   string `json:"request_id"`
	Status                      string `json:"status"`
	NativeReceiptObserved       bool   `json:"native_receipt_observed"`
	ProviderRequestAcknowledged bool   `json:"provider_request_acknowledged"`
	ReceiptKind                 string `json:"receipt_kind,omitempty"`
	Causality                   string `json:"causality"`
	TransportEnqueued           bool   `json:"transport_enqueued"`
	TransportBytesEnqueued      int    `json:"transport_bytes_enqueued"`
	DefinitelyNotSent           bool   `json:"definitely_not_sent"`
	ReservedCursor              int64  `json:"reserved_cursor"`
	ReceiptCursor               int64  `json:"receipt_cursor,omitempty"`
	Retried                     bool   `json:"retried"`
	Reason                      string `json:"reason,omitempty"`
}

func SubmitSessionPrompt added in v0.148.0

func SubmitSessionPrompt(ctx context.Context, dir string, o SessionPromptOptions) (SessionPromptResult, error)

SubmitSessionPrompt reserves before sending and never resends an existing request. Receipt means matching exact-provider native human user text, not a request-specific provider acknowledgement (providers do not expose that ID). The caller supplies authorization/routing and the PTY transport; this primitive owns serialization, bounded waiting, durable reservation and replay semantics.

type SessionView added in v0.148.0

type SessionView struct {
	SessionID         string `json:"session_id"`
	Agent             string `json:"agent"`
	ProviderSessionID string `json:"provider_session_id,omitempty"`
	State             string `json:"state"`
	Status            string `json:"status"`
	StateSource       string `json:"state_source"`
	StateCursor       int64  `json:"state_cursor"`
	Reason            string `json:"reason,omitempty"`
	Ready             bool   `json:"ready"`
	ProcessAlive      bool   `json:"process_alive"`
	// Cursor is the last delivered event, not the journal head when paginated.
	Cursor     int64          `json:"cursor"`
	HeadCursor int64          `json:"head_cursor"`
	HasMore    bool           `json:"has_more"`
	Events     []SessionEvent `json:"events"`
}

func ReadSessionLifecycle added in v0.148.0

func ReadSessionLifecycle(eggDir, agent, cwd, providerHome, exactProviderID string, processAlive bool, after int64, limit int) (SessionView, error)

ReadSessionLifecycle imports exact native records into a durable journal and returns bounded cursor replay. State completion means the foreground turn; process_alive separately identifies whether this conversation can accept work.

func TryReadSessionLifecycle added in v0.148.0

func TryReadSessionLifecycle(eggDir, agent, cwd, providerHome, exactProviderID string, processAlive bool, after int64, limit int) (SessionView, error)

TryReadSessionLifecycle returns immediately if another reader or importer holds the journal lock. Inventory callers can then display unknown status.

type SocketPathTooLongError added in v0.148.0

type SocketPathTooLongError struct {
	Path     string
	Bytes    int
	MaxBytes int
}

SocketPathTooLongError reports the exact filesystem address that cannot fit in sockaddr_un. Lengths are bytes, including any multibyte path components.

func (*SocketPathTooLongError) Error added in v0.148.0

func (e *SocketPathTooLongError) Error() string

type ToolContext added in v0.148.0

type ToolContext struct {
	Client    *contextclient.Client
	Owner     string // verified EggIdentity.Email, fixed for this listener's lifetime
	OwnerID   string // verified EggIdentity.UserID, also fixed
	Reclaimed bool   // surviving egg has no trusted owner/client binding after restart
}

ToolContext binds a listener to its wing-owned Context client and verified owner.

type ToolListEntry added in v0.130.0

type ToolListEntry struct {
	Name        string             `json:"name"`
	Description string             `json:"description,omitempty"`
	Params      []config.ToolParam `json:"params,omitempty"`
}

ToolListEntry describes one tool for the list action.

type ToolListResponse added in v0.130.0

type ToolListResponse struct {
	Tools []ToolListEntry `json:"tools"`
}

ToolListResponse is returned for the "list" action.

type ToolListener added in v0.130.0

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

ToolListener accepts connections on a Unix socket and dispatches tool execution to a shared ToolRunner. Egg sessions reach tools this way; the remote MCP server wraps the same runner over HTTP.

func NewToolListener added in v0.130.0

func NewToolListener(sockPath string, tools []*config.ToolConfig, contexts ...ToolContext) (*ToolListener, error)

NewToolListener creates and starts a tool socket listener. sockPath is the path for the Unix socket (e.g. ~/.wingthing/eggs/<session>/tool.sock).

func (*ToolListener) Close added in v0.130.0

func (tl *ToolListener) Close() error

Close stops the listener and waits for in-flight requests to finish.

func (*ToolListener) ObserveController added in v0.148.0

func (tl *ToolListener) ObserveController(userID string)

ObserveController permanently revokes Context authority when another verified user claims input. Returning to the original owner never restores it.

func (*ToolListener) Reload added in v0.130.0

func (tl *ToolListener) Reload(tools []*config.ToolConfig)

Reload replaces the tool configs atomically.

type ToolRequest added in v0.130.0

type ToolRequest struct {
	Action string   `json:"action,omitempty"` // "list" for tool discovery
	Tool   string   `json:"tool,omitempty"`
	Args   []string `json:"args,omitempty"`
}

ToolRequest is sent by `wt tool-call` over the Unix socket.

type ToolResponse added in v0.130.0

type ToolResponse struct {
	ExitCode int    `json:"exit_code,omitempty"`
	Stdout   string `json:"stdout,omitempty"`
	Stderr   string `json:"stderr,omitempty"`
	Error    string `json:"error,omitempty"`
}

ToolResponse is returned to the client.

type ToolRunner added in v0.140.0

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

ToolRunner owns the privileged tool registry and executes tools. It is the shared execution core behind both the egg tool socket (ToolListener) and the remote MCP server — so a tool behaves identically whether an in-egg agent or a remote MCP client invokes it, and credentials stay in one place.

func NewToolRunner added in v0.140.0

func NewToolRunner(tools []*config.ToolConfig, clients ...*contextclient.Client) *ToolRunner

NewToolRunner builds a runner from tool configs.

func (*ToolRunner) Call added in v0.140.0

func (r *ToolRunner) Call(name string, args []string) ToolResponse

Call executes a tool by name with positional args, enforcing per-tool concurrency.

func (*ToolRunner) CallAs added in v0.148.0

func (r *ToolRunner) CallAs(name string, args []string, owner string, extraEnv map[string]string) ToolResponse

CallAs receives an owner verified by the wing, never from tool args or environment.

func (*ToolRunner) CallWithEnv added in v0.140.0

func (r *ToolRunner) CallWithEnv(name string, args []string, extraEnv map[string]string) ToolResponse

CallWithEnv executes a tool with additional per-call identity metadata. Extra environment values are appended last, so a static tool config cannot spoof caller identity.

func (*ToolRunner) Has added in v0.140.0

func (r *ToolRunner) Has(name string) bool

Has reports whether a tool is registered.

func (*ToolRunner) List added in v0.140.0

func (r *ToolRunner) List() []ToolListEntry

List returns all registered tools (name + description), unfiltered.

func (*ToolRunner) ParamsFor added in v0.140.0

func (r *ToolRunner) ParamsFor(name string) ([]config.ToolParam, bool)

ParamsFor returns a tool's optional ordered parameter metadata.

func (*ToolRunner) Reload added in v0.140.0

func (r *ToolRunner) Reload(tools []*config.ToolConfig)

Reload replaces the tool configs atomically, reusing compatible semaphores.

func (*ToolRunner) TimeoutFor added in v0.140.0

func (r *ToolRunner) TimeoutFor(name string) time.Duration

TimeoutFor returns a tool's configured timeout, or 0 if unknown.

type VTerm added in v0.58.0

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

VTerm wraps charmbracelet/x/vt with scrollback capture via ScrollOut callback. All methods are thread-safe. Callbacks fire inside Write, so mu is already held.

func NewVTerm added in v0.58.0

func NewVTerm(cols, rows int) *VTerm

NewVTerm creates a VTerm with the given dimensions.

func (*VTerm) Close added in v0.58.0

func (v *VTerm) Close() error

Close releases the emulator resources.

func (*VTerm) OnTitle added in v0.148.4

func (v *VTerm) OnTitle(fn func(string))

OnTitle registers fn to receive each change of the title the agent sets for its terminal. fn runs on the VTerm goroutine, outside the lock.

func (*VTerm) Resize added in v0.58.0

func (v *VTerm) Resize(cols, rows int)

Resize changes the terminal dimensions.

func (*VTerm) ScreenText added in v0.149.0

func (v *VTerm) ScreenText() string

ScreenText returns only the currently rendered grid, excluding scrollback.

func (*VTerm) ScrollbackLen added in v0.58.0

func (v *VTerm) ScrollbackLen() int

ScrollbackLen returns the number of scrollback lines currently stored.

func (*VTerm) Snapshot added in v0.58.0

func (v *VTerm) Snapshot() []byte

Snapshot generates a reconnect payload: scrollback + grid + cursor restore. The output is valid ANSI that any terminal emulator can consume directly.

func (*VTerm) Write added in v0.58.0

func (v *VTerm) Write(p []byte) (int, error)

Write feeds PTY output to the emulator.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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