From 22ec25a4f3ccf3baa29a1f7cfae2da8e291350d7 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 14:21:11 +0000 Subject: [PATCH 1/7] libs/agent: DATABRICKS_NOT_AN_AGENT makes the CLI act as if no agent calls it Agent detection reads the calling agent's own environment, so a baseline run of an eval still sees the agent and gets the agent-facing output. With DATABRICKS_NOT_AN_AGENT set to a true value, detection reports no agent: stderr hints, the group help footer, the agent quickstart, auto-install and the calling agent in MCP telemetry are all off, as they are for a person. Unset, nothing changes. Co-authored-by: Isaac --- .../cmd/aitools/not-an-agent/out.test.toml | 1 + .../cmd/aitools/not-an-agent/output.txt | 39 +++++++++++++ acceptance/cmd/aitools/not-an-agent/script | 25 +++++++++ acceptance/cmd/aitools/not-an-agent/test.toml | 5 ++ bundle/config/mutator/validate_git_details.go | 2 +- .../check_dashboards_modified_remotely.go | 2 +- bundle/phases/bind.go | 2 +- bundle/phases/deploy.go | 2 +- cmd/aitools/autoinstall_run.go | 17 ++++-- cmd/aitools/autoinstall_run_test.go | 18 ++++++ cmd/aitools/install.go | 20 +++---- cmd/aitools/mcp_telemetry.go | 8 ++- cmd/aitools/mcp_telemetry_test.go | 20 +++++++ cmd/aitools/uninstall.go | 2 +- cmd/auth/login_device_code.go | 10 ++-- cmd/bundle/utils/destroy.go | 2 +- cmd/feedback/feedback.go | 5 +- cmd/quickstart/quickstart.go | 13 +++-- cmd/root/help.go | 5 +- libs/agent/agent_notice.go | 33 +++++++++-- libs/agent/agent_notice_test.go | 55 +++++++++++++++++-- libs/aitools/agents/calling.go | 10 ++-- libs/aitools/agents/calling_test.go | 10 +++- libs/aitools/agents/hint.go | 3 +- libs/aitools/agents/recommend.go | 4 +- libs/aitools/installer/useragent.go | 2 +- libs/aitools/mcp/proxy/run.go | 7 ++- 27 files changed, 264 insertions(+), 58 deletions(-) create mode 100644 acceptance/cmd/aitools/not-an-agent/out.test.toml create mode 100644 acceptance/cmd/aitools/not-an-agent/output.txt create mode 100644 acceptance/cmd/aitools/not-an-agent/script create mode 100644 acceptance/cmd/aitools/not-an-agent/test.toml diff --git a/acceptance/cmd/aitools/not-an-agent/out.test.toml b/acceptance/cmd/aitools/not-an-agent/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/aitools/not-an-agent/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/aitools/not-an-agent/output.txt b/acceptance/cmd/aitools/not-an-agent/output.txt new file mode 100644 index 00000000000..915890802f6 --- /dev/null +++ b/acceptance/cmd/aitools/not-an-agent/output.txt @@ -0,0 +1,39 @@ + +=== Claude Code is hinted, and its help and quickstart are the agent ones + +>>> CLAUDECODE=1 [CLI] jobs list +Before you work with Databricks, run: databricks skills list + +>>> CLAUDECODE=1 [CLI] fs --help + +Coding agents: read the skills for this command group before you use it. + databricks skills read demo-skill + +>>> CLAUDECODE=1 [CLI] quickstart + +=== With the variable set, no hint is printed + +>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] jobs list + +=== With the variable set, the help has no skills footer + +>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] fs --help + -t, --target string bundle target to use (if applicable) + +Use "databricks fs [command] --help" for more information about a command. + +>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] --help + +Use "databricks [command] --help" for more information about a command. + +=== With the variable set, quickstart prints the human guide + +>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] quickstart +# Welcome to Databricks + +>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] quickstart + +=== A false value leaves agent detection on + +>>> DATABRICKS_NOT_AN_AGENT=0 CODEX_CI=1 CODEX_THREAD_ID=thread-1 [CLI] jobs list +Before you work with Databricks, run: databricks skills list diff --git a/acceptance/cmd/aitools/not-an-agent/script b/acceptance/cmd/aitools/not-an-agent/script new file mode 100644 index 00000000000..429ca8ce157 --- /dev/null +++ b/acceptance/cmd/aitools/not-an-agent/script @@ -0,0 +1,25 @@ +# DATABRICKS_NOT_AN_AGENT makes agent detection report no agent, so a run that +# has an agent variable set gets the human output. Claude Code's variable is set +# throughout; the skills catalog is the one cmd/skills fixture, which maps the fs group. +sethome ./home +export DATABRICKS_SKILLS_DIR="$TESTDIR/../../skills/release" +unset XDG_CONFIG_HOME + +title "Claude Code is hinted, and its help and quickstart are the agent ones" +trace CLAUDECODE=1 $CLI jobs list +trace CLAUDECODE=1 $CLI fs --help | tail -n 3 +trace CLAUDECODE=1 $CLI quickstart | contains.py 'databricks skills list' > /dev/null + +title "With the variable set, no hint is printed" +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI jobs list + +title "With the variable set, the help has no skills footer" +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI fs --help | tail -n 3 +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI --help | tail -n 2 + +title "With the variable set, quickstart prints the human guide" +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI quickstart | head -n 1 +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI quickstart | contains.py '!databricks skills list' > /dev/null + +title "A false value leaves agent detection on" +trace DATABRICKS_NOT_AN_AGENT=0 CODEX_CI=1 CODEX_THREAD_ID=thread-1 $CLI jobs list diff --git a/acceptance/cmd/aitools/not-an-agent/test.toml b/acceptance/cmd/aitools/not-an-agent/test.toml new file mode 100644 index 00000000000..a83981e8cd4 --- /dev/null +++ b/acceptance/cmd/aitools/not-an-agent/test.toml @@ -0,0 +1,5 @@ +Env.DATABRICKS_SKILLS_PREVIEW = "1" +Env.DATABRICKS_SKILLS_HINTS = "1" +# The throttle markers live in the file cache, which a host could disable. +Env.DATABRICKS_CACHE_ENABLED = "true" +Ignore = ["home"] diff --git a/bundle/config/mutator/validate_git_details.go b/bundle/config/mutator/validate_git_details.go index bb25a198093..d6e2f471327 100644 --- a/bundle/config/mutator/validate_git_details.go +++ b/bundle/config/mutator/validate_git_details.go @@ -25,7 +25,7 @@ func (m *validateGitDetails) Apply(ctx context.Context, b *bundle.Bundle) diag.D if b.Config.Bundle.Git.Branch != b.Config.Bundle.Git.ActualBranch && !b.Config.Bundle.Force { return diag.Errorf("not on the right Git branch:\n expected according to configuration: %s\n actual: %s\nTo deploy from this branch anyway, use --force. Note that this may push unexpected code to the target.%s", - b.Config.Bundle.Git.Branch, b.Config.Bundle.Git.ActualBranch, agent.AgentNotice()) + b.Config.Bundle.Git.Branch, b.Config.Bundle.Git.ActualBranch, agent.AgentNotice(ctx)) } return nil } diff --git a/bundle/deploy/check_dashboards_modified_remotely.go b/bundle/deploy/check_dashboards_modified_remotely.go index d685f7ebeb6..8e30a9d9e1d 100644 --- a/bundle/deploy/check_dashboards_modified_remotely.go +++ b/bundle/deploy/check_dashboards_modified_remotely.go @@ -108,7 +108,7 @@ func (l *checkDashboardsModifiedRemotely) Apply(ctx context.Context, b *bundle.B "before proceeding with the deployment.\n" + "\n" + "To overwrite the remote changes with your local version, use --force.\n" + - "The remote modifications will be lost." + agent.AgentNotice(), + "The remote modifications will be lost." + agent.AgentNotice(ctx), Paths: []*structpath.PathNode{path}, Locations: []diag.Location{loc}, }) diff --git a/bundle/phases/bind.go b/bundle/phases/bind.go index 8f19f67a7fa..639d46ec0c0 100644 --- a/bundle/phases/bind.go +++ b/bundle/phases/bind.go @@ -90,7 +90,7 @@ func Bind(ctx context.Context, b *bundle.Bundle, opts *BindOptions, stateDesc *s if !cmdio.IsPromptSupported(ctx) { result.Cancel() - logdiag.LogError(ctx, fmt.Errorf("this bind operation requires user confirmation, but the current console does not support prompting.\nTo proceed, use --auto-approve after reviewing the plan above.%s", agent.AgentNotice())) + logdiag.LogError(ctx, fmt.Errorf("this bind operation requires user confirmation, but the current console does not support prompting.\nTo proceed, use --auto-approve after reviewing the plan above.%s", agent.AgentNotice(ctx))) return } diff --git a/bundle/phases/deploy.go b/bundle/phases/deploy.go index aba696173bb..54d45c86ace 100644 --- a/bundle/phases/deploy.go +++ b/bundle/phases/deploy.go @@ -53,7 +53,7 @@ func approvalForDeploy(ctx context.Context, b *bundle.Bundle, plan *deployplan.P if !cmdio.IsPromptSupported(ctx) { return false, errors.New("the deployment requires destructive actions, but the current console does not support prompting.\n" + DataLossWarning + "\n" + - "To proceed, use --auto-approve after reviewing the plan above." + agent.AgentNotice()) + "To proceed, use --auto-approve after reviewing the plan above." + agent.AgentNotice(ctx)) } cmdio.LogString(ctx, "") diff --git a/cmd/aitools/autoinstall_run.go b/cmd/aitools/autoinstall_run.go index 4f3d2919731..ea037d32ff2 100644 --- a/cmd/aitools/autoinstall_run.go +++ b/cmd/aitools/autoinstall_run.go @@ -17,6 +17,7 @@ import ( "strings" "time" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/aitools/installer" @@ -29,7 +30,6 @@ import ( "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" "github.com/databricks/cli/libs/versioncheck" - "github.com/databricks/databricks-sdk-go/useragent" "github.com/spf13/cobra" ) @@ -116,6 +116,11 @@ const autoInstallDisable = "databricks aitools auto-install disable" // that ran the command, as it would have without auto-install. func AutoInstall(cmd *cobra.Command) os.Signal { ctx := cmd.Context() + // A run that does not notice agents (DATABRICKS_NOT_AN_AGENT) installs nothing and asks nothing, so an eval + // baseline keeps its machine as it is. + if agent.NotAnAgent(ctx) { + return nil + } defer func() { if r := recover(); r != nil { log.Debugf(ctx, "auto-install: panic: %v", r) @@ -203,7 +208,7 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { log.Debugf(ctx, "auto-install: skipped: %s", tools.skipWhy) return nil } - if err == nil && autoInstallAsks() && in.State.AcceptedVersion != version && !canAsk(ctx) && len(tools.newAgents()) > 0 { + if err == nil && autoInstallAsks(ctx) && in.State.AcceptedVersion != version && !canAsk(ctx) && len(tools.newAgents()) > 0 { skipUnaskable(ctx, in.State.ID) return nil } @@ -272,7 +277,7 @@ func autoInstall(ctx context.Context, skippedCommand bool) os.Signal { version: version, id: id, arm: holdoutArm(in.Bucket), - interactive: cmdio.HasTerminal(ctx) && autoInstallAsks(), + interactive: cmdio.HasTerminal(ctx) && autoInstallAsks(ctx), now: in.Now, } if !reason.Due() { @@ -306,7 +311,7 @@ func (r autoInstallRun) attempt(ctx context.Context, prior autoinstall.State) os // once per version: a "yes" covers that version's retries. A planning // failure is a failed attempt, and its retry asks. asked := false - if err == nil && autoInstallAsks() && prior.AcceptedVersion != r.version && len(tools.newAgents()) > 0 { + if err == nil && autoInstallAsks(ctx) && prior.AcceptedVersion != r.version && len(tools.newAgents()) > 0 { // autoInstall skips this case before the lock; the state it decided // on may have changed since. if !canAsk(ctx) { @@ -468,8 +473,8 @@ func saveInstallStateDigest(ctx context.Context, globalDir string) { // autoInstallAsks reports whether auto-install asks before a first install: // no coding agent is detected. A run that cannot ask (see canAsk) skips; // coding agents install without a question. -func autoInstallAsks() bool { - return useragent.AgentProvider() == "" +func autoInstallAsks(ctx context.Context) bool { + return agent.Provider(ctx) == "" } // canAsk reports whether the question can be seen and answered: see diff --git a/cmd/aitools/autoinstall_run_test.go b/cmd/aitools/autoinstall_run_test.go index 812eed3fddf..ade3949905b 100644 --- a/cmd/aitools/autoinstall_run_test.go +++ b/cmd/aitools/autoinstall_run_test.go @@ -19,6 +19,7 @@ import ( "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/dbr" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/process" "github.com/databricks/cli/libs/telemetry" @@ -752,6 +753,23 @@ func TestAutoInstallSkipsTheGateLookup(t *testing.T) { } } +// With DATABRICKS_NOT_AN_AGENT set, a coding agent's run is not an agent's call: auto-install neither asks nor +// installs, and it does not look the gate up. +func TestAutoInstallSkipsUnderNotAnAgent(t *testing.T) { + home := setupAutoInstallHome(t, "", "CLAUDECODE", "1") + t.Cleanup(func() { gateOn = autoinstall.GateOn }) + gateOn = func(context.Context, string) (bool, error) { + t.Error("the gate was looked up") + return true, nil + } + ctx := cmdio.MockDiscard(t.Context()) + ctx = telemetry.WithNewLogger(ctx) + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + runAutoInstallHook(ctx) + assert.Empty(t, telemetry.BufferedEvents(ctx)) + assert.NoDirExists(t, filepath.Join(home, ".cursor", "skills")) +} + // Root running in a user's home (sudo with HOME kept) leaves the home alone: // it takes no lock, reads and writes no state, looks no gate up and installs // nothing, so the user's own runs can still write there. The same run as the diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index ea43c89606e..f1af4526fdf 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -11,6 +11,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/huh" "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/aitools/installer" @@ -18,7 +19,6 @@ import ( "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/telemetry/protos" - "github.com/databricks/databricks-sdk-go/useragent" "github.com/spf13/cobra" ) @@ -55,18 +55,18 @@ var errNoAgentsSelected = errors.New("at least one agent must be selected") // An agent caller always gets the documented non-interactive behavior, as a // run without a terminal does. func promptsSupported(ctx context.Context) bool { - return cmdio.IsPromptSupported(ctx) && useragent.AgentProvider() == "" + return cmdio.IsPromptSupported(ctx) && agent.Provider(ctx) == "" } // noPromptsNote says that prompts were skipped because the caller is a coding // agent. It names the detected agent by its --agents value when it has one. -func noPromptsNote() string { - provider := useragent.AgentProvider() +func noPromptsNote(ctx context.Context) string { + provider := agent.Provider(ctx) detected := "a coding agent was" if provider == "multiple" { detected = "more than one coding agent was" - } else if agent := agents.AgentForProvider(provider); agent != nil { - detected = fmt.Sprintf("a coding agent (%s) was", agent.Name) + } else if a := agents.AgentForProvider(provider); a != nil { + detected = fmt.Sprintf("a coding agent (%s) was", a.Name) } return fmt.Sprintf("No prompts shown because %s detected.", detected) } @@ -78,7 +78,7 @@ func noPromptsNote() string { // prompts there. func logSkippedPromptNote(ctx context.Context) { if cmdio.IsPromptSupported(ctx) && !promptsSupported(ctx) { - cmdio.LogString(ctx, noPromptsNote()) + cmdio.LogString(ctx, noPromptsNote(ctx)) } } @@ -87,8 +87,8 @@ func logSkippedPromptNote(ctx context.Context) { // flags of `databricks aitools install` that would have replaced the skipped // prompts. The command is named because the deprecated // `experimental aitools skills install` alias does not accept these flags. -func agentCallerNote(missingFlags []string) string { - return fmt.Sprintf("%s Pass %s to databricks aitools install to choose what to install.", noPromptsNote(), strings.Join(missingFlags, " and ")) +func agentCallerNote(ctx context.Context, missingFlags []string) string { + return fmt.Sprintf("%s Pass %s to databricks aitools install to choose what to install.", noPromptsNote(ctx), strings.Join(missingFlags, " and ")) } // delivery is how the databricks tools are delivered to one agent. @@ -331,7 +331,7 @@ Supported agents: ` + strings.Join(agents.SupportedNames(), ", "), missing = append(missing, "--agents") } if len(missing) > 0 { - cmdio.LogString(ctx, agentCallerNote(missing)) + cmdio.LogString(ctx, agentCallerNote(ctx, missing)) } } diff --git a/cmd/aitools/mcp_telemetry.go b/cmd/aitools/mcp_telemetry.go index 9c240c8b6da..565d59a8d8c 100644 --- a/cmd/aitools/mcp_telemetry.go +++ b/cmd/aitools/mcp_telemetry.go @@ -4,6 +4,7 @@ import ( "context" "strings" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/auth" @@ -11,6 +12,7 @@ import ( "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" "github.com/databricks/databricks-sdk-go/config" + "github.com/databricks/databricks-sdk-go/useragent" ) // setUploadConfig prepares telemetry after the command has resolved its workspace. @@ -111,7 +113,7 @@ func mcpServiceType(fullName string) protos.AitoolsMcpService { // callingAgentType returns the agent that drives the CLI, Unspecified when none is detected. func callingAgentType() protos.AitoolsAgentType { - a := agents.CallingAgent() + a := agents.AgentForProvider(useragent.AgentProvider()) if a == nil { return protos.AitoolsAgentTypeUnspecified } @@ -135,6 +137,10 @@ func logMcpEvent(ctx context.Context, event protos.AitoolsMcpEvent) bool { if telemetry.Disabled(ctx) || len(event.Servers) == 0 { return false } + // Every event passes here, so this is where the calling agent is left out while DATABRICKS_NOT_AN_AGENT holds. + if agent.NotAnAgent(ctx) { + event.CallingAgent = protos.AitoolsAgentTypeUnspecified + } state, err := mcp.LoadState(ctx) if err != nil { log.Debugf(ctx, "telemetry: cannot read the MCP state; dropping the event: %s", err) diff --git a/cmd/aitools/mcp_telemetry_test.go b/cmd/aitools/mcp_telemetry_test.go index a6e05d331c3..d54b7e02f4b 100644 --- a/cmd/aitools/mcp_telemetry_test.go +++ b/cmd/aitools/mcp_telemetry_test.go @@ -213,6 +213,26 @@ func TestLogMcpEventLogsRejectedCredential(t *testing.T) { assert.True(t, uploads) } +// With DATABRICKS_NOT_AN_AGENT set, the event is logged without the calling agent. +func TestLogMcpEventOmitsCallingAgentUnderNotAnAgent(t *testing.T) { + withHome(t) + ctx := env.Set(telemetry.WithNewLogger(t.Context()), "DATABRICKS_CLI_DISABLE_TELEMETRY", "") + telemetry.SetUploadConfig(ctx, &config.Config{Profile: "logfood", Host: "https://adb-1.test"}) + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + event := protos.AitoolsMcpEvent{ + CallingAgent: protos.AitoolsAgentTypeClaudeCode, + Operation: protos.AitoolsMcpOperationSignIn, + Servers: []protos.AitoolsMcpServerResult{{ + Service: protos.AitoolsMcpServiceGitHub, + Outcome: protos.AitoolsTargetOutcomeFailed, + }}, + } + require.True(t, logMcpEvent(ctx, event)) + buffered := telemetry.BufferedEvents(ctx) + require.Len(t, buffered, 1) + assert.Equal(t, protos.AitoolsAgentTypeUnspecified, buffered[0].AitoolsMcpEvent.CallingAgent) +} + func TestLogMcpEventWithoutLogger(t *testing.T) { withHome(t) assert.False(t, logMcpEvent(t.Context(), proxyStartedEvent(protos.AitoolsAgentTypeCodex, "system.ai.github"))) diff --git a/cmd/aitools/uninstall.go b/cmd/aitools/uninstall.go index e38598e70ba..440c65946ec 100644 --- a/cmd/aitools/uninstall.go +++ b/cmd/aitools/uninstall.go @@ -122,7 +122,7 @@ The command exits with code 1 when every removal it attempts fails.`, // A coding agent on a terminal: say what is removed and why // nobody was asked to confirm it. cmdio.LogString(ctx, msg) - cmdio.LogString(ctx, noPromptsNote()) + cmdio.LogString(ctx, noPromptsNote(ctx)) } // With something installed the run removes files and runs agent CLIs, diff --git a/cmd/auth/login_device_code.go b/cmd/auth/login_device_code.go index 819c11424d1..fc4ac34435a 100644 --- a/cmd/auth/login_device_code.go +++ b/cmd/auth/login_device_code.go @@ -210,7 +210,7 @@ func (l nonInteractiveDeviceCodeLogin) start(ctx context.Context) error { return fmt.Errorf("store pending login: %w", err) } agentNote := deviceCodeAgentNote + "Ask the user for the confirmation code their browser shows." - cmdio.LogString(ctx, strings.Join(append(approvalInstructions(*da, agentNote), + cmdio.LogString(ctx, strings.Join(append(approvalInstructions(ctx, *da, agentNote), "Once finished, complete the login by running the same command with", "--user-code "+formatCode(da.UserCode)+" and --confirmation-code set to the confirmation code", "provided in your browser.", @@ -262,7 +262,7 @@ func (l nonInteractiveDeviceCodeLogin) complete(ctx context.Context, userCode, c err = fmt.Errorf("%w. Check the confirmation code and approve the login if you haven't, then rerun this command. %s if it still fails", err, startNewLoginHint) // The agent runs this step, so the error above is addressed to it. // Only the user may approve the login. - if note := agent.AgentNote("ask the user to check the confirmation code\n" + + if note := agent.AgentNote(ctx, "ask the user to check the confirmation code\n"+ "and to approve the login if they haven't. Do not approve it yourself"); note != "" { err = fmt.Errorf("%w\n\n%s", err, note) } @@ -314,7 +314,7 @@ func promptForConfirmationCode(ctx context.Context, da u2m.DeviceAuthorization, if lastErr == nil { agentNote := deviceCodeAgentNote + "Ask the user for the confirmation code their browser shows, and enter it\n" + `at the "Confirmation code" prompt of this command.` - cmdio.LogString(ctx, strings.Join(append(approvalInstructions(da, agentNote), + cmdio.LogString(ctx, strings.Join(append(approvalInstructions(ctx, da, agentNote), "Once finished, enter the confirmation code provided in your browser.", ), "\n")) } else { @@ -339,7 +339,7 @@ func promptForConfirmationCode(ctx context.Context, da u2m.DeviceAuthorization, // the login. Both flows print them before saying how to complete the login. // An AI agent also gets a note to pass the login on to the user, whether or // not it runs the command in a terminal. -func approvalInstructions(da u2m.DeviceAuthorization, agentNote string) []string { +func approvalInstructions(ctx context.Context, da u2m.DeviceAuthorization, agentNote string) []string { lines := []string{ "Using a browser on another device, visit:", da.VerificationURI, @@ -348,7 +348,7 @@ func approvalInstructions(da u2m.DeviceAuthorization, agentNote string) []string formatCode(da.UserCode), "", } - if note := agent.AgentNote(agentNote); note != "" { + if note := agent.AgentNote(ctx, agentNote); note != "" { lines = append(lines, note, "") } return lines diff --git a/cmd/bundle/utils/destroy.go b/cmd/bundle/utils/destroy.go index 61326ef0837..bb803c0f890 100644 --- a/cmd/bundle/utils/destroy.go +++ b/cmd/bundle/utils/destroy.go @@ -21,7 +21,7 @@ func CommandBundleDestroy(cmd *cobra.Command, args []string, autoApprove, forceD return errors.New("this command will destroy all resources deployed by this bundle, " + "including workspace files in the deployment directory.\n" + phases.DataLossWarning + "\n" + - "To proceed, use --auto-approve." + agent.AgentNotice()) + "To proceed, use --auto-approve." + agent.AgentNotice(cmd.Context())) } // Check if context is already initialized (e.g., when called from apps delete override) diff --git a/cmd/feedback/feedback.go b/cmd/feedback/feedback.go index 7ad42e87835..4c3ccaa8f15 100644 --- a/cmd/feedback/feedback.go +++ b/cmd/feedback/feedback.go @@ -13,6 +13,7 @@ import ( "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/internal/build" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/cmdctx" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/telemetry" @@ -110,7 +111,7 @@ the reference ID.` if err != nil { return err } - if cmd.Flags().Changed(legacyConfirmationFlag) && !opts.yes && useragent.AgentProvider() != "" { + if cmd.Flags().Changed(legacyConfirmationFlag) && !opts.yes && agent.Provider(cmd.Context()) != "" { return errors.New("feedback was not sent because --yes=false") } cmd.SetContext(root.SkipLoadBundle(cmd.Context())) @@ -170,7 +171,7 @@ func send(ctx context.Context, s submission) error { if s.runID != "" { ctx = useragent.InContext(ctx, runIDKey, s.runID) } - if provider := useragent.AgentProvider(); provider != "" { + if provider := agent.Provider(ctx); provider != "" { // The SDK adds the agent to HTTP request headers, but the feedback record // needs it too so triage can distinguish agent reports. ctx = useragent.InContext(ctx, useragent.AgentKey, provider) diff --git a/cmd/quickstart/quickstart.go b/cmd/quickstart/quickstart.go index fc47391c943..63c1a0bd15b 100644 --- a/cmd/quickstart/quickstart.go +++ b/cmd/quickstart/quickstart.go @@ -8,6 +8,7 @@ import ( _ "embed" "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" @@ -65,7 +66,8 @@ denser, agent-oriented version instead.` if printSkill { content = skillFor() } else { - content = quickstartFor(cmdio.IsPromptSupported(cmd.Context()), skillsVariant) + ctx := cmd.Context() + content = quickstartFor(cmdio.IsPromptSupported(ctx) || agent.NotAnAgent(ctx), skillsVariant) } _, err := fmt.Fprintln(cmd.OutOrStdout(), content) return err @@ -73,10 +75,11 @@ denser, agent-oriented version instead.` } // quickstartFor returns the quickstart text for the caller. Interactive -// terminals (people) get the friendly guide; non-interactive callers (coding -// agents, scripts, CI) get the agent-oriented version. The detection is -// intentionally simple for now and can grow more precise later. skillsVariant -// selects the agent text that points at `databricks skills`. +// terminals (people), and every caller under DATABRICKS_NOT_AN_AGENT, get the +// friendly guide; non-interactive callers (coding agents, scripts, CI) get the +// agent-oriented version. The detection is intentionally simple for now and can +// grow more precise later. skillsVariant selects the agent text that points at +// `databricks skills`. func quickstartFor(interactive, skillsVariant bool) string { if interactive { return strings.TrimRight(humanQuickstart, "\n") diff --git a/cmd/root/help.go b/cmd/root/help.go index 18d91ebdf83..6f911593172 100644 --- a/cmd/root/help.go +++ b/cmd/root/help.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" ) @@ -29,7 +30,9 @@ func setHelpFunc(root *cobra.Command) { // skills catalog, so help never makes a network call. func WriteSkillsHint(c *cobra.Command) { ctx := c.Context() - if !skills.HintsEnabled(ctx) { + // The footer and the root line address coding agents, so they stay out of output for a caller that + // DATABRICKS_NOT_AN_AGENT says is not one. + if !skills.HintsEnabled(ctx) || agent.NotAnAgent(ctx) { return } w := c.OutOrStdout() diff --git a/libs/agent/agent_notice.go b/libs/agent/agent_notice.go index 251e7982535..aee2f730ec3 100644 --- a/libs/agent/agent_notice.go +++ b/libs/agent/agent_notice.go @@ -1,16 +1,39 @@ package agent import ( + "context" "fmt" + "github.com/databricks/cli/libs/env" "github.com/databricks/databricks-sdk-go/useragent" ) +// notAnAgentEnv makes the CLI act as if no agent calls it, for example when an eval runs a baseline arm. Agent +// detection reports no agent, so every agent-facing output is the human one. +const notAnAgentEnv = "DATABRICKS_NOT_AN_AGENT" + +// NotAnAgent reports whether DATABRICKS_NOT_AN_AGENT is set to a true value in the context or the environment. An +// invalid value counts as not set, as other boolean variables do. +func NotAnAgent(ctx context.Context) bool { + on, _ := env.GetBool(ctx, notAnAgentEnv) + return on +} + +// Provider returns the agent name that useragent.AgentProvider reports, or "" when no agent is detected or +// NotAnAgent holds. Code that reads the calling agent for output or telemetry goes through it, so the variable +// reaches every such path. +func Provider(ctx context.Context) string { + if NotAnAgent(ctx) { + return "" + } + return useragent.AgentProvider() +} + // AgentNotice returns a notice string to append to error messages when an AI // agent is detected. Returns an empty string for non-agent callers. -func AgentNotice() string { - note := AgentNote("do not retry with the flag suggested above\n" + - "unless the user has explicitly approved it. The flag bypasses a safety check\n" + +func AgentNotice(ctx context.Context) string { + note := AgentNote(ctx, "do not retry with the flag suggested above\n"+ + "unless the user has explicitly approved it. The flag bypasses a safety check\n"+ "and the operation may be irreversible.") if note == "" { return "" @@ -20,8 +43,8 @@ func AgentNotice() string { // AgentNote returns text as a note addressed to the detected AI agent. Returns // an empty string for non-agent callers. -func AgentNote(text string) string { - name := useragent.AgentProvider() +func AgentNote(ctx context.Context, text string) string { + name := Provider(ctx) if name == "" { return "" } diff --git a/libs/agent/agent_notice_test.go b/libs/agent/agent_notice_test.go index 62a3a70a8ec..caf721c8363 100644 --- a/libs/agent/agent_notice_test.go +++ b/libs/agent/agent_notice_test.go @@ -4,27 +4,74 @@ import ( "testing" "github.com/databricks/cli/internal/testutil" + "github.com/databricks/cli/libs/env" "github.com/stretchr/testify/assert" ) func TestAgentNote(t *testing.T) { testutil.SetAgent(t, "test-agent") - assert.Equal(t, "Note for AI agents (test-agent): ask the user.", AgentNote("ask the user.")) + assert.Equal(t, "Note for AI agents (test-agent): ask the user.", AgentNote(t.Context(), "ask the user.")) } func TestAgentNoteWithoutAgent(t *testing.T) { testutil.SetAgent(t, "") - assert.Empty(t, AgentNote("ask the user.")) + assert.Empty(t, AgentNote(t.Context(), "ask the user.")) +} + +func TestAgentNoteNotAnAgent(t *testing.T) { + testutil.SetAgent(t, "test-agent") + ctx := env.Set(t.Context(), "DATABRICKS_NOT_AN_AGENT", "1") + assert.Empty(t, AgentNote(ctx, "ask the user.")) + assert.Empty(t, AgentNotice(ctx)) } func TestAgentNotice(t *testing.T) { testutil.SetAgent(t, "test-agent") assert.Equal(t, "\n\nNote for AI agents (test-agent): do not retry with the flag suggested above\n"+ "unless the user has explicitly approved it. The flag bypasses a safety check\n"+ - "and the operation may be irreversible.", AgentNotice()) + "and the operation may be irreversible.", AgentNotice(t.Context())) } func TestAgentNoticeWithoutAgent(t *testing.T) { testutil.SetAgent(t, "") - assert.Empty(t, AgentNotice()) + assert.Empty(t, AgentNotice(t.Context())) +} + +func TestNotAnAgent(t *testing.T) { + cases := []struct { + name string + value *string // DATABRICKS_NOT_AN_AGENT in the context; nil leaves it unset + want bool + }{ + {name: "unset", want: false}, + {name: "set", value: new("1"), want: true}, + {name: "set to yes", value: new("yes"), want: true}, + {name: "false", value: new("false"), want: false}, + {name: "zero", value: new("0"), want: false}, + {name: "empty", value: new(""), want: false}, + {name: "invalid", value: new("maybe"), want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + testutil.SetAgentEnv(t, "CLAUDECODE", "1") + ctx := t.Context() + if tc.value != nil { + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", *tc.value) + } + assert.Equal(t, tc.want, NotAnAgent(ctx)) + + // The guard hides the detected agent from every reader that goes through Provider. + if tc.want { + assert.Empty(t, Provider(ctx)) + } else { + assert.Equal(t, "claude-code", Provider(ctx)) + } + }) + } +} + +func TestNotAnAgentFromEnvironment(t *testing.T) { + testutil.SetAgentEnv(t, "CLAUDECODE", "1", "DATABRICKS_NOT_AN_AGENT", "true") + assert.True(t, NotAnAgent(t.Context())) + assert.Empty(t, Provider(t.Context())) } diff --git a/libs/aitools/agents/calling.go b/libs/aitools/agents/calling.go index fef472b1f13..9ed44e85f2f 100644 --- a/libs/aitools/agents/calling.go +++ b/libs/aitools/agents/calling.go @@ -5,8 +5,8 @@ import ( "os" "path/filepath" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/folders" - "github.com/databricks/databricks-sdk-go/useragent" ) // providerAliases maps the SDK agent products (useragent.AgentProvider values) @@ -29,10 +29,10 @@ func AgentForProvider(provider string) *Agent { } // CallingAgent returns the registry agent driving the CLI, or nil when no -// agent is detected, several are, or the agent is one the CLI cannot install -// into. -func CallingAgent() *Agent { - return AgentForProvider(useragent.AgentProvider()) +// agent is detected (see agent.Provider), several are, or the agent is one the +// CLI cannot install into. +func CallingAgent(ctx context.Context) *Agent { + return AgentForProvider(agent.Provider(ctx)) } // Tooling is what Databricks AI tooling an agent has in its own location. diff --git a/libs/aitools/agents/calling_test.go b/libs/aitools/agents/calling_test.go index 8500a94f165..107a041c43a 100644 --- a/libs/aitools/agents/calling_test.go +++ b/libs/aitools/agents/calling_test.go @@ -49,7 +49,7 @@ func TestCallingAgent(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { testutil.SetAgentEnv(t, tc.env...) - a := agents.CallingAgent() + a := agents.CallingAgent(t.Context()) if tc.want == "" { assert.Nil(t, a) return @@ -60,6 +60,14 @@ func TestCallingAgent(t *testing.T) { } } +func TestCallingAgentNotAnAgent(t *testing.T) { + testutil.SetAgentEnv(t, "CLAUDECODE", "1") + require.NotNil(t, agents.CallingAgent(t.Context())) + + ctx := env.Set(t.Context(), "DATABRICKS_NOT_AN_AGENT", "1") + assert.Nil(t, agents.CallingAgent(ctx)) +} + // toolingFixture isolates HOME, the working directory and agent config env so // DatabricksTooling reads only what the test writes. cwd holds a .git, so the // project lookup never walks above it into the host's directories. diff --git a/libs/aitools/agents/hint.go b/libs/aitools/agents/hint.go index d1ea4d61d36..9f61cec2d47 100644 --- a/libs/aitools/agents/hint.go +++ b/libs/aitools/agents/hint.go @@ -5,6 +5,7 @@ import ( "strings" "time" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/cache" "github.com/databricks/cli/libs/cmdio" @@ -233,7 +234,7 @@ func (h *agentHint) nativeLine(ctx context.Context) string { // is installed by then. A failed command, a gate that turns out off or a // failed install then still gets the hint. Otherwise it returns nil. func MaybeHint(ctx context.Context, cmd *cobra.Command, pluginRecorded PluginRecordedFunc) (deferred func()) { - hint := hintForAgent(useragent.AgentProvider(), pluginRecorded) + hint := hintForAgent(agent.Provider(ctx), pluginRecorded) if hint == nil { return nil } diff --git a/libs/aitools/agents/recommend.go b/libs/aitools/agents/recommend.go index 2509ae95d43..bee350fe66f 100644 --- a/libs/aitools/agents/recommend.go +++ b/libs/aitools/agents/recommend.go @@ -3,12 +3,12 @@ package agents import ( "context" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/dbr" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/telemetry/protos" - "github.com/databricks/databricks-sdk-go/useragent" ) // skillsTipText is the tip printed by PrintSkillsTip and MaybeVersionCheckTip. @@ -32,7 +32,7 @@ func PrintSkillsTip(ctx context.Context) { // known version. No telemetry is logged: `databricks version` never resolves // auth, so the event would not be uploaded (see logHintShown). func MaybeVersionCheckTip(ctx context.Context, installedPlugins func(context.Context) []string) { - if isHintedAgent(useragent.AgentProvider()) { + if isHintedAgent(agent.Provider(ctx)) { return } if dbr.HasDetection(ctx) && dbr.RunsOnRuntime(ctx) { diff --git a/libs/aitools/installer/useragent.go b/libs/aitools/installer/useragent.go index 5f6c75ed6e1..f99503643dc 100644 --- a/libs/aitools/installer/useragent.go +++ b/libs/aitools/installer/useragent.go @@ -58,7 +58,7 @@ func WithAiDevKitInUserAgent(ctx context.Context) context.Context { // for the registry agent calling the CLI. Nothing is added when no agent is // detected, several are, or the CLI cannot install into the agent. func WithCallingAgentToolingInUserAgent(ctx context.Context) context.Context { - a := agents.CallingAgent() + a := agents.CallingAgent(ctx) if a == nil { return ctx } diff --git a/libs/aitools/mcp/proxy/run.go b/libs/aitools/mcp/proxy/run.go index 93bc86eecea..ffde5335ccd 100644 --- a/libs/aitools/mcp/proxy/run.go +++ b/libs/aitools/mcp/proxy/run.go @@ -8,13 +8,14 @@ import ( "net/http" "sync" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/auth" "github.com/databricks/databricks-sdk-go/config" "github.com/databricks/databricks-sdk-go/useragent" ) // User-Agent extras of a proxied session. useragent.FromContext carries cli/ but not -// agent/, so Run adds that from useragent.AgentProvider. The extras identify the proxy and +// agent/, so Run adds that from agent.Provider. The extras identify the proxy and // the calling agent. const ( proxyAgentKey = "aitools-mcp" @@ -50,8 +51,8 @@ func Run(ctx context.Context, opts Options) error { if opts.Agent != "" { ctx = useragent.InContext(ctx, clientAgentKey, opts.Agent) } - if agent := useragent.AgentProvider(); agent != "" { - ctx = useragent.InContext(ctx, useragent.AgentKey, agent) + if name := agent.Provider(ctx); name != "" { + ctx = useragent.InContext(ctx, useragent.AgentKey, name) } headers := map[string]string{"User-Agent": useragent.FromContext(ctx)} From 66b69e19ab255dd9fbccf417778fcd344d40432d Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 14:45:56 +0000 Subject: [PATCH 2/7] acceptance: pin the Claude session id in the not-an-agent test Claude Code's hint throttle is keyed by CLAUDE_CODE_SESSION_ID. Developer machines inherit that id, so the test passed locally, but CI has none and printed the hint on every call. Set it in the script so the output does not depend on the environment. Co-authored-by: Isaac --- acceptance/cmd/aitools/not-an-agent/script | 3 +++ 1 file changed, 3 insertions(+) diff --git a/acceptance/cmd/aitools/not-an-agent/script b/acceptance/cmd/aitools/not-an-agent/script index 429ca8ce157..8096ef4323b 100644 --- a/acceptance/cmd/aitools/not-an-agent/script +++ b/acceptance/cmd/aitools/not-an-agent/script @@ -4,6 +4,9 @@ sethome ./home export DATABRICKS_SKILLS_DIR="$TESTDIR/../../skills/release" unset XDG_CONFIG_HOME +# Claude Code's per-session throttle keys the hint by this id. Without it a +# machine with no session id (CI) prints the hint on every call, so pin it. +export CLAUDE_CODE_SESSION_ID=session-1 title "Claude Code is hinted, and its help and quickstart are the agent ones" trace CLAUDECODE=1 $CLI jobs list From fad4955d95d512b1f47191643a23428329eac9ec Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 15:38:58 +0000 Subject: [PATCH 3/7] aitools: gate tips and MCP telemetry on DATABRICKS_NOT_AN_AGENT MaybeVersionCheckTip, PrintSkillsTip and RecommendSkillsInstall do nothing under DATABRICKS_NOT_AN_AGENT, so an eval baseline sees no install tip and no prompt. The MCP telemetry calling agent is read through agent.Provider at its source instead of being blanked after the event is built, so an explicit serve --agent value is kept. The acceptance test gives its no-hint steps a fresh Claude session id, so the positive control's throttle marker cannot hide a regression. Co-authored-by: Isaac --- acceptance/cmd/aitools/not-an-agent/script | 4 +++ cmd/aitools/mcp_add.go | 6 ++-- cmd/aitools/mcp_login.go | 8 ++--- cmd/aitools/mcp_remove.go | 2 +- cmd/aitools/mcp_serve.go | 2 +- cmd/aitools/mcp_telemetry.go | 20 +++++-------- cmd/aitools/mcp_telemetry_test.go | 23 ++++++++++---- libs/agent/agent_notice.go | 6 ++-- libs/aitools/agents/hint.go | 11 +++---- libs/aitools/agents/hint_test.go | 11 +++++++ libs/aitools/agents/recommend.go | 8 +++-- libs/aitools/agents/recommend_test.go | 35 ++++++++++++++++++++++ 12 files changed, 99 insertions(+), 37 deletions(-) diff --git a/acceptance/cmd/aitools/not-an-agent/script b/acceptance/cmd/aitools/not-an-agent/script index 8096ef4323b..aba0b824344 100644 --- a/acceptance/cmd/aitools/not-an-agent/script +++ b/acceptance/cmd/aitools/not-an-agent/script @@ -13,6 +13,10 @@ trace CLAUDECODE=1 $CLI jobs list trace CLAUDECODE=1 $CLI fs --help | tail -n 3 trace CLAUDECODE=1 $CLI quickstart | contains.py 'databricks skills list' > /dev/null +# The positive control above recorded session-1's hint throttle. The variable steps +# get a fresh session, so a build that ignored the variable would print the hint here. +export CLAUDE_CODE_SESSION_ID=session-2 + title "With the variable set, no hint is printed" trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI jobs list diff --git a/cmd/aitools/mcp_add.go b/cmd/aitools/mcp_add.go index d392c6fde69..95b5ab54566 100644 --- a/cmd/aitools/mcp_add.go +++ b/cmd/aitools/mcp_add.go @@ -189,7 +189,7 @@ Supported agents: ` + strings.Join(mcpAgentNames(), ", "), } runErr := runMcpAdd(ctx, cmd, f, jsonMode, out) logMcpEvent(ctx, protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: callingAgentType(ctx), Operation: protos.AitoolsMcpOperationAdd, Servers: addServerResults(out.Servers), }) @@ -1256,7 +1256,7 @@ func signInInstalled(ctx context.Context, errOut io.Writer, w *databricks.Worksp if signedIn(ctx, w, plans[i].service.FullName) { server.SignIn = &addSignInOutput{State: signInStateActive} reportSignedIn(errOut, plans[i].service, req.profile, true) - logMcpEvent(ctx, signInEventOf(server.Service, signInStateActive, true, nil)) + logMcpEvent(ctx, signInEventOf(ctx, server.Service, signInStateActive, true, nil)) continue } yes, err := promptSignInNow(server.Service) @@ -1280,7 +1280,7 @@ func signInInstalled(ctx context.Context, errOut io.Writer, w *databricks.Worksp eventState = state } server.SignIn = &addSignInOutput{State: state} - logMcpEvent(ctx, signInEventOf(server.Service, eventState, alreadySignedIn, err)) + logMcpEvent(ctx, signInEventOf(ctx, server.Service, eventState, alreadySignedIn, err)) if err != nil { server.SignIn.ErrorCategory = errorCategory(err) server.SignIn.Error = err.Error() diff --git a/cmd/aitools/mcp_login.go b/cmd/aitools/mcp_login.go index 83e94c01466..9914ea74238 100644 --- a/cmd/aitools/mcp_login.go +++ b/cmd/aitools/mcp_login.go @@ -101,7 +101,7 @@ func runMcpSignInCommand(cmd *cobra.Command, service string, action mcpSignInAct runErr := runMcpSignIn(ctx, cmd.ErrOrStderr(), profileFlag(cmd), service, action, out) // The host is set once the profile's binding has passed and its client exists, so a run that reached no server logs nothing. if out.Host != "" { - logMcpEvent(ctx, signInEvent(operation, out, runErr)) + logMcpEvent(ctx, signInEvent(ctx, operation, out, runErr)) } if !jsonMode { return runErr @@ -173,12 +173,12 @@ func runMcpSignIn(ctx context.Context, errOut io.Writer, flagValue, service stri } // signInEvent is the SIGN_IN or SIGN_OUT event of one login or logout. -func signInEvent(operation protos.AitoolsMcpOperation, out *mcpSignInOutput, err error) protos.AitoolsMcpEvent { +func signInEvent(ctx context.Context, operation protos.AitoolsMcpOperation, out *mcpSignInOutput, err error) protos.AitoolsMcpEvent { if operation == protos.AitoolsMcpOperationSignIn { - return signInEventOf(out.Service, out.State, out.alreadySignedIn, err) + return signInEventOf(ctx, out.Service, out.State, out.alreadySignedIn, err) } return protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: callingAgentType(ctx), Operation: operation, Servers: []protos.AitoolsMcpServerResult{signOutServerResult(out.Service, out.State, err)}, } diff --git a/cmd/aitools/mcp_remove.go b/cmd/aitools/mcp_remove.go index 188d0f584bb..296b0ebb2a0 100644 --- a/cmd/aitools/mcp_remove.go +++ b/cmd/aitools/mcp_remove.go @@ -152,7 +152,7 @@ func writeRemoveJSON(cmd *cobra.Command, out *removeOutput, runErr error) error // output is written. A run that logged no event touched no server, so it has nothing to upload and sets no config. func logRemoveEvent(ctx context.Context, out *removeOutput) { if !logMcpEvent(ctx, protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: callingAgentType(ctx), Operation: protos.AitoolsMcpOperationRemove, Servers: out.results, }) { diff --git a/cmd/aitools/mcp_serve.go b/cmd/aitools/mcp_serve.go index 2e826708bb9..22b1dbd91fa 100644 --- a/cmd/aitools/mcp_serve.go +++ b/cmd/aitools/mcp_serve.go @@ -223,7 +223,7 @@ func runMcpServe(cmd *cobra.Command, f mcpServeFlags) error { if err != nil { return serveFailure(cmd, err, serveBindStatus) } - agent := proxyAgentType(f.agent) + agent := proxyAgentType(cmd.Context(), f.agent) var authorization string cfg, entry, err := mcp.Bind(cmd.Context(), mcp.BindOptions{ Profile: profileName, diff --git a/cmd/aitools/mcp_telemetry.go b/cmd/aitools/mcp_telemetry.go index 565d59a8d8c..e885d742d12 100644 --- a/cmd/aitools/mcp_telemetry.go +++ b/cmd/aitools/mcp_telemetry.go @@ -12,7 +12,6 @@ import ( "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" "github.com/databricks/databricks-sdk-go/config" - "github.com/databricks/databricks-sdk-go/useragent" ) // setUploadConfig prepares telemetry after the command has resolved its workspace. @@ -111,9 +110,10 @@ func mcpServiceType(fullName string) protos.AitoolsMcpService { return protos.AitoolsMcpServiceOtherSystem } -// callingAgentType returns the agent that drives the CLI, Unspecified when none is detected. -func callingAgentType() protos.AitoolsAgentType { - a := agents.AgentForProvider(useragent.AgentProvider()) +// callingAgentType returns the agent that drives the CLI, Unspecified when none is detected or +// DATABRICKS_NOT_AN_AGENT holds (see agent.Provider). +func callingAgentType(ctx context.Context) protos.AitoolsAgentType { + a := agents.AgentForProvider(agent.Provider(ctx)) if a == nil { return protos.AitoolsAgentTypeUnspecified } @@ -122,9 +122,9 @@ func callingAgentType() protos.AitoolsAgentType { // proxyAgentType returns the agent that started the proxy: the --agent flag when given, else the // detected agent. -func proxyAgentType(flag string) protos.AitoolsAgentType { +func proxyAgentType(ctx context.Context, flag string) protos.AitoolsAgentType { if flag == "" { - return callingAgentType() + return callingAgentType(ctx) } return agentType(flag) } @@ -137,10 +137,6 @@ func logMcpEvent(ctx context.Context, event protos.AitoolsMcpEvent) bool { if telemetry.Disabled(ctx) || len(event.Servers) == 0 { return false } - // Every event passes here, so this is where the calling agent is left out while DATABRICKS_NOT_AN_AGENT holds. - if agent.NotAnAgent(ctx) { - event.CallingAgent = protos.AitoolsAgentTypeUnspecified - } state, err := mcp.LoadState(ctx) if err != nil { log.Debugf(ctx, "telemetry: cannot read the MCP state; dropping the event: %s", err) @@ -250,9 +246,9 @@ func signInServerResult(service, state string, alreadySignedIn bool, err error) // signInEventOf is the SIGN_IN event of one provider sign-in, under add --login or login. A sign-in that found the caller // already signed in is UNCHANGED. -func signInEventOf(service, state string, alreadySignedIn bool, err error) protos.AitoolsMcpEvent { +func signInEventOf(ctx context.Context, service, state string, alreadySignedIn bool, err error) protos.AitoolsMcpEvent { return protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: callingAgentType(ctx), Operation: protos.AitoolsMcpOperationSignIn, Servers: []protos.AitoolsMcpServerResult{signInServerResult(service, state, alreadySignedIn, err)}, } diff --git a/cmd/aitools/mcp_telemetry_test.go b/cmd/aitools/mcp_telemetry_test.go index d54b7e02f4b..0648f329af9 100644 --- a/cmd/aitools/mcp_telemetry_test.go +++ b/cmd/aitools/mcp_telemetry_test.go @@ -13,6 +13,7 @@ import ( "slices" "testing" + "github.com/databricks/cli/internal/testutil" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/env" @@ -213,14 +214,24 @@ func TestLogMcpEventLogsRejectedCredential(t *testing.T) { assert.True(t, uploads) } -// With DATABRICKS_NOT_AN_AGENT set, the event is logged without the calling agent. -func TestLogMcpEventOmitsCallingAgentUnderNotAnAgent(t *testing.T) { +// Under DATABRICKS_NOT_AN_AGENT the detected agent is left out, and an explicit --agent is kept. +func TestCallingAgentNotAnAgent(t *testing.T) { + testutil.SetAgentEnv(t, "CLAUDECODE", "1") + ctx := env.Set(t.Context(), "DATABRICKS_NOT_AN_AGENT", "1") + assert.Equal(t, protos.AitoolsAgentTypeClaudeCode, callingAgentType(t.Context())) + assert.Equal(t, protos.AitoolsAgentTypeUnspecified, callingAgentType(ctx)) + assert.Equal(t, protos.AitoolsAgentTypeUnspecified, proxyAgentType(ctx, "")) + assert.Equal(t, protos.AitoolsAgentTypeCodex, proxyAgentType(ctx, agents.NameCodex)) +} + +func TestLogMcpEventKeepsExplicitAgentNotAnAgent(t *testing.T) { + testutil.SetAgentEnv(t, "CLAUDECODE", "1") withHome(t) ctx := env.Set(telemetry.WithNewLogger(t.Context()), "DATABRICKS_CLI_DISABLE_TELEMETRY", "") telemetry.SetUploadConfig(ctx, &config.Config{Profile: "logfood", Host: "https://adb-1.test"}) ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") event := protos.AitoolsMcpEvent{ - CallingAgent: protos.AitoolsAgentTypeClaudeCode, + CallingAgent: proxyAgentType(ctx, agents.NameCodex), Operation: protos.AitoolsMcpOperationSignIn, Servers: []protos.AitoolsMcpServerResult{{ Service: protos.AitoolsMcpServiceGitHub, @@ -230,7 +241,7 @@ func TestLogMcpEventOmitsCallingAgentUnderNotAnAgent(t *testing.T) { require.True(t, logMcpEvent(ctx, event)) buffered := telemetry.BufferedEvents(ctx) require.Len(t, buffered, 1) - assert.Equal(t, protos.AitoolsAgentTypeUnspecified, buffered[0].AitoolsMcpEvent.CallingAgent) + assert.Equal(t, protos.AitoolsAgentTypeCodex, buffered[0].AitoolsMcpEvent.CallingAgent) } func TestLogMcpEventWithoutLogger(t *testing.T) { @@ -355,14 +366,14 @@ func TestBoundProfileCount(t *testing.T) { func TestSignInEventOf(t *testing.T) { // An ACTIVE credential that the add found signed in is UNCHANGED, as add --login reports it. assert.Equal(t, protos.AitoolsMcpEvent{ - CallingAgent: callingAgentType(), + CallingAgent: callingAgentType(t.Context()), Operation: protos.AitoolsMcpOperationSignIn, Servers: []protos.AitoolsMcpServerResult{{ Service: protos.AitoolsMcpServiceGitHub, Outcome: protos.AitoolsTargetOutcomeUnchanged, SignInState: protos.AitoolsMcpSignInStateActive, }}, - }, signInEventOf("system.ai.github", signInStateActive, true, nil)) + }, signInEventOf(t.Context(), "system.ai.github", signInStateActive, true, nil)) } // TestSignInInstalledURLFailureLogsFailedSignIn checks that an add --login whose sign-in URL cannot be built logs the diff --git a/libs/agent/agent_notice.go b/libs/agent/agent_notice.go index aee2f730ec3..73edf4430a4 100644 --- a/libs/agent/agent_notice.go +++ b/libs/agent/agent_notice.go @@ -13,15 +13,15 @@ import ( const notAnAgentEnv = "DATABRICKS_NOT_AN_AGENT" // NotAnAgent reports whether DATABRICKS_NOT_AN_AGENT is set to a true value in the context or the environment. An -// invalid value counts as not set, as other boolean variables do. +// invalid value counts as false. func NotAnAgent(ctx context.Context) bool { on, _ := env.GetBool(ctx, notAnAgentEnv) return on } // Provider returns the agent name that useragent.AgentProvider reports, or "" when no agent is detected or -// NotAnAgent holds. Code that reads the calling agent for output or telemetry goes through it, so the variable -// reaches every such path. +// NotAnAgent holds. The CLI's own readers of the calling agent (output, telemetry, the User-Agent) go through it. +// The SDK's agent request header still reads useragent.AgentProvider directly, so NotAnAgent does not reach it. func Provider(ctx context.Context) string { if NotAnAgent(ctx) { return "" diff --git a/libs/aitools/agents/hint.go b/libs/aitools/agents/hint.go index 9f61cec2d47..ec2380f5d2c 100644 --- a/libs/aitools/agents/hint.go +++ b/libs/aitools/agents/hint.go @@ -171,8 +171,9 @@ type agentHint struct { nativeKind protos.AitoolsHintKind } -// hintForAgent returns the hint for an agent, keyed by its -// useragent.AgentProvider() value, or nil when that agent is not hinted. +// hintForAgent returns the hint for an agent, keyed by its agent.Provider name +// (the SDK's useragent.AgentProvider value, or "" under DATABRICKS_NOT_AN_AGENT), +// or nil when that agent is not hinted. func hintForAgent(provider string, pluginRecorded PluginRecordedFunc) *agentHint { switch provider { case claudeAgentProvider: @@ -194,7 +195,7 @@ func hintForAgent(provider string, pluginRecorded PluginRecordedFunc) *agentHint } // isHintedAgent reports whether MaybeHint hints the agent with this -// useragent.AgentProvider() value. It defers to hintForAgent so both follow +// agent.Provider name. It defers to hintForAgent so both follow // the same dispatch; pluginRecorded is only read when the hint's installed // check runs, so none is needed here. func isHintedAgent(provider string) bool { @@ -210,8 +211,8 @@ func (h *agentHint) nativeLine(ctx context.Context) string { } // MaybeHint nudges a supported agent toward Databricks AI tooling when it drives -// the CLI without it installed. It is a no-op for human callers, -// unsupported agents, hint-exempt commands (isHintExemptCommand), the +// the CLI without it installed. It is a no-op for human callers (including +// every caller under DATABRICKS_NOT_AN_AGENT), unsupported agents, hint-exempt commands (isHintExemptCommand), the // `databricks skills` commands when skills.HintsEnabled is true, the `auth // token` and `auth docker token` credential helpers, a CLI process the CLI // started itself, when there is no output stream, and once the tooling is diff --git a/libs/aitools/agents/hint_test.go b/libs/aitools/agents/hint_test.go index 9b486b21a1a..7beafedc391 100644 --- a/libs/aitools/agents/hint_test.go +++ b/libs/aitools/agents/hint_test.go @@ -313,6 +313,17 @@ func TestMaybeHint_SkillsHintKindFollowsGuard(t *testing.T) { } } +// DATABRICKS_NOT_AN_AGENT hides the calling agent, so a Claude Code caller gets no hint. +func TestMaybeHint_NotAnAgentSilent(t *testing.T) { + setClaudeAgent(t) + ctx, stderr := claudeCtx(t, t.TempDir()) + ctx = telemetry.WithNewLogger(ctx) + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + MaybeHint(ctx, regularCmd(), noPluginRecorded) + assert.Empty(t, stderr.String()) + assert.Empty(t, hintKinds(t, ctx)) +} + func TestMaybeHint_SkillsCommandExemptFollowsGuard(t *testing.T) { for _, tc := range []struct { name string diff --git a/libs/aitools/agents/recommend.go b/libs/aitools/agents/recommend.go index bee350fe66f..cb66f1969f5 100644 --- a/libs/aitools/agents/recommend.go +++ b/libs/aitools/agents/recommend.go @@ -18,6 +18,9 @@ const skillsTipText = "Tip: coding agents detected without Databricks skills. Ru // and records that it was shown. Callers decide whether the tooling is missing // (see HasDatabricksToolingInstalled). func PrintSkillsTip(ctx context.Context) { + if agent.NotAnAgent(ctx) { + return + } cmdio.LogString(ctx, skillsTipText) logHintShown(ctx, protos.AitoolsHintKindAppsInitTip) } @@ -32,7 +35,7 @@ func PrintSkillsTip(ctx context.Context) { // known version. No telemetry is logged: `databricks version` never resolves // auth, so the event would not be uploaded (see logHintShown). func MaybeVersionCheckTip(ctx context.Context, installedPlugins func(context.Context) []string) { - if isHintedAgent(agent.Provider(ctx)) { + if agent.NotAnAgent(ctx) || isHintedAgent(agent.Provider(ctx)) { return } if dbr.HasDetection(ctx) && dbr.RunsOnRuntime(ctx) { @@ -64,7 +67,8 @@ func noInstalledPlugins(context.Context) []string { return nil } // auto-install off, and a "yes" stores the consent to keep the tools up to date unless the // user answered before. In non-interactive mode, prints a hint. func RecommendSkillsInstall(ctx context.Context, installedPlugins func(context.Context) []string, installFn func(context.Context) error) error { - if HasDatabricksToolingInstalled(ctx, installedPlugins) { + // Under DATABRICKS_NOT_AN_AGENT the run is a baseline: no prompt, no tip and no install. + if agent.NotAnAgent(ctx) || HasDatabricksToolingInstalled(ctx, installedPlugins) { return nil } diff --git a/libs/aitools/agents/recommend_test.go b/libs/aitools/agents/recommend_test.go index cdf1525016a..dfb7b66faa2 100644 --- a/libs/aitools/agents/recommend_test.go +++ b/libs/aitools/agents/recommend_test.go @@ -11,6 +11,7 @@ import ( "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/dbr" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" "github.com/stretchr/testify/assert" @@ -116,6 +117,39 @@ func TestRecommendSkillsInstallNonInteractive(t *testing.T) { assert.Equal(t, []protos.AitoolsHintKind{protos.AitoolsHintKindAppsInitTip}, hintKinds(t, ctx)) } +// Under DATABRICKS_NOT_AN_AGENT the recommendation neither prompts nor prints, though a coding agent's config dir exists. +func TestRecommendSkillsInstallNotAnAgent(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("HOME", tmpDir) + t.Setenv("USERPROFILE", tmpDir) + + origRegistry := Registry + Registry = []*Agent{agentWithConfigDir(tmpDir)} + defer func() { Registry = origRegistry }() + + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + ctx = telemetry.WithNewLogger(ctx) + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + err := RecommendSkillsInstall(ctx, noInstalledPlugins, noopInstall) + require.NoError(t, err) + assert.Empty(t, stderr.String()) + assert.Empty(t, hintKinds(t, ctx)) +} + +// PrintSkillsTip prints the tip unless DATABRICKS_NOT_AN_AGENT is set. +func TestPrintSkillsTipNotAnAgent(t *testing.T) { + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) + ctx = telemetry.WithNewLogger(ctx) + quiet := env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + PrintSkillsTip(quiet) + assert.Empty(t, stderr.String()) + assert.Empty(t, hintKinds(t, quiet)) + + PrintSkillsTip(ctx) + assert.Equal(t, skillsTipText+"\n", stderr.String()) + assert.Equal(t, []protos.AitoolsHintKind{protos.AitoolsHintKindAppsInitTip}, hintKinds(t, ctx)) +} + func TestRecommendSkillsInstallInteractiveDecline(t *testing.T) { t.Cleanup(autoinstall.ResetDeclined) tmpDir := t.TempDir() @@ -252,6 +286,7 @@ func TestMaybeVersionCheckTip(t *testing.T) { {name: "databricks runtime", agentDirs: []string{".codex"}, onDBR: true, installedPlugins: noPlugins}, {name: "claude code caller is left to MaybeHint", agentEnv: []string{"CLAUDECODE", "1"}, agentDirs: []string{".claude"}, installedPlugins: noPlugins}, {name: "codex caller is left to MaybeHint", agentEnv: []string{"CODEX_CI", "1"}, agentDirs: []string{".codex"}, installedPlugins: noPlugins}, + {name: "not an agent is silent", agentEnv: []string{"DATABRICKS_NOT_AN_AGENT", "1"}, agentDirs: []string{".codex"}, installedPlugins: noPlugins}, {name: "several agents calling get the tip, since MaybeHint skips them", agentEnv: []string{"CLAUDECODE", "1", "CODEX_CI", "1"}, agentDirs: []string{".codex"}, installedPlugins: noPlugins, wantTip: true}, } { t.Run(tc.name, func(t *testing.T) { From b167d41e2226a5092989dbd67b5628e50d42696b Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 16:31:58 +0000 Subject: [PATCH 4/7] aitools: use CallingAgent for telemetry and list DATABRICKS_NOT_AN_AGENT in hostenv callingAgentType now calls agents.CallingAgent instead of re-implementing it. The test host environment lists DATABRICKS_NOT_AN_AGENT next to the other agent variables, so a developer shell that exports it does not change the goldens. The notAnAgentEnv doc now says that agent tips and notes are suppressed too. Co-authored-by: Isaac --- cmd/aitools/mcp_telemetry.go | 3 +-- internal/testutil/hostenv/hostenv.go | 1 + libs/agent/agent_notice.go | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/cmd/aitools/mcp_telemetry.go b/cmd/aitools/mcp_telemetry.go index e885d742d12..df600f27e2b 100644 --- a/cmd/aitools/mcp_telemetry.go +++ b/cmd/aitools/mcp_telemetry.go @@ -4,7 +4,6 @@ import ( "context" "strings" - "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/aitools/mcp" "github.com/databricks/cli/libs/auth" @@ -113,7 +112,7 @@ func mcpServiceType(fullName string) protos.AitoolsMcpService { // callingAgentType returns the agent that drives the CLI, Unspecified when none is detected or // DATABRICKS_NOT_AN_AGENT holds (see agent.Provider). func callingAgentType(ctx context.Context) protos.AitoolsAgentType { - a := agents.AgentForProvider(agent.Provider(ctx)) + a := agents.CallingAgent(ctx) if a == nil { return protos.AitoolsAgentTypeUnspecified } diff --git a/internal/testutil/hostenv/hostenv.go b/internal/testutil/hostenv/hostenv.go index 3646bce7266..febc2f637a9 100644 --- a/internal/testutil/hostenv/hostenv.go +++ b/internal/testutil/hostenv/hostenv.go @@ -41,6 +41,7 @@ var hostAgentEnv = []string{ "COPILOT_CLI", "COPILOT_HOME", "CURSOR_AGENT", + "DATABRICKS_NOT_AN_AGENT", "GEMINI_CLI", "GEMINI_CLI_HOME", "GOOSE_PATH_ROOT", diff --git a/libs/agent/agent_notice.go b/libs/agent/agent_notice.go index 73edf4430a4..42c685f20ab 100644 --- a/libs/agent/agent_notice.go +++ b/libs/agent/agent_notice.go @@ -9,7 +9,8 @@ import ( ) // notAnAgentEnv makes the CLI act as if no agent calls it, for example when an eval runs a baseline arm. Agent -// detection reports no agent, so every agent-facing output is the human one. +// detection reports no agent, so every agent-facing output is the human one, and agent tips and notes are +// suppressed too. const notAnAgentEnv = "DATABRICKS_NOT_AN_AGENT" // NotAnAgent reports whether DATABRICKS_NOT_AN_AGENT is set to a true value in the context or the environment. An From 1601cec6ec1c394add3834e3dd8577580bd881ea Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 20:36:09 +0000 Subject: [PATCH 5/7] aitools: warn that DATABRICKS_NOT_AN_AGENT stops auto-install auto-install enable now says when DATABRICKS_NOT_AN_AGENT still stops the hook in this environment, as it already does for DATABRICKS_AITOOLS_AUTO_INSTALL. The not-an-agent acceptance script shows the --help footer line in the first section, routes the quickstart discards to LOG files, and covers the enable output. Co-authored-by: Isaac --- acceptance/cmd/aitools/not-an-agent/output.txt | 10 ++++++++++ acceptance/cmd/aitools/not-an-agent/script | 8 ++++++-- cmd/aitools/autoinstall.go | 4 ++++ libs/agent/agent_notice.go | 6 +++--- 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/acceptance/cmd/aitools/not-an-agent/output.txt b/acceptance/cmd/aitools/not-an-agent/output.txt index 915890802f6..4f78bce4dda 100644 --- a/acceptance/cmd/aitools/not-an-agent/output.txt +++ b/acceptance/cmd/aitools/not-an-agent/output.txt @@ -9,6 +9,10 @@ Before you work with Databricks, run: databricks skills list Coding agents: read the skills for this command group before you use it. databricks skills read demo-skill +>>> CLAUDECODE=1 [CLI] --help + +Coding agents: run `databricks skills list` to find skills for the commands you use. + >>> CLAUDECODE=1 [CLI] quickstart === With the variable set, no hint is printed @@ -33,6 +37,12 @@ Use "databricks [command] --help" for more information about a command. >>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] quickstart +=== With the variable set, auto-install enable says it is still stopped here + +>>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] aitools auto-install enable +Automatic installation of Databricks AI tools is enabled. +DATABRICKS_NOT_AN_AGENT still stops it in this environment; unset it to let it run. + === A false value leaves agent detection on >>> DATABRICKS_NOT_AN_AGENT=0 CODEX_CI=1 CODEX_THREAD_ID=thread-1 [CLI] jobs list diff --git a/acceptance/cmd/aitools/not-an-agent/script b/acceptance/cmd/aitools/not-an-agent/script index aba0b824344..a54cb074465 100644 --- a/acceptance/cmd/aitools/not-an-agent/script +++ b/acceptance/cmd/aitools/not-an-agent/script @@ -11,7 +11,8 @@ export CLAUDE_CODE_SESSION_ID=session-1 title "Claude Code is hinted, and its help and quickstart are the agent ones" trace CLAUDECODE=1 $CLI jobs list trace CLAUDECODE=1 $CLI fs --help | tail -n 3 -trace CLAUDECODE=1 $CLI quickstart | contains.py 'databricks skills list' > /dev/null +trace CLAUDECODE=1 $CLI --help | tail -n 2 +trace CLAUDECODE=1 $CLI quickstart | contains.py 'databricks skills list' > LOG.quickstart-agent # The positive control above recorded session-1's hint throttle. The variable steps # get a fresh session, so a build that ignored the variable would print the hint here. @@ -26,7 +27,10 @@ trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI --help | tail -n 2 title "With the variable set, quickstart prints the human guide" trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI quickstart | head -n 1 -trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI quickstart | contains.py '!databricks skills list' > /dev/null +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI quickstart | contains.py '!databricks skills list' > LOG.quickstart-human + +title "With the variable set, auto-install enable says it is still stopped here" +trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI aitools auto-install enable title "A false value leaves agent detection on" trace DATABRICKS_NOT_AN_AGENT=0 CODEX_CI=1 CODEX_THREAD_ID=thread-1 $CLI jobs list diff --git a/cmd/aitools/autoinstall.go b/cmd/aitools/autoinstall.go index 647496ca7e5..49485e9fe2a 100644 --- a/cmd/aitools/autoinstall.go +++ b/cmd/aitools/autoinstall.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/cmdio" "github.com/spf13/cobra" @@ -74,4 +75,7 @@ func printAutoInstallSetting(ctx context.Context, enabled bool) { if autoinstall.EnvOptedOut(ctx) { cmdio.LogString(ctx, cmdio.Yellow(ctx, autoinstall.EnvVar+" still disables it in this environment; unset it to let it run.")) } + if agent.NotAnAgent(ctx) { + cmdio.LogString(ctx, cmdio.Yellow(ctx, agent.NotAnAgentEnv+" still stops it in this environment; unset it to let it run.")) + } } diff --git a/libs/agent/agent_notice.go b/libs/agent/agent_notice.go index 42c685f20ab..707ead27ac6 100644 --- a/libs/agent/agent_notice.go +++ b/libs/agent/agent_notice.go @@ -8,15 +8,15 @@ import ( "github.com/databricks/databricks-sdk-go/useragent" ) -// notAnAgentEnv makes the CLI act as if no agent calls it, for example when an eval runs a baseline arm. Agent +// NotAnAgentEnv makes the CLI act as if no agent calls it, for example when an eval runs a baseline arm. Agent // detection reports no agent, so every agent-facing output is the human one, and agent tips and notes are // suppressed too. -const notAnAgentEnv = "DATABRICKS_NOT_AN_AGENT" +const NotAnAgentEnv = "DATABRICKS_NOT_AN_AGENT" // NotAnAgent reports whether DATABRICKS_NOT_AN_AGENT is set to a true value in the context or the environment. An // invalid value counts as false. func NotAnAgent(ctx context.Context) bool { - on, _ := env.GetBool(ctx, notAnAgentEnv) + on, _ := env.GetBool(ctx, NotAnAgentEnv) return on } From 1077d97bf2b9fc2accb45f114823e66e38effe2c Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 22:55:17 +0000 Subject: [PATCH 6/7] Keep safety notes under DATABRICKS_NOT_AN_AGENT DATABRICKS_NOT_AN_AGENT hides the calling agent from nudges and records. The notes that ask an agent not to act for the user (approving a login, retrying with a flag the user has not approved) and the feedback --yes=false refusal still read the detected agent, so an eval baseline keeps them. The acceptance harness now unsets the variable, the quickstart test pins it off, and the not-an-agent script checks that the hint still shows on the same session once the variable is unset. Co-authored-by: Isaac --- acceptance/acceptance_test.go | 4 +++ .../cmd/aitools/not-an-agent/output.txt | 5 ++++ acceptance/cmd/aitools/not-an-agent/script | 4 +++ bundle/config/mutator/validate_git_details.go | 2 +- .../check_dashboards_modified_remotely.go | 2 +- bundle/phases/bind.go | 2 +- bundle/phases/deploy.go | 2 +- cmd/auth/login_device_code.go | 10 ++++---- cmd/bundle/utils/destroy.go | 2 +- cmd/feedback/feedback.go | 2 +- cmd/quickstart/quickstart.go | 10 ++++---- cmd/quickstart/quickstart_test.go | 4 ++- internal/testutil/hostenv/hostenv.go | 1 - libs/agent/agent_notice.go | 25 +++++++++++-------- libs/agent/agent_notice_test.go | 17 +++++++------ 15 files changed, 55 insertions(+), 37 deletions(-) diff --git a/acceptance/acceptance_test.go b/acceptance/acceptance_test.go index 664964eb30b..30ac05c799e 100644 --- a/acceptance/acceptance_test.go +++ b/acceptance/acceptance_test.go @@ -298,6 +298,10 @@ func testAccept(t *testing.T, inprocessMode bool, selectedTests []string, skipTo // so a host value would add skill/ pairs to recorded user agents. os.Unsetenv("DATABRICKS_SKILLS_INVOKED") //nolint:usetesting // t.Setenv cannot unset + // DATABRICKS_NOT_AN_AGENT hides the calling agent from the CLI. A host value would drop the nudges + // that the goldens expect, so the acceptance run starts without it. + os.Unsetenv("DATABRICKS_NOT_AN_AGENT") //nolint:usetesting // t.Setenv cannot unset + if !requirePrerequisites(t) { // Don't run the suite against a stale toolchain; the failed subtest // has already marked the parent test as failed. diff --git a/acceptance/cmd/aitools/not-an-agent/output.txt b/acceptance/cmd/aitools/not-an-agent/output.txt index 4f78bce4dda..1341e458b31 100644 --- a/acceptance/cmd/aitools/not-an-agent/output.txt +++ b/acceptance/cmd/aitools/not-an-agent/output.txt @@ -19,6 +19,11 @@ Coding agents: run `databricks skills list` to find skills for the commands you >>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] jobs list +=== Without the variable, the hint still shows on the same session + +>>> CLAUDECODE=1 [CLI] jobs list +Before you work with Databricks, run: databricks skills list + === With the variable set, the help has no skills footer >>> DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 [CLI] fs --help diff --git a/acceptance/cmd/aitools/not-an-agent/script b/acceptance/cmd/aitools/not-an-agent/script index a54cb074465..ac5dc98e3d8 100644 --- a/acceptance/cmd/aitools/not-an-agent/script +++ b/acceptance/cmd/aitools/not-an-agent/script @@ -21,6 +21,10 @@ export CLAUDE_CODE_SESSION_ID=session-2 title "With the variable set, no hint is printed" trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI jobs list +# The same session without the variable still gets the hint, so the run above wrote no throttle marker. +title "Without the variable, the hint still shows on the same session" +trace CLAUDECODE=1 $CLI jobs list + title "With the variable set, the help has no skills footer" trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI fs --help | tail -n 3 trace DATABRICKS_NOT_AN_AGENT=1 CLAUDECODE=1 $CLI --help | tail -n 2 diff --git a/bundle/config/mutator/validate_git_details.go b/bundle/config/mutator/validate_git_details.go index d6e2f471327..bb25a198093 100644 --- a/bundle/config/mutator/validate_git_details.go +++ b/bundle/config/mutator/validate_git_details.go @@ -25,7 +25,7 @@ func (m *validateGitDetails) Apply(ctx context.Context, b *bundle.Bundle) diag.D if b.Config.Bundle.Git.Branch != b.Config.Bundle.Git.ActualBranch && !b.Config.Bundle.Force { return diag.Errorf("not on the right Git branch:\n expected according to configuration: %s\n actual: %s\nTo deploy from this branch anyway, use --force. Note that this may push unexpected code to the target.%s", - b.Config.Bundle.Git.Branch, b.Config.Bundle.Git.ActualBranch, agent.AgentNotice(ctx)) + b.Config.Bundle.Git.Branch, b.Config.Bundle.Git.ActualBranch, agent.AgentNotice()) } return nil } diff --git a/bundle/deploy/check_dashboards_modified_remotely.go b/bundle/deploy/check_dashboards_modified_remotely.go index 8e30a9d9e1d..d685f7ebeb6 100644 --- a/bundle/deploy/check_dashboards_modified_remotely.go +++ b/bundle/deploy/check_dashboards_modified_remotely.go @@ -108,7 +108,7 @@ func (l *checkDashboardsModifiedRemotely) Apply(ctx context.Context, b *bundle.B "before proceeding with the deployment.\n" + "\n" + "To overwrite the remote changes with your local version, use --force.\n" + - "The remote modifications will be lost." + agent.AgentNotice(ctx), + "The remote modifications will be lost." + agent.AgentNotice(), Paths: []*structpath.PathNode{path}, Locations: []diag.Location{loc}, }) diff --git a/bundle/phases/bind.go b/bundle/phases/bind.go index 639d46ec0c0..8f19f67a7fa 100644 --- a/bundle/phases/bind.go +++ b/bundle/phases/bind.go @@ -90,7 +90,7 @@ func Bind(ctx context.Context, b *bundle.Bundle, opts *BindOptions, stateDesc *s if !cmdio.IsPromptSupported(ctx) { result.Cancel() - logdiag.LogError(ctx, fmt.Errorf("this bind operation requires user confirmation, but the current console does not support prompting.\nTo proceed, use --auto-approve after reviewing the plan above.%s", agent.AgentNotice(ctx))) + logdiag.LogError(ctx, fmt.Errorf("this bind operation requires user confirmation, but the current console does not support prompting.\nTo proceed, use --auto-approve after reviewing the plan above.%s", agent.AgentNotice())) return } diff --git a/bundle/phases/deploy.go b/bundle/phases/deploy.go index 1f9bd08a0d9..a8e523b49ca 100644 --- a/bundle/phases/deploy.go +++ b/bundle/phases/deploy.go @@ -52,7 +52,7 @@ func approvalForDeploy(ctx context.Context, b *bundle.Bundle, plan *deployplan.P if !cmdio.IsPromptSupported(ctx) { return false, errors.New("the deployment requires destructive actions, but the current console does not support prompting.\n" + DataLossWarning + "\n" + - "To proceed, use --auto-approve after reviewing the plan above." + agent.AgentNotice(ctx)) + "To proceed, use --auto-approve after reviewing the plan above." + agent.AgentNotice()) } cmdio.LogString(ctx, "") diff --git a/cmd/auth/login_device_code.go b/cmd/auth/login_device_code.go index fc4ac34435a..819c11424d1 100644 --- a/cmd/auth/login_device_code.go +++ b/cmd/auth/login_device_code.go @@ -210,7 +210,7 @@ func (l nonInteractiveDeviceCodeLogin) start(ctx context.Context) error { return fmt.Errorf("store pending login: %w", err) } agentNote := deviceCodeAgentNote + "Ask the user for the confirmation code their browser shows." - cmdio.LogString(ctx, strings.Join(append(approvalInstructions(ctx, *da, agentNote), + cmdio.LogString(ctx, strings.Join(append(approvalInstructions(*da, agentNote), "Once finished, complete the login by running the same command with", "--user-code "+formatCode(da.UserCode)+" and --confirmation-code set to the confirmation code", "provided in your browser.", @@ -262,7 +262,7 @@ func (l nonInteractiveDeviceCodeLogin) complete(ctx context.Context, userCode, c err = fmt.Errorf("%w. Check the confirmation code and approve the login if you haven't, then rerun this command. %s if it still fails", err, startNewLoginHint) // The agent runs this step, so the error above is addressed to it. // Only the user may approve the login. - if note := agent.AgentNote(ctx, "ask the user to check the confirmation code\n"+ + if note := agent.AgentNote("ask the user to check the confirmation code\n" + "and to approve the login if they haven't. Do not approve it yourself"); note != "" { err = fmt.Errorf("%w\n\n%s", err, note) } @@ -314,7 +314,7 @@ func promptForConfirmationCode(ctx context.Context, da u2m.DeviceAuthorization, if lastErr == nil { agentNote := deviceCodeAgentNote + "Ask the user for the confirmation code their browser shows, and enter it\n" + `at the "Confirmation code" prompt of this command.` - cmdio.LogString(ctx, strings.Join(append(approvalInstructions(ctx, da, agentNote), + cmdio.LogString(ctx, strings.Join(append(approvalInstructions(da, agentNote), "Once finished, enter the confirmation code provided in your browser.", ), "\n")) } else { @@ -339,7 +339,7 @@ func promptForConfirmationCode(ctx context.Context, da u2m.DeviceAuthorization, // the login. Both flows print them before saying how to complete the login. // An AI agent also gets a note to pass the login on to the user, whether or // not it runs the command in a terminal. -func approvalInstructions(ctx context.Context, da u2m.DeviceAuthorization, agentNote string) []string { +func approvalInstructions(da u2m.DeviceAuthorization, agentNote string) []string { lines := []string{ "Using a browser on another device, visit:", da.VerificationURI, @@ -348,7 +348,7 @@ func approvalInstructions(ctx context.Context, da u2m.DeviceAuthorization, agent formatCode(da.UserCode), "", } - if note := agent.AgentNote(ctx, agentNote); note != "" { + if note := agent.AgentNote(agentNote); note != "" { lines = append(lines, note, "") } return lines diff --git a/cmd/bundle/utils/destroy.go b/cmd/bundle/utils/destroy.go index bb803c0f890..61326ef0837 100644 --- a/cmd/bundle/utils/destroy.go +++ b/cmd/bundle/utils/destroy.go @@ -21,7 +21,7 @@ func CommandBundleDestroy(cmd *cobra.Command, args []string, autoApprove, forceD return errors.New("this command will destroy all resources deployed by this bundle, " + "including workspace files in the deployment directory.\n" + phases.DataLossWarning + "\n" + - "To proceed, use --auto-approve." + agent.AgentNotice(cmd.Context())) + "To proceed, use --auto-approve." + agent.AgentNotice()) } // Check if context is already initialized (e.g., when called from apps delete override) diff --git a/cmd/feedback/feedback.go b/cmd/feedback/feedback.go index 4c3ccaa8f15..b8aaa296344 100644 --- a/cmd/feedback/feedback.go +++ b/cmd/feedback/feedback.go @@ -111,7 +111,7 @@ the reference ID.` if err != nil { return err } - if cmd.Flags().Changed(legacyConfirmationFlag) && !opts.yes && agent.Provider(cmd.Context()) != "" { + if cmd.Flags().Changed(legacyConfirmationFlag) && !opts.yes && useragent.AgentProvider() != "" { return errors.New("feedback was not sent because --yes=false") } cmd.SetContext(root.SkipLoadBundle(cmd.Context())) diff --git a/cmd/quickstart/quickstart.go b/cmd/quickstart/quickstart.go index 63c1a0bd15b..2cd6b1bf5b3 100644 --- a/cmd/quickstart/quickstart.go +++ b/cmd/quickstart/quickstart.go @@ -74,14 +74,14 @@ denser, agent-oriented version instead.` } } -// quickstartFor returns the quickstart text for the caller. Interactive -// terminals (people), and every caller under DATABRICKS_NOT_AN_AGENT, get the -// friendly guide; non-interactive callers (coding agents, scripts, CI) get the +// quickstartFor returns the quickstart text for the caller. A human guide goes +// to interactive terminals (people) and to every caller under +// DATABRICKS_NOT_AN_AGENT; other callers (coding agents, scripts, CI) get the // agent-oriented version. The detection is intentionally simple for now and can // grow more precise later. skillsVariant selects the agent text that points at // `databricks skills`. -func quickstartFor(interactive, skillsVariant bool) string { - if interactive { +func quickstartFor(humanGuide, skillsVariant bool) string { + if humanGuide { return strings.TrimRight(humanQuickstart, "\n") } return stripFrontmatter(variantText(agentQuickstart, skillsVariant)) diff --git a/cmd/quickstart/quickstart_test.go b/cmd/quickstart/quickstart_test.go index 3644c232a52..b48db671cbc 100644 --- a/cmd/quickstart/quickstart_test.go +++ b/cmd/quickstart/quickstart_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/env" "github.com/spf13/cobra" @@ -123,7 +124,8 @@ func TestQuickstartVariantSelectedByEnv(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - ctx := cmdio.MockDiscard(t.Context()) + // An exported DATABRICKS_NOT_AN_AGENT would print the human guide, so pin it off. + ctx := env.Set(cmdio.MockDiscard(t.Context()), agent.NotAnAgentEnv, "") if c.set { ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.value) } diff --git a/internal/testutil/hostenv/hostenv.go b/internal/testutil/hostenv/hostenv.go index febc2f637a9..3646bce7266 100644 --- a/internal/testutil/hostenv/hostenv.go +++ b/internal/testutil/hostenv/hostenv.go @@ -41,7 +41,6 @@ var hostAgentEnv = []string{ "COPILOT_CLI", "COPILOT_HOME", "CURSOR_AGENT", - "DATABRICKS_NOT_AN_AGENT", "GEMINI_CLI", "GEMINI_CLI_HOME", "GOOSE_PATH_ROOT", diff --git a/libs/agent/agent_notice.go b/libs/agent/agent_notice.go index 707ead27ac6..2fa4db9c677 100644 --- a/libs/agent/agent_notice.go +++ b/libs/agent/agent_notice.go @@ -9,8 +9,7 @@ import ( ) // NotAnAgentEnv makes the CLI act as if no agent calls it, for example when an eval runs a baseline arm. Agent -// detection reports no agent, so every agent-facing output is the human one, and agent tips and notes are -// suppressed too. +// detection reports no agent for the nudges and records, so they behave as for a person. const NotAnAgentEnv = "DATABRICKS_NOT_AN_AGENT" // NotAnAgent reports whether DATABRICKS_NOT_AN_AGENT is set to a true value in the context or the environment. An @@ -21,8 +20,9 @@ func NotAnAgent(ctx context.Context) bool { } // Provider returns the agent name that useragent.AgentProvider reports, or "" when no agent is detected or -// NotAnAgent holds. The CLI's own readers of the calling agent (output, telemetry, the User-Agent) go through it. -// The SDK's agent request header still reads useragent.AgentProvider directly, so NotAnAgent does not reach it. +// NotAnAgent holds. The CLI's nudges and records of the calling agent (output, telemetry, the CLI's own User-Agent +// pairs) go through it. The SDK's agent request header still reads useragent.AgentProvider directly, so NotAnAgent +// does not reach it. func Provider(ctx context.Context) string { if NotAnAgent(ctx) { return "" @@ -31,10 +31,11 @@ func Provider(ctx context.Context) string { } // AgentNotice returns a notice string to append to error messages when an AI -// agent is detected. Returns an empty string for non-agent callers. -func AgentNotice(ctx context.Context) string { - note := AgentNote(ctx, "do not retry with the flag suggested above\n"+ - "unless the user has explicitly approved it. The flag bypasses a safety check\n"+ +// agent is detected. Returns an empty string for non-agent callers. It is a +// safety note, so NotAnAgent does not drop it. +func AgentNotice() string { + note := AgentNote("do not retry with the flag suggested above\n" + + "unless the user has explicitly approved it. The flag bypasses a safety check\n" + "and the operation may be irreversible.") if note == "" { return "" @@ -43,9 +44,11 @@ func AgentNotice(ctx context.Context) string { } // AgentNote returns text as a note addressed to the detected AI agent. Returns -// an empty string for non-agent callers. -func AgentNote(ctx context.Context, text string) string { - name := Provider(ctx) +// an empty string for non-agent callers. It reads useragent.AgentProvider, not +// Provider: a note like this asks the agent not to act for the user (approve a +// login, retry with an unapproved flag), so an eval baseline keeps it. +func AgentNote(text string) string { + name := useragent.AgentProvider() if name == "" { return "" } diff --git a/libs/agent/agent_notice_test.go b/libs/agent/agent_notice_test.go index caf721c8363..97f91177083 100644 --- a/libs/agent/agent_notice_test.go +++ b/libs/agent/agent_notice_test.go @@ -10,31 +10,32 @@ import ( func TestAgentNote(t *testing.T) { testutil.SetAgent(t, "test-agent") - assert.Equal(t, "Note for AI agents (test-agent): ask the user.", AgentNote(t.Context(), "ask the user.")) + assert.Equal(t, "Note for AI agents (test-agent): ask the user.", AgentNote("ask the user.")) } func TestAgentNoteWithoutAgent(t *testing.T) { testutil.SetAgent(t, "") - assert.Empty(t, AgentNote(t.Context(), "ask the user.")) + assert.Empty(t, AgentNote("ask the user.")) } -func TestAgentNoteNotAnAgent(t *testing.T) { +// The safety notes keep the detected agent under DATABRICKS_NOT_AN_AGENT: only nudges and records drop it. +func TestAgentNoteKeepsSafetyNoteNotAnAgent(t *testing.T) { testutil.SetAgent(t, "test-agent") - ctx := env.Set(t.Context(), "DATABRICKS_NOT_AN_AGENT", "1") - assert.Empty(t, AgentNote(ctx, "ask the user.")) - assert.Empty(t, AgentNotice(ctx)) + t.Setenv(NotAnAgentEnv, "1") + assert.Equal(t, "Note for AI agents (test-agent): ask the user.", AgentNote("ask the user.")) + assert.NotEmpty(t, AgentNotice()) } func TestAgentNotice(t *testing.T) { testutil.SetAgent(t, "test-agent") assert.Equal(t, "\n\nNote for AI agents (test-agent): do not retry with the flag suggested above\n"+ "unless the user has explicitly approved it. The flag bypasses a safety check\n"+ - "and the operation may be irreversible.", AgentNotice(t.Context())) + "and the operation may be irreversible.", AgentNotice()) } func TestAgentNoticeWithoutAgent(t *testing.T) { testutil.SetAgent(t, "") - assert.Empty(t, AgentNotice(t.Context())) + assert.Empty(t, AgentNotice()) } func TestNotAnAgent(t *testing.T) { From 7065dd4cd729cffa4c0a9669ff1d781aa1723e6d Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Sat, 28 Nov 2026 09:23:56 +0000 Subject: [PATCH 7/7] aitools: keep prompt gating on the detected agent under DATABRICKS_NOT_AN_AGENT A coding agent in a pseudo-terminal must still never get a prompt that nobody answers, so the prompt gate keeps reading the detected agent. The variable now only hides the notes that say prompts were skipped, and the tests pin the terminal case for install and recommend, and the record lines for feedback and the MCP proxy. Co-authored-by: Isaac --- cmd/aitools/install.go | 14 +++++++++----- cmd/aitools/install_test.go | 13 +++++++++++++ cmd/aitools/uninstall.go | 5 ++++- cmd/feedback/feedback_test.go | 16 ++++++++++++---- libs/aitools/agents/recommend_test.go | 27 +++++++++++++++++++++++++++ libs/aitools/mcp/proxy/run_test.go | 19 +++++++++++++++++++ 6 files changed, 84 insertions(+), 10 deletions(-) diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index f1af4526fdf..dade4f2e2be 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -19,6 +19,7 @@ import ( "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/log" "github.com/databricks/cli/libs/telemetry/protos" + "github.com/databricks/databricks-sdk-go/useragent" "github.com/spf13/cobra" ) @@ -53,9 +54,11 @@ var errNoAgentsSelected = errors.New("at least one agent must be selected") // variables: // https://github.com/databricks/databricks-sdk-go/blob/main/useragent/agent.go // An agent caller always gets the documented non-interactive behavior, as a -// run without a terminal does. +// run without a terminal does. DATABRICKS_NOT_AN_AGENT does not change this +// gate: a prompt that no one answers would block the agent, so it is a safety +// check, not a nudge. func promptsSupported(ctx context.Context) bool { - return cmdio.IsPromptSupported(ctx) && agent.Provider(ctx) == "" + return cmdio.IsPromptSupported(ctx) && useragent.AgentProvider() == "" } // noPromptsNote says that prompts were skipped because the caller is a coding @@ -75,9 +78,10 @@ func noPromptsNote(ctx context.Context) string { // have run on a terminal: a person may be at it with an agent env var // inherited from an agent session, and the note says why the prompt they // expect is gone. Without a terminal nothing is printed: no caller is shown -// prompts there. +// prompts there. Under DATABRICKS_NOT_AN_AGENT the note is a nudge, so it is +// left out; the prompt is still skipped. func logSkippedPromptNote(ctx context.Context) { - if cmdio.IsPromptSupported(ctx) && !promptsSupported(ctx) { + if cmdio.IsPromptSupported(ctx) && !promptsSupported(ctx) && !agent.NotAnAgent(ctx) { cmdio.LogString(ctx, noPromptsNote(ctx)) } } @@ -322,7 +326,7 @@ Supported agents: ` + strings.Join(agents.SupportedNames(), ", "), // A person may be at this terminal with an agent env var inherited // from an agent session, so say why the prompts they would expect // were skipped. - if !interactive && cmdio.IsPromptSupported(ctx) { + if !interactive && cmdio.IsPromptSupported(ctx) && !agent.NotAnAgent(ctx) { var missing []string if scope == "" { missing = append(missing, "--scope") diff --git a/cmd/aitools/install_test.go b/cmd/aitools/install_test.go index f4c7eff22c5..edef0b4c1bb 100644 --- a/cmd/aitools/install_test.go +++ b/cmd/aitools/install_test.go @@ -2129,6 +2129,19 @@ func TestInstallAgentCallerInPTYNeverPrompts(t *testing.T) { assert.Equal(t, installer.ScopeGlobal, (*skills)[0].opts.Scope) } +// DATABRICKS_NOT_AN_AGENT drops the note but not the skipped prompts: the agent in the pseudo-terminal still +// never gets a picker or a scope prompt. +func TestInstallAgentCallerInPTYNotAnAgentStillNeverPrompts(t *testing.T) { + _, _, scopePrompted := setupAgentCallerInstall(t, "CURSOR_AGENT", "1", "DATABRICKS_NOT_AN_AGENT", "1") + + ctx, stderr := runInstallWithStderr(t, true) + assert.NotContains(t, stderr, "No prompts shown") + events := funnelEvents(ctx) + require.NotEmpty(t, events) + assert.False(t, events[0].Interactive) + assert.False(t, *scopePrompted) +} + func TestInstallAgentCallerNoteNamesOnlyMissingFlags(t *testing.T) { setupAgentCallerInstall(t, "CURSOR_AGENT", "1") diff --git a/cmd/aitools/uninstall.go b/cmd/aitools/uninstall.go index 440c65946ec..93c5d56cdad 100644 --- a/cmd/aitools/uninstall.go +++ b/cmd/aitools/uninstall.go @@ -7,6 +7,7 @@ import ( "slices" "strings" + "github.com/databricks/cli/libs/agent" "github.com/databricks/cli/libs/aitools/autoinstall" "github.com/databricks/cli/libs/aitools/installer" "github.com/databricks/cli/libs/cmdio" @@ -122,7 +123,9 @@ The command exits with code 1 when every removal it attempts fails.`, // A coding agent on a terminal: say what is removed and why // nobody was asked to confirm it. cmdio.LogString(ctx, msg) - cmdio.LogString(ctx, noPromptsNote(ctx)) + if !agent.NotAnAgent(ctx) { + cmdio.LogString(ctx, noPromptsNote(ctx)) + } } // With something installed the run removes files and runs agent CLIs, diff --git a/cmd/feedback/feedback_test.go b/cmd/feedback/feedback_test.go index eff95d661dd..4bce5a46e9f 100644 --- a/cmd/feedback/feedback_test.go +++ b/cmd/feedback/feedback_test.go @@ -12,6 +12,7 @@ import ( "github.com/databricks/cli/internal/testutil" "github.com/databricks/cli/libs/cmdctx" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/flags" "github.com/databricks/cli/libs/telemetry" "github.com/databricks/cli/libs/telemetry/protos" @@ -177,13 +178,15 @@ func TestNewSubmission(t *testing.T) { func TestSendWithoutConfirmation(t *testing.T) { tests := []struct { - name string - agent string - terminal bool + name string + agent string + terminal bool + notAnAgent bool }{ {name: "human without a terminal"}, {name: "agent without a terminal", agent: "test-agent"}, {name: "agent with a terminal", agent: "test-agent", terminal: true}, + {name: "agent under not-an-agent", agent: "test-agent", notAnAgent: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -218,6 +221,9 @@ func TestSendWithoutConfirmation(t *testing.T) { errOut = cmdio.FakeTTY(errOut) } ctx := t.Context() + if tt.notAnAgent { + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + } ctx = cmdio.InContext(ctx, cmdio.NewIO(ctx, flags.OutputText, in, out, errOut, "", "")) ctx = cmdctx.SetWorkspaceClient(ctx, w) ctx = cmdctx.GenerateExecId(ctx) @@ -227,7 +233,9 @@ func TestSendWithoutConfirmation(t *testing.T) { require.Len(t, sent, 1) assert.Equal(t, "exact feedback", sent[0].Text) assert.False(t, sent[0].CanBeContacted) - if tt.agent != "" { + if tt.notAnAgent { + assert.NotContains(t, sent[0].UserAgent, "agent/"+tt.agent) + } else if tt.agent != "" { assert.Contains(t, sent[0].UserAgent, "agent/"+tt.agent) } assert.Empty(t, stderr.String()) diff --git a/libs/aitools/agents/recommend_test.go b/libs/aitools/agents/recommend_test.go index dfb7b66faa2..ef1c13c9145 100644 --- a/libs/aitools/agents/recommend_test.go +++ b/libs/aitools/agents/recommend_test.go @@ -136,6 +136,33 @@ func TestRecommendSkillsInstallNotAnAgent(t *testing.T) { assert.Empty(t, hintKinds(t, ctx)) } +// Under DATABRICKS_NOT_AN_AGENT a terminal still gets no install prompt. Without the guard the call would wait for +// an answer that never comes. +func TestRecommendSkillsInstallNotAnAgentNeverPrompts(t *testing.T) { + tmpDir := t.TempDir() + t.Setenv("HOME", tmpDir) + t.Setenv("USERPROFILE", tmpDir) + + origRegistry := Registry + Registry = []*Agent{agentWithConfigDir(tmpDir)} + defer func() { Registry = origRegistry }() + + ctx, testIO := cmdio.SetupTest(t.Context(), cmdio.TestOptions{PromptSupported: true}) + defer testIO.Done() + ctx = telemetry.WithNewLogger(ctx) + ctx = env.Set(ctx, "DATABRICKS_NOT_AN_AGENT", "1") + + stderr := make(chan string, 1) + go func() { + b, _ := io.ReadAll(testIO.Stderr) + stderr <- string(b) + }() + require.NoError(t, RecommendSkillsInstall(ctx, noInstalledPlugins, noopInstall)) + testIO.Done() + assert.Empty(t, <-stderr) + assert.Empty(t, hintKinds(t, ctx)) +} + // PrintSkillsTip prints the tip unless DATABRICKS_NOT_AN_AGENT is set. func TestPrintSkillsTipNotAnAgent(t *testing.T) { ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) diff --git a/libs/aitools/mcp/proxy/run_test.go b/libs/aitools/mcp/proxy/run_test.go index f4020a9d3a1..b4e485a7d5e 100644 --- a/libs/aitools/mcp/proxy/run_test.go +++ b/libs/aitools/mcp/proxy/run_test.go @@ -6,6 +6,8 @@ import ( "strings" "testing" + "github.com/databricks/cli/internal/testutil" + "github.com/databricks/cli/libs/env" "github.com/databricks/databricks-sdk-go/config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -62,6 +64,23 @@ func TestRunSendsProxyUserAgentAndRoutingHeader(t *testing.T) { assert.Equal(t, testToken, reqs[0].Header.Get("Authorization")) } +// Under DATABRICKS_NOT_AN_AGENT the proxy keeps the client name it was given but adds no detected agent to its User-Agent. +func TestRunOmitsDetectedAgentUnderNotAnAgent(t *testing.T) { + srv, fake := newFakeEndpoint(t, answerInitialize) + testutil.SetAgent(t, "claude-code") + cfg := &config.Config{Host: "https://workspace.test", WorkspaceID: "1965859176160743"} + opts, _, _ := runOptions(t, srv.URL, cfg, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`+"\n") + ctx := env.Set(t.Context(), "DATABRICKS_NOT_AN_AGENT", "1") + + require.NoError(t, Run(ctx, opts)) + + reqs := fake.requests() + require.Len(t, reqs, 1) + ua := reqs[0].Header.Get("User-Agent") + assert.Contains(t, ua, "aitools-mcp-client/claude-code") + assert.NotContains(t, ua, "agent/claude-code") +} + func TestRunOmitsRoutingHeaderWithoutWorkspaceID(t *testing.T) { srv, fake := newFakeEndpoint(t, answerInitialize) opts, _, _ := runOptions(t, srv.URL, &config.Config{Host: "https://workspace.test"}, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`+"\n")