GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(tui): offer mid-run model escalation behind --allow-escalation · Twigpine/zero@a83c48b

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • internal
    • cli
      • app.go
      • completions.go
      • exec.go
      • setup.go
      • tui_escalation_test.go
    • providers
      • escalation.go
      • escalation_test.go
    • tui
      • model.go
      • options.go
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎internal/cli/app.go‎

Copy file name to clipboardExpand all lines: internal/cli/app.go
+57-5Lines changed: 57 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -327,9 +327,15 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
327327
return writeAppError(stderr, err.Error(), 1)
328328
}
329329
addDirs = append(addDirs, moreDirs...)
330+
// --allow-escalation opts the interactive session into mid-run model
331+
// escalation, mirroring the exec flag of the same name.
332+
allowEscalation, args, err := splitLeadingAllowEscalationFlag(args)
333+
if err != nil {
334+
return writeAppError(stderr, err.Error(), 1)
335+
}
330336

331337
if len(args) == 0 {
332-
return runInteractiveTUI(stderr, deps, agent.PermissionModeAsk, addDirs, theme)
338+
return runInteractiveTUI(stderr, deps, agent.PermissionModeAsk, addDirs, theme, allowEscalation)
333339
}
334340

335341
// --add-dir grants an extra write root, and only the interactive TUI and
@@ -374,6 +380,13 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
374380
return writeAppError(stderr, err.Error(), 1)
375381
}
376382
moreDirs = append(moreDirs, evenMoreDirs...)
383+
// --allow-escalation may sit on either side of --skip-permissions-unsafe,
384+
// like --theme and --add-dir, so re-split it here and OR the two results
385+
// rather than letting the side it was written on decide.
386+
skipAllowEscalation, rest, err := splitLeadingAllowEscalationFlag(rest)
387+
if err != nil {
388+
return writeAppError(stderr, err.Error(), 1)
389+
}
377390
// A misplaced --add-dir anywhere in the remainder is the more specific error,
378391
// so check for it across all of rest before rejecting stray args.
379392
for _, arg := range rest {
@@ -390,7 +403,7 @@ func runWithDeps(args []string, stdout io.Writer, stderr io.Writer, deps appDeps
390403
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)
391404
}
392405
}
393-
return runInteractiveTUI(stderr, deps, agent.PermissionModeUnsafe, append(append([]string{}, addDirs...), moreDirs...), skipTheme)
406+
return runInteractiveTUI(stderr, deps, agent.PermissionModeUnsafe, append(append([]string{}, addDirs...), moreDirs...), skipTheme, allowEscalation || skipAllowEscalation)
394407
case "-h", "--help", "help":
395408
if err := writeHelp(stdout); err != nil {
396409
return 1
@@ -694,11 +707,11 @@ func fillAppDeps(deps appDeps) appDeps {
694707
return deps
695708
}
696709

697-
func runInteractiveTUI(stderr io.Writer, deps appDeps, permissionMode agent.PermissionMode, addDirs []string, theme string) int {
698-
return runInteractiveTUIWithSetup(stderr, deps, permissionMode, addDirs, theme, false)
710+
func runInteractiveTUI(stderr io.Writer, deps appDeps, permissionMode agent.PermissionMode, addDirs []string, theme string, allowEscalation bool) int {
711+
return runInteractiveTUIWithSetup(stderr, deps, permissionMode, addDirs, theme, false, allowEscalation)
699712
}
700713

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

791804
registry := newCoreRegistryScoped(workspaceRoot, scope)
792805
registerLocalControlTools(registry, workspaceRoot, resolved.LocalControl)
806+
// Mid-run model escalation is opt-in on this surface too. The tool is present
807+
// only when the operator asked for it with --allow-escalation, and the
808+
// switchers that make it do anything ride on the same flag through
809+
// Options.AllowEscalation below. Registering one without the other ships a
810+
// tool the loop will never act on, which looks like a feature and is not.
811+
if allowEscalation {
812+
registry.Register(tools.NewEscalateModelTool())
813+
}
793814
executionRunner := execution.NewRunner(nil)
794815
sandboxStore, err := deps.newSandboxStore()
795816
if err != nil {
@@ -1033,6 +1054,7 @@ func runInteractiveTUIWithSetup(stderr io.Writer, deps appDeps, permissionMode a
10331054
Specialists: specialistRuntime.specialists,
10341055
Skills: pluginActivation.skillInfos(deps.skillsDir()),
10351056
},
1057+
AllowEscalation: allowEscalation,
10361058
// LoadSkills backs /skills and direct /<skill-name> invocation in the TUI.
10371059
// It resolves against the same merged set (default dir + plugin skill
10381060
// roots) as the skill tool and the system-prompt list, re-read per use so
@@ -1378,6 +1400,7 @@ Flags:
13781400
-v, --version Print version
13791401
-p, --prompt Run a one-shot prompt
13801402
--add-dir <path> Allow writes in an extra directory (repeatable)
1403+
--allow-escalation Let the agent escalate to a stronger model mid-run via escalate_model
13811404
--skip-permissions-unsafe Launch the interactive shell in unsafe mode (enables the ! shell escape)
13821405
`)
13831406
return err
@@ -1434,6 +1457,35 @@ func splitLeadingAddDirFlags(args []string) ([]string, []string, error) {
14341457
return addDirs, args, nil
14351458
}
14361459

1460+
// splitLeadingAllowEscalationFlag strips a leading --allow-escalation from the
1461+
// root argument list, opting the interactive session into mid-run model
1462+
// escalation.
1463+
//
1464+
// OPT-IN, THE SAME WAY exec IS. Escalation moves a run onto a different model,
1465+
// which changes what the run costs and which provider sees the conversation, so
1466+
// it is a decision the operator makes rather than a default. The exec flag
1467+
// already answers this conservatively and the interactive surface should not
1468+
// answer it differently.
1469+
//
1470+
// Bare flag only: repeating it is harmless, and an =value form is rejected so a
1471+
// mistyped --allow-escalation=false is a loud error instead of silently enabling
1472+
// the thing it was trying to turn off.
1473+
func splitLeadingAllowEscalationFlag(args []string) (bool, []string, error) {
1474+
allow := false
1475+
for len(args) > 0 {
1476+
switch {
1477+
case args[0] == "--allow-escalation":
1478+
allow = true
1479+
args = args[1:]
1480+
case strings.HasPrefix(args[0], "--allow-escalation="):
1481+
return false, nil, errors.New("--allow-escalation takes no value; pass it bare to enable mid-run model escalation, or omit it")
1482+
default:
1483+
return allow, args, nil
1484+
}
1485+
}
1486+
return allow, args, nil
1487+
}
1488+
14371489
// splitLeadingThemeFlag strips a leading --theme <auto|theme-name> (space or =form)
14381490
// from the root argument list and validates it against the registered themes. The
14391491
// last occurrence wins. A value outside the allowed set is a loud error rather than
Collapse file

‎internal/cli/completions.go‎

Copy file name to clipboardExpand all lines: internal/cli/completions.go
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ type completionContext struct {
2020
}
2121

2222
var completionRoot = completionNode{
23-
flags: []string{"-h", "--help", "-v", "--version", "-p", "--prompt", "--add-dir", "--theme", "--skip-permissions-unsafe"},
23+
flags: []string{"-h", "--help", "-v", "--version", "-p", "--prompt", "--add-dir", "--allow-escalation", "--theme", "--skip-permissions-unsafe"},
2424
children: []completionNode{
2525
{names: []string{"exec"}, flags: []string{
2626
"-h", "--help", "-f", "--file", "--image", "--add-dir", "--mode", "-m", "--model",
Collapse file

‎internal/cli/exec.go‎

Copy file name to clipboardExpand all lines: internal/cli/exec.go
+14-49Lines changed: 14 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -442,57 +442,22 @@ func runExec(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) in
442442
// the resolved model and is reassigned by the model switcher on a mid-run
443443
// escalation so post-switch turns are attributed to the escalated model.
444444
currentModel := resolved.Provider.Model
445-
var modelSwitcher func(context.Context, string) (agent.Provider, error)
446-
if options.allowEscalation {
447-
modelSwitcher = func(_ context.Context, modelID string) (agent.Provider, error) {
448-
// deps.newProvider is wrapped (fillAppDeps) to apply the stored key, so
449-
// the escalated provider is authenticated even though resolved.Provider
450-
// is the pure profile — no per-site key handling here.
451-
switchedProfile := resolved.Provider
452-
switchedProfile.Model = modelID
453-
switchedProvider, err := deps.newProvider(switchedProfile)
454-
if err != nil {
455-
return nil, err
456-
}
457-
// Mirror the agent loop's switch guard (it only reassigns the provider
458-
// when newProvider != nil). Updating currentModel only on a non-nil
459-
// provider keeps usage attribution consistent with whether the loop
460-
// actually switched — a (nil, nil) return leaves both untouched.
461-
if switchedProvider != nil {
462-
currentModel = modelID
463-
}
464-
return switchedProvider, nil
465-
}
466-
}
467-
468-
// Optimized OpenAI turn sessions (ZERO_OPENAI_TURN_SESSION, default off).
469-
// nil when gated off or the profile is ineligible: agent.Run then wraps the
470-
// provider in its default adapter — the exact code path of today. The
471-
// session switcher is installed only when the run START is optimized, so
472-
// the legacy ModelSwitcher path above stays untouched otherwise.
445+
// Optimized OpenAI turn sessions (ZERO_OPENAI_TURN_SESSION, default off). nil
446+
// when gated off or the profile is ineligible: agent.Run then wraps the
447+
// provider in its default adapter. This is the run's STARTING session provider
448+
// and is used whether or not escalation is enabled.
473449
turnSessions, _ := providers.OptimizedTurnSessions(resolved.Provider, provider, providers.Options{})
450+
// Both switchers come from one shared builder so exec and the interactive TUI
451+
// cannot drift on the nil contracts the agent loop depends on. The session
452+
// switcher is nil unless this run STARTED optimized, which is what keeps a
453+
// default-adapter run on the default adapter.
454+
var modelSwitcher func(context.Context, string) (agent.Provider, error)
474455
var modelSessionSwitcher func(context.Context, string) (zeroruntime.TurnSessionProvider, error)
475-
if options.allowEscalation && turnSessions != nil {
476-
modelSessionSwitcher = func(_ context.Context, modelID string) (zeroruntime.TurnSessionProvider, error) {
477-
switchedProfile := resolved.Provider
478-
switchedProfile.Model = modelID
479-
switchedProvider, err := deps.newProvider(switchedProfile)
480-
if err != nil {
481-
return nil, err
482-
}
483-
if switchedProvider == nil {
484-
// The loop treats a nil session source as "no swap" — mirror the
485-
// legacy closure's (nil, nil) contract.
486-
return nil, nil
487-
}
488-
currentModel = modelID
489-
if optimized, ok := providers.OptimizedTurnSessions(switchedProfile, switchedProvider, providers.Options{}); ok {
490-
return optimized, nil
491-
}
492-
// Ineligible switch target: default adapter, but with the switched
493-
// model's resolved capability projection preserved.
494-
return providers.DefaultTurnSessions(switchedProfile, switchedProvider, providers.Options{}), nil
495-
}
456+
if options.allowEscalation {
457+
modelSwitcher, modelSessionSwitcher = providers.EscalationSwitchers(
458+
resolved.Provider, provider, deps.newProvider,
459+
func(modelID string) { currentModel = modelID },
460+
)
496461
}
497462

498463
runMetadata, err := resolveExecRunMetadata(resolved.Provider)
Collapse file

‎internal/cli/setup.go‎

Copy file name to clipboardExpand all lines: internal/cli/setup.go
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func runSetup(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) i
4242
return exitSuccess
4343
}
4444
if strings.TrimSpace(options.catalogID) == "" {
45-
return runInteractiveTUIWithSetup(stderr, deps, "", nil, "", true)
45+
return runInteractiveTUIWithSetup(stderr, deps, "", nil, "", true, false)
4646
}
4747

4848
result, err := saveSetupProvider(deps, tui.SetupSelection{
Collapse file

‎internal/cli/tui_escalation_test.go‎

Copy file name to clipboard
+125Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package cli
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"strings"
7+
"testing"
8+
9+
"github.com/Gitlawb/zero/internal/tui"
10+
)
11+
12+
// captureTUIOptions runs the root command with the TUI launch intercepted, and
13+
// returns the options the interactive session would have started with.
14+
func captureTUIOptions(t *testing.T, args ...string) tui.Options {
15+
t.Helper()
16+
var captured tui.Options
17+
var stdout, stderr bytes.Buffer
18+
workspace := t.TempDir()
19+
exitCode := runWithDeps(args, &stdout, &stderr, appDeps{
20+
getwd: func() (string, error) { return workspace, nil },
21+
runTUI: func(_ context.Context, options tui.Options) int {
22+
captured = options
23+
return exitSuccess
24+
},
25+
})
26+
if exitCode != exitSuccess {
27+
t.Fatalf("exitCode = %d stdout=%s stderr=%s", exitCode, stdout.String(), stderr.String())
28+
}
29+
return captured
30+
}
31+
32+
func hasEscalateModel(options tui.Options) bool {
33+
if options.AgentOptions.Registry == nil {
34+
return false
35+
}
36+
_, registered := options.AgentOptions.Registry.Get("escalate_model")
37+
return registered
38+
}
39+
40+
// ESCALATION IS OFF UNLESS THE OPERATOR ASKS FOR IT.
41+
//
42+
// Escalation moves a run onto a different model, changing what it costs and which
43+
// provider sees the conversation, so the interactive surface answers this the same
44+
// conservative way `zero exec --allow-escalation` already does.
45+
func TestInteractiveTUIRegistersEscalateModelOnlyWithTheFlag(t *testing.T) {
46+
if hasEscalateModel(captureTUIOptions(t)) {
47+
t.Error("escalate_model was registered without --allow-escalation")
48+
}
49+
if !hasEscalateModel(captureTUIOptions(t, "--allow-escalation")) {
50+
t.Error("--allow-escalation did not register escalate_model")
51+
}
52+
}
53+
54+
// THE TOOL AND THE SWITCHERS ARE ONE FEATURE, NOT TWO.
55+
//
56+
// This is the failure the whole change exists to avoid. The agent loop performs a
57+
// switch only when a switcher is wired, so registering escalate_model without
58+
// wiring one ships a tool the model can call and the loop will silently ignore:
59+
// the run reports an escalation that never happened. The reverse is merely dead
60+
// code. Both halves ride on the same flag and this asserts they cannot be
61+
// separated, whichever half a future change touches.
62+
func TestInteractiveTUIEscalationToolAndSwitchersAreWiredTogether(t *testing.T) {
63+
for _, testCase := range []struct {
64+
name string
65+
args []string
66+
want bool
67+
}{
68+
{name: "default", args: nil, want: false},
69+
{name: "flagged", args: []string{"--allow-escalation"}, want: true},
70+
} {
71+
t.Run(testCase.name, func(t *testing.T) {
72+
options := captureTUIOptions(t, testCase.args...)
73+
if got := hasEscalateModel(options); got != testCase.want {
74+
t.Fatalf("escalate_model registered = %v, want %v", got, testCase.want)
75+
}
76+
if options.AllowEscalation != testCase.want {
77+
t.Errorf("AllowEscalation = %v, want %v: the tool is registered on one gate and the switchers on another, so they can drift apart",
78+
options.AllowEscalation, testCase.want)
79+
}
80+
})
81+
}
82+
}
83+
84+
// The flag is accepted on either side of --skip-permissions-unsafe, like the
85+
// other root flags that may appear there.
86+
func TestInteractiveTUIAcceptsAllowEscalationAroundUnsafe(t *testing.T) {
87+
for _, args := range [][]string{
88+
{"--allow-escalation", "--skip-permissions-unsafe"},
89+
{"--skip-permissions-unsafe", "--allow-escalation"},
90+
} {
91+
options := captureTUIOptions(t, args...)
92+
if !options.AllowEscalation {
93+
t.Errorf("%v did not enable escalation", args)
94+
}
95+
if !hasEscalateModel(options) {
96+
t.Errorf("%v did not register escalate_model", args)
97+
}
98+
}
99+
}
100+
101+
// An =value form is a loud error rather than a silent enable, so a mistyped
102+
// --allow-escalation=false cannot turn the feature ON.
103+
func TestAllowEscalationRejectsAValue(t *testing.T) {
104+
var stdout, stderr bytes.Buffer
105+
exitCode := runWithDeps([]string{"--allow-escalation=false"}, &stdout, &stderr, appDeps{
106+
getwd: func() (string, error) { return t.TempDir(), nil },
107+
runTUI: func(context.Context, tui.Options) int { return exitSuccess },
108+
})
109+
if exitCode == exitSuccess {
110+
t.Fatal("--allow-escalation=false was accepted; a mistyped disable must not silently enable escalation")
111+
}
112+
if !strings.Contains(stderr.String(), "--allow-escalation takes no value") {
113+
t.Errorf("stderr does not explain the flag: %s", stderr.String())
114+
}
115+
}
116+
117+
func TestRootHelpDocumentsAllowEscalation(t *testing.T) {
118+
var stdout, stderr bytes.Buffer
119+
if exitCode := runWithDeps([]string{"--help"}, &stdout, &stderr, appDeps{}); exitCode != exitSuccess {
120+
t.Fatalf("exitCode = %d stderr=%s", exitCode, stderr.String())
121+
}
122+
if !strings.Contains(stdout.String(), "--allow-escalation") {
123+
t.Error("the root help does not mention --allow-escalation, so the flag is undiscoverable")
124+
}
125+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.