A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Rename AI modes to notebook access levels (#11611)
Trevor Manze2b72b55c051
diff --git a/docs/guides/editor_features/ai_completion.md b/docs/guides/editor_features/ai_completion.mdindex af4e85af56..da012ffd13 100644--- a/docs/guides/editor_features/ai_completion.md+++ b/docs/guides/editor_features/ai_completion.md@@ -91,12 +91,21 @@ into your notebook.<iframe width="740" height="420" src="https://www.youtube.com/embed/4DC1E2UBwAM?si=zzrzl0VlvOU6JiZP" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" loading="lazy" allowfullscreen></iframe>-The chat panel currently supports the following modes:+Use the **Notebook access** selector to choose what the assistant can do:-- **Manual**: No tool access; the AI responds based only on the conversation and manually injected context-- **Ask**: Enables read-only [AI tools](tools.md) and [tools from added MCP Client servers](mcp.md#mcp-client) for context gathering, allowing the assistant to inspect your notebooks-- **Agent**: Enables all tools in **Ask Mode** plus additional tools to [edit notebook cells (add, remove, update) and run stale cells](tools.md#editing-agent-mode-only)-- **Code mode**: Gives the assistant access to the [notebook kernel](tools.md#code-mode) which allows the assistant to inspect the marimo runtime and manipulate the notebook in powerful ways.+- **Read only**: Read notebook code, outputs, and variable previews.+- **Suggest edits**: Read the notebook and propose cell changes for review.+- **Full access**: Read, edit, and run cells, with Python scratchpad access.++**Suggest edits** uses [cell proposals](tools.md#editing) that you can keep or discard.+**Full access** can modify the notebook directly and [execute Python in the live kernel](tools.md#full-access).++See [AI tools](tools.md) for details about notebook tools and MCP integrations.+[Web search and fetch](tools.md#web-search-and-fetch) can be enabled separately+at any notebook access level.++The `ai.mode` configuration values are `ask` for **Read only** (the default),+`agent` for **Suggest edits**, and `code_mode` for **Full access**.### Refactor existing cellsdiff --git a/docs/guides/editor_features/tools.md b/docs/guides/editor_features/tools.mdindex 793e0faaff..e2604b5422 100644--- a/docs/guides/editor_features/tools.md+++ b/docs/guides/editor_features/tools.md@@ -7,16 +7,21 @@ marimo exposes a set of tools that allow AI assistants to interact with your not## Using tools-Tool availability depends on which [chat panel mode](ai_completion.md#chat-panel) you use:+Tool availability depends on the [notebook access level](ai_completion.md#chat-panel) you choose in the chat panel:-| Mode | Marimo notebook tools |-|------|----------------------|-| **Manual** | — |-| **Ask** | Read-only inspection, data, debugging, and reference tools |-| **Agent** | All **Ask** tools plus editing tools |-| **Code mode** | Code execution tool and on-demand reference guides (see below) |+| Notebook access | Marimo notebook tools |+|-----------------|-----------------------|+| **Read only** | Read-only inspection, data, debugging, and reference tools |+| **Suggest edits** | All **Read only** notebook tools plus cell proposals for review |+| **Full access** | Python execution in the live kernel and on-demand reference guides (see below) |-External AI applications can also access the **Ask** and **Agent** notebook tools through the [marimo MCP server](mcp.md#mcp-server).+**Read only** and **Suggest edits** also enable tools from connected MCP servers. These+access levels apply to marimo's built-in notebook tools; they do not restrict+what connected MCP tools can do. Manage external tools in your+[MCP client configuration](mcp.md#mcp-client).++External AI applications can also access the inspection, data, debugging, and+reference tools through the [marimo MCP server](mcp.md#mcp-server).## Available tools@@ -50,19 +55,21 @@ External AI applications can also access the **Ask** and **Agent** notebook tool|------|-------------|| **get_marimo_rules** | Get official marimo guidelines and best practices for AI assistants. Returns the content of the marimo rules file and source URL for understanding marimo-specific conventions. |-### Editing (Agent mode only)+<span id="editing-agent-mode-only"></span>++### Editing!!! note "Availability"- These tools are only available when using the [chat panel in agent mode](ai_completion.md#chat-panel). They are not exposed through the [MCP server](mcp.md#mcp-server).+ These tools are only available when using the [chat panel with **Suggest edits** access](ai_completion.md#chat-panel). They are not exposed through the [MCP server](mcp.md#mcp-server).| Tool | Description ||------|-------------|-| **edit_notebook** | Add, remove, or update cells in the notebook. Takes cell operations and modifications as parameters. Allows the AI agent to generate diffs that modify notebook structure and content. |+| **edit_notebook** | Propose adding, removing, or updating cells. Changes appear in the notebook for the user to keep or discard. This tool does not run cells. || **run_stale_cells** | Run cells that are stale (outdated due to upstream changes). Triggers execution of affected cells to update the notebook state. |## Web search and fetch-In any chat panel mode (**Manual**, **Ask**, **Agent**, or **Code mode**), marimo can give the assistant access to web search and URL fetching. These are [provider-adaptive capabilities](https://pydantic.dev/docs/ai/core-concepts/capabilities/#provider-adaptive-tools) from [Pydantic AI](https://ai.pydantic.dev): marimo enables them automatically based on your installed packages and the model you are using.+At any notebook access level, the chat panel's **Capabilities** menu lets you enable web search and URL fetching. These are [provider-adaptive capabilities](https://pydantic.dev/docs/ai/core-concepts/capabilities/#provider-adaptive-tools) from [Pydantic AI](https://ai.pydantic.dev): marimo enables them automatically based on your installed packages and the model you are using.### How capabilities are enabled@@ -94,12 +101,15 @@ When local packages are not installed, marimo enables native tools only if yourConfigure xAI in your `marimo.toml` or through the notebook settings — see the [xAI provider guide](../configuration/llm_providers.md#xai).-## Code mode+<span id="code-mode"></span>++## Full access-!!! warning "Experimental"- Code mode gives the assistant direct access to your notebook's kernel so it can make destructive changes to your notebook.+!!! warning "Full access"+ The assistant can execute Python in your live notebook kernel and make+ destructive changes to notebook cells and runtime state without review.-Code mode is available from the chat panel mode selector. Instead of the inspection and editing tools above, the assistant uses a different toolset oriented around running Python in the live kernel:+Select **Full access** from the chat panel's **Notebook access** selector. Instead of the inspection and editing tools above, the assistant uses a different toolset oriented around running Python in the live kernel:| Tool / capability | Description ||-------------------|-------------|@@ -108,7 +118,7 @@ Code mode is available from the chat panel mode selector. Instead of the inspect| **notebook-improvements** | On-demand reference for improving, optimizing, or cleaning up an existing notebook. || **rich-representations** | On-demand reference for custom widgets, visual encodings, and interactive output. |-Code mode loads the [marimo pair](../generate_with_ai/marimo_pair.md) skill as its system prompt, so the assistant follows the same conventions as external agent CLIs paired on your notebook.+Full access loads the [marimo pair](../generate_with_ai/marimo_pair.md) skill as its system prompt, so the assistant follows the same conventions as external agent CLIs paired on your notebook.## Related documentationdiff --git a/frontend/src/components/chat/__tests__/notebook-access-selector.test.tsx b/frontend/src/components/chat/__tests__/notebook-access-selector.test.tsxnew file mode 100644index 0000000000..7bc040f885--- /dev/null+++ b/frontend/src/components/chat/__tests__/notebook-access-selector.test.tsx@@ -0,0 +1,64 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import type { CopilotMode } from "@/core/config/config-schema";+import { NotebookAccessSelector } from "../notebook-access-selector";++Element.prototype.scrollIntoView = vi.fn();++describe("NotebookAccessSelector", () => {+ it("shows legacy Manual as Read only and offers exactly three levels", async () => {+ const onValueChange = vi.fn();+ render(+ <NotebookAccessSelector value="manual" onValueChange={onValueChange} />,+ );++ fireEvent.keyDown(+ screen.getByRole("combobox", { name: "Notebook access: Read only" }),+ { key: "ArrowDown" },+ );+ const options = await screen.findAllByRole("option");+ expect(options.map((option) => option.getAttribute("data-state"))).toEqual([+ "checked",+ "unchecked",+ "unchecked",+ ]);+ expect(options.map((option) => option.textContent)).toEqual([+ "Read onlyRead notebook code, outputs, and variable previews.",+ "Suggest editsRead the notebook and propose cell changes for review.",+ "Full accessRead, edit, and run cells, with Python scratchpad access.",+ ]);+ expect(onValueChange).not.toHaveBeenCalled();+ });++ it.each<{ mode: CopilotMode; label: string }>([+ { mode: "ask", label: "Read only" },+ { mode: "agent", label: "Suggest edits" },+ { mode: "code_mode", label: "Full access" },+ ])("maps $label to the existing $mode setting", async ({ mode, label }) => {+ const onValueChange = vi.fn();+ const { rerender } = render(+ <NotebookAccessSelector value={mode} onValueChange={onValueChange} />,+ );++ expect(+ screen.getByRole("combobox", { name: `Notebook access: ${label}` }),+ ).toHaveTextContent(label);+ expect(onValueChange).not.toHaveBeenCalled();++ rerender(+ <NotebookAccessSelector+ value={mode === "ask" ? "agent" : "ask"}+ onValueChange={onValueChange}+ />,+ );+ fireEvent.keyDown(screen.getByRole("combobox"), { key: "ArrowDown" });+ const option = await screen.findByRole("option", {+ name: new RegExp(`^${label} `),+ });+ fireEvent.keyDown(option, { key: "Enter" });++ expect(onValueChange).toHaveBeenCalledExactlyOnceWith(mode);+ });+});diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex 59fd2406ce..072ee6fd48 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -13,28 +13,15 @@ import {import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";import {BotMessageSquareIcon,- HatGlasses,ArrowRightIcon,Loader2,- type LucideIcon,- MessageCircleIcon,- NotebookText,PlusIcon,SparklesIcon,SettingsIcon,- CodeIcon,} from "lucide-react";import { memo, useEffect, useRef, useState } from "react";import useEvent from "react-use-event-hook";import { Button } from "@/components/ui/button";-import {- Select,- SelectContent,- SelectGroup,- SelectItem,- SelectLabel,- SelectTrigger,-} from "@/components/ui/select";import { replaceMessagesInChat } from "@/core/ai/chat-utils";import { useAIConfigActions } from "@/core/ai/config";import { AI_SDK_UI_THROTTLE_MS } from "@/core/ai/constants";@@ -49,10 +36,7 @@ import {pendingAiPromptAtom,} from "@/core/ai/state";import type { ToolNotebookContext } from "@/core/ai/tools/base";-import {- type CopilotMode,- FRONTEND_TOOL_REGISTRY,-} from "@/core/ai/tools/registry";+import { FRONTEND_TOOL_REGISTRY } from "@/core/ai/tools/registry";import { useCellActions } from "@/core/cells/actions";import { aiAtom, aiModelConfiguredAtom } from "@/core/config/config";import { DEFAULT_AI_MODEL } from "@/core/config/config-schema";@@ -97,6 +81,7 @@ import {import { renderUIMessage } from "./chat-display";import { ChatHistoryPopover } from "./chat-history-popover";import { CapabilitiesPopover } from "./capabilities-popover";+import { NotebookAccessSelector } from "./notebook-access-selector";import {type ChatMessagePart,convertToFileUIPart,@@ -117,7 +102,7 @@ import ScrollToBottomButton from "./acp/scroll-to-bottom-button";import { useChatControllerId } from "./use-chat-controller-id";// Default mode for the AI-const DEFAULT_MODE = "manual";+const DEFAULT_MODE = "ask";const QueuedMessageDisplay = memo(({ message }: { message: QueuedUserMessage }) => {@@ -321,82 +306,17 @@ const ChatInputFooter: React.FC<ChatInputFooterProps> = memo(const { saveModeChange } = useAIConfigActions();- const modeOptions: {- value: CopilotMode;- label: string;- subtitle: string;- Icon: LucideIcon;- }[] = [- {- value: "manual",- label: "Manual",- subtitle: "Pure chat, no tool usage",- Icon: MessageCircleIcon,- },- {- value: "ask",- label: "Ask",- subtitle: "AI with access to read-only tools like documentation search",- Icon: NotebookText,- },- {- value: "agent",- label: "Agent",- subtitle: "AI with access to read and write tools",- Icon: HatGlasses,- },- {- value: "code_mode",- label: "Code Mode (beta)",- subtitle:- "AI with access to the notebook's kernel. Potentially destructive.",- Icon: CodeIcon,- },- ];-const isAttachmentSupported =PROVIDERS_THAT_SUPPORT_ATTACHMENTS.has(currentProvider);- const currentModeOption = modeOptions.find((o) => o.value === currentMode);- const CurrentModeIcon = currentModeOption?.Icon;- const CurrentModeLabel = currentModeOption?.label;-return (<TooltipProvider><div className="px-3 py-2 border-t border-border/20 flex flex-wrap items-center gap-1"><div className="flex flex-wrap items-center gap-1">- <Select value={currentMode} onValueChange={saveModeChange}>- <SelectTrigger className="h-6 text-xs border-border shadow-none! ring-0! bg-muted hover:bg-muted/30 py-0 px-2 gap-1.5 shrink-0">- {CurrentModeIcon && <CurrentModeIcon className="h-3 w-3" />}- <span className="text-nowrap">{CurrentModeLabel}</span>- </SelectTrigger>- <SelectContent>- <SelectGroup>- <SelectLabel className="text-xs uppercase tracking-wider text-muted-foreground/70 font-medium">- AI Mode- </SelectLabel>- {modeOptions.map((option) => (- <SelectItem- key={option.value}- value={option.value}- className="text-xs py-1"- >- <div className="flex items-start gap-2.5">- <span className="mt-1 text-muted-foreground">- <option.Icon className="h-3 w-3" />- </span>- <div className="flex flex-col gap-0.5">- <span className="font-semibold">{option.label}</span>- <span className="text-muted-foreground">- {option.subtitle}- </span>- </div>- </div>- </SelectItem>- ))}- </SelectGroup>- </SelectContent>- </Select>+ <NotebookAccessSelector+ value={currentMode}+ onValueChange={saveModeChange}+ /><AIModelDropdownplaceholder="Model"triggerClassName="h-6 text-xs shadow-none! ring-0! bg-muted hover:bg-muted/30 rounded-sm max-w-[200px]"diff --git a/frontend/src/components/chat/notebook-access-selector.stories.tsx b/frontend/src/components/chat/notebook-access-selector.stories.tsxnew file mode 100644index 0000000000..9f338b7559--- /dev/null+++ b/frontend/src/components/chat/notebook-access-selector.stories.tsx@@ -0,0 +1,22 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Meta, StoryObj } from "@storybook/react-vite";+import { useState } from "react";+import { NotebookAccessSelector } from "./notebook-access-selector";++const meta = {+ title: "Chat/Notebook access",+ component: NotebookAccessSelector,+ args: { value: "ask", onValueChange: () => undefined },+ render: function Render(args) {+ const [value, setValue] = useState(args.value);+ return <NotebookAccessSelector value={value} onValueChange={setValue} />;+ },+} satisfies Meta<typeof NotebookAccessSelector>;++export default meta;+type Story = StoryObj<typeof meta>;++export const ReadOnly: Story = { args: { value: "ask" } };+export const SuggestEdits: Story = { args: { value: "agent" } };+export const FullAccess: Story = { args: { value: "code_mode" } };diff --git a/frontend/src/components/chat/notebook-access-selector.tsx b/frontend/src/components/chat/notebook-access-selector.tsxnew file mode 100644index 0000000000..19dcf708ff--- /dev/null+++ b/frontend/src/components/chat/notebook-access-selector.tsx@@ -0,0 +1,100 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ EyeIcon,+ type LucideIcon,+ PencilIcon,+ TerminalIcon,+} from "lucide-react";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+} from "@/components/ui/select";+import type { CopilotMode } from "@/core/config/config-schema";++const ACCESS_LEVELS = {+ ask: {+ label: "Read only",+ description: "Read notebook code, outputs, and variable previews.",+ Icon: EyeIcon,+ },+ agent: {+ label: "Suggest edits",+ description: "Read the notebook and propose cell changes for review.",+ Icon: PencilIcon,+ },+ code_mode: {+ label: "Full access",+ description: "Read, edit, and run cells, with Python scratchpad access.",+ Icon: TerminalIcon,+ },+} satisfies Record<+ Exclude<CopilotMode, "manual">,+ { label: string; description: string; Icon: LucideIcon }+>;++const ACCESS_MODES = ["ask", "agent", "code_mode"] as const;++interface NotebookAccessSelectorProps {+ value: CopilotMode;+ onValueChange: (value: CopilotMode) => void;+}++export const NotebookAccessSelector = ({+ value,+ onValueChange,+}: NotebookAccessSelectorProps) => {+ const mode = value === "manual" ? "ask" : value;+ const selected = ACCESS_LEVELS[mode];++ return (+ <Select+ value={mode}+ onValueChange={(value) => {+ const mode = ACCESS_MODES.find((mode) => mode === value);+ if (mode) {+ onValueChange(mode);+ }+ }}+ >+ <SelectTrigger+ aria-label={`Notebook access: ${selected.label}`}+ title={`Notebook access: ${selected.description}`}+ className="h-6 text-xs border-border shadow-none! ring-0! bg-muted hover:bg-muted/30 py-0 px-2 gap-1.5 shrink-0"+ >+ <selected.Icon className="h-3 w-3" />+ <span className="text-nowrap">{selected.label}</span>+ </SelectTrigger>+ <SelectContent className="max-w-[calc(100vw-2rem)]">+ <SelectGroup>+ <SelectLabel className="text-xs uppercase tracking-wider text-muted-foreground/70 font-medium">+ Notebook access+ </SelectLabel>+ {ACCESS_MODES.map((mode) => {+ const { label, description, Icon } = ACCESS_LEVELS[mode];+ return (+ <SelectItem+ key={mode}+ value={mode}+ textValue={label}+ className="text-xs py-1"+ >+ <div className="flex items-start gap-2.5">+ <Icon className="h-3 w-3 mt-1 shrink-0 text-muted-foreground" />+ <div className="flex flex-col gap-0.5">+ <span className="font-semibold">{label}</span>+ <span className="text-muted-foreground">{description}</span>+ </div>+ </div>+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ );+};diff --git a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.tsindex 6a4f50cb29..e186e0d7b6 100644--- a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts+++ b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts@@ -100,7 +100,7 @@ describe("EditNotebookTool", () => {it("should have correct metadata", () => {expect(tool.name).toBe("edit_notebook_tool");expect(tool.description).toBeDefined();- expect(tool.description.baseDescription).toContain("editing operations");+ expect(tool.description.baseDescription).toContain("Propose cell edits");expect(tool.schema).toBeDefined();expect(tool.outputSchema).toBeDefined();expect(tool.mode).toEqual(["agent"]);diff --git a/frontend/src/core/ai/tools/edit-notebook-tool.ts b/frontend/src/core/ai/tools/edit-notebook-tool.tsindex 2e7f1133ad..c7539bea9e 100644--- a/frontend/src/core/ai/tools/edit-notebook-tool.ts+++ b/frontend/src/core/ai/tools/edit-notebook-tool.ts@@ -21,7 +21,7 @@ import type { CopilotMode } from "./registry";const description: ToolDescription = {baseDescription:- "Perform editing operations on the current notebook. You should prefer to create new cells unless you need to edit existing cells. Call this tool multiple times to perform multiple edits. Separate code into logical individual cells to take advantage of the notebook's reactive execution model.",+ "Propose cell edits for the user to review in the current notebook. You should prefer to create new cells unless you need to edit existing cells. Call this tool multiple times to perform multiple edits. Separate code into logical individual cells to take advantage of the notebook's reactive execution model.",prerequisites: ["If you are updating existing cells, you need the cellIds. If they are not known, call the lightweight_cell_map_tool to find out.",],diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex f667f6bd63..02f2e2859d 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -16,6 +16,11 @@ import {UserConfigSchema,} from "../config-schema";+test("legacy Manual config resolves to Read only", () => {+ const config = UserConfigSchema.parse({ ai: { mode: "manual" } });+ expect(config).toEqual(UserConfigSchema.parse({ ai: { mode: "ask" } }));+});+test("default AppConfig", () => {const defaultConfig = AppConfigSchema.parse({});expect(defaultConfig).toMatchInlineSnapshot(`@@ -51,7 +56,7 @@ test("default UserConfig - empty", () => {"custom_providers": {},"enabled": true,"inline_tooltip": false,- "mode": "manual",+ "mode": "ask","models": {"custom_models": [],"displayed_models": [],@@ -128,7 +133,7 @@ test("default UserConfig - one level", () => {"custom_providers": {},"enabled": true,"inline_tooltip": false,- "mode": "manual",+ "mode": "ask","models": {"custom_models": [],"displayed_models": [],diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex 3d447912c7..47317db787 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -170,7 +170,10 @@ export const UserConfigSchema = zenabled: z.boolean().prefault(true),rules: z.string().prefault(""),max_tokens: z.number().int().positive().nullable().optional(),- mode: z.enum(COPILOT_MODES).prefault("manual"),+ mode: z+ .enum(COPILOT_MODES)+ .transform((mode) => (mode === "manual" ? "ask" : mode))+ .prefault("ask"),inline_tooltip: z.boolean().prefault(false),allow_provider_config: z.boolean().prefault(true),open_ai: AiConfigSchema.optional(),diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 1346385dbd..c7b69e84cf 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -306,7 +306,7 @@ class AiConfig(TypedDict, total=False):- `enabled`: if `False`, hide AI actions and panels in the marimo UI- `rules`: custom rules to include in all AI completion prompts- `max_tokens`: the maximum number of tokens to use in AI completions- - `mode`: the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`+ - `mode`: notebook access for the built-in assistant: `"ask"` (read only), `"agent"` (suggest edits), or `"code_mode"` (full access). Defaults to `"ask"`.- `inline_tooltip`: if `True`, enable inline AI tooltip suggestions- `allow_provider_config`: if `False`, lock provider setup in the settings UI, making them read-only. Users cannot bring their own credentials or add custom providers. Default `True`.- `models`: the models to use for AI completionsdiff --git a/marimo/_config/config_schema.py b/marimo/_config/config_schema.pyindex 26e4b4cd2d..ee4fb49e42 100644--- a/marimo/_config/config_schema.py+++ b/marimo/_config/config_schema.py@@ -388,7 +388,7 @@ class AiConfig(Config, kw_only=True):mode: Annotated[CopilotMode | UnsetType,Meta(- description='the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`'+ description='notebook access for the built-in assistant: `"ask"` (read only), `"agent"` (suggest edits), or `"code_mode"` (full access). Defaults to `"ask"`.'),] = UNSETinline_tooltip: Annotated[diff --git a/marimo/_server/ai/config.py b/marimo/_server/ai/config.pyindex 990f9a550b..7c2fa65df9 100644--- a/marimo/_server/ai/config.py+++ b/marimo/_server/ai/config.py@@ -263,7 +263,7 @@ class AnyProviderConfig:"ca_bundle_path": ca_bundle_path,"client_pem": ai_config.get("client_pem", None),"extra_headers": ai_config.get("extra_headers", None),- "tools": _get_tools(config.get("mode", "manual")),+ "tools": _get_tools(config.get("mode", "ask")),}return AnyProviderConfig(**kwargs)@@ -289,7 +289,7 @@ class AnyProviderConfig:return cls(base_url=_get_base_url(ai_config),api_key=key,- tools=_get_tools(config.get("mode", "manual")),+ tools=_get_tools(config.get("mode", "ask")),)@classmethod@@ -314,7 +314,7 @@ class AnyProviderConfig:base_url=_get_base_url(ai_config),api_key=key,ssl_verify=True,- tools=_get_tools(config.get("mode", "manual")),+ tools=_get_tools(config.get("mode", "ask")),)@classmethod@@ -324,7 +324,7 @@ class AnyProviderConfig:return cls(base_url=_get_base_url(ai_config, "Bedrock"),api_key=key,- tools=_get_tools(config.get("mode", "manual")),+ tools=_get_tools(config.get("mode", "ask")),)@classmethoddiff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.pyindex 9b5c8511e2..cde6b5c293 100644--- a/marimo/_server/ai/prompts.py+++ b/marimo/_server/ai/prompts.py@@ -221,32 +221,23 @@ def _get_mode_intro_message(mode: CopilotMode) -> str:"You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.\n""Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.\n")- if mode == "manual":+ if mode == "manual" or mode == "ask":return (f"{base_intro}""## Capabilities\n"- "- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.\n"- "\n"- "## Limitations\n"- "- You do NOT have access to any external tools, plugins, or APIs.\n"- "- You may not perform any actions beyond generating text and code suggestions.\n"- )- elif mode == "ask":- return (- f"{base_intro}"- "## Capabilities\n"- "- You can use a set of read-only tools to gather additional context from the notebook or environment (e.g., searching code, summarizing data, or reading documentation).\n"+ "- You can use marimo's built-in notebook tools to gather additional context (e.g., searching code, summarizing data, or reading documentation).\n""- You may use these tools ONLY to gather information, not to modify code or state.\n"+ "- Connected MCP tools are configured separately and are not restricted by this notebook access level.\n""\n""## Limitations\n"- "- All tool use is strictly read-only. You may not perform write, edit, or execution actions.\n"+ "- Notebook access is read-only. You may not modify notebook code or state, or execute notebook code.\n""- You must always explain to the user why you are using a tool before invoking it.\n")elif mode == "agent":return (f"{base_intro}"- "You are in agent mode - you have autonomy to resolve the user's query by using the tools provided. Please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. \n"- "\n\n## Agent Mode\n"+ "You have Suggest edits access - you have autonomy to resolve the user's query by using the tools provided. Please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.\n"+ "\n\n## Suggest edits\n""- You are encouraged to edit existing cells in the notebook or add new cells.\n""- You should do the following things after editing the notebook:\n""\t 1. Use the lint notebook tool to check for errors and lint issues\n"@@ -262,7 +253,7 @@ def _get_mode_intro_message(mode: CopilotMode) -> str:elif mode == "code_mode":return (f"{base_intro}"- "You are in code mode - you have access to the notebook's kernel and can execute code."+ "You have full notebook access: you can read, edit, and run cells, and execute Python in the live kernel scratchpad.")diff --git a/marimo/_server/ai/tools/tool_manager.py b/marimo/_server/ai/tools/tool_manager.pyindex de02fe7a0f..bbc80a1aba 100644--- a/marimo/_server/ai/tools/tool_manager.py+++ b/marimo/_server/ai/tools/tool_manager.py@@ -82,6 +82,8 @@ class ToolManager:Returns:A list of tool definitions available for the given mode."""+ if mode == "manual":+ mode = "ask"all_tools = self._get_all_tools()return [tool for tool in all_tools if mode in tool.mode]diff --git a/marimo/_server/api/endpoints/ai.py b/marimo/_server/api/endpoints/ai.pyindex 1ed4241398..eb0fad82ab 100644--- a/marimo/_server/api/endpoints/ai.py+++ b/marimo/_server/api/endpoints/ai.py@@ -234,7 +234,9 @@ async def ai_chat(ai_config = get_ai_config(config)custom_rules = ai_config.get("rules", None)- mode: CopilotMode = ai_config.get("mode", "manual")+ mode: CopilotMode = ai_config.get("mode", "ask")+ if mode == "manual":+ mode = "ask"system_prompt = get_chat_system_prompt(custom_rules=custom_rules,include_other_code=body.include_other_code,@@ -265,6 +267,8 @@ async def ai_chat()enable_capabilities = body.options.web_search+ # TODO: Unify these paths behind one toolset with different access levels.+ # Full access should use our Pair MCP scoped to this notebook.if mode == "code_mode":return await provider.stream_completion_harness(messages=body.ui_messages,diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex bb235a3298..54648b26a9 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -3763,7 +3763,7 @@ export interface components {* - `enabled`: if `False`, hide AI actions and panels in the marimo UI* - `rules`: custom rules to include in all AI completion prompts* - `max_tokens`: the maximum number of tokens to use in AI completions- * - `mode`: the mode to use for AI completions. Can be one of: `"ask"` or `"manual"`+ * - `mode`: notebook access for the built-in assistant: `"ask"` (read only), `"agent"` (suggest edits), or `"code_mode"` (full access). Defaults to `"ask"`.* - `inline_tooltip`: if `True`, enable inline AI tooltip suggestions* - `allow_provider_config`: if `False`, lock provider setup in the settings UI, making them read-only. Users cannot bring their own credentials or add custom providers. Default `True`.* - `models`: the models to use for AI completionsdiff --git a/tests/_server/ai/snapshots/chat_system_prompts.txt b/tests/_server/ai/snapshots/chat_system_prompts.txtindex 94dc236ac1..8e2145d676 100644--- a/tests/_server/ai/snapshots/chat_system_prompts.txt+++ b/tests/_server/ai/snapshots/chat_system_prompts.txt@@ -6,11 +6,13 @@You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.## Capabilities-- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.+- You can use marimo's built-in notebook tools to gather additional context (e.g., searching code, summarizing data, or reading documentation).+- You may use these tools ONLY to gather information, not to modify code or state.+- Connected MCP tools are configured separately and are not restricted by this notebook access level.## Limitations-- You do NOT have access to any external tools, plugins, or APIs.-- You may not perform any actions beyond generating text and code suggestions.+- Notebook access is read-only. You may not modify notebook code or state, or execute notebook code.+- You must always explain to the user why you are using a tool before invoking it.Current notebook session ID: s_test. Use this session_id with tools that require it.@@ -153,11 +155,13 @@ chartYou are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.## Capabilities-- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.+- You can use marimo's built-in notebook tools to gather additional context (e.g., searching code, summarizing data, or reading documentation).+- You may use these tools ONLY to gather information, not to modify code or state.+- Connected MCP tools are configured separately and are not restricted by this notebook access level.## Limitations-- You do NOT have access to any external tools, plugins, or APIs.-- You may not perform any actions beyond generating text and code suggestions.+- Notebook access is read-only. You may not modify notebook code or state, or execute notebook code.+- You must always explain to the user why you are using a tool before invoking it.Current notebook session ID: s_test. Use this session_id with tools that require it.@@ -303,11 +307,13 @@ Always be polite.You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.## Capabilities-- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.+- You can use marimo's built-in notebook tools to gather additional context (e.g., searching code, summarizing data, or reading documentation).+- You may use these tools ONLY to gather information, not to modify code or state.+- Connected MCP tools are configured separately and are not restricted by this notebook access level.## Limitations-- You do NOT have access to any external tools, plugins, or APIs.-- You may not perform any actions beyond generating text and code suggestions.+- Notebook access is read-only. You may not modify notebook code or state, or execute notebook code.+- You must always explain to the user why you are using a tool before invoking it.Current notebook session ID: s_test. Use this session_id with tools that require it.@@ -449,15 +455,15 @@ import pandas as pdimport numpy as np</code_from_other_cells>-==================== with agent mode ====================+==================== with suggested edits ====================You are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.-You are in agent mode - you have autonomy to resolve the user's query by using the tools provided. Please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.+You have Suggest edits access - you have autonomy to resolve the user's query by using the tools provided. Please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.-## Agent Mode+## Suggest edits- You are encouraged to edit existing cells in the notebook or add new cells.- You should do the following things after editing the notebook:1. Use the lint notebook tool to check for errors and lint issues@@ -619,11 +625,13 @@ For sql cells, use `mo.sql(f"""{content}""")`. If a database engine is specifiedYou are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.## Capabilities-- Answer questions and provide guidance using only your internal knowledge and the notebook context provided by the user.+- You can use marimo's built-in notebook tools to gather additional context (e.g., searching code, summarizing data, or reading documentation).+- You may use these tools ONLY to gather information, not to modify code or state.+- Connected MCP tools are configured separately and are not restricted by this notebook access level.## Limitations-- You do NOT have access to any external tools, plugins, or APIs.-- You may not perform any actions beyond generating text and code suggestions.+- Notebook access is read-only. You may not modify notebook code or state, or execute notebook code.+- You must always explain to the user why you are using a tool before invoking it.Current notebook session ID: s_test. Use this session_id with tools that require it.diff --git a/tests/_server/ai/test_prompts.py b/tests/_server/ai/test_prompts.pyindex 05060c097b..e7677934e0 100644--- a/tests/_server/ai/test_prompts.py+++ b/tests/_server/ai/test_prompts.py@@ -220,13 +220,24 @@ def test_edit_inline_prompts():assert FIM_SUFFIX_TAG in result+def test_legacy_manual_uses_read_only_prompt():+ kwargs = {+ "custom_rules": None,+ "include_other_code": "",+ "session_id": SessionId("s_test"),+ }+ assert get_chat_system_prompt(+ mode="manual", **kwargs+ ) == get_chat_system_prompt(mode="ask", **kwargs)++def test_chat_system_prompts():result: str = ""result += _header("no custom rules")result += get_chat_system_prompt(custom_rules=None,include_other_code="",- mode="manual",+ mode="ask",session_id=SessionId("s_test"), # stable fake session id for snapshot)@@ -234,7 +245,7 @@ def test_chat_system_prompts():result += get_chat_system_prompt(custom_rules="Always be polite.",include_other_code="",- mode="manual",+ mode="ask",session_id=SessionId("s_test"),)@@ -242,11 +253,11 @@ def test_chat_system_prompts():result += get_chat_system_prompt(custom_rules=None,include_other_code="import pandas as pd\nimport numpy as np\n",- mode="manual",+ mode="ask",session_id=SessionId("s_test"),)- result += _header("with agent mode")+ result += _header("with suggested edits")result += get_chat_system_prompt(custom_rules=None,include_other_code="",@@ -258,7 +269,7 @@ def test_chat_system_prompts():result += get_chat_system_prompt(custom_rules="Always be polite.",include_other_code="import pandas as pd\nimport numpy as np\n",- mode="manual",+ mode="ask",session_id=SessionId("s_test"),)@@ -290,7 +301,7 @@ def test_markdown_rules_include_latex():chat_prompt = get_chat_system_prompt(custom_rules=None,include_other_code="",- mode="manual",+ mode="ask",session_id=SessionId("test"),)assert "double dollar signs ($$)" in chat_prompt@@ -462,13 +473,13 @@ def test_chat_system_prompt_agent_mode_inserts_cell_rules():mode="agent",session_id=SessionId("s_test"),)- manual_prompt = get_chat_system_prompt(+ read_only_prompt = get_chat_system_prompt(custom_rules=None,include_other_code="",- mode="manual",+ mode="ask",session_id=SessionId("s_test"),)- # Agent mode adds guidance for inserting cells; manual mode does not.+ # Agent mode adds guidance for inserting cells; read-only access does not.assert "## Rules for inserting cells:" in agent_promptassert 'mo.md(f"""{content}""")' in agent_prompt- assert "## Rules for inserting cells:" not in manual_prompt+ assert "## Rules for inserting cells:" not in read_only_promptdiff --git a/tests/_server/ai/tools/test_tool_manager.py b/tests/_server/ai/tools/test_tool_manager.pyindex fa4e5e7bef..a0978b5180 100644--- a/tests/_server/ai/tools/test_tool_manager.py+++ b/tests/_server/ai/tools/test_tool_manager.py@@ -40,6 +40,12 @@ def test_get_tools_for_mode(manager: ToolManager):assert "ask" in tool.mode+def test_legacy_manual_uses_read_only_tools(manager: ToolManager):+ assert manager.get_tools_for_mode("manual") == manager.get_tools_for_mode(+ "ask"+ )++async def test_invoke_tool_backend_success(manager: ToolManager):"""Test successful backend tool invocation."""diff --git a/tests/_server/api/endpoints/test_ai.py b/tests/_server/api/endpoints/test_ai.pyindex 0e20c4ed02..fb7ebad4bc 100644--- a/tests/_server/api/endpoints/test_ai.py+++ b/tests/_server/api/endpoints/test_ai.py@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom starlette.exceptions import HTTPException-from marimo._config.config import MarimoConfig+from marimo._config.config import CopilotMode, MarimoConfigfrom marimo._server.ai.completion_output import (CELL_COMPLETION_DATA_TYPE,NOTEBOOK_CELLS_COMPLETION_DATA_TYPE,@@ -21,6 +21,7 @@ from marimo._server.ai.prompts import (FIM_SUFFIX_TAG,)from marimo._server.ai.tools.types import ToolCallResult+from marimo._server.ai.tracing import SpanInfofrom marimo._server.api.endpoints.ai import (get_provider_config,resolve_completion_messages,@@ -781,49 +782,64 @@ def _google_ai_config():@pytest.mark.requires("openai", "pydantic_ai")-@with_session(SESSION_ID)-@patch("marimo._server.ai.providers.OpenAIProvider.stream_completion")[email protected]("mode", [None, "manual", "ask", "agent"])def test_chat_without_code(- client: TestClient, mock_stream_completion: Any+ client: TestClient, temp_marimo_file: str, mode: CopilotMode | None) -> None:- user_config_manager = get_session_config_manager(client)+ @with_session(SESSION_ID)+ @patch("marimo._server.ai.providers.OpenAIProvider.stream_completion")+ def check_chat(client: TestClient, mock_stream_completion: Any) -> None:+ user_config_manager = get_session_config_manager(client)+ config = _openai_config()+ if mode is not None:+ config["ai"]["mode"] = mode- # Create a mock StreamingResponse- from starlette.responses import StreamingResponse+ # Create a mock StreamingResponse+ from starlette.responses import StreamingResponse- async def mock_stream():- yield b"Hello, how can I help you?"+ async def mock_stream():+ yield b"Hello, how can I help you?"- mock_response = StreamingResponse(- content=mock_stream(),- media_type="text/event-stream",- )- mock_stream_completion.return_value = mock_response-- with patch.object(- user_config_manager, "get_config", return_value=_openai_config()- ):- response = client.post(- "/api/ai/chat",- headers=HEADERS,- json={- "messages": _create_messages("Hello"),- "uiMessages": _create_messages("Hello"),- "model": "gpt-4-turbo",- "variables": [],- "includeOtherCode": "",- "context": {},- "id": "123",- "options": {"webSearch": True},- },- )- assert response.status_code == 200, response.text- # Verify stream_completion was called- mock_stream_completion.assert_called_once()- assert (- mock_stream_completion.call_args.kwargs["enable_capabilities"]- is True+ mock_response = StreamingResponse(+ content=mock_stream(),+ media_type="text/event-stream",)+ mock_stream_completion.return_value = mock_response++ with patch.object(+ user_config_manager, "get_config", return_value=config+ ):+ response = client.post(+ "/api/ai/chat",+ headers=HEADERS,+ json={+ "messages": _create_messages("Hello"),+ "uiMessages": _create_messages("Hello"),+ "model": "gpt-4-turbo",+ "variables": [],+ "includeOtherCode": "",+ "context": {},+ "id": "123",+ "options": {"webSearch": True},+ },+ )+ assert response.status_code == 200, response.text+ # Verify stream_completion was called+ mock_stream_completion.assert_called_once()+ assert mock_stream_completion.call_args.kwargs[+ "stream_options"+ ].span_info == SpanInfo(+ endpoint="chat",+ model="gpt-4-turbo",+ mode="agent" if mode == "agent" else "ask",+ session_id=SESSION_ID,+ )+ assert (+ mock_stream_completion.call_args.kwargs["enable_capabilities"]+ is True+ )++ check_chat(client, temp_marimo_file)@pytest.mark.requires("openai", "pydantic_ai")