daemon

package
v0.0.0-...-c5ded03 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 24 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 daemon implements the Phase 0 codebridged authority: a foreground or per-user-launchd process that owns the MCP ingress (Streamable HTTP over a Unix socket), the Host IPC listener for CodeBridge.app, the tunnel-client supervision and the runtime store port.

Phase 0 deliberately exposes one MCP tool pair (ping, health) and no Computer capability; every computer.*/approval.* Host IPC method answers unsupported.

Index

Constants

View Source
const (
	EnvRunDir          = "CODEBRIDGE_RUN_DIR"
	EnvDataDir         = "CODEBRIDGE_DATA_DIR"
	EnvMCPSocket       = "CODEBRIDGE_MCP_SOCKET"
	EnvHostSocket      = "CODEBRIDGE_HOSTIPC_SOCKET"
	EnvLogFile         = "CODEBRIDGE_LOG"
	EnvAppTeamID       = "CODEBRIDGE_APP_TEAM_ID"
	EnvAppBundleID     = "CODEBRIDGE_APP_BUNDLE_ID"
	EnvTunnelBinary    = "CODEBRIDGE_TUNNEL_BINARY"
	EnvTunnelTokenEnv  = "CODEBRIDGE_TUNNEL_TOKEN_ENV"
	EnvTunnelTokenFile = "CODEBRIDGE_TUNNEL_TOKEN_FILE"
	EnvDisableTunnel   = "CODEBRIDGE_DISABLE_TUNNEL"
	EnvRuntimeDB       = "CODEBRIDGE_RUNTIME_DB"
	EnvNoStore         = "CODEBRIDGE_NO_STORE"
	EnvWidgetSpike     = "CODEBRIDGE_WIDGET_SPIKE"
	EnvPhase0Debug     = "CODEBRIDGE_PHASE0_DEBUG"
	EnvPhase0Probe     = "CODEBRIDGE_PHASE0_PROBE"
	EnvPhase0Harness   = "CODEBRIDGE_PHASE0_HARNESS"
	// DefaultTunnelTokenEnv is the environment variable the daemon fills with
	// the per-launch tunnel bearer secret for its tunnel-client child.
	DefaultTunnelTokenEnv = "CODEBRIDGE_TUNNEL_TOKEN"
)

Env var names. Values are never logged.

View Source
const (
	TunnelDisabled      = "disabled"
	TunnelNotConfigured = "not_configured"
	TunnelRunning       = "running"
	TunnelRestarting    = "restarting"
	TunnelFailed        = "failed"
	TunnelStopped       = "stopped"
)

Tunnel states reported by host.health and the MCP health tool.

View Source
const Version = "0.1.0-phase0"

Version is the Phase 0 daemon version reported over both wires. It can be overridden at link time with -X main.version=...

Variables

View Source
var ErrNoRunDir = errors.New("daemon: run dir does not exist")

ErrNoRunDir reports a missing run directory.

Functions

func DefaultRuntimeDBPath

func DefaultRuntimeDBPath(dataDir string) string

DefaultRuntimeDBPath is the durable database location for a data directory. It equals runtime.DefaultPath() for the default data directory.

func DerivedFlagEnv

func DerivedFlagEnv() map[string]string

DerivedFlagEnv maps each derived setting to the environment variable that marks it explicit.

func EnsureRunDir

func EnsureRunDir(dir string) error

EnsureRunDir creates the per-user run directory 0700.

func KnownProbes

func KnownProbes() []string

KnownProbes lists the accepted probe names.

func NativeHostChecks

func NativeHostChecks() []string

NativeHostChecks lists the frozen check names in order.

func ReadTokenFile

func ReadTokenFile(path string) (string, error)

ReadTokenFile reads the per-launch bearer secret for local probes. The value is returned to the caller and must not be printed.

func SetWidgetSpikeRegistrar

func SetWidgetSpikeRegistrar(fn func(s *mcp.Server))

SetWidgetSpikeRegistrar installs the opt-in widget spike registration. The parent integration calls it from main before Run.

func SocketPath

func SocketPath(runDir, name string) string

SocketPath returns the default socket path inside a run directory.

Types

type CallerClass

type CallerClass string

CallerClass classifies the ingress caller.

const (
	// CallerRemoteAI is a request authenticated with the per-launch tunnel
	// bearer secret: the remote model path through tunnel-client.
	CallerRemoteAI CallerClass = "remote_ai"
	// CallerLocalMCP is a same-user local connection without the tunnel secret.
	CallerLocalMCP CallerClass = "local_mcp"
)

type ComputerTCCGuardState

type ComputerTCCGuardState struct {
	Safe      bool   `json:"safe"`
	Reason    string `json:"reason,omitempty"`
	Screen    bool   `json:"screen_preflight_granted"`
	AXTrusted bool   `json:"ax_trusted"`
	Listen    bool   `json:"listen_preflight_granted"`
	CheckedAt string `json:"checked_at"`
}

ComputerTCCGuardState reports the fail-closed Computer-TCC posture guard (invariant DAEMON_COMPUTER_TCC_MUST_BE_NONE).

type ComputerTCCStatus

type ComputerTCCStatus struct {
	ScreenPreflightGranted bool   `json:"screen_preflight_granted"`
	AXTrusted              bool   `json:"ax_trusted"`
	ListenPreflightGranted bool   `json:"listen_preflight_granted"`
	AnyComputerPrivilege   bool   `json:"any_computer_privilege"`
	Detail                 string `json:"detail,omitempty"`
}

ComputerTCCStatus is the passive Computer-TCC posture of the daemon process.

type Config

type Config struct {
	Version       string
	DataDir       string
	RunDir        string
	MCPSocket     string
	HostSocket    string
	LogFile       string
	ProtocolMinor int

	// AppTeamID/AppBundleID configure the code requirement an "app" peer must
	// satisfy. When either is empty the app role is refused (fail closed).
	AppTeamID   string
	AppBundleID string

	// Tunnel configures supervision of the [OI] tunnel-client child.
	Tunnel TunnelConfig

	// PingCommand is the fixed, non-caller-controlled command the MCP `ping`
	// tool executes to prove real native host execution.
	PingCommand []string

	// WidgetSpike registers the opt-in Phase 0 widget/approval spike tools.
	WidgetSpike bool

	// Phase0Debug enables fixed harness and same-process native diagnostics.
	Phase0Debug bool
	// Phase0ProbePath is an absolute path to the standalone probe binary.
	Phase0ProbePath string
	// Phase0HarnessPath is an absolute path to a harness probe binary.
	Phase0HarnessPath string

	// SmokeTimeout bounds each fixed native-host smoke check.
	SmokeTimeout time.Duration
	// ProbeTimeout bounds a probe subprocess run.
	ProbeTimeout time.Duration
	// ShutdownGrace bounds graceful shutdown before the tunnel is killed.
	ShutdownGrace time.Duration

	// RuntimeDB is the durable runtime database path. Empty selects
	// DataDir/runtime.db.
	RuntimeDB string
	// NoStore disables opening the runtime store entirely (runtime.* then
	// answers unsupported).
	NoStore bool

	// Store is the runtime store port. cmd/codebridged opens it from RuntimeDB;
	// nil leaves runtime.* answering unsupported.
	Store Store
}

Config is the daemon configuration. Zero values are not valid; start from DefaultConfig and override.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the Phase 0 defaults under the user's Application Support / Logs directories.

func (*Config) AppSigningConfigured

func (c *Config) AppSigningConfigured() bool

AppSigningConfigured reports whether an app-role peer can ever be verified.

func (*Config) ApplyEnv

func (c *Config) ApplyEnv()

ApplyEnv overlays environment overrides onto the config.

func (*Config) DerivePaths

func (c *Config) DerivePaths(explicit map[string]bool)

DerivePaths re-derives the paths that hang off RunDir and DataDir unless the caller set them explicitly (through a flag or the environment). This is what makes "-run-dir /tmp/x -data-dir /tmp/y" meaningful instead of leaving the sockets and the database in the default Application Support directory.

func (*Config) RegisterFlags

func (c *Config) RegisterFlags(fs *flag.FlagSet)

RegisterFlags adds the daemon flags to fs.

func (*Config) Validate

func (c *Config) Validate() error

Validate reports configuration errors that must stop startup.

type Daemon

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

Daemon is the Phase 0 codebridged authority.

func New

func New(cfg Config, log *slog.Logger) (*Daemon, error)

New builds a daemon. The caller owns the logger and Store lifetime.

func (*Daemon) ComputerTCCBoundaryCheck

func (d *Daemon) ComputerTCCBoundaryCheck() *ComputerTCCGuardState

ComputerTCCBoundaryCheck forces a fresh passive evaluation (used at runtime boundaries: Run creation, harness spawn, ComputerSession setup, restart).

func (*Daemon) Config

func (d *Daemon) Config() Config

Config returns the effective configuration.

func (*Daemon) GuardUnsafe

func (d *Daemon) GuardUnsafe() bool

GuardUnsafe reports whether the daemon must fail closed right now.

func (*Daemon) PingNativeHost

func (d *Daemon) PingNativeHost(ctx context.Context) ExecResult

PingNativeHost runs the configured fixed ping command. It is the only command the MCP ping tool executes and it takes no caller input.

func (*Daemon) ProbeBinary

func (d *Daemon) ProbeBinary(probe string) string

ProbeBinary resolves the probe binary for a probe name: the harness binary for "harness" when configured, otherwise the standalone probe binary.

func (*Daemon) ProbeEnabled

func (d *Daemon) ProbeEnabled() bool

ProbeEnabled reports whether the debug-gated probe method is available.

func (*Daemon) Run

func (d *Daemon) Run(ctx context.Context) error

Run serves until ctx is cancelled or a fatal listener error occurs. It performs a controlled shutdown: stop accepting, close listeners, terminate tunnel-client with a grace period, then close the store.

func (*Daemon) RunNativeHostSmoke

func (d *Daemon) RunNativeHostSmoke(ctx context.Context, only []string) (NativeHostReport, error)

RunNativeHostSmoke executes the fixed check set (optionally filtered by only) and returns the serialized report. An unknown name in only is an error rather than a silent skip.

func (*Daemon) RunPhase0Probe

func (d *Daemon) RunPhase0Probe(ctx context.Context, probe string, timeoutMS int) (ProbeResult, error)

RunPhase0Probe runs fixed native diagnostics in the daemon or spawns the exact configured harness with fixed argv. Callers cannot supply executable paths or extra argv; native calls never spawn a permission-test child.

func (*Daemon) SocketPaths

func (d *Daemon) SocketPaths() (mcp, host string)

SocketPaths reports the two sockets the daemon owns (tests and evidence).

func (*Daemon) Token

func (d *Daemon) Token() string

Token returns the per-launch bearer secret. Callers must never log it.

func (*Daemon) Tunnel

func (d *Daemon) Tunnel() *TunnelSupervisor

Tunnel exposes the supervisor for the CLI doctor and health surfaces.

type ExecResult

type ExecResult struct {
	Name       string   `json:"name"`
	Argv       []string `json:"argv"`
	Started    bool     `json:"started"`
	ExitCode   int      `json:"exit_code"`
	TimedOut   bool     `json:"timed_out"`
	DurationMS int64    `json:"duration_ms"`
	Stdout     string   `json:"stdout"`
	Stderr     string   `json:"stderr"`
	Err        string   `json:"error,omitempty"`
}

ExecResult is one executed fixed command.

type JournalEvent

type JournalEvent struct {
	Pos           int64           `json:"pos"`
	Stream        string          `json:"stream"`
	Seq           int64           `json:"seq"`
	Kind          string          `json:"kind"`
	Source        string          `json:"source"`
	At            time.Time       `json:"at"`
	SessionID     string          `json:"session_id,omitempty"`
	ProjectID     string          `json:"project_id,omitempty"`
	RunID         string          `json:"run_id,omitempty"`
	CorrelationID string          `json:"correlation_id,omitempty"`
	Payload       json.RawMessage `json:"payload,omitempty"`
	RawRef        string          `json:"raw_ref,omitempty"`
}

JournalEvent is the daemon-local projection of one runtime journal entry (architecture.md §8). internal/runtime's concrete Event is adapted to this shape by the integration owner so the daemon core never imports the store.

type LaunchIdentity

type LaunchIdentity struct {
	PID        int    `json:"pid"`
	PPID       int    `json:"ppid"`
	Executable string `json:"executable"`
	Cwd        string `json:"cwd"`
	RunDir     string `json:"run_dir"`
	HostSocket string `json:"host_socket"`
}

LaunchIdentity reports which process tree the checks ran in. It is the daemon's own identity, not the caller's.

type MCPProbeResult

type MCPProbeResult struct {
	Tool       string          `json:"tool"`
	IsError    bool            `json:"is_error"`
	Structured json.RawMessage `json:"structured,omitempty"`
	Text       string          `json:"text,omitempty"`
}

MCPProbeResult is one tool call against the daemon's own ingress.

func ProbeMCP

func ProbeMCP(ctx context.Context, socketPath, token, tool string, args map[string]any) (MCPProbeResult, error)

ProbeMCP connects to the ingress, authenticates with token (when non-empty) and calls one tool. token is never logged or echoed.

type NativeHostReport

type NativeHostReport struct {
	StartedAt  string         `json:"started_at"`
	FinishedAt string         `json:"finished_at"`
	DaemonPID  int            `json:"daemon_pid"`
	Cwd        string         `json:"cwd"`
	Env        envReport      `json:"env"`
	Launch     LaunchIdentity `json:"launch"`
	Checks     []ExecResult   `json:"checks"`
}

NativeHostReport is the serialized result of the fixed native-host smoke.

type ProbeResult

type ProbeResult struct {
	Probe    string   `json:"probe"`
	Argv     []string `json:"argv"`
	ExitCode int      `json:"exit_code"`
	Stdout   string   `json:"stdout"`
	Stderr   string   `json:"stderr"`
	TimedOut bool     `json:"timed_out"`
	Err      string   `json:"error,omitempty"`
}

ProbeResult reports one fixed harness or same-process native probe run.

type SmokeCheck

type SmokeCheck struct {
	Name string
	Argv []string
}

SmokeCheck is one fixed, daemon-owned harmless check. The argv is a compile time constant of the daemon; no caller input ever reaches it, which is what keeps host.native_host_smoke from being a general exec surface.

type Store

type Store interface {
	// Close releases the store.
	Close() error
	// Ping is a cheap liveness check.
	Ping(ctx context.Context) error
	// SchemaVersion reports the durable schema version.
	SchemaVersion() int
	// JournalHead reports the highest committed global position (0 when empty).
	JournalHead() (int64, error)
	// EventsAfter returns events with pos > after, oldest first, bounded.
	EventsAfter(pos int64, limit int) ([]JournalEvent, error)
	// EventsForStream returns events on one stream with seq > afterSeq.
	EventsForStream(stream string, afterSeq int64, limit int) ([]JournalEvent, error)
	// Stats returns the runtime counters.
	Stats() (StoreStats, error)
}

Store is the narrow runtime-store port the daemon consumes. It is satisfied by an adapter over internal/runtime's *Store; the daemon never imports that package, so store and daemon stay independently replaceable.

func OpenRuntimeStore

func OpenRuntimeStore(path string) (Store, error)

OpenRuntimeStore opens (creating and migrating when needed) the durable runtime database at path and returns it as the daemon's store port.

type StoreStats

type StoreStats struct {
	SchemaVersion        int   `json:"schema_version"`
	RunsActive           int   `json:"runs_active"`
	RunsTotal            int   `json:"runs_total"`
	SessionsOpen         int   `json:"sessions_open"`
	ComputerSessionsOpen int   `json:"computer_sessions_open"`
	PendingApprovals     int   `json:"pending_approvals"`
	JournalPos           int64 `json:"journal_pos"`
}

StoreStats is the read model behind host.health, runtime.health and the MCP health tool.

type TunnelConfig

type TunnelConfig struct {
	Enabled bool
	// Subcommand is the tunnel-client command that owns the mcp/health flags
	// (upstream CLI shape: "tunnel-client run --mcp.server-url ...").
	Subcommand   string
	Binary       string
	ExtraArgs    []string
	TokenEnv     string
	TokenFile    string
	HealthSocket string
	// RestartBackoff is the initial delay between restarts; it doubles up to
	// RestartBackoffMax.
	RestartBackoff    time.Duration
	RestartBackoffMax time.Duration
	// MaxRestarts stops supervision after this many consecutive restarts.
	// Zero means unlimited (launchd owns the outer lifetime).
	MaxRestarts int
}

TunnelConfig configures the tunnel-client supervision.

type TunnelHealth

type TunnelHealth struct {
	Configured   bool   `json:"configured"`
	Supervised   bool   `json:"supervised"`
	State        string `json:"state"`
	PID          int    `json:"pid,omitempty"`
	Restarts     int    `json:"restarts"`
	MaxRestarts  int    `json:"max_restarts,omitempty"`
	LastError    string `json:"last_error,omitempty"`
	Binary       string `json:"binary,omitempty"`
	ServerURL    string `json:"server_url,omitempty"`
	HealthSocket string `json:"health_socket,omitempty"`
	TokenEnv     string `json:"token_env,omitempty"`
	TokenFile    string `json:"token_file,omitempty"`
}

TunnelHealth is the read model for tunnel supervision.

type TunnelSupervisor

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

TunnelSupervisor owns the tunnel-client child process. The per-launch bearer secret is passed to the child through its environment only: it is never an argument and never appears in a log line.

func NewTunnelSupervisor

func NewTunnelSupervisor(cfg Config, token string, log *slog.Logger) *TunnelSupervisor

NewTunnelSupervisor builds a supervisor for cfg.

func (*TunnelSupervisor) BuildArgs

func (t *TunnelSupervisor) BuildArgs() []string

BuildArgs renders the tunnel-client argument vector. The flags live on the "run" subcommand upstream, so that is always argv[1].

func (*TunnelSupervisor) BuildEnv

func (t *TunnelSupervisor) BuildEnv() []string

BuildEnv returns the child environment: the daemon's own plus the per-launch bearer secret. The value is "Bearer <secret>" because tunnel-client substitutes env references verbatim into the header value.

func (*TunnelSupervisor) Health

func (t *TunnelSupervisor) Health() TunnelHealth

Health reports the current supervision state.

func (*TunnelSupervisor) ServerURL

func (t *TunnelSupervisor) ServerURL() string

ServerURL is the value passed to tunnel-client's --mcp.server-url: the daemon's Streamable HTTP MCP endpoint reached over a Unix socket. No TCP endpoint exists.

func (*TunnelSupervisor) Start

func (t *TunnelSupervisor) Start(ctx context.Context)

Start launches the supervision loop. It never blocks.

func (*TunnelSupervisor) Stop

func (t *TunnelSupervisor) Stop()

Stop terminates the child (SIGTERM, then SIGKILL after the shutdown grace).

func (*TunnelSupervisor) Token

func (t *TunnelSupervisor) Token() string

Token returns the per-launch bearer secret. Callers must never log it.

Jump to

Keyboard shortcuts

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