{"modulePath":"github.com/Twigpine/zero","version":"v0.14.0","isLatest":true,"isStandardLibrary":false,"goos":"linux","goarch":"amd64","docs":"# package execution\n\nPackage execution defines the platform-neutral command execution contract. Frontends and tools use these types without depending on native sandbox or process-management details.\n\n## Constants\n\n```go\nconst PolicyVersion = 2\n```\nPolicyVersion is the version of the approval policy that recorded grants were evaluated under. Bump it whenever a change narrows what may be approved: the grant store then backs the file up, keeps deny grants, invalidates prior approvals, and tells the user once, instead of silently honoring approvals that the current rules would have refused.\n\nv2 tightened command-prefix validation so a launcher spelled with a version or an executable extension (\"python3.11\", \"python.exe\") can no longer be approved as an ordinary command.\n\n## Variables\n\n```go\nvar (\n\tErrProcessNotFound      = errors.New(\"execution process not found\")\n\tErrProcessStdinDisabled = errors.New(\"execution process does not accept stdin\")\n\tErrProcessCapacity      = errors.New(\"execution process capacity reached; stop a running process before starting another\")\n)\n```\n\n## Functions\n\n```go\nfunc ConfigureProcessGroup(cmd *exec.Cmd)\n```\nConfigureProcessGroup makes cmd the leader of a process group so lifecycle operations cover descendants instead of orphaning them.\n\n```go\nfunc KillProcessTree(pid int) error\n```\nKillProcessTree immediately kills pid and, when it is a group leader, its descendant process group.\n\n```go\nfunc TerminateProcessGroup(pid int, grace, poll time.Duration) error\n```\nTerminateProcessGroup is like TerminateProcessTree, but for a caller that already knows pid is (or was, at launch) its own process-group leader — e.g. a command started after ConfigureProcessGroup(cmd), which sets Setpgid so cmd.Process.Pid always leads its own group at the moment it is signalled.\n\nTerminateProcessTree instead rediscovers the group via syscall.Getpgid(pid) at call time. On Darwin, that lookup can return ESRCH once an unreaped group leader has already exited, even though live descendants remain in the group it configured — TerminateProcessTree would then silently fall back to signalling only the (already dead) leader PID and leave those descendants running. Skipping rediscovery in favor of the launch-time invariant avoids that: the negative PID is used directly, regardless of whether the leader is still alive to be looked up.\n\n```go\nfunc TerminateProcessTree(pid int, grace, poll time.Duration) error\n```\nTerminateProcessTree requests graceful termination, then force-kills the process tree after grace. Callers retain their distinct persistence models; this function owns only the OS lifecycle primitive.\n\nThe signal target is REDISCOVERED here via processSignalTarget(pid), which asks the OS for pid's current group. A caller that already knows pid was configured as its own group leader at launch (e.g. via ConfigureProcessGroup) should use TerminateProcessGroup instead — see its doc comment for why this rediscovery is fragile once the leader may have already exited.\n\n## Types\n\n```go\ntype AdapterReport struct {\n\tDenial *Denial `json:\"denial,omitempty\"`\n}\n```\nAdapterReport is the structured, machine-readable result emitted by a platform enforcement adapter. It is separate from stdout and stderr so command text cannot impersonate a policy decision.\n\n```go\ntype ApprovalContext struct {\n\tSessionID     string `json:\"sessionId,omitempty\"`\n\tPolicyVersion int    `json:\"policyVersion\"`\n}\n```\n\n```go\ntype Capability struct {\n\tKind  CapabilityKind `json:\"kind\"`\n\tScope string         `json:\"scope,omitempty\"`\n}\n```\n\n```go\ntype CapabilityKind string\n```\n\n```go\nconst (\n\tCapabilityRead               CapabilityKind = \"filesystem_read\"\n\tCapabilityWorkspaceWrite     CapabilityKind = \"workspace_write\"\n\tCapabilityProtectedMetadata  CapabilityKind = \"protected_metadata\"\n\tCapabilityExternalNetwork    CapabilityKind = \"external_network\"\n\tCapabilityIsolatedLoopback   CapabilityKind = \"isolated_loopback\"\n\tCapabilityHostVisibleBinding CapabilityKind = \"host_visible_binding\"\n\tCapabilityProcessSpawn       CapabilityKind = \"process_spawn\"\n\tCapabilityProcessControl     CapabilityKind = \"process_control\"\n\tCapabilityEnvironment        CapabilityKind = \"environment\"\n\tCapabilityUnrestricted       CapabilityKind = \"unrestricted\"\n)\n```\n\n```go\ntype CapturedRequest struct {\n\tRequest Request\n\tStdin   []byte\n}\n```\n\n```go\ntype CapturedResult struct {\n\tStdout    string\n\tStderr    string\n\tTruncated bool\n\tOutcome   Outcome\n\tErr       error\n}\n```\n\n```go\ntype Change struct {\n\tPath       string     `json:\"path\"`\n\tKind       ChangeKind `json:\"kind\"`\n\tAggregated bool       `json:\"aggregated,omitempty\"`\n\tCount      int        `json:\"count,omitempty\"`\n}\n```\n\n```go\ntype ChangeKind string\n```\n\n```go\nconst (\n\tChangeCreated  ChangeKind = \"created\"\n\tChangeModified ChangeKind = \"modified\"\n\tChangeDeleted  ChangeKind = \"deleted\"\n)\n```\n\n```go\ntype ChangeObserver struct {\n\t// contains filtered or unexported fields\n}\n```\nChangeObserver records a bounded workspace snapshot around a command. It deliberately skips Zero/repository control metadata and large generated dependency trees; those paths must neither be read as command evidence nor flood the Files panel.\n\n```go\nfunc NewChangeObserver(root string) *ChangeObserver\n```\n\n```go\nfunc (observer *ChangeObserver) Changes() []Change\n```\n\n```go\ntype Command struct {\n\tName string   `json:\"name\"`\n\tArgs []string `json:\"args,omitempty\"`\n\tEnv  []string `json:\"env,omitempty\"`\n}\n```\n\n```go\ntype Denial struct {\n\tCapability  Capability       `json:\"capability\"`\n\tSource      DenialSource     `json:\"source\"`\n\tReason      string           `json:\"reason\"`\n\tRecoverable bool             `json:\"recoverable\"`\n\tNextAction  DenialNextAction `json:\"nextAction\"`\n}\n```\n\n```go\nfunc (denial Denial) Validate() error\n```\n\n```go\ntype DenialNextAction string\n```\n\n```go\nconst (\n\tDenialNextActionNone            DenialNextAction = \"none\"\n\tDenialNextActionRequestApproval DenialNextAction = \"request_approval\"\n\tDenialNextActionChangeCommand   DenialNextAction = \"change_command\"\n\tDenialNextActionEnableSandbox   DenialNextAction = \"enable_sandbox\"\n)\n```\n\n```go\ntype DenialSource string\n```\n\n```go\nconst (\n\tDenialSourceConfiguredPolicy DenialSource = \"configured_policy\"\n\tDenialSourcePlatformSandbox  DenialSource = \"platform_sandbox\"\n\tDenialSourceApproval         DenialSource = \"approval\"\n)\n```\n\n```go\ntype Enforcement struct {\n\tBackend         string `json:\"backend,omitempty\"`\n\tLevel           string `json:\"level,omitempty\"`\n\tDegraded        bool   `json:\"degraded,omitempty\"`\n\tDowngradeReason string `json:\"downgradeReason,omitempty\"`\n}\n```\n\n```go\ntype Exit struct {\n\tCode   int    `json:\"code\"`\n\tSignal string `json:\"signal,omitempty\"`\n}\n```\n\n```go\ntype Mode string\n```\n\n```go\nconst (\n\tModeCaptured    Mode = \"captured\"\n\tModeInteractive Mode = \"interactive\"\n\tModeDurable     Mode = \"durable\"\n)\n```\n\n```go\ntype Origin string\n```\n\n```go\nconst (\n\tOriginInteractiveCommand Origin = \"interactive_command\"\n\tOriginHook               Origin = \"hook\"\n\tOriginPlugin             Origin = \"plugin\"\n\tOriginMCPServer          Origin = \"mcp_server\"\n\tOriginBackgroundTask     Origin = \"background_task\"\n)\n```\n\n```go\ntype Outcome struct {\n\tState       State       `json:\"state\"`\n\tKind        OutcomeKind `json:\"kind\"`\n\tProcessID   string      `json:\"processId,omitempty\"`\n\tExit        *Exit       `json:\"exit,omitempty\"`\n\tDenial      *Denial     `json:\"denial,omitempty\"`\n\tEnforcement Enforcement `json:\"enforcement\"`\n\tChanges     []Change    `json:\"changes,omitempty\"`\n}\n```\n\n```go\nfunc (outcome Outcome) Validate() error\n```\n\n```go\ntype OutcomeKind string\n```\n\n```go\nconst (\n\tOutcomeRunning             OutcomeKind = \"running\"\n\tOutcomeSuccess             OutcomeKind = \"success\"\n\tOutcomePolicyDenied        OutcomeKind = \"policy_denied\"\n\tOutcomeEnforcementDenied   OutcomeKind = \"enforcement_denied\"\n\tOutcomeApplicationFailure  OutcomeKind = \"application_failure\"\n\tOutcomeSandboxSetupFailure OutcomeKind = \"sandbox_setup_failure\"\n\tOutcomeExecutableNotFound  OutcomeKind = \"executable_not_found\"\n\tOutcomeCancelled           OutcomeKind = \"cancelled\"\n\tOutcomeTimedOut            OutcomeKind = \"timed_out\"\n\tOutcomeEnforcementDegraded OutcomeKind = \"enforcement_degraded\"\n)\n```\n\n```go\ntype PreparedCommand struct {\n\tCommand     *exec.Cmd\n\tEnforcement Enforcement\n\tReport      func() (AdapterReport, error)\n\tCleanup     func()\n}\n```\n\n```go\ntype Preparer interface {\n\tPrepareExecution(context.Context, Request) (PreparedCommand, error)\n}\n```\nPreparer is the platform-adapter seam. It turns a platform-neutral request into one enforceable OS command while keeping native sandbox mechanics out of every caller.\n\n```go\ntype ProcessContinue struct {\n\tProcessID int\n\tInput     []byte\n\tInterrupt bool\n\tWait      time.Duration\n}\n```\n\n```go\ntype ProcessManager struct {\n\t// contains filtered or unexported fields\n}\n```\nProcessManager owns retained interactive-process identity, transport, bounded output, continuation, cancellation, completion, and cleanup.\n\n```go\nfunc NewProcessManager(options ProcessManagerOptions) *ProcessManager\n```\n\n```go\nfunc (manager *ProcessManager) Continue(ctx context.Context, input ProcessContinue) (ProcessResult, error)\n```\n\n```go\nfunc (manager *ProcessManager) Len() int\n```\n\n```go\nfunc (manager *ProcessManager) List() []ProcessSnapshot\n```\n\n```go\nfunc (manager *ProcessManager) Remove(id int)\n```\nRemove forgets completed history only. A live process must remain tracked until completion, even if a termination attempt fails.\n\n```go\nfunc (manager *ProcessManager) ResizeInput(id int, cols, rows int) error\n```\nResizeInput updates the PTY window size of a retained interactive process so an attached terminal can fill its viewport. Non-positive dimensions are a no-op; platforms without PTY support report the transport's error.\n\n```go\nfunc (manager *ProcessManager) Snapshot(id int) (ProcessSnapshot, bool)\n```\n\n```go\nfunc (manager *ProcessManager) Start(ctx context.Context, input ProcessStart, wait time.Duration) (ProcessResult, error)\n```\n\n```go\nfunc (manager *ProcessManager) Stop(id int) bool\n```\n\n```go\nfunc (manager *ProcessManager) StopAll() []int\n```\n\n```go\nfunc (manager *ProcessManager) WriteInput(id int, data []byte) error\n```\nWriteInput writes bytes to a retained interactive process's stdin without collecting output. Unlike Continue it never drains the pending output buffer, so a concurrent write\\_stdin poll still sees everything the process emitted; callers that only need the rolling tail use Snapshot instead.\n\n```go\ntype ProcessManagerOptions struct {\n\tCompletedRetention time.Duration\n\t// MaxProcesses bounds retained processes and in-flight launches. Completed\n\t// history is pruned before rejecting a start; live processes are never evicted.\n\t// Zero uses the default limit; a negative value disables the limit.\n\tMaxProcesses int\n}\n```\n\n```go\ntype ProcessResult struct {\n\tProcessID       int\n\tCommandText     string\n\tRelativeCwd     string\n\tTTY             bool\n\tOutput          string\n\tOutputTruncated bool\n\tExited          bool\n\tExitCode        int\n\tInterrupted     bool\n\tRequest         Request\n\tEnforcement     Enforcement\n\tReport          AdapterReport\n\tReportErr       error\n\tChanges         []Change\n\tMetadata        map[string]string\n}\n```\n\n```go\ntype ProcessSnapshot struct {\n\tID              int\n\tCommand         string\n\tCwd             string\n\tRelativeCwd     string\n\tStartedAt       time.Time\n\tLastUsedAt      time.Time\n\tTTY             bool\n\tStatus          string\n\tExitCode        *int\n\tRecentOutput    string\n\tOutputTruncated bool\n}\n```\n\n```go\ntype ProcessStart struct {\n\tPrepared    PreparedCommand\n\tRequest     Request\n\tCommandText string\n\tRelativeCwd string\n\tTTY         bool\n\tMetadata    map[string]string\n\t// AfterWait may append adapter diagnostics collected by a platform monitor.\n\tAfterWait func() []byte\n}\n```\n\n```go\ntype Request struct {\n\tOrigin           Origin          `json:\"origin\"`\n\tMode             Mode            `json:\"mode\"`\n\tCommand          Command         `json:\"command\"`\n\tWorkingDirectory string          `json:\"workingDirectory\"`\n\tWorkspaceRoots   []string        `json:\"workspaceRoots\"`\n\tCapabilities     []Capability    `json:\"capabilities,omitempty\"`\n\tApproval         ApprovalContext `json:\"approval\"`\n}\n```\n\n```go\nfunc (request Request) Validate() error\n```\n\n```go\ntype Runner struct {\n\t// contains filtered or unexported fields\n}\n```\nRunner is the deep execution module used by Zero-owned subprocess launchers. The preparer may be installed after tool registration, but execution fails closed until an adapter is present.\n\n```go\nfunc NewRunner(preparer Preparer) *Runner\n```\n\n```go\nfunc (runner *Runner) ExecuteCaptured(ctx context.Context, input CapturedRequest) CapturedResult\n```\n\n```go\nfunc (runner *Runner) Prepare(ctx context.Context, request Request) (PreparedCommand, error)\n```\nPrepare evaluates and prepares a typed request for callers that require streaming pipes or protocol-specific lifecycle handling, such as stdio MCP. The returned cleanup remains mandatory; ordinary captured commands should use ExecuteCaptured so the Runner owns it automatically.\n\n```go\nfunc (runner *Runner) SetPreparer(preparer Preparer)\n```\n\n```go\ntype State string\n```\n\n```go\nconst (\n\tStateRequested        State = \"requested\"\n\tStateEvaluated        State = \"evaluated\"\n\tStateAwaitingApproval State = \"awaiting_approval\"\n\tStatePrepared         State = \"prepared\"\n\tStateRunning          State = \"running\"\n\tStateRetained         State = \"retained\"\n\tStateCompleted        State = \"completed\"\n\tStateDenied           State = \"denied\"\n\tStateFailed           State = \"failed\"\n\tStateCancelled        State = \"cancelled\"\n)\n```\n\n","path":"github.com/Twigpine/zero/internal/execution","name":"execution","synopsis":"Package execution defines the platform-neutral command execution contract.","isRedistributable":true}
