Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
16.0 KB
Raw Blame
package execenv

import (
	"fmt"
	"log/slog"
	"os"
	"regexp"
	"sort"
	"strings"

	"github.com/pelletier/go-toml/v2"
	"github.com/pelletier/go-toml/v2/unstable"
)

// Background
//
// Recent Codex `app-server` releases enable `features.multi_agent` by
// default, exposing spawn_agent / send_input / wait / resume_agent /
// close_agent tools to the model so a Codex thread can fan out into nested
// subagents. The Multica daemon currently models only the parent Codex
// thread per task: when the parent emits `turn/completed`, the task is
// marked terminal even if spawned children are still running or have not
// flushed their output. The result is a class of premature-completion
// failures where useful child-agent work is dropped.
//
// Until either Codex exposes a "parent done but children still open"
// lifecycle state with drain/cancel primitives, or the Multica runtime
// models child threads as first-class task entities, the daemon disables
// Codex native multi-agent by default for daemon-managed task sessions.
// The override only touches the per-task `CODEX_HOME/config.toml`; the
// user's global `~/.codex/config.toml` is never modified.
//
// Users who explicitly want Codex native subagents inside a Multica task
// (and accept the lifecycle risk) can keep the feature enabled by setting
// `MULTICA_CODEX_MULTI_AGENT=1` in the daemon environment.
//
// Newer Codex releases select the multi-agent version per model:
// an explicit config override wins, otherwise the model catalog's
// `multi_agent_version` is used. `features.multi_agent = false` is not an
// override, so catalog-v2 models (gpt-5.6-sol, gpt-6.x) still receive
// spawn_agent / send_message / followup_task. `agents.enabled = false`
// forces the Disabled version even on resumed threads, unless
// `features.multi_agent_v2 = true` overrides it. Disable both for Codex
// 0.145.0 and later. Older releases can interpret agents.enabled as a custom
// role and reject its boolean value; unknown versions keep the legacy
// feature-only block.
//
// Layout note
//
// TOML rejects redefining a table that has already been created — including
// implicitly via a dotted key. So each managed block must adapt to the
// user's existing config:
//
//   - If the user's config contains a top-level `[features]` table, the
//     managed `multi_agent = false` is injected INSIDE that table (with
//     marker comments). Writing `features.multi_agent = false` at the
//     TOML root would implicitly redefine the same `features` table and
//     the strict TOML parser used by Codex (`toml-rs`) would fail with
//     `table 'features' already exists`.
//   - Otherwise, the managed block lives at the top of the file with the
//     dotted-key form `features.multi_agent = false`.
//   - `agents.enabled = false` follows the same rule against a top-level
//     `[agents]` table.
//   - V2 is disabled via its `enabled` field so existing structured options
//     remain valid. An explicit `[features.multi_agent_v2]` table receives
//     its own managed block; otherwise a dotted enabled key is used.

// MulticaCodexMultiAgentEnv is the env var users can set to keep Codex
// native multi-agent enabled inside daemon-managed tasks. Anything truthy
// (1, true, yes, on; case-insensitive) keeps the feature on; everything
// else (including unset) disables it.
const MulticaCodexMultiAgentEnv = "MULTICA_CODEX_MULTI_AGENT"

// multicaMultiAgentBeginMarker / multicaMultiAgentEndMarker delimit the
// multi-agent-specific managed block. Kept separate from the sandbox
// block so each can evolve and migrate independently.
const (
	multicaMultiAgentBeginMarker   = "# BEGIN multica-managed multi-agent (do not edit; regenerated by daemon)"
	multicaMultiAgentEndMarker     = "# END multica-managed multi-agent"
	multicaAgentsBeginMarker       = "# BEGIN multica-managed agents (do not edit; regenerated by daemon)"
	multicaAgentsEndMarker         = "# END multica-managed agents"
	multicaMultiAgentV2BeginMarker = "# BEGIN multica-managed multi-agent-v2 (do not edit; regenerated by daemon)"
	multicaMultiAgentV2EndMarker   = "# END multica-managed multi-agent-v2"
)

// `\n*` rather than `\n?` so reruns don't accumulate blank lines when this
// block coexists with the sandbox managed block in the same file. The same
// regex matches the block whether it sits at the file root (dotted-key
// form) or inside a `[features]` table — only the body keys differ.
var multiAgentBlockRe = regexp.MustCompile(
	`(?ms)^` + regexp.QuoteMeta(multicaMultiAgentBeginMarker) +
		`.*?^` + regexp.QuoteMeta(multicaMultiAgentEndMarker) + `\n*`)

var agentsBlockRe = regexp.MustCompile(
	`(?ms)^` + regexp.QuoteMeta(multicaAgentsBeginMarker) +
		`.*?^` + regexp.QuoteMeta(multicaAgentsEndMarker) + `\n*`)

var multiAgentV2BlockRe = regexp.MustCompile(
	`(?ms)^` + regexp.QuoteMeta(multicaMultiAgentV2BeginMarker) +
		`.*?^` + regexp.QuoteMeta(multicaMultiAgentV2EndMarker) + `\n*`)

var (
	// matches a top-level `[features]` table header, allowing TOML's optional
	// whitespace inside brackets and inline comments after the header.
	rootFeaturesTableHeaderRe = regexp.MustCompile(`^\s*\[\s*features\s*\]\s*(?:#.*)?$`)
	// matches either multi-agent feature (with optional whitespace) inside a
	// `[features]` table.
	featuresTableMultiAgentRe = regexp.MustCompile(`^\s*multi_agent(?:_v2(?:\s*\.\s*enabled)?)?\s*=`)
	// matches either multi-agent feature at the TOML root (top-level
	// dotted-key form, including TOML's optional whitespace around dots).
	rootDottedMultiAgentRe        = regexp.MustCompile(`^\s*features\s*\.\s*multi_agent(?:_v2(?:\s*\.\s*enabled)?)?\s*=`)
	rootMultiAgentV2TableHeaderRe = regexp.MustCompile(`^\s*\[\s*features\s*\.\s*multi_agent_v2\s*\]\s*(?:#.*)?$`)
	// matches a top-level `[agents]` table header. `[agents.<role>]`
	// sub-tables do not match.
	rootAgentsTableHeaderRe = regexp.MustCompile(`^\s*\[\s*agents\s*\]\s*(?:#.*)?$`)
	// matches `enabled = ...` inside an agents or multi-agent V2 table.
	tableEnabledRe = regexp.MustCompile(`^\s*enabled\s*=`)
	// matches `agents.enabled = ...` at the TOML root.
	rootDottedAgentsEnabledRe = regexp.MustCompile(`^\s*agents\s*\.\s*enabled\s*=`)
)

// codexMultiAgentEnabled reports whether the user opted into keeping Codex
// native multi-agent on for daemon-managed tasks.
func codexMultiAgentEnabled() bool {
	raw := strings.TrimSpace(os.Getenv(MulticaCodexMultiAgentEnv))
	switch strings.ToLower(raw) {
	case "1", "true", "yes", "on":
		return true
	}
	return false
}

func codexAgentsEnabledSupported(detectedVersion string) bool {
	version, err := parseCodexSemver(detectedVersion)
	return err == nil && !version.lessThan(codexSemver{Minor: 145})
}

// renderMulticaMultiAgentBlock returns the daemon-managed multi-agent
// block. The body uses `multi_agent = false` when injected inside a
// `[features]` table, and `features.multi_agent = false` otherwise.
func renderMulticaMultiAgentBlock(inFeaturesTable, disableV2 bool) string {
	var b strings.Builder
	b.WriteString(multicaMultiAgentBeginMarker)
	b.WriteString("\n")
	if inFeaturesTable {
		b.WriteString("multi_agent = false\n")
	} else {
		b.WriteString("features.multi_agent = false\n")
	}
	if disableV2 {
		if inFeaturesTable {
			b.WriteString("multi_agent_v2.enabled = false\n")
		} else {
			b.WriteString("features.multi_agent_v2.enabled = false\n")
		}
	}
	b.WriteString(multicaMultiAgentEndMarker)
	b.WriteString("\n")
	return b.String()
}

func renderMulticaMultiAgentV2Block() string {
	return multicaMultiAgentV2BeginMarker + "\nenabled = false\n" + multicaMultiAgentV2EndMarker + "\n"
}

// renderMulticaAgentsBlock returns the daemon-managed agents block. The
// body uses `enabled = false` when injected inside an `[agents]` table,
// and `agents.enabled = false` otherwise.
func renderMulticaAgentsBlock(inAgentsTable bool) string {
	var b strings.Builder
	b.WriteString(multicaAgentsBeginMarker)
	b.WriteString("\n")
	if inAgentsTable {
		b.WriteString("enabled = false\n")
	} else {
		b.WriteString("agents.enabled = false\n")
	}
	b.WriteString(multicaAgentsEndMarker)
	b.WriteString("\n")
	return b.String()
}

// Inline tables cannot be extended by the managed enabled key. Expand only
// their V2 options into dotted assignments, preserving unrelated expressions.
func expandInlineMultiAgentV2(content string) (string, error) {
	var parser unstable.Parser
	parser.Reset([]byte(content))
	var currentTable []string
	var out strings.Builder
	previous := 0
	for parser.NextExpression() {
		expr := parser.Expression()
		keys := tomlNodeKeys(expr)
		if expr.Kind == unstable.Table || expr.Kind == unstable.ArrayTable {
			currentTable = keys
			continue
		}
		if expr.Kind != unstable.KeyValue || expr.Value().Kind != unstable.InlineTable {
			continue
		}
		fullKey := append(append([]string(nil), currentTable...), keys...)
		if len(fullKey) != 2 || fullKey[0] != "features" || fullKey[1] != "multi_agent_v2" {
			continue
		}
		start := int(expr.Raw.Offset)
		end := start + int(expr.Raw.Length)
		var settings map[string]any
		if err := toml.Unmarshal([]byte(content[start:end]), &settings); err != nil {
			return "", fmt.Errorf("parse inline multi-agent V2 settings: %w", err)
		}
		for _, key := range keys {
			settings = settings[key].(map[string]any)
		}
		delete(settings, "enabled")
		optionKeys := make([]string, 0, len(settings))
		for key := range settings {
			optionKeys = append(optionKeys, key)
		}
		sort.Strings(optionKeys)
		out.WriteString(content[previous:start])
		for _, key := range optionKeys {
			out.WriteString(strings.Join(keys, ".") + ".")
			if err := toml.NewEncoder(&out).SetTablesInline(true).Encode(map[string]any{key: settings[key]}); err != nil {
				return "", fmt.Errorf("encode multi-agent V2 option %q: %w", key, err)
			}
		}
		previous = end
	}
	if err := parser.Error(); err != nil {
		return "", fmt.Errorf("parse multi-agent V2 expressions: %w", err)
	}
	out.WriteString(content[previous:])
	return out.String(), nil
}

// stripUserMultiAgentDirectives removes user-written directives that would
// conflict with the managed blocks:
//
//   - `features.multi_agent`, `features.multi_agent_v2`,
//     `features.multi_agent_v2.enabled` and `agents.enabled` at the TOML root.
//   - `multi_agent`, `multi_agent_v2` and `multi_agent_v2.enabled` inside a
//     top-level `[features]` table.
//   - `enabled` inside `[agents]` or `[features.multi_agent_v2]`.
//
// Other tables (`[features.experimental]`, `[agents.researcher]`,
// `[profiles.foo]`, ...) are preserved untouched: they live under their own
// scope and don't redefine the managed keys.
func stripUserMultiAgentDirectives(content string) string {
	lines := strings.Split(content, "\n")
	out := make([]string, 0, len(lines))
	currentTable := "" // empty = TOML root
	for _, line := range lines {
		trimmed := strings.TrimSpace(line)
		if rootFeaturesTableHeaderRe.MatchString(line) {
			currentTable = "[features]"
			out = append(out, line)
			continue
		}
		if rootAgentsTableHeaderRe.MatchString(line) {
			currentTable = "[agents]"
			out = append(out, line)
			continue
		}
		if rootMultiAgentV2TableHeaderRe.MatchString(line) {
			currentTable = "[features.multi_agent_v2]"
			out = append(out, line)
			continue
		}
		if strings.HasPrefix(trimmed, "[") {
			currentTable = trimmed
			out = append(out, line)
			continue
		}
		switch currentTable {
		case "":
			if rootDottedMultiAgentRe.MatchString(trimmed) ||
				rootDottedAgentsEnabledRe.MatchString(trimmed) {
				continue
			}
		case "[features]":
			if featuresTableMultiAgentRe.MatchString(trimmed) {
				continue
			}
		case "[agents]", "[features.multi_agent_v2]":
			if tableEnabledRe.MatchString(trimmed) {
				continue
			}
		}
		out = append(out, line)
	}
	return strings.Join(out, "\n")
}

// hasRootFeaturesTable reports whether the file contains a top-level
// `[features]` table header. Sub-tables like `[features.experimental]` do
// NOT count: they implicitly create `features` but don't conflict with a
// root-level `features.multi_agent` dotted key.
func hasRootFeaturesTable(content string) bool {
	for _, line := range strings.Split(content, "\n") {
		if rootFeaturesTableHeaderRe.MatchString(line) {
			return true
		}
	}
	return false
}

// injectManagedBlockIntoFeaturesTable inserts the in-table managed block
// immediately after the first `[features]` header line. Caller must have
// already stripped any prior managed block and any user-set `multi_agent`
// directive from inside the table.
func injectManagedBlockIntoFeaturesTable(content string, disableV2 bool) string {
	return injectAfterHeader(content, rootFeaturesTableHeaderRe, renderMulticaMultiAgentBlock(true, disableV2))
}

// hasRootAgentsTable reports whether the file contains a top-level
// `[agents]` table header. Role sub-tables like `[agents.researcher]` do
// NOT count: they don't conflict with a root-level `agents.enabled` key.
func hasRootAgentsTable(content string) bool {
	for _, line := range strings.Split(content, "\n") {
		if rootAgentsTableHeaderRe.MatchString(line) {
			return true
		}
	}
	return false
}

func hasRootMultiAgentV2Table(content string) bool {
	for _, line := range strings.Split(content, "\n") {
		if rootMultiAgentV2TableHeaderRe.MatchString(line) {
			return true
		}
	}
	return false
}

// ensureCodexMultiAgentConfig writes the daemon-managed multi-agent and
// agents blocks into the per-task config.toml so Codex native subagents
// stay disabled.
// Idempotent: running it twice produces the same file.
//
// When MULTICA_CODEX_MULTI_AGENT is set to a truthy value, the function is
// a no-op — the user has explicitly opted into Codex native subagents and
// accepts the lifecycle risk. Toggling the env var across prepare runs is
// not supported: the per-task config is short-lived (recreated per task),
// so users should set the var once at daemon start.
func ensureCodexMultiAgentConfig(configPath, detectedVersion string, logger *slog.Logger) error {
	if codexMultiAgentEnabled() {
		if logger != nil {
			logger.Info("codex multi-agent: leaving Codex native multi-agent untouched per MULTICA_CODEX_MULTI_AGENT",
				"config_path", configPath,
			)
		}
		return nil
	}

	data, err := os.ReadFile(configPath)
	if err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("read config.toml: %w", err)
	}
	existing := string(data)

	// Always strip any previously written managed blocks (root or in-table
	// form) so reruns and layout transitions stay clean.
	existing = multiAgentBlockRe.ReplaceAllString(existing, "")
	existing = agentsBlockRe.ReplaceAllString(existing, "")
	existing = multiAgentV2BlockRe.ReplaceAllString(existing, "")
	existing, err = expandInlineMultiAgentV2(existing)
	if err != nil {
		return err
	}
	// Strip user-set directives in every encoding; the managed blocks re-add
	// the canonical forms below.
	existing = stripUserMultiAgentDirectives(existing)

	supportsAgentsEnabled := codexAgentsEnabledSupported(detectedVersion)
	hasFeatures := hasRootFeaturesTable(existing)
	hasAgents := hasRootAgentsTable(existing)
	hasV2Table := hasRootMultiAgentV2Table(existing)
	disableDottedV2 := supportsAgentsEnabled && !hasV2Table

	// In-table injections happen first so the root-prepended blocks land
	// at the very top of the file (above any user tables).
	if hasFeatures {
		existing = injectManagedBlockIntoFeaturesTable(existing, disableDottedV2)
	}
	if supportsAgentsEnabled && hasAgents {
		existing = injectAfterHeader(existing, rootAgentsTableHeaderRe, renderMulticaAgentsBlock(true))
	}
	if supportsAgentsEnabled && hasV2Table {
		existing = injectAfterHeader(existing, rootMultiAgentV2TableHeaderRe, renderMulticaMultiAgentV2Block())
	}

	var prepend strings.Builder
	if !hasFeatures {
		prepend.WriteString(renderMulticaMultiAgentBlock(false, disableDottedV2))
	}
	if supportsAgentsEnabled && !hasAgents {
		prepend.WriteString(renderMulticaAgentsBlock(false))
	}
	prependStr := prepend.String()

	updated := existing
	if prependStr != "" {
		updated = strings.TrimLeft(updated, "\n")
		if updated == "" {
			updated = prependStr
		} else {
			updated = prependStr + "\n" + updated
		}
	}

	if updated == string(data) {
		return nil
	}

	if err := os.WriteFile(configPath, []byte(updated), 0o644); err != nil {
		return fmt.Errorf("write config.toml: %w", err)
	}
	return nil
}