SPB Git

Repository Public

executor.go 22.2 KB 665 lines go

1package executor23import (4	"context"5	"encoding/json"6	"errors"7	"fmt"8	"io/fs"9	"net"10	"os"11	"os/user"12	"path/filepath"13	"regexp"14	"runtime"15	"strconv"16	"strings"17	"time"1819	"clustr.spboucher.ai/mcc/internal/agent/collect"20	"clustr.spboucher.ai/mcc/internal/agent/policy"21	"clustr.spboucher.ai/mcc/internal/agent/runcmd"22	"clustr.spboucher.ai/mcc/internal/agent/services"23	"clustr.spboucher.ai/mcc/internal/protocol"24)2526// RestartExitCode is the exit status of the agent after an accepted27// agent.restart: the supervisor (launchd KeepAlive / systemd Restart=always)28// starts it again. 75 is EX_TEMPFAIL.29const RestartExitCode = 753031// Outcome is the result of an executed command.32type Outcome struct {33	Status   string // succeeded | failed | timed_out | cancelled34	ExitCode *int35	Error    string36	Result   map[string]any37	// RestartAgent asks the runner to exit (RestartExitCode) once the result is delivered.38	RestartAgent bool39}4041func failed(format string, a ...any) Outcome {42	return Outcome{Status: "failed", Error: fmt.Sprintf(format, a...)}43}4445// Deps are the hooks into the running agent.46type Deps struct {47	// RefreshInventory collects a fresh inventory and schedules it for the next report.48	RefreshInventory func(ctx context.Context) protocol.Inventory49	// Gateway returns the default gateway address (may be empty).50	Gateway func(ctx context.Context) string51	// Cancel requests the cooperative cancellation of a running command.52	Cancel func(commandID string) bool53	// OwnLabel is the launchd label / systemd unit of the agent itself.54	OwnLabel string55}5657// Executor executes validated commands.58type Executor struct {59	deps Deps60}6162func New(d Deps) *Executor { return &Executor{deps: d} }6364// Parameter documents (decoded strictly: unknown fields are refused).65type (66	diagnosticParams struct {67		Profile string `json:"profile"`68	}69	serviceParams struct {70		Manager string `json:"manager"`71		Name    string `json:"name"`72		Port    int    `json:"port,omitempty"`  // service.health_check73		Lines   int    `json:"lines,omitempty"` // service.logs.tail74	}75	cacheParams struct {76		Cache string `json:"cache"`77	}78	jobParams struct {79		Template string         `json:"template"`80		Params   map[string]any `json:"params,omitempty"`81		JobID    string         `json:"job_id,omitempty"`82	}83	cancelParams struct {84		CommandID string `json:"command_id"`85	}86)8788func decodeParams(raw json.RawMessage, dst any) error {89	if len(raw) == 0 || string(raw) == "null" {90		raw = []byte("{}")91	}92	dec := json.NewDecoder(strings.NewReader(string(raw)))93	dec.DisallowUnknownFields()94	if err := dec.Decode(dst); err != nil {95		return fmt.Errorf("invalid parameters: %w", err)96	}97	return nil98}99100var (101	serviceNameRE = regexp.MustCompile(`^[A-Za-z0-9@_][A-Za-z0-9@._:+-]{0,199}$`)102	managers      = map[string]bool{"pm2": true, "launchd": true, "systemd": true, "docker": true}103)104105func checkService(p *serviceParams) error {106	if !managers[p.Manager] {107		return errors.New("unknown service manager")108	}109	if !serviceNameRE.MatchString(p.Name) {110		return errors.New("invalid service name")111	}112	if p.Port < 0 || p.Port > 65535 {113		return errors.New("invalid port")114	}115	return nil116}117118// Plan is a command that passed local policy, ready to run.119type Plan struct {120	Target string // lock key: one command per target at a time121	run    func(ctx context.Context, out *Output) Outcome122}123124// Run executes the plan.125func (p *Plan) Run(ctx context.Context, out *Output) Outcome { return p.run(ctx, out) }126127// Refusal is a policy or validation refusal, reported in the ack.128type Refusal struct{ Reason string }129130func (r *Refusal) Error() string { return r.Reason }131132func refuse(format string, a ...any) error { return &Refusal{Reason: fmt.Sprintf(format, a...)} }133134// Prepare checks a verified command against the local policy and validates135// its parameters. Nothing is executed here. A non-nil error is a *Refusal.136func (e *Executor) Prepare(ctx context.Context, cmd *protocol.Command, pol *policy.Policy) (*Plan, error) {137	if !pol.Allows(cmd.Type) {138		return nil, refuse("policy: command type %s is not allowed on this node", cmd.Type)139	}140	switch cmd.Type {141	case "inventory.refresh":142		var p struct{}143		if err := decodeParams(cmd.Params, &p); err != nil {144			return nil, refuse("%v", err)145		}146		return &Plan{Target: "node:inventory", run: e.inventoryRefresh}, nil147148	case "diagnostic.run":149		var p diagnosticParams150		if err := decodeParams(cmd.Params, &p); err != nil {151			return nil, refuse("%v", err)152		}153		if p.Profile == "" {154			p.Profile = "basic"155		}156		if p.Profile != "basic" && p.Profile != "network" && p.Profile != "disk" {157			return nil, refuse("unknown diagnostic profile")158		}159		return &Plan{Target: "node:diagnostic", run: func(ctx context.Context, out *Output) Outcome { return e.diagnostic(ctx, out, p.Profile) }}, nil160161	case "service.health_check", "service.logs.tail", "service.start", "service.stop", "service.restart":162		var p serviceParams163		if err := decodeParams(cmd.Params, &p); err != nil {164			return nil, refuse("%v", err)165		}166		if err := checkService(&p); err != nil {167			return nil, refuse("%v", err)168		}169		target := "service:" + p.Manager + "/" + p.Name170		switch cmd.Type {171		case "service.health_check":172			return &Plan{Target: target, run: func(ctx context.Context, out *Output) Outcome { return e.healthCheck(ctx, out, p) }}, nil173		case "service.logs.tail":174			if p.Lines == 0 {175				p.Lines = 200176			}177			if p.Lines < 1 || p.Lines > TailMaxLines {178				return nil, refuse("lines must be between 1 and %d", TailMaxLines)179			}180			return &Plan{Target: target + ":logs", run: func(ctx context.Context, out *Output) Outcome { return e.logsTail(ctx, out, p) }}, nil181		}182		if !pol.ServiceAllowed(p.Manager, p.Name) {183			return nil, refuse("policy: service %s/%s is not in the local allowlist", p.Manager, p.Name)184		}185		if e.deps.OwnLabel != "" && p.Name == e.deps.OwnLabel {186			return nil, refuse("the agent's own service is managed with agent.restart only")187		}188		verb := strings.TrimPrefix(cmd.Type, "service.")189		return &Plan{Target: target, run: func(ctx context.Context, out *Output) Outcome { return e.serviceControl(ctx, out, p, verb) }}, nil190191	case "agent.restart":192		var p struct{}193		if err := decodeParams(cmd.Params, &p); err != nil {194			return nil, refuse("%v", err)195		}196		return &Plan{Target: "node:agent", run: func(context.Context, *Output) Outcome {197			return Outcome{Status: "succeeded", Result: map[string]any{"restarting": true, "exit_code": RestartExitCode}, RestartAgent: true}198		}}, nil199200	case "cache.purge":201		var p cacheParams202		if err := decodeParams(cmd.Params, &p); err != nil {203			return nil, refuse("%v", err)204		}205		dir, err := pol.CachePath(p.Cache)206		if err != nil {207			return nil, refuse("policy: %v", err)208		}209		return &Plan{Target: "cache:" + p.Cache, run: func(ctx context.Context, out *Output) Outcome { return purgeCache(ctx, out, p.Cache, dir) }}, nil210211	case "job.run":212		var p jobParams213		if err := decodeParams(cmd.Params, &p); err != nil {214			return nil, refuse("%v", err)215		}216		jc, err := pol.BuildJob(p.Template, p.Params)217		if err != nil {218			return nil, refuse("policy: %v", err)219		}220		return &Plan{Target: "job:" + p.Template, run: func(ctx context.Context, out *Output) Outcome { return runJob(ctx, out, jc) }}, nil221222	case "job.cancel":223		var p cancelParams224		if err := decodeParams(cmd.Params, &p); err != nil {225			return nil, refuse("%v", err)226		}227		if p.CommandID == "" {228			return nil, refuse("command_id is required")229		}230		return &Plan{Target: "cancel:" + p.CommandID, run: func(context.Context, *Output) Outcome {231			if e.deps.Cancel == nil || !e.deps.Cancel(p.CommandID) {232				return failed("no running command %s on this agent", p.CommandID)233			}234			return Outcome{Status: "succeeded", Result: map[string]any{"cancel_requested": p.CommandID}}235		}}, nil236237	case "system.reboot", "system.shutdown":238		var p struct{}239		if err := decodeParams(cmd.Params, &p); err != nil {240			return nil, refuse("%v", err)241		}242		sudo := runcmd.Find("sudo", "/usr/bin/sudo")243		if sudo == "" {244			return nil, refuse("sudo is not installed: the unprivileged agent cannot %s", cmd.Type)245		}246		// The agent never runs as root: it needs passwordless sudo, which the247		// node owner grants or not. No password is ever stored or typed.248		if res, err := runcmd.Run(ctx, 5*time.Second, 4<<10, nil, sudo, "-n", "true"); err != nil || res.ExitCode != 0 {249			return nil, refuse("passwordless sudo is not available on this node: %s refused", cmd.Type)250		}251		flag := "-r"252		if cmd.Type == "system.shutdown" {253			flag = "-h"254		}255		return &Plan{Target: "node:power", run: func(ctx context.Context, out *Output) Outcome {256			shutdown := runcmd.Find("shutdown", "/sbin/shutdown", "/usr/sbin/shutdown")257			if shutdown == "" {258				return failed("shutdown program not found")259			}260			// One minute of delay so that this result reaches the server first.261			res := runStreaming(ctx, out, KillGrace, "", nil, sudo, "-n", shutdown, flag, "+1")262			if res.Status != "succeeded" {263				return Outcome{Status: res.Status, ExitCode: &res.ExitCode, Error: res.Err}264			}265			return Outcome{Status: "succeeded", ExitCode: &res.ExitCode, Result: map[string]any{"scheduled_in_s": 60}}266		}}, nil267	}268	return nil, refuse("command type %s is not implemented by this agent", cmd.Type)269}270271func (e *Executor) inventoryRefresh(ctx context.Context, out *Output) Outcome {272	if e.deps.RefreshInventory == nil {273		return failed("inventory collection is not available")274	}275	inv := e.deps.RefreshInventory(ctx)276	if inv.HardwareUUID == "" {277		return failed("inventory collection returned no hardware identity")278	}279	out.Info("inventory collected; it is sent with the next report")280	return Outcome{Status: "succeeded", Result: map[string]any{281		"hostname": inv.Hostname, "model": inv.Model, "chip": inv.Chip, "os_version": inv.OSVersion,282		"cpu_cores": inv.CPUCores, "interfaces": len(inv.Interfaces),283	}}284}285286// diagnostic runs a fixed list of read-only programs for the profile.287func (e *Executor) diagnostic(ctx context.Context, out *Output, profile string) Outcome {288	type step struct {289		title string290		argv  []string291	}292	darwin := runtime.GOOS == "darwin"293	var steps []step294	switch profile {295	case "basic":296		steps = []step{{"uptime", []string{"/usr/bin/uptime"}}, {"disk space", []string{"/bin/df", "-k"}}}297		if darwin {298			steps = append(steps, step{"os", []string{"/usr/bin/sw_vers"}}, step{"memory", []string{"/usr/bin/vm_stat"}})299		} else {300			steps = append(steps, step{"os", []string{"/usr/bin/uname", "-a"}}, step{"memory", []string{"/usr/bin/free", "-m"}})301		}302	case "network":303		steps = []step{{"routes", []string{"/usr/sbin/netstat", "-rn"}}}304		if darwin {305			steps = append(steps, step{"interfaces", []string{"/sbin/ifconfig"}})306		} else {307			steps = []step{{"routes", []string{"/usr/sbin/ip", "route"}}, {"interfaces", []string{"/usr/sbin/ip", "addr"}}}308		}309	case "disk":310		steps = []step{{"disk space", []string{"/bin/df", "-k"}}}311		if darwin {312			steps = append(steps, step{"disks", []string{"/usr/sbin/diskutil", "list"}})313		} else {314			steps = append(steps, step{"disks", []string{"/usr/bin/lsblk"}})315		}316	}317	summary := []map[string]any{}318	okAll := true319	for _, st := range steps {320		if ctx.Err() != nil {321			break322		}323		bin := st.argv[0]324		if _, err := os.Stat(bin); err != nil {325			if alt := runcmd.Find(filepath.Base(bin)); alt != "" {326				bin = alt327			} else {328				out.Info("== " + st.title + ": " + filepath.Base(bin) + " not installed")329				summary = append(summary, map[string]any{"step": st.title, "skipped": true})330				continue331			}332		}333		out.Info("== " + st.title + " (" + filepath.Base(bin) + ")")334		sctx, cancel := context.WithTimeout(ctx, 15*time.Second)335		res := runStreaming(sctx, out, 2*time.Second, "", nil, append([]string{bin}, st.argv[1:]...)...)336		cancel()337		summary = append(summary, map[string]any{"step": st.title, "exit_code": res.ExitCode, "status": res.Status})338		if res.Status != "succeeded" {339			okAll = false340		}341	}342	if profile == "network" && e.deps.Gateway != nil && ctx.Err() == nil {343		if gw := e.deps.Gateway(ctx); gw != "" {344			out.Info("== ping gateway")345			if r, err := collect.Ping(ctx, gw); err != nil {346				out.Info("ping failed: " + err.Error())347				summary = append(summary, map[string]any{"step": "ping gateway", "status": "failed"})348			} else {349				line := fmt.Sprintf("%d sent, %d received, %.0f%% loss", r.Sent, r.Received, r.LossPct)350				if r.HasRTT {351					line += fmt.Sprintf(", avg %.2f ms", r.AvgMS)352				}353				out.Line("stdout", line)354				summary = append(summary, map[string]any{"step": "ping gateway", "status": "succeeded", "loss_percent": r.LossPct})355			}356		} else {357			out.Info("== ping gateway: no default gateway")358		}359	}360	oc := Outcome{Status: "succeeded", Result: map[string]any{"profile": profile, "steps": summary, "output_truncated": out.Truncated()}}361	if err := context.Cause(ctx); err != nil {362		oc.Status = "timed_out"363		if errors.Is(err, errCancelled) {364			oc.Status = "cancelled"365		}366	} else if !okAll {367		oc.Status, oc.Error = "failed", "one or more diagnostic steps failed"368	}369	return oc370}371372// observe returns the current state of one service from its manager.373func observe(ctx context.Context, manager, name string) (*protocol.Service, error) {374	var items []protocol.Service375	var err error376	switch manager {377	case "pm2":378		items, err = services.PM2List(ctx)379	case "launchd":380		items, err = services.LaunchdList(ctx)381	case "systemd":382		items, err = services.SystemdList(ctx)383	case "docker":384		items, err = services.DockerList(ctx)385	}386	if err != nil {387		return nil, fmt.Errorf("%s is not observable on this node: %w", manager, err)388	}389	for i := range items {390		if items[i].Name == name {391			return &items[i], nil392		}393	}394	return nil, nil395}396397func (e *Executor) healthCheck(ctx context.Context, out *Output, p serviceParams) Outcome {398	svc, err := observe(ctx, p.Manager, p.Name)399	if err != nil {400		return failed("%v", err)401	}402	if svc == nil {403		return failed("service %s/%s does not exist on this node", p.Manager, p.Name)404	}405	res := map[string]any{"manager": p.Manager, "name": p.Name, "state": svc.State, "raw_state": svc.RawState}406	if svc.PID > 0 {407		res["pid"] = svc.PID408	}409	healthy := svc.State == "online"410	if p.Port > 0 {411		d := net.Dialer{Timeout: 2 * time.Second}412		start := time.Now()413		conn, err := d.DialContext(ctx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(p.Port)))414		open := err == nil415		if open {416			conn.Close()417			res["port_connect_ms"] = float64(time.Since(start).Microseconds()) / 1000418		}419		res["port"], res["port_open"] = p.Port, open420		healthy = healthy && open421	}422	res["healthy"] = healthy423	out.Info(fmt.Sprintf("%s/%s: state %s, healthy %t", p.Manager, p.Name, svc.State, healthy))424	return Outcome{Status: "succeeded", Result: res}425}426427var plistKeyRE = regexp.MustCompile(`^(StandardOutPath|StandardErrorPath)$`)428429func userDomain() string { return "gui/" + strconv.Itoa(os.Getuid()) }430431func launchAgentPlist(label string) string {432	home, _ := os.UserHomeDir()433	return filepath.Join(home, "Library", "LaunchAgents", label+".plist")434}435436func plistString(ctx context.Context, plist, key string) string {437	if !plistKeyRE.MatchString(key) {438		return ""439	}440	res, err := runcmd.Run(ctx, 3*time.Second, 8<<10, nil, "/usr/bin/plutil", "-extract", key, "raw", "-o", "-", plist)441	if err != nil || res.ExitCode != 0 {442		return ""443	}444	return strings.TrimSpace(string(res.Stdout))445}446447func (e *Executor) logsTail(ctx context.Context, out *Output, p serviceParams) Outcome {448	out.Limit(TailMaxLines, TailMaxBytes)449	files := map[string]string{} // stream -> path450	switch p.Manager {451	case "pm2":452		procs, err := services.PM2Raw(ctx)453		if err != nil {454			return failed("pm2 is not observable on this node: %v", err)455		}456		found := false457		for _, pr := range procs {458			if pr.Name == p.Name {459				found = true460				files["stdout"], files["stderr"] = pr.Env.OutLog, pr.Env.ErrLog461				break462			}463		}464		if !found {465			return failed("pm2 process %s does not exist on this node", p.Name)466		}467	case "launchd":468		plist := launchAgentPlist(p.Name)469		if _, err := os.Stat(plist); err != nil {470			return failed("no user LaunchAgent plist for %s: its log paths are unknown", p.Name)471		}472		files["stdout"] = plistString(ctx, plist, "StandardOutPath")473		files["stderr"] = plistString(ctx, plist, "StandardErrorPath")474	case "systemd":475		bin := runcmd.Find("journalctl", "/usr/bin/journalctl", "/bin/journalctl")476		if bin == "" {477			return failed("journalctl not found")478		}479		res := runStreaming(ctx, out, 2*time.Second, "", nil, bin, "-u", p.Name, "-n", strconv.Itoa(p.Lines), "--no-pager", "-o", "short-iso")480		return Outcome{Status: res.Status, ExitCode: &res.ExitCode, Error: res.Err, Result: map[string]any{"truncated": out.Truncated()}}481	case "docker":482		bin := services.DockerBinary()483		if bin == "" {484			return failed("docker not found")485		}486		res := runStreaming(ctx, out, 2*time.Second, "", nil, bin, "logs", "--tail", strconv.Itoa(p.Lines), p.Name)487		return Outcome{Status: res.Status, ExitCode: &res.ExitCode, Error: res.Err, Result: map[string]any{"truncated": out.Truncated()}}488	}489	read := 0490	seen := map[string]bool{}491	for _, stream := range []string{"stdout", "stderr"} {492		path := files[stream]493		if path == "" || path == "/dev/null" || seen[path] {494			continue495		}496		seen[path] = true497		if !filepath.IsAbs(path) {498			continue499		}500		if err := tailFile(out, stream, path, p.Lines, TailMaxBytes); err != nil {501			out.Info(stream + " log not readable: " + err.Error())502			continue503		}504		read++505	}506	if read == 0 {507		return failed("service %s/%s declares no readable log file", p.Manager, p.Name)508	}509	return Outcome{Status: "succeeded", Result: map[string]any{"files": read, "truncated": out.Truncated()}}510}511512func (e *Executor) serviceControl(ctx context.Context, out *Output, p serviceParams, verb string) Outcome {513	var argv []string514	switch p.Manager {515	case "pm2":516		bin := services.PM2Binary()517		if bin == "" || !services.PM2DaemonRunning() {518			return failed("pm2 is not running on this node")519		}520		svc, err := observe(ctx, "pm2", p.Name)521		if err != nil {522			return failed("%v", err)523		}524		if svc == nil {525			return failed("pm2 process %s does not exist on this node", p.Name)526		}527		argv = []string{bin, verb, p.Name, "--silent"}528	case "launchd":529		target := userDomain() + "/" + p.Name530		loaded := false531		if res, err := runcmd.Run(ctx, 3*time.Second, 64<<10, nil, "/bin/launchctl", "print", target); err == nil && res.ExitCode == 0 {532			loaded = true533		}534		switch verb {535		case "restart":536			if !loaded {537				return failed("launchd job %s is not loaded in the user domain", p.Name)538			}539			argv = []string{"/bin/launchctl", "kickstart", "-k", target}540		case "start":541			if loaded {542				argv = []string{"/bin/launchctl", "kickstart", target}543			} else {544				plist := launchAgentPlist(p.Name)545				if _, err := os.Stat(plist); err != nil {546					return failed("launchd job %s is not loaded and has no user LaunchAgent plist", p.Name)547				}548				argv = []string{"/bin/launchctl", "bootstrap", userDomain(), plist}549			}550		case "stop":551			if !loaded {552				return Outcome{Status: "succeeded", Result: map[string]any{"already_stopped": true}}553			}554			argv = []string{"/bin/launchctl", "bootout", target}555		}556	case "systemd":557		bin := runcmd.Find("systemctl", "/usr/bin/systemctl", "/bin/systemctl")558		if bin == "" {559			return failed("systemctl not found")560		}561		argv = []string{bin, "--no-ask-password", verb, p.Name}562	case "docker":563		bin := services.DockerBinary()564		if bin == "" {565			return failed("docker not found")566		}567		argv = []string{bin, verb, p.Name}568	}569	res := runStreaming(ctx, out, KillGrace, "", nil, argv...)570	oc := Outcome{Status: res.Status, ExitCode: &res.ExitCode, Error: res.Err}571	if res.Status == "succeeded" {572		// Report what the manager says afterwards, not what we hope.573		octx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 6*time.Second)574		defer cancel()575		time.Sleep(700 * time.Millisecond)576		if svc, err := observe(octx, p.Manager, p.Name); err == nil && svc != nil {577			oc.Result = map[string]any{"state": svc.State, "raw_state": svc.RawState}578		} else {579			oc.Result = map[string]any{"state": "unknown"}580		}581	}582	return oc583}584585// purgeCache deletes the contents of dir (never dir itself). It works586// through an os.Root, so no path can escape the directory: symlinks inside587// are removed as links and never followed outside.588func purgeCache(ctx context.Context, out *Output, name, dir string) Outcome {589	root, err := os.OpenRoot(dir)590	if err != nil {591		return failed("cannot open cache %s: %v", name, err)592	}593	defer root.Close()594	var bytes int64595	fs.WalkDir(root.FS(), ".", func(_ string, d fs.DirEntry, err error) error {596		if err != nil || ctx.Err() != nil {597			return nil598		}599		if d.Type().IsRegular() {600			if info, err := d.Info(); err == nil {601				bytes += info.Size()602			}603		}604		return nil605	})606	f, err := root.Open(".")607	if err != nil {608		return failed("cannot list cache %s: %v", name, err)609	}610	entries, err := f.ReadDir(-1)611	f.Close()612	if err != nil {613		return failed("cannot list cache %s: %v", name, err)614	}615	removed, errs := 0, 0616	for _, en := range entries {617		if cause := context.Cause(ctx); cause != nil {618			st := "timed_out"619			if errors.Is(cause, errCancelled) {620				st = "cancelled"621			}622			return Outcome{Status: st, Error: "interrupted", Result: map[string]any{"cache": name, "entries_removed": removed}}623		}624		if err := root.RemoveAll(en.Name()); err != nil {625			errs++626			continue627		}628		removed++629	}630	out.Info(fmt.Sprintf("cache %s: %d entries removed, about %d bytes", name, removed, bytes))631	oc := Outcome{Status: "succeeded", Result: map[string]any{"cache": name, "entries_removed": removed, "bytes_before": bytes, "errors": errs}}632	if errs > 0 {633		oc.Status, oc.Error = "failed", fmt.Sprintf("%d entries could not be removed", errs)634	}635	return oc636}637638func runJob(ctx context.Context, out *Output, jc *policy.JobCommand) Outcome {639	if jc.TimeoutS > 0 {640		var cancel context.CancelFunc641		ctx, cancel = context.WithTimeout(ctx, time.Duration(jc.TimeoutS)*time.Second)642		defer cancel()643	}644	var env []string645	for k, v := range jc.Env {646		env = append(env, k+"="+v)647	}648	start := time.Now()649	res := runStreaming(ctx, out, KillGrace, jc.Cwd, env, jc.Argv...)650	return Outcome{Status: res.Status, ExitCode: &res.ExitCode, Error: res.Err, Result: map[string]any{651		"program": filepath.Base(jc.Argv[0]), "elapsed_s": time.Since(start).Seconds(), "output_truncated": out.Truncated(),652	}}653}654655// CancelCause is passed to context.CancelCauseFunc for a cooperative cancel.656func CancelCause() error { return errCancelled }657658// CurrentUser returns the name of the user the agent runs as.659func CurrentUser() string {660	if u, err := user.Current(); err == nil {661		return u.Username662	}663	return strconv.Itoa(os.Getuid())664}665
Files main
Menu

Theme