package toolguard import ( "context" "fmt" "io" "os" "os/exec" "os/signal" "runtime" "strconv" "strings" "sync" "syscall" "time" "github.com/Autumn-27/artex/internal/sandbox" actool "github.com/Autumn-27/norma/tool" ) const ( backgroundArg = "--artex-internal-background-tool" backgroundExe = "_ARTEX_BG_EXE" backgroundCommand = "_ARTEX_BG_COMMAND" backgroundTimeout = "_ARTEX_BG_TIMEOUT" backgroundCgroup = "_ARTEX_BG_CGROUP" backgroundSandboxScope = "_ARTEX_BG_SANDBOX_SCOPE" backgroundSandboxOwner = "_ARTEX_BG_SANDBOX_OWNER" backgroundSandboxWorkDir = "_ARTEX_BG_SANDBOX_WORKDIR" outputLimitNote = "\n\n[output truncated at capture limit]" ) // The SDK's task manager only accepts a shell command, not an exec hook. Its // shell execs this binary in a lightweight helper mode, keeping the manager's // task ID, streaming output, notifications, and cancellation semantics. func runGuardedBashBackground(tc *actool.ToolContext, cfg Config, command string, timeout time.Duration) (actool.Result, error) { exe, err := os.Executable() if err != nil { return actool.Errorf("Error: failed to locate background helper: " + err.Error()), nil } var dir string scope := newCgroupScope(cfg.MemoryLimitBytes(), cfg.PidsLimit) if scope != nil { dir = scope.dir scope.CloseFD() } env := append([]string{}, tc.Env...) // Pass the command as data, not shell syntax in the trampoline. env = append(env, backgroundExe+"="+exe, backgroundCommand+"="+command, backgroundTimeout+"="+timeout.String(), backgroundCgroup+"="+dir, EnvToolMemoryLimitMB+"="+strconv.Itoa(cfg.MemoryLimitMB), EnvToolPidsLimit+"="+strconv.Itoa(cfg.PidsLimit)) trampoline := `exec "$` + backgroundExe + `" ` + backgroundArg if runtime.GOOS == "windows" { trampoline = `& $env:` + backgroundExe + ` '` + backgroundArg + `'; exit $LASTEXITCODE` } desc := strings.TrimSpace(strings.ReplaceAll(command, "\n", " ")) if len(desc) > 60 { desc = desc[:57] + "..." } mgr := tc.Tasks t, err := mgr.Spawn(actool.SpawnSpec{ Command: trampoline, Kind: actool.KindBash, WorkingDir: tc.WorkingDir, Description: desc, Env: env, }) if err != nil { if scope != nil { scope.Cleanup() } return actool.Errorf("Error: failed to start background command: " + err.Error()), nil } mgr.Background(t.ID) if scope != nil { go func(id string) { // The helper might be SIGKILLed by TaskStop; its parent therefore // owns the scope and cleans it up after the task exits. _, done := mgr.Wait(context.Background(), id, timeout) if !done { _, done = mgr.Wait(context.Background(), id, 5*time.Second) } if !done { mgr.Kill(id) } scope.Cleanup() }(t.ID) } return actool.Text(fmt.Sprintf( "Running in background as %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to read its output; you are notified when it completes.", t.ID, t.OutputPath, t.ID)), nil } // BackgroundHelper handles the internal helper invocation before normal app // startup. The helper uses the task manager's cwd, environment, and output file. func BackgroundHelper(args []string) (exitCode int, handled bool) { if len(args) != 1 || args[0] != backgroundArg { return 0, false } command, dir := os.Getenv(backgroundCommand), os.Getenv(backgroundCgroup) timeout, err := time.ParseDuration(os.Getenv(backgroundTimeout)) sbScope := os.Getenv(backgroundSandboxScope) sbOwner := os.Getenv(backgroundSandboxOwner) sbWorkDir := os.Getenv(backgroundSandboxWorkDir) for _, name := range []string{ backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup, backgroundSandboxScope, backgroundSandboxOwner, backgroundSandboxWorkDir, } { _ = os.Unsetenv(name) } if command == "" || err != nil || timeout <= 0 { fmt.Fprintln(os.Stderr, "invalid background tool invocation") return 1, true } cfg := FromEnv() cfg.MaxOutputBytes -= 4096 // leave room for the error note below norma's task-file cap if sbScope != "" && sbOwner != "" { return runBackgroundHelperSandbox(cfg, sandbox.Target{Scope: sandbox.Scope(sbScope), OwnerID: sbOwner}, sbWorkDir, command, timeout), true } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() shell, flags := platformShellCmd() cmd := exec.Command(shell, append(flags, command)...) group := os.Getpid() if runtime.GOOS == "windows" { group = 0 // Windows terminates the process tree by PID, without a Unix group. } res := run(ctx, cfg, cmd, openCgroupScope(dir), group, os.Stdout) if res.OutputTruncated { fmt.Fprintln(os.Stderr, outputLimitNote) } switch { case res.MemoryKilled: fmt.Fprintln(os.Stderr, FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup)) return 1, true case res.TimedOut: fmt.Fprintln(os.Stderr, timeoutNote(timeout)) return 1, true case res.ExitCode >= 0: return res.ExitCode, true default: fmt.Fprintf(os.Stderr, "[failed to run: %v]\n", res.Err) return 1, true } } func runGuardedBashBackgroundSandbox(tc *actool.ToolContext, mgr *sandbox.Manager, target sandbox.Target, containerWorkDir string, cfg Config, command string, timeout time.Duration) (actool.Result, error) { exe, err := os.Executable() if err != nil { return actool.Errorf("Error: failed to locate background helper: " + err.Error()), nil } sbCfg := mgr.Config() env := append([]string{}, tc.Env...) env = append(env, backgroundExe+"="+exe, backgroundCommand+"="+command, backgroundTimeout+"="+timeout.String(), backgroundSandboxScope+"="+string(target.Scope), backgroundSandboxOwner+"="+target.OwnerID, backgroundSandboxWorkDir+"="+containerWorkDir, "ARTEX_SANDBOX_MODE=docker", "ARTEX_DOCKER_HOST="+sbCfg.DockerHost, "ARTEX_SANDBOX_IMAGE="+sbCfg.Image, "ARTEX_SANDBOX_NETWORK="+sbCfg.Network, "ARTEX_SANDBOX_RUNTIME="+sbCfg.Runtime, "ARTEX_SANDBOX_USER="+sbCfg.User, "ARTEX_SANDBOX_INSTANCE="+sbCfg.InstanceID, "ARTEX_HOST_DATA_DIR="+sbCfg.HostDataDir, "_ARTEX_BG_DATA_DIR="+sbCfg.DataDir, EnvToolMemoryLimitMB+"="+strconv.Itoa(cfg.MemoryLimitMB), EnvToolPidsLimit+"="+strconv.Itoa(cfg.PidsLimit), ) trampoline := `exec "$` + backgroundExe + `" ` + backgroundArg if runtime.GOOS == "windows" { trampoline = `& $env:` + backgroundExe + ` '` + backgroundArg + `'; exit $LASTEXITCODE` } desc := strings.TrimSpace(strings.ReplaceAll(command, "\n", " ")) if len(desc) > 60 { desc = desc[:57] + "..." } mgrTasks := tc.Tasks t, err := mgrTasks.Spawn(actool.SpawnSpec{ Command: trampoline, Kind: actool.KindBash, WorkingDir: tc.WorkingDir, Description: desc, Env: env, }) if err != nil { return actool.Errorf("Error: failed to start background command: " + err.Error()), nil } mgrTasks.Background(t.ID) return actool.Text(fmt.Sprintf( "Running in background as %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to read its output; you are notified when it completes.", t.ID, t.OutputPath, t.ID)), nil } func runBackgroundHelperSandbox(cfg Config, target sandbox.Target, workDir, command string, timeout time.Duration) int { dataDir := os.Getenv("_ARTEX_BG_DATA_DIR") _ = os.Unsetenv("_ARTEX_BG_DATA_DIR") sbCfg := sandbox.ConfigFromEnv(dataDir, "") mgr, err := sandbox.New(sbCfg) if err != nil { fmt.Fprintf(os.Stderr, "[sandbox init failed: %v]\n", err) return 1 } sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() ctx, cancel := context.WithTimeout(sigCtx, timeout) defer cancel() // Pass proxy env vars only (avoid leaking host env vars into container). var passEnv []string for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "NODE_USE_ENV_PROXY", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO", "NODE_EXTRA_CA_CERTS"} { if v := os.Getenv(k); v != "" { passEnv = append(passEnv, k+"="+v) } } stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{ Cmd: []string{"bash", "-c", command}, WorkDir: workDir, Env: passEnv, }) if err != nil { fmt.Fprintf(os.Stderr, "[sandbox exec failed: %v]\n", err) return 1 } var outMu sync.Mutex written := 0 truncated := false writeCapped := func(r io.Reader) { buf := make([]byte, 16*1024) for { n, rerr := r.Read(buf) if n > 0 { outMu.Lock() if cfg.MaxOutputBytes > 0 && written >= cfg.MaxOutputBytes { truncated = true } else { chunk := buf[:n] if cfg.MaxOutputBytes > 0 && written+len(chunk) > cfg.MaxOutputBytes { chunk = chunk[:cfg.MaxOutputBytes-written] truncated = true } _, _ = os.Stdout.Write(chunk) written += len(chunk) } outMu.Unlock() } if rerr != nil { return } } } var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done(); writeCapped(stream.Stdout) }() go func() { defer wg.Done(); writeCapped(stream.Stderr) }() doneCh := make(chan int, 1) go func() { code, _ := stream.Wait() wg.Wait() doneCh <- code }() select { case code := <-doneCh: if truncated { fmt.Fprintln(os.Stderr, outputLimitNote) } if code < 0 { return 1 } return code case <-ctx.Done(): _ = stream.Close() select { case <-doneCh: case <-time.After(3 * time.Second): } if ctx.Err() == context.DeadlineExceeded { fmt.Fprintln(os.Stderr, timeoutNote(timeout)) } return 1 } }