Skip to content
Open
193 changes: 142 additions & 51 deletions internal/cli/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,40 +311,35 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
// cache file on the machine. The refresh itself is fired in exec/TUI startup.
modelregistry.EnableModelsDevOverlay()

addDirs, args, err := splitLeadingAddDirFlags(args)
// --add-dir, --theme and --allow-escalation may be written in any order;
// see splitLeadingRootFlags for why they are split together.
root, args, err := splitLeadingRootFlags(args)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
if err != nil {
return writeAppError(stderr, err.Error(), 1)
}
// --theme <name> selects the TUI palette non-interactively (auto or any registered
// theme; populates tui.Options.Theme, which resolveThemeMode prefers over
// ZERO_THEME). Re-split --add-dir afterward so it may appear on either side of --theme.
theme, args, err := splitLeadingThemeFlag(args)
if err != nil {
return writeAppError(stderr, err.Error(), 1)
}
moreDirs, args, err := splitLeadingAddDirFlags(args)
if err != nil {
return writeAppError(stderr, err.Error(), 1)
}
addDirs = append(addDirs, moreDirs...)
addDirs, theme, allowEscalation := root.addDirs, root.theme, root.allowEscalation

if len(args) == 0 {
return runInteractiveTUI(stderr, deps, agent.PermissionModeAsk, addDirs, theme)
return runInteractiveTUI(stderr, deps, agent.PermissionModeAsk, addDirs, theme, allowEscalation)
}

// --add-dir grants an extra write root, and only the interactive TUI and
// exec dispatch paths consume one. Fail loud everywhere else rather than
// silently discarding an explicit grant — including help/version, which
// run no agent and could only ignore it. The allowlist names exactly the
// cases below that forward addDirs; a future subcommand is rejected by
// default until it opts in here.
if len(addDirs) > 0 {
switch args[0] {
case "--skip-permissions-unsafe", "-p", "--prompt", "exec":
// Forwarded by the matching case below.
default:
return writeAppError(stderr, "--add-dir is only supported for the interactive TUI and exec", 1)
}
// --add-dir grants an extra write root and --allow-escalation opts a run
// into mid-run model escalation; only the interactive TUI and exec consume
// either. Both are forwarded to exec below and rejected loudly everywhere
// else rather than silently discarded, including help/version, which run
// no agent and could only ignore them. The allowlist names exactly the
// cases below that forward; a future subcommand is rejected by default
// until it opts in here.
forwardsRootFlags := false
switch args[0] {
case "--skip-permissions-unsafe", "-p", "--prompt", "exec":
forwardsRootFlags = true
}
if len(addDirs) > 0 && !forwardsRootFlags {
return writeAppError(stderr, "--add-dir is only supported for the interactive TUI and exec", 1)
}
if allowEscalation && !forwardsRootFlags {
return writeAppError(stderr, "--allow-escalation is only supported for the interactive TUI and exec", 1)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

switch args[0] {
Expand All @@ -354,26 +349,24 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
// reach unsafe mode in the shell — and the "!" shell escape (which is
// gated behind unsafe) was therefore unreachable.
//
// --add-dir may legally appear on either side of the flag, so re-split
// the remaining args and merge with the dirs already collected. Any
// trailing non-flag args were ignored on this path before --add-dir
// existed and still are — but an --add-dir hidden BEHIND one would be
// silently dropped with them, so reject that misplacement loudly.
moreDirs, rest, err := splitLeadingAddDirFlags(args[1:])
if err != nil {
return writeAppError(stderr, err.Error(), 1)
}
// --theme may appear here too; extract it before the stray-arg checks so it is
// not rejected as an unexpected positional, then re-split --add-dir after it.
skipTheme, rest, err := splitLeadingThemeFlag(rest)
// The root flags may legally appear on either side of this flag, so
// split them again from what follows it and merge with what the root
// already took. Any trailing non-flag args were ignored on this path
// before --add-dir existed and still are, but an --add-dir hidden
// BEHIND one would be silently dropped with them, so reject that
// misplacement loudly below.
more, rest, err := splitLeadingRootFlags(args[1:])
if err != nil {
return writeAppError(stderr, err.Error(), 1)
}
evenMoreDirs, rest, err := splitLeadingAddDirFlags(rest)
if err != nil {
return writeAppError(stderr, err.Error(), 1)
moreDirs := more.addDirs
// A --theme written before the flag was taken at the root and used to be
// dropped here; one written after it wins, as the last occurrence does.
skipTheme := theme
if more.theme != "" {
skipTheme = more.theme
}
moreDirs = append(moreDirs, evenMoreDirs...)
skipAllowEscalation := more.allowEscalation
// A misplaced --add-dir anywhere in the remainder is the more specific error,
// so check for it across all of rest before rejecting stray args.
for _, arg := range rest {
Expand All @@ -390,7 +383,7 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
return writeAppError(stderr, "--skip-permissions-unsafe launches the interactive TUI and takes no prompt or subcommand; for a one-shot unsafe run use `zero exec --skip-permissions-unsafe -p \"...\"`", 1)
}
}
return runInteractiveTUI(stderr, deps, agent.PermissionModeUnsafe, append(append([]string{}, addDirs...), moreDirs...), skipTheme)
return runInteractiveTUI(stderr, deps, agent.PermissionModeUnsafe, append(append([]string{}, addDirs...), moreDirs...), skipTheme, allowEscalation || skipAllowEscalation)
case "-h", "--help", "help":
if err := writeHelp(stdout); err != nil {
return 1
Expand Down Expand Up @@ -423,16 +416,16 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
if len(args) < 2 {
return writePromptRequired(stderr)
}
// Forward leading --add-dir occurrences so exec's own parser collects them.
// Forward the root flags exec consumes so its own parser collects them.
// Use the inline --prompt=<value> form so a prompt whose first character is a
// dash (e.g. `zero -p "-foo"`) is taken verbatim instead of being mistaken for
// a flag and rejected with "--prompt requires a value" (matches the cron path).
execArgs := append(addDirFlagArgs(addDirs), "--prompt="+args[1])
execArgs := append(rootFlagArgs(addDirs, allowEscalation), "--prompt="+args[1])
execArgs = append(execArgs, args[2:]...)
return runExec(execArgs, stdout, stderr, deps)
case "exec":
// Forward leading --add-dir occurrences so exec's own parser collects them.
return runExec(append(addDirFlagArgs(addDirs), args[1:]...), stdout, stderr, deps)
// Forward the root flags exec consumes so its own parser collects them.
return runExec(append(rootFlagArgs(addDirs, allowEscalation), args[1:]...), stdout, stderr, deps)
case "completions":
return runCompletions(args[1:], stdout, stderr)
case "daemon":
Expand Down Expand Up @@ -694,11 +687,11 @@ func fillAppDeps(deps appDeps) appDeps {
return deps
}

func runInteractiveTUI(stderr io.Writer, deps appDeps, permissionMode agent.PermissionMode, addDirs []string, theme string) int {
return runInteractiveTUIWithSetup(stderr, deps, permissionMode, addDirs, theme, false)
func runInteractiveTUI(stderr io.Writer, deps appDeps, permissionMode agent.PermissionMode, addDirs []string, theme string, allowEscalation bool) int {
return runInteractiveTUIWithSetup(stderr, deps, permissionMode, addDirs, theme, false, allowEscalation)
}

func runInteractiveTUIWithSetup(stderr io.Writer, deps appDeps, permissionMode agent.PermissionMode, addDirs []string, theme string, forceSetup bool) int {
func runInteractiveTUIWithSetup(stderr io.Writer, deps appDeps, permissionMode agent.PermissionMode, addDirs []string, theme string, forceSetup bool, allowEscalation bool) int {
// Refresh the models.dev pricing/limits cache in the background when stale;
// the overlay is read at registry construction from the cache file, so this
// benefits the next run and never blocks or fails this one.
Expand Down Expand Up @@ -790,6 +783,14 @@ func runInteractiveTUIWithSetup(stderr io.Writer, deps appDeps, permissionMode a

registry := newCoreRegistryScoped(workspaceRoot, scope)
registerLocalControlTools(registry, workspaceRoot, resolved.LocalControl)
// Mid-run model escalation is opt-in on this surface too. The tool is present
// only when the operator asked for it with --allow-escalation, and the
// switchers that make it do anything ride on the same flag through
// Options.AllowEscalation below. Registering one without the other ships a
// tool the loop will never act on, which looks like a feature and is not.
if allowEscalation {
registry.Register(tools.NewEscalateModelTool())
}
executionRunner := execution.NewRunner(nil)
sandboxStore, err := deps.newSandboxStore()
if err != nil {
Expand Down Expand Up @@ -1033,6 +1034,7 @@ func runInteractiveTUIWithSetup(stderr io.Writer, deps appDeps, permissionMode a
Specialists: specialistRuntime.specialists,
Skills: pluginActivation.skillInfos(deps.skillsDir()),
},
AllowEscalation: allowEscalation,
// LoadSkills backs /skills and direct /<skill-name> invocation in the TUI.
// It resolves against the same merged set (default dir + plugin skill
// roots) as the skill tool and the system-prompt list, re-read per use so
Expand Down Expand Up @@ -1378,6 +1380,7 @@ Flags:
-v, --version Print version
-p, --prompt Run a one-shot prompt
--add-dir <path> Allow writes in an extra directory (repeatable)
--allow-escalation Let the agent escalate to a stronger model mid-run via escalate_model
--skip-permissions-unsafe Launch the interactive shell in unsafe mode (enables the ! shell escape)
`)
return err
Expand All @@ -1394,6 +1397,17 @@ func addDirFlagArgs(addDirs []string) []string {
return flags
}

// rootFlagArgs re-synthesises the root flags exec consumes, in the spelling
// its own parser accepts, so a flag written before the subcommand reaches
// the run exactly as one written after it would.
func rootFlagArgs(addDirs []string, allowEscalation bool) []string {
flags := addDirFlagArgs(addDirs)
if allowEscalation {
flags = append(flags, "--allow-escalation")
}
return flags
}

// splitLeadingAddDirFlags strips leading --add-dir flags from the root
// argument list (zero --add-dir <path> [--add-dir <path>] [subcommand …]).
// Subcommands like exec parse their own --add-dir occurrences.
Expand Down Expand Up @@ -1434,6 +1448,83 @@ func splitLeadingAddDirFlags(args []string) ([]string, []string, error) {
return addDirs, args, nil
}

// rootFlags is what the leading root flags amount to once every one of them
// has been stripped from the front of the argument list.
type rootFlags struct {
addDirs []string
theme string
allowEscalation bool
}

// splitLeadingRootFlags strips --add-dir, --theme and --allow-escalation from
// the front of args in whatever order they were written, stopping at the
// first token none of them claims.
//
// EACH SPLITTER STOPS AT THE FIRST TOKEN IT DOES NOT OWN, so running them once
// in a fixed sequence made the order the operator wrote them in load-bearing:
// a flag handled late in the sequence stranded every flag written after it as
// an unknown command, and `zero --allow-escalation --theme auto` exited with
// an argument error instead of launching. Running the sequence until it makes
// no progress accepts every ordering, including a flag repeated on both sides
// of another.
func splitLeadingRootFlags(args []string) (rootFlags, []string, error) {
var flags rootFlags
for {
before := len(args)
addDirs, rest, err := splitLeadingAddDirFlags(args)
if err != nil {
return rootFlags{}, nil, err
}
flags.addDirs = append(flags.addDirs, addDirs...)
theme, rest, err := splitLeadingThemeFlag(rest)
if err != nil {
return rootFlags{}, nil, err
}
if theme != "" {
// The last occurrence wins across passes, as it does within one.
flags.theme = theme
}
allowEscalation, rest, err := splitLeadingAllowEscalationFlag(rest)
if err != nil {
return rootFlags{}, nil, err
}
flags.allowEscalation = flags.allowEscalation || allowEscalation
args = rest
if len(args) == before {
return flags, args, nil
}
}
}

// splitLeadingAllowEscalationFlag strips a leading --allow-escalation from the
// root argument list, opting the interactive session into mid-run model
// escalation.
//
// OPT-IN, THE SAME WAY exec IS. Escalation moves a run onto a different model,
// which changes what the run costs and which provider sees the conversation, so
// it is a decision the operator makes rather than a default. The exec flag
// already answers this conservatively and the interactive surface should not
// answer it differently.
//
// Bare flag only: repeating it is harmless, and an =value form is rejected so a
// mistyped --allow-escalation=false is a loud error instead of silently enabling
// the thing it was trying to turn off.
func splitLeadingAllowEscalationFlag(args []string) (bool, []string, error) {
allow := false
for len(args) > 0 {
switch {
case args[0] == "--allow-escalation":
allow = true
args = args[1:]
case strings.HasPrefix(args[0], "--allow-escalation="):
return false, nil, errors.New("--allow-escalation takes no value; pass it bare to enable mid-run model escalation, or omit it")
default:
return allow, args, nil
}
}
return allow, args, nil
}

// splitLeadingThemeFlag strips a leading --theme <auto|theme-name> (space or =form)
// from the root argument list and validates it against the registered themes. The
// last occurrence wins. A value outside the allowed set is a loud error rather than
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type completionContext struct {
}

var completionRoot = completionNode{
flags: []string{"-h", "--help", "-v", "--version", "-p", "--prompt", "--add-dir", "--theme", "--skip-permissions-unsafe"},
flags: []string{"-h", "--help", "-v", "--version", "-p", "--prompt", "--add-dir", "--allow-escalation", "--theme", "--skip-permissions-unsafe"},
children: []completionNode{
{names: []string{"exec"}, flags: []string{
"-h", "--help", "-f", "--file", "--image", "--add-dir", "--mode", "-m", "--model",
Expand Down
63 changes: 14 additions & 49 deletions internal/cli/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -442,57 +442,22 @@ func runExec(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) in
// the resolved model and is reassigned by the model switcher on a mid-run
// escalation so post-switch turns are attributed to the escalated model.
currentModel := resolved.Provider.Model
var modelSwitcher func(context.Context, string) (agent.Provider, error)
if options.allowEscalation {
modelSwitcher = func(_ context.Context, modelID string) (agent.Provider, error) {
// deps.newProvider is wrapped (fillAppDeps) to apply the stored key, so
// the escalated provider is authenticated even though resolved.Provider
// is the pure profile — no per-site key handling here.
switchedProfile := resolved.Provider
switchedProfile.Model = modelID
switchedProvider, err := deps.newProvider(switchedProfile)
if err != nil {
return nil, err
}
// Mirror the agent loop's switch guard (it only reassigns the provider
// when newProvider != nil). Updating currentModel only on a non-nil
// provider keeps usage attribution consistent with whether the loop
// actually switched — a (nil, nil) return leaves both untouched.
if switchedProvider != nil {
currentModel = modelID
}
return switchedProvider, nil
}
}

// Optimized OpenAI turn sessions (ZERO_OPENAI_TURN_SESSION, default off).
// nil when gated off or the profile is ineligible: agent.Run then wraps the
// provider in its default adapter — the exact code path of today. The
// session switcher is installed only when the run START is optimized, so
// the legacy ModelSwitcher path above stays untouched otherwise.
// Optimized OpenAI turn sessions (ZERO_OPENAI_TURN_SESSION, default off). nil
// when gated off or the profile is ineligible: agent.Run then wraps the
// provider in its default adapter. This is the run's STARTING session provider
// and is used whether or not escalation is enabled.
turnSessions, _ := providers.OptimizedTurnSessions(resolved.Provider, provider, providers.Options{})
// Both switchers come from one shared builder so exec and the interactive TUI
// cannot drift on the nil contracts the agent loop depends on. The session
// switcher is nil unless this run STARTED optimized, which is what keeps a
// default-adapter run on the default adapter.
var modelSwitcher func(context.Context, string) (agent.Provider, error)
var modelSessionSwitcher func(context.Context, string) (zeroruntime.TurnSessionProvider, error)
if options.allowEscalation && turnSessions != nil {
modelSessionSwitcher = func(_ context.Context, modelID string) (zeroruntime.TurnSessionProvider, error) {
switchedProfile := resolved.Provider
switchedProfile.Model = modelID
switchedProvider, err := deps.newProvider(switchedProfile)
if err != nil {
return nil, err
}
if switchedProvider == nil {
// The loop treats a nil session source as "no swap" — mirror the
// legacy closure's (nil, nil) contract.
return nil, nil
}
currentModel = modelID
if optimized, ok := providers.OptimizedTurnSessions(switchedProfile, switchedProvider, providers.Options{}); ok {
return optimized, nil
}
// Ineligible switch target: default adapter, but with the switched
// model's resolved capability projection preserved.
return providers.DefaultTurnSessions(switchedProfile, switchedProvider, providers.Options{}), nil
}
if options.allowEscalation {
modelSwitcher, modelSessionSwitcher = providers.EscalationSwitchers(
resolved.Provider, provider, deps.newProvider,
func(modelID string) { currentModel = modelID },
)
}

runMetadata, err := resolveExecRunMetadata(resolved.Provider)
Expand Down
Loading
Loading