daemon

package
v0.0.0-...-36bfa78 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: GPL-3.0 Imports: 31 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

Index

Constants

View Source
const AgentNeedsRebindMarker = "S2U_NEEDS_REBIND: "

AgentNeedsRebindMarker prefixes a reported "waiting" result when a prompt could not be typed into its target session because that session's bound window/pane can no longer be verified (it moved panes, left Zellij, or was never re-bound after a restart). Senders detect this prefix to tell the user to re-bind the session. The hop is NOT abandoned: once the session is re-bound it delivers on the next poll, no re-send needed. Keep this string in sync with the desktop app (share2us-gui internal/core/agent.go) and the CLI `agent status` display.

View Source
const ChannelServerName = "share2us"

ChannelServerName is the MCP server name: `server:share2us` on Claude's command line and `<channel source="share2us">` in the session.

Variables

View Source
var (
	// ErrSenderKeyChanged is a hop whose delivered key differs from the pinned one.
	ErrSenderKeyChanged = errors.New("the sender's signing key does not match the one this machine pinned")
	// ErrUnsignedFromPinned is an unsigned hop from a sender that has signed before.
	ErrUnsignedFromPinned = errors.New("this sender signs its hops, but this one is unsigned")
	// ErrHopReplayed is a nonce this machine has already run from this sender.
	ErrHopReplayed = errors.New("this hop has already been delivered once")
	// ErrUnsignedHop is an unsigned hop from a sender never seen before. Every
	// hop is signed now (ADR-041 §5, phase 7.6); the server refuses unsigned ones,
	// so one arriving here was written or stripped by something that should not
	// be trusted.
	ErrUnsignedHop = errors.New("this hop is unsigned; every hop must be signed")
)
View Source
var ErrNotInSession = errors.New("not running inside an agent session")

ErrNotInSession means no ancestor of this process is a live agent session.

View Source
var ErrServiceUnsupported = errors.New("share2us daemon service install is not available on this OS yet; run `share2us daemon run` under your own service manager")

ErrServiceUnsupported is returned by the service-manager operations on platforms whose integration is not built yet (macOS launchd and Windows Scheduled Task are ADR-035 Phase 3). `daemon run` itself still works there (launch it under your own service manager); only install/uninstall/start/logs are gated.

View Source
var ErrSessionHeld = errors.New("the session is open in a window")

ErrSessionHeld: Claude will not run a prompt headlessly in a session that a running process (an open window) holds. The hop waits instead of forking.

Functions

func AgentIDForProject

func AgentIDForProject(list []Binding, project string) (string, bool)

AgentIDForProject returns the stable agent id bound to a project directory, whatever its tool. It reports false when there is none, or when several tools are bound to the directory with different ids and the choice would be a guess.

func AppendHop

func AppendHop(r HopRecord) error

AppendHop records a hop, trimming the log to the newest hopLogKeep records.

func BeginTypedGuard

func BeginTypedGuard(session, request string, pid int) error

BeginTypedGuard persists the active hop before any remote text is pasted. If the daemon dies, the hook can still deny tool use until the turn ends.

func BindTypedPromptID

func BindTypedPromptID(session, prompt, promptID string) bool

BindTypedPromptID is called by UserPromptSubmit for the exact pasted Share2Us prompt. Claude carries this prompt_id through its tool hooks even when internal transcript entries are appended during the turn.

func BindingsPath

func BindingsPath() (string, error)

BindingsPath is where the local whitelist lives: beside the enforced policies, outside any project, so an injected run cannot bind itself into visibility.

func ClaudeChannelArgs

func ClaudeChannelArgs(mcpPath, settingsPath string) []string

ClaudeChannelArgs are the flags that load the share2us channel.

func EnableLinger

func EnableLinger() error

EnableLinger keeps this user's services running after logout (and starts them at boot). For your OWN user, systemd's default policy allows this from an active session (SSH included) without sudo. --no-ask-password makes it fail fast instead of hanging on a password prompt nobody can answer (agent join runs inside an agent session, with no terminal to type into).

func EndTerminalSession

func EndTerminalSession(session string, pid int)

EndTerminalSession clears only records owned by the Claude process that exited. Another process may have resumed the same session ID and be running a guarded hop, even while the daemon is unavailable.

func EndTypedGuard

func EndTypedGuard(session, request string) error

EndTypedGuard only removes the marker for the request that owned it.

func EnforcedPolicyPath

func EnforcedPolicyPath(projectDir string) (string, error)

EnforcedPolicyPath is where the policy the daemon OBEYS lives: outside the agent's writable tree, keyed by the project directory (ADR-041 §5, Q119).

It is deliberately not inside the repo. An agent runs with write access to its own project, so a policy it can edit is a policy it can widen — and `.s2u/` inside a git clone also gets committed, which is fine for team defaults and wrong for anything enforced.

func HeadlessGitDecision

func HeadlessGitDecision(project, tool string, input map[string]any) (bool, string)

HeadlessGitDecision is the non-removable Git boundary for unattended Claude runs. Literal --disallowedTools paths cannot describe symlink aliases or a linked worktree's gitdir, so a PreToolUse hook checks the resolved target.

func HookDecision

func HookDecision(cwd, tool string, input map[string]any, forceRestricted bool) (deny bool, reason string)

HookDecision says whether the policy for cwd refuses this tool call, and why.

Parity with a headless hop, whatever the window's mode (owner, 2026-09-29): a headless hop ran in acceptEdits (plan when restricted), so it could edit inside the project and run only the allowlisted reads, and anything else needed an approval nobody was there to give. A prompt delivered into an auto-mode window would otherwise run any command; this keeps it to what the headless hop could do.

func IsBound

func IsBound(list []Binding, project, tool string) bool

IsBound reports whether sessions of this tool in this project may be advertised. An empty project (a session whose directory we could not determine) is never bound: we will not advertise what we cannot name.

func LingerEnabled

func LingerEnabled() bool

LingerEnabled reports whether this user's services keep running after logout.

func LingerSupported

func LingerSupported() bool

LingerSupported reports whether "keep running after logout" is a thing here: only for a systemd --user service.

func LoadRules

func LoadRules(projectDir string) []string

LoadRules reads the rules that apply to a project: the global rules (if any) then the project's own .s2u.rules (repo root == the session cwd), union. Strictest-wins is inherent — CompileRules only ever ADDS deny patterns.

func LogWriter

func LogWriter(stderr io.Writer) io.Writer

LogWriter returns the log sink. On non-Windows the service manager (systemd journal / launchd StandardOutPath) captures stderr, so no extra file is needed.

func ProveTerminalHook

func ProveTerminalHook(session string, pid int, pane *ZellijPane) error

ProveTerminalHook is called from inside Claude's SessionStart or Stop hook. The PID comes from process ancestry, not from hook JSON supplied by Claude.

func ProveTerminalPromptHook

func ProveTerminalPromptHook(session string, pid int, pane *ZellijPane) error

ProveTerminalPromptHook records that this exact process loaded the newer UserPromptSubmit hook needed to bind prompt ids. Old wrapper sessions must restart before accepting another typed hop.

func ReconcileZellij

func ReconcileZellij(sessionID string, pane *ZellijPane) (bool, error)

ReconcileZellij refreshes the terminal-pane hint for the binding whose current session is sessionID, when that session's process has moved to a different pane (e.g. the zellij session was recreated, or tabs were added/removed, shifting the pane ids). It updates the stored pane in place so delivery resolves again WITHOUT a manual `s2u agent bind`.

Keyed on sessionID, not the zellij session name, so it tracks the SAME session to its current pane and never retargets a different one — the caller supplies the pane read from that session's own process (ProcessZellijPane / the terminal-guard proof), exactly as `agent bind` does. Returns (changed, error); a no-op when the pane already matches or the session is not bound.

func Run

func Run(ctx context.Context, opts Options, deps Deps) error

Run starts the daemon: the single-instance lock + control server, then the inbox poll, the LAN receiver, and the maintenance scheduler, each under ctx. It returns when ctx is cancelled (SIGTERM/SIGINT) or a fatal error occurs.

func RunClaudeInject

func RunClaudeInject(ctx context.Context, sessionID, cwd, prompt string, forceRestricted bool) (string, error)

RunClaudeInject continues a Claude session non-interactively with the injected prompt, under the compiled guardrail profile for the session's project (ADR-036 P3): a restricted permission mode (never bypassPermissions / auto-accept from the live session), hard --disallowedTools denies compiled from .s2u.rules, and the advisory rules in the system prompt. cwd is the session's project dir, used to locate .s2u.rules. Returns the run's combined output. (Phase 4 adds the delivered file.)

func RunClaudeInjectSession

func RunClaudeInjectSession(ctx context.Context, sessionID, cwd, prompt string, forceRestricted bool) (string, string, error)

RunClaudeInjectSession runs a hop IN sessionID and reports the session the agent is in afterwards, read from Claude's JSON result. It never forks: if a window holds the session, Claude refuses and this returns ErrSessionHeld.

func RunCodexInject

func RunCodexInject(ctx context.Context, sessionID, cwd, prompt string, forceRestricted bool) (string, error)

RunCodexInject resumes a Codex session non-interactively with the injected prompt, under a workspace-write sandbox (writes confined to the workspace, no network — which blocks push/deploy/fetch). Never bypasses the sandbox.

Codex has no per-tool deny layer to compile .s2u.rules into, so the rules ride in the prompt (best-effort) and the sandbox is the hard gate.

func RunGeminiInject

func RunGeminiInject(ctx context.Context, sessionID, cwd, prompt string, forceRestricted bool) (string, error)

RunGeminiInject resumes a Gemini session headlessly with the prompt, under a restricted approval mode (auto-approve edits, never yolo). Resume is by index, so it re-lists to find the index of the target UUID.

func SameProject

func SameProject(a, b string) bool

SameProject reports whether two paths name the same project folder, the way bindings compare them.

func SenderPinsPath

func SenderPinsPath() (string, error)

SenderPinsPath lives beside the bindings and enforced policies, outside any project, so an injected run cannot rewrite who this machine trusts.

func ServiceActive

func ServiceActive() bool

ServiceActive reports whether the per-user service unit is running.

func ServiceInstall

func ServiceInstall(exePath, destDir string, out io.Writer) error

ServiceInstall writes the user unit and enables+starts it. exePath is the share2us binary to run; destDir (may be "") is added to ReadWritePaths.

func ServiceLogs

func ServiceLogs(follow bool) error

ServiceLogs tails the unit's journal, inheriting stdio.

func ServiceNeedsRefresh

func ServiceNeedsRefresh(exePath string) bool

ServiceNeedsRefresh reports whether the installed unit is not what this build would write now (a new PATH, agents bound since it was written, or an older template). Only an installed unit can be stale.

func ServiceRefresh

func ServiceRefresh(exePath string, out io.Writer) error

ServiceRefresh rewrites the unit (keeping its receive folder) and restarts it.

func ServiceRestart

func ServiceRestart() error

ServiceRestart restarts the unit, so it runs the binary now on disk.

func ServiceStart

func ServiceStart() error

ServiceStart starts the installed unit.

func ServiceStop

func ServiceStop() error

ServiceStop stops the installed unit.

func ServiceSupported

func ServiceSupported() bool

ServiceSupported reports that per-OS service integration exists here.

func ServiceUninstall

func ServiceUninstall(out io.Writer) error

ServiceUninstall disables+stops the unit and removes it.

func TerminalHookReady

func TerminalHookReady(session string, pid int) bool

TerminalHookReady is deliberately independent of MCP channel polling.

func TerminalTypedReady

func TerminalTypedReady(session string, pid int) bool

func TranscriptHasLastUserRequest

func TranscriptHasLastUserRequest(path, request string) bool

func TranscriptRequestState

func TranscriptRequestState(path, request string) (matches, known bool)

TranscriptRequestState distinguishes the delivered turn from a later owner turn. An unreadable transcript is unknown and must never release the guard.

func TranscriptToolIsLaterOwnerTurn

func TranscriptToolIsLaterOwnerTurn(path, request, toolUseID string) bool

TranscriptToolIsLaterOwnerTurn is deliberately stricter than comparing the newest user-role entry. Compaction, meta context, and a prompt queued while Claude is busy can all appear after the delivered prompt. Only release when the *current tool call* is a descendant of a different human prompt, not of the delivered one. The transcript is asynchronous, so missing ids fail closed.

func TypedGuardPromptID

func TypedGuardPromptID(session string) string

func TypedGuardRequest

func TypedGuardRequest(session string) string

func Unbind

func Unbind(project, tool string) (int, error)

Unbind removes bindings for a project, for one tool or (when tool is empty) for every tool. It returns how many were removed.

func WriteChannelLaunchConfig

func WriteChannelLaunchConfig(exe string) (mcpPath, settingsPath string, err error)

WriteChannelLaunchConfig writes the two files `s2u claude` passes to Claude: an MCP config that starts this binary as the share2us channel, and settings that add the guardrail hooks. They live beside the bindings and are rewritten on every launch, so a moved or updated binary is picked up.

func WriteEnforcedPolicy

func WriteEnforcedPolicy(projectDir string, p Privilege) (string, error)

WriteEnforcedPolicy records an agent's privilege for projectDir. This is the owner's act, run from their own shell — never something an injected run can do (the enforced file sits outside the project the agent can write).

Types

type AgentClient

type AgentClient interface {
	RegisterAgentSession(ctx context.Context, in clicore.AgentRegisterInput) error
	// ListAgentSessions is used once at startup to retire sessions this device
	// advertised before they were bound (ADR-041 §1 / F2).
	ListAgentSessions(ctx context.Context) ([]clicore.AgentSessionInfo, error)
	DeregisterAgentSession(ctx context.Context, sessionID string) error
	AgentLongPoll(ctx context.Context, waitSeconds int) ([]clicore.AgentRequest, error)
	AgentReportResult(ctx context.Context, id, status, result string) error
	// AgentRequeueWaiting gets back, once at startup, the hops this device was
	// holding for an open window when it last stopped.
	AgentRequeueWaiting(ctx context.Context) (int, error)
}

AgentClient is the subset of the server API the bridge loop drives (implemented by *clicore.Client). Kept an interface so the loop is unit-testable.

type AgentFileStage

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

AgentFileStage holds only encrypted bytes until a signed inject names the nonce and the LAN peer's fingerprint. Its files are not an agent inbox: an orphaned push is never placed or run, and is swept after the TTL.

type AgentRunner

type AgentRunner interface {
	Tool() string
	Discover(ctx context.Context) ([]DiscoveredSession, error)
	Run(ctx context.Context, sessionID, cwd, prompt string) (string, error)
}

AgentRunner discovers this machine's sessions for one tool and runs an injected prompt into one of them (implemented by the Claude adapter in agents_claude.go).

type Binding

type Binding struct {
	// AgentID is this agent's stable identity (ADR-041 §1a): created once when the
	// binding is made and NEVER changed afterwards. A session id can change on
	// recreation (a new bind), so anything that must outlive a
	// single prompt, above all an invitation into another owner's project, is keyed
	// to this. It lives here, outside the project, because the agent can edit its
	// own project and an identity it could rewrite is not an identity.
	AgentID string `json:"agent_id,omitempty"`
	// Project is the absolute, cleaned session working directory.
	Project string `json:"project"`
	// Tool is "claude", "codex" or "gemini". A binding is per tool: binding a
	// Claude session in a directory does not advertise a Codex one beside it.
	Tool string `json:"tool"`
	// Label is the sharenet project this is meant to join. Nothing consumes it
	// yet — server-side projects are ADR-041 P2 — but the owner names it when
	// binding, so it is recorded rather than asked for twice.
	Label   string    `json:"label,omitempty"`
	BoundAt time.Time `json:"bound_at"`
	// SessionID is the ONE session this agent currently is (owner, 2026-09-27:
	// bind a single session, not every session in the folder). Set by
	// `agent join` / `agent bind <session>` and never moved by a hop: hops run
	// in this session or wait for it, they never fork (owner, 2026-09-29).
	// Empty in a binding made before this existed: that one still covers every session of its tool
	// in the folder until it is bound again.
	SessionID string `json:"session_id,omitempty"`
	// Zellij records where the bound session lived when it was last bound. It
	// is only a hint: every delivery re-proves the process, pane, command and
	// project before typing anything. Nil means live typing is unavailable.
	Zellij *ZellijPane `json:"zellij,omitempty"`
	// TypedDeliveryDisabled is the owner's switch for automatic Zellij paste.
	// Channel and headless delivery remain available when this is true.
	TypedDeliveryDisabled bool `json:"typed_delivery_disabled,omitempty"`
}

A Binding is a session's permission to exist on the server: the daemon advertises a discovered agent session ONLY when its project and tool are bound (ADR-041 §1).

Before this, registration was "everything the adapter can find", which the P0 prototype showed for what it is (p0-orchestration-run.md, F2): running the bridge for two project directories advertised every other Claude and Codex session on the machine — unrelated client work, by name and working directory. On a shared sharenet that is another member's view of your whole desk.

So a binding is a whitelist entry, and it is also where the privilege for that project lives (privilege.go). One object, three jobs, per ADR-041.

func Bind

func Bind(project, tool, label string) (Binding, bool, error)

Bind adds a binding, or updates the label of one that already exists. It returns the stored binding and whether it was newly created.

func BindSession

func BindSession(project, tool, label, sessionID string) (Binding, bool, error)

BindSession binds exactly one session: the binding for its folder and tool (created if new, keeping its agent id if not) now points at sessionID.

func BindSessionInPane

func BindSessionInPane(project, tool, label, sessionID string, pane *ZellijPane) (Binding, bool, error)

BindSessionInPane binds exactly one session and refreshes its terminal-pane hint. Passing nil deliberately clears an older hint: rebinding outside zellij must never leave a stale pane eligible for typing.

func BindingFor

func BindingFor(list []Binding, project, tool string) (Binding, bool)

BindingFor returns the binding covering a session's project and tool.

func BindingForSession

func BindingForSession(list []Binding, sessionID string) (Binding, bool)

BindingForSession returns the binding whose current session is sessionID.

func LoadBindings

func LoadBindings() ([]Binding, error)

LoadBindings reads the whitelist. A missing file is not an error: it means nothing is bound, which is the safe reading — no sessions are advertised.

func SetTypedDelivery

func SetTypedDelivery(project string, enabled bool) (Binding, error)

SetTypedDelivery lets the owner disable or re-enable automatic terminal typing for an existing Claude binding without changing its identity.

func (Binding) Covers

func (b Binding) Covers(s DiscoveredSession) bool

Covers reports whether a discovered session belongs to this binding.

type ChannelCaller

type ChannelCaller func(daemonctl.Request) (daemonctl.Response, bool)

ChannelCaller sends a control request to the daemon (daemonctl.Call in production).

type ChannelDelivery

type ChannelDelivery struct {
	RequestID string `json:"request_id"`
	Prompt    string `json:"prompt"`
	From      string `json:"from,omitempty"`
	// Strict: the daemon runs agents read-only (--agent-strict); the hook
	// enforces that too while this hop is in progress.
	Strict bool `json:"-"`
}

ChannelDelivery is one hop handed to a session's channel.

type ChannelServer

type ChannelServer struct {
	// FindSession returns the Claude session this server runs in.
	FindSession func(context.Context) (string, error)
	Call        ChannelCaller
	Poll        time.Duration
	Logf        func(string, ...any)
	// contains filtered or unexported fields
}

ChannelServer is one running channel.

func (*ChannelServer) Serve

func (s *ChannelServer) Serve(ctx context.Context, in io.Reader, out io.Writer) error

Serve runs the server until in closes or ctx ends.

type ClaudeRunner

type ClaudeRunner struct{ Strict bool }

ClaudeRunner adapts the Claude Code CLI. Strict selects the read-only mode.

func (ClaudeRunner) Discover

func (ClaudeRunner) Discover(ctx context.Context) ([]DiscoveredSession, error)

func (ClaudeRunner) Run

func (r ClaudeRunner) Run(ctx context.Context, sessionID, cwd, prompt string) (string, error)

func (ClaudeRunner) RunSession

func (r ClaudeRunner) RunSession(ctx context.Context, sessionID, cwd, prompt string) (string, string, error)

func (ClaudeRunner) Tool

func (ClaudeRunner) Tool() string

type CodexRunner

type CodexRunner struct{ Strict bool }

CodexRunner adapts the Codex CLI. Strict is the daemon-wide safety override (`--agent-strict`); without it each project's own policy decides (AgentPolicy).

func (CodexRunner) Discover

func (CodexRunner) Discover(ctx context.Context) ([]DiscoveredSession, error)

func (CodexRunner) Run

func (r CodexRunner) Run(ctx context.Context, sessionID, cwd, prompt string) (string, error)

func (CodexRunner) Tool

func (CodexRunner) Tool() string

type Deps

type Deps struct {
	// ReceiveOnce runs one account-inbox poll, saving new files to destDir, and
	// returns how many arrived. Wraps receiveInboxOnce.
	ReceiveOnce func(ctx context.Context, destDir string) (int, error)
	// RefreshTrust refreshes the server-signed LAN trust cache (best-effort).
	RefreshTrust func(ctx context.Context)
	// RefreshOwnDevices refreshes the cache of this account's own device LAN
	// fingerprints, used by IsOwnAccountDevice (best-effort). nil = not refreshed.
	RefreshOwnDevices func(ctx context.Context)
	// CheckUpdate returns whether a newer build exists plus a human upgrade line.
	CheckUpdate func(ctx context.Context) (available bool, message string)
	// Cleanup removes stale temp/staging files (best-effort).
	Cleanup func(ctx context.Context) error
	// AgentClient + AgentRunner drive the agent-session bridge (ADR-036); nil when
	// the bridge is off.
	AgentClient  AgentClient
	AgentRunners []AgentRunner
	// Unseal opens a prompt/envelope sealed to this device (ADR-036 E2E); nil = plaintext.
	Unseal func(sealed string) (string, error)
	// DownloadContent fetches an injected file's ciphertext by request id; nil = no files.
	DownloadContent func(ctx context.Context, id string) ([]byte, error)
	// OpenContentKey opens a sealed file content key with this device's key.
	OpenContentKey func(sealed string) ([]byte, error)
	// AgentFiles holds encrypted LAN pushes until a signed request claims them.
	AgentFiles *AgentFileStage
	// DeviceSessionID is this device's session id, used to tell our own agent
	// sessions from another device's when retiring unbound ones, and as the
	// target a signed hop must have been signed for.
	DeviceSessionID string
	// SenderPins pins each sender's signing key on first use and verifies every
	// later hop against it (ADR-041 §5). nil means the daemon refuses every hop.
	SenderPins *SenderPins
	// Logf writes an operational log line (to stderr/journal).
	Logf func(format string, args ...any)
}

Deps are the behaviours the daemon composes, injected from package main so this package stays free of the CLI's app god-struct and is unit-testable.

type DiscoveredSession

type DiscoveredSession struct {
	SessionID string
	Tool      string
	Name      string
	Project   string // cwd
	Status    string // available | busy | unknown
	// PID is the process currently holding the interactive session, when the
	// adapter can identify it. It is used only for local identity checks (for
	// example, proving which zellij pane owns a bound session).
	PID int
	// Live: a running tool process holds the session (Claude lists it in
	// `claude agents`), so a hop waits until it lets the session go.
	Live bool
}

DiscoveredSession is a live coding-agent session found on this machine.

func DiscoverClaude

func DiscoverClaude(ctx context.Context) ([]DiscoveredSession, error)

DiscoverClaude lists this machine's live Claude Code sessions via the supported `claude agents --json` (no TTY needed). Deduped by sessionId, preferring an entry that reports a concrete idle/busy status.

func DiscoverCodex

func DiscoverCodex(ctx context.Context) ([]DiscoveredSession, error)

DiscoverCodex lists recent Codex sessions from the rollout store.

func DiscoverGemini

func DiscoverGemini(ctx context.Context) ([]DiscoveredSession, error)

DiscoverGemini lists Gemini sessions across the known projects.

func FindOwnSession

func FindOwnSession(ctx context.Context) (DiscoveredSession, error)

FindOwnSession returns the agent session this process is running inside.

type GeminiRunner

type GeminiRunner struct{ Strict bool }

GeminiRunner adapts the Gemini CLI. Strict is the daemon-wide safety override (`--agent-strict`); without it each project's own policy decides (AgentPolicy).

func (GeminiRunner) Discover

func (GeminiRunner) Discover(ctx context.Context) ([]DiscoveredSession, error)

func (GeminiRunner) Run

func (r GeminiRunner) Run(ctx context.Context, sessionID, cwd, prompt string) (string, error)

func (GeminiRunner) Tool

func (GeminiRunner) Tool() string

type HopRecord

type HopRecord struct {
	Time      time.Time `json:"time"`
	RequestID string    `json:"request_id"`
	Tool      string    `json:"tool"`
	From      string    `json:"from_device"`
	Target    string    `json:"target_session"`
	RanIn     string    `json:"ran_in,omitempty"`
	Mode      string    `json:"mode"`   // "typed", "resumed" (same session), "ran", or "expired"
	Status    string    `json:"status"` // "done" or "failed"
	// Waited is how long the hop waited for an open window to let the session go.
	Waited string `json:"waited,omitempty"`
	Prompt string `json:"prompt"`
}

HopRecord is one hop as this machine ran it.

func LoadHops

func LoadHops(n int) ([]HopRecord, error)

LoadHops returns the logged hops, oldest first; the newest n when n > 0.

type InjectEnvelope

type InjectEnvelope struct {
	Prompt   string `json:"prompt"`
	FileName string `json:"file_name,omitempty"`
	Deliver  string `json:"deliver,omitempty"`
	// The sender's LAN key fingerprint is inside the signed, sealed prompt.
	// It must match the TLS-proven peer that staged this hop's ciphertext.
	SenderLANFingerprint string `json:"sender_lan_fingerprint,omitempty"`
	SenderDeviceName     string `json:"sender_device_name,omitempty"`
}

InjectEnvelope is the sealed payload of an inject: the prompt and, when a file rides along, its name. Sealing the whole envelope keeps the filename E2E too (the server sees neither). A P4a raw-string prompt (no envelope) is handled by ParseEnvelope's fallback.

func ParseEnvelope

func ParseEnvelope(raw string) InjectEnvelope

ParseEnvelope reads a decrypted inject payload. If it isn't a JSON envelope it is treated as a bare prompt (back-compat).

type NoopNotifier

type NoopNotifier struct{}

NoopNotifier drops every notification. Used when --no-notify is set or on a build without the notification backend.

func (NoopNotifier) Info

func (NoopNotifier) Info(string, string)

func (NoopNotifier) SupportsActions

func (NoopNotifier) SupportsActions() bool

type Notifier

type Notifier interface {
	// Info posts a fire-and-forget notification. Errors are swallowed (a missing
	// notification daemon is not an error worth failing a receive over).
	Info(title, message string)
	// SupportsActions reports whether this backend can present Accept/Reject
	// buttons and return the choice. Today no backend does (see notify_beeep.go),
	// so approval falls back to notify-then-decline; the hook exists so a richer
	// backend can light up ask-mode approvals without touching the runtime.
	SupportsActions() bool
}

Notifier delivers native desktop notifications. The daemon runs with no terminal and (in this phase) no window, so a notification is the only way it reaches the user. Implementations must be safe to call from any goroutine and must never block the caller: a stuck notification backend cannot be allowed to stall a transfer or the run loop.

func NewNotifier

func NewNotifier() Notifier

NewNotifier returns the platform notification backend. Build with the "nonotify" tag to drop beeep and its transitive deps for a headless/server binary (see notify_stub.go).

type Options

type Options struct {
	DestDir         string // where received files land ("" = lanshare/receiveInboxOnce default)
	LANDiscoverable bool   // run the background LAN receiver
	RunInbox        bool   // run the account-inbox poll (false under a PAT)
	Notify          bool   // post desktop notifications
	WarnTab         bool   // open a loud zellij tab when a bound pane can't be located for a waiting prompt
	Instance        string // mDNS advertised name ("" = hostname)
	Bind            string // LAN bind address ("" = all interfaces)
	Port            int    // LAN port (0 = auto)
	// IsTrustedSender reports whether a verified LAN sender key is a trusted
	// device (ADR-034). Replaces the old trust-by-IP, which a LAN attacker could
	// claim by taking the address (todo W-M5).
	IsTrustedSender func(senderKey []byte) bool
	// IsOwnAccountDevice reports whether a verified LAN sender key belongs to
	// another device on THIS account. The agent-file receiver admits such a
	// sender without a separate ADR-034 pairing (see acceptAgentFilePush); the
	// ordinary file receiver does not use it.
	IsOwnAccountDevice func(senderKey []byte) bool
	InboxInterval      time.Duration // inbox poll cadence (0 = default 5s)
	ApprovalPolicy     string        // LAN approval policy (clicore.ApprovalPolicy*)
	AgentBridge        bool          // ADR-036: register sessions + receive inject requests
}

Options configures a daemon run. Zero values fall back to sensible defaults.

type Policy

type Policy struct {
	// Privilege is the level this policy was compiled under (ADR-041 §6). At
	// PrivilegePrivileged the baseline denies are dropped, because an agent whose
	// owner set it that way is meant to push and deploy; self-protection is not.
	Privilege Privilege
	// DisallowedTools are Claude permission patterns passed to --disallowedTools.
	// The tool executor refuses them regardless of what the prompt says (hard).
	DisallowedTools []string
	// AllowedTools are Claude permission patterns passed to --allowedTools: the
	// read-only commands a hop may run without an approval nobody is there to give.
	AllowedTools []string
	// Advisory rules could not be mapped to a hard gate; they ride in the system
	// prompt and are best-effort only.
	Advisory []string
}

Policy is the compiled enforcement for one injected run.

func CompileRules

func CompileRules(lines []string, priv Privilege) Policy

CompileRules turns plain-text rules into a Policy. Lines starting with a prohibition word are matched against the hard-rule vocabulary; matched ones become deny patterns, unmatched prohibitions become advisory. Self-protection deny patterns are always included. Comments (#) and blank lines are ignored.

func (Policy) AppendSystemPrompt

func (p Policy) AppendSystemPrompt() string

AppendSystemPrompt renders the advisory rules for --append-system-prompt, honestly flagged as best-effort (the hard denies are separately enforced).

func (Policy) PromptPreamble

func (p Policy) PromptPreamble() string

PromptPreamble renders the rules as prompt text for tools that have no per-tool deny layer to compile into. Claude gets hard --disallowedTools patterns; Codex and Gemini only have a sandbox / approval mode, which stops writes and network but knows nothing about "never push". So for those the compiled denies are restated in the prompt — best-effort, and honestly labelled as such in the ADR.

type Privilege

type Privilege string

Privilege is how much an injected run may do, chosen PER AGENT by the machine's owner (ADR-041 §6). It used to be one `--agent-strict` flag for every runner on the machine, which could not express the thing the design needs: a locked-down QA agent and a deploying devops agent side by side on one laptop.

The P0 prototype is the evidence (docs/ideas/inbox/p0-orchestration-run.md, F1): Codex could not push, and the reason was not Codex — it was our adapter hardcoding `workspace-write` from a machine-wide flag. Agents may legitimately run with full privilege on their owner's laptop or an SSH session.

const (
	// PrivilegeRestricted is read-only: Claude `plan`, Codex `read-only`,
	// Gemini `plan`. What `--agent-strict` used to mean.
	PrivilegeRestricted Privilege = "restricted"
	// PrivilegeStandard is the DEFAULT and is unchanged from ADR-036: edit inside
	// the workspace, no network, baseline denies (push/delete/network) enforced.
	PrivilegeStandard Privilege = "standard"
	// PrivilegePrivileged is the explicit opt-out an owner sets for an agent that
	// is supposed to deploy: network and pushes allowed, baseline denies dropped.
	// It never reaches a tool's "no guardrails at all" mode (Claude
	// bypassPermissions, Gemini yolo) — see privilegedNote in the adapters.
	PrivilegePrivileged Privilege = "privileged"
)

func AgentPolicy

func AgentPolicy(projectDir string, forceRestricted bool) Privilege

AgentPolicy resolves the privilege for one injected run in projectDir.

Three sources, and the rule between them is asymmetric on purpose:

  • the ENFORCED file (outside the tree) may loosen or tighten — it is the owner speaking;
  • the IN-REPO file may only tighten, because the agent can write it;
  • forceRestricted (the daemon's `--agent-strict`) always wins, as a machine-wide safety override.

With no files at all this returns PrivilegeStandard, which is exactly what ADR-036 did before this existed.

func (Privilege) Valid

func (p Privilege) Valid() bool

Valid reports whether p is a privilege we understand. An unknown value in a policy file is treated as absent rather than as an escalation.

type Runtime

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

Runtime holds run state (start time, what it owns, the stop hook) so the control server can answer status/owns-receiver and honour a stop request.

type SenderPins

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

SenderPins is the on-disk store of pinned sender keys and seen nonces. It is shared by concurrent inject handlers, so every read-modify-write holds mu.

func NewSenderPins

func NewSenderPins() (*SenderPins, error)

NewSenderPins opens (lazily) the store at its default path.

func (*SenderPins) VerifyDelivered

func (s *SenderPins) VerifyDelivered(req clicore.AgentRequest, selfDeviceID string, now time.Time) error

VerifyDelivered decides whether a delivered hop may run on this machine. It returns nil to run it, or the reason it must not. On success it records the nonce (and, on a sender's first signed hop, pins its key), so calling it twice for the same hop refuses the second — which is the point.

selfDeviceID is THIS device's session id: the target the sender signed for.

type ZellijLocation

type ZellijLocation struct {
	Session string
	Pane    string
	TabName string
}

ZellijLocation is safe display metadata for a pane whose process identity was revalidated. TabName is presentation only and is never used as an id.

func FindZellijLocation

func FindZellijLocation(ctx context.Context, binding Binding, session DiscoveredSession) (ZellijLocation, bool)

FindZellijLocation resolves a binding for CLI display using the same strict identity checks as delivery.

type ZellijPane

type ZellijPane struct {
	Session string `json:"session"`
	Pane    string `json:"pane"`
}

ZellijPane is the small, non-secret part of a session process environment needed to locate its terminal pane. Session can become stale after a zellij rename; delivery resolves the current zellij session and requires one unique match instead of trusting this name as an address.

func CurrentZellijPane

func CurrentZellijPane() *ZellijPane

CurrentZellijPane returns the pane inherited by the command currently running inside an agent. Only the two zellij identifiers are read.

func ProcessZellijPane

func ProcessZellijPane(pid int) *ZellijPane

ProcessZellijPane reads only the two zellij identifiers from pid's environment. Unsupported or inaccessible processes simply have no pane.

func TerminalHookPane

func TerminalHookPane(session string, pid int) *ZellijPane

TerminalHookPane is the two inherited Zellij identifiers attested by the hook. The service may be unable to read /proc/PID/environ under systemd's ProtectSystem=full; this stays tied to the same Claude session and PID.

Jump to

Keyboard shortcuts

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