---
title: "How Claude Code Works"
url: "https://romankryvolapov.com/en/claude-code-how-it-works/"
description: "Claude Code from the inside: the agent loop, the tools for reading, editing and searching, context and its compaction, memory, rules, skills, subagents, hooks, MCP and plugins, what lives in the .claude folder and on disk, permissions, the sandbox, the browser and computer use, background and cloud sessions, working on a remote machine, and a comparison with other harnesses."
language: en
published: 2026-11-19
updated: 2026-11-19
---
**Hi!**

My site already has three articles about Claude Code: [the commands and settings reference](/en/claude-code-commands-and-settings/), [a breakdown of hooks](/en/claude-code-hooks/) and [working practices](/en/claude-code-best-practices/). All three answer the question "what do I press and how do I configure it". This one answers a different question: how it works inside.

Why would you want to know that? Claude Code looks like a chat in the terminal, but behind the chat there is a fairly big machine: dozens of tools, several kinds of memory, rules, skills, subagents, hooks, permissions, a sandbox, background and cloud sessions. Until you understand how these parts fit together, the settings look like a pile of random switches. Once you do, most of them become obvious.

The article goes from simple to complex. First, what happens between your message and the reply. Then, what the agent uses to read, edit and search. Then, everything that lives in the project folder and in the home directory on disk. Then, security and isolation. And at the end, where you can run all this: from a laptop to a virtual machine on the network, and how Claude Code differs from similar tools.

Everything described here is checked against the official documentation and against version 2.1.328, which I have installed, in November 2026. Claude Code ships several times a week, so small details change fast, while the overall design changes slowly. I show paths on disk the way they look on my Windows machine, and next to them I say where the same thing is on macOS and Linux.

## Model and harness: who does what

Let's start with the main split. Claude Code has two parts, and people constantly mix them up.

The **model** is the Claude neural network on Anthropic's servers. It can do one thing: take text in and produce text out. It does not see your disk, cannot run a command, and remembers nothing between requests.

The **harness** is the `claude` program that runs on your computer. This is what you install. It reads files, runs commands, shows the interface, asks for permissions, stores the history and decides what to send to the model in each request.

The model thinks, the harness acts. They are connected through **tools**. A tool is a function the harness knows how to run: "read a file", "run a command", "find a string". The harness describes a list of tools to the model, and in its reply the model can write not plain text but a request: "call the read tool with this path". The harness carries out the request and returns the result to the model.

```text
        your computer                          Anthropic servers
┌──────────────────────────────┐            ┌────────────────────┐
│  harness (the claude program)│  request → │                    │
│                              │            │   Claude model     │
│  interface, permissions,     │  ← reply   │                    │
│  history, settings           │            └────────────────────┘
│            │                 │
│          tools               │
│  ┌─────────┬───────┬───────┐ │
│  │ files   │ shell │ web   │ │
│  └─────────┴───────┴───────┘ │
└──────────────────────────────┘
```

This diagram leads to a conclusion that will be useful many times later. Your code is not "uploaded to Claude". It stays on disk, and only what the harness put into a request goes to the servers: your messages, the files it read, the output of commands. The model has seen nothing else.

And a second conclusion. The same model behaves differently in different harnesses, because they have different tools, different system instructions, and handle context differently. I looked at how much this affects the result in the [harness comparison](/en/ai-agent-harnesses/).

## The agent loop: what happens after Enter

An ordinary chat works like this: question, answer. An agent works differently: question, many steps, answer. These steps are called the agent loop.

Let's walk through an example. You wrote: "the auth test is failing, fix it".

1. The harness assembles a request: the system instructions, the tool descriptions, the project instructions, your phrase. It sends this to the model.
2. The model replies not with text but with a tool call: "run the auth tests".
3. The harness checks whether this can be done without asking. If not, it asks you. Then it runs the command and gets the output.
4. The harness sends the model a new request: everything from before plus the test output.
5. The model sees the error and asks to find the function that failed in the code. The harness searches and returns the result.
6. The model asks to read a file. Then it asks to replace one line in it with another. Then to run the tests again.
7. The tests pass. The model replies with plain text: what was wrong and what it fixed. There are no tool calls in the reply, so the turn is over.

The documentation describes this loop as three phases: **gather context → act → verify the result**. The phases do not go strictly in turn: after each step the model decides what to do next, looking at what the previous step returned.

Three details are worth knowing.

**Every request carries the whole conversation.** The model remembers nothing between requests, so at step 6 the harness sends it everything from step 1 again. This is where the whole topic of context, compaction and cost comes from. I cover it below.

**Calls can run in parallel.** If the model needs to read five files, it asks for all five in one reply, and the harness runs them at the same time.

**You can step in at any moment.** Esc stops the current call and gives control back to you. And if you simply type a message while the agent is working, it reads it after the current calls, within the same turn. This is a handy way to correct course without interrupting the work.

## What the model sees at the start of a session

Before your first message, the request already holds quite a lot. It is important to understand exactly what, because every line there is paid for in every request and affects behavior.

| What | Where it comes from | When it is loaded |
|---|---|---|
| System prompt | built into Claude Code | always |
| Descriptions of built-in tools | built in | always |
| Environment information | working folder, OS, git branch, uncommitted changes, recent commits | always |
| Project instructions | `CLAUDE.md` files and rules not tied to paths | always |
| Auto memory | the start of the `MEMORY.md` file | always |
| Skill list | only the name and description of each | always; the body on invocation |
| MCP servers | only tool names and server instructions | always; schemas on demand |
| Output style | the chosen output style | if set |

A subtlety about project instructions. `CLAUDE.md` does not become part of the system prompt. It reaches the model as a user message right after the system prompt. That is why these are instructions the model usually follows, not hard configuration. For what must always be done without exceptions, there are hooks and permission rules: mechanisms of the harness, not of the text.

You can see what the context is made of right now with the `/context` command: it draws a grid and shows how much is taken by tools, memory, skills and the conversation itself.

## Tools: what the agent works with

There are more than thirty tools. You don't need to memorize them all, but it is useful to know the main ones by name: the same names are written in permission rules and in hooks.

| Group | Tools | Ask for permission |
|---|---|---|
| Files | `Read`, `Edit`, `Write`, `NotebookEdit` | reading: no, editing: yes |
| Search | `Grep`, `Glob`, `LSP` | no |
| Commands | `Bash`, `PowerShell`, `Monitor` | yes, except clearly safe commands |
| Web | `WebFetch`, `WebSearch` | yes |
| Agents | `Agent`, `SendMessage`, `ListAgents`, `Workflow` | mostly no |
| Planning | `EnterPlanMode`, `ExitPlanMode`, `TaskCreate` and others, `AskUserQuestion` | no |
| Extensions | `Skill`, `ToolSearch`, tools of MCP servers | depends on the skill and the server |
| Schedule | `CronCreate`, `CronList`, `CronDelete`, `ScheduleWakeup` | no |
| Worktrees | `EnterWorktree`, `ExitWorktree` | entering: yes |

Now, one by one, the tools that almost all the work is made of.

### Reading files

All the examples in this section were taken from a small demo project. It has five files: a sessions module, two API handlers, a test, and a built bundle in the `dist` folder, which is listed in `.gitignore`.

```text
demo/
├── .gitignore            node_modules/ and dist/
├── dist/bundle.js
├── src/
│   ├── auth/session.ts
│   └── api/
│       ├── login.ts
│       └── profile.ts
└── tests/session.test.ts
```

A tool call is JSON with parameters: that is exactly the form in which the model sends it, and I put the tool name above the block as a caption. A line break inside a value is written as `\n`, which is the normal JSON rule. The responses are shown as the harness returned them; long absolute paths are shortened to relative ones.

`Read` takes a file path and returns its contents. Each line has its number on the left:

```json title="Read call"
{
  "file_path": "src/auth/session.ts"
}
```

```typescript title="Read response"
1	import { db } from '../db';
2	
3	const TTL = 60 * 60;
4	
5	export function createSession(userId: string) {
6	  const token = crypto.randomUUID();
7	  db.sessions.insert({ token, userId, expiresAt: Date.now() + TTL * 1000 });
8	  return token;
9	}
10	
11	export function findSession(token: string) {
12	  const session = db.sessions.find(token);
13	  if (!session) {
14	    return null;
15	  }
16	  if (session.expiresAt < Date.now()) {
17	    return null;
18	  }
19	  return session;
20	}
```

The line numbers help the model find its way and refer to a place in the file. They are not part of the file itself, of course, and when editing, the model has to drop them.

There is no point in reading a big file in full. `Read` has two optional parameters: which line to start from and how many lines to take. This way the agent reads only the function it needs:

```json title="Read call"
{
  "file_path": "src/auth/session.ts",
  "offset": 11,
  "limit": 6
}
```

```typescript title="Read response"
11	export function findSession(token: string) {
12	  const session = db.sessions.find(token);
13	  if (!session) {
14	    return null;
15	  }
16	  if (session.expiresAt < Date.now()) {
```

Usually it looks like this: a search reports that what is needed is at line 340 of a two-thousand-line file, and the agent reads lines 320 to 380 instead of the whole file.

The limits are these. One call returns up to 25 thousand tokens. A file larger than 256 KB is not read in full unless asked explicitly: the agent gets a refusal and reads it in parts. If the file does not exist, the response is an ordinary error, and the model sees it as the result of the call:

```text languages="Read response"
File does not exist. Note: your current working directory is D:\projects\demo.
```

That hint about the working folder deserves attention. The most common cause of such an error is a relative path counted from the wrong folder. This is why the file tools require absolute paths.

`Read` reads more than text. The model will see a picture (PNG, JPEG, GIF, WebP) as an image: this is how the agent looks at screenshots and mockups. A PDF is read page by page, a Jupyter notebook cell by cell together with the output. Binary formats like `.xlsx` or `.zip` the tool will not open: for those the agent writes a small script.

### Editing: exact string replacement

This is the least obvious part, and it is worth lingering on.

The agent does not rewrite a file in full and does not create a patch in diff format. The `Edit` tool takes three things: a path, an old fragment and a new fragment. The harness finds the old fragment in the file and replaces it with the new one.

The simplest case is changing one line. A session should live for a day, not an hour:

```json title="Edit call"
{
  "file_path": "src/auth/session.ts",
  "old_string": "const TTL = 60 * 60;",
  "new_string": "const TTL = 60 * 60 * 24;"
}
```

```text languages="Edit response"
The file src/auth/session.ts has been updated successfully.
```

The response is short: the contents of the file are not returned. The model already knows what is in the file now, because it wrote the new fragment itself.

This scheme has three rules, and all three protect against silent corruption of the code. Let's go through each with an example.

**Rule one: the match is exact.** No regular expressions and no "roughly similar". Suppose the model decided from memory that the file says `const TTL = 3600;`:

```json title="Edit call"
{
  "file_path": "src/auth/session.ts",
  "old_string": "const TTL = 3600;",
  "new_string": "const TTL = 86400;"
}
```

```text languages="Edit response"
String to replace not found in file.
String: const TTL = 3600;
```

The edit was not applied and the file is untouched. The model sees the error, rereads the file and repeats the call with the real text. The same happens if even one space in the indentation differs, or a tab stands in place of spaces. This is annoying to watch from the side, but the alternative is worse: a "smart" replacement on an approximate match would sometimes hit the wrong place, and you would find out a week later.

**Rule two: the fragment must occur in the file exactly once.** In our file the line `return null;` appears twice. Let's try to replace it:

```json title="Edit call"
{
  "file_path": "src/auth/session.ts",
  "old_string": "    return null;",
  "new_string": "    return undefined;"
}
```

```text languages="Edit response"
Found 2 matches of the string to replace, but replace_all is false.
To replace all occurrences, set replace_all to true. To replace only one
occurrence, please provide more context to uniquely identify the instance.
String:     return null;
```

The harness did not guess which of the two places was meant. The model then has two ways forward.

If it needs one specific place, it takes more of the surrounding code into `old_string`, enough to make the fragment unique. For example, suppose an expired session must be deleted before returning. The model captures the line `return null;` together with the condition above it:

```json title="Edit call"
{
  "file_path": "src/auth/session.ts",
  "old_string": "  if (session.expiresAt < Date.now()) {\n    return null;",
  "new_string": "  if (session.expiresAt < Date.now()) {\n    db.sessions.delete(token);\n    return null;"
}
```

Now the two-line fragment occurs once in the file, and the edit goes through. Notice that `new_string` repeats the unchanged lines: the tool does not "insert a line", it replaces one piece of text with another.

If all occurrences are needed, for example when renaming a variable within a file, the model sets a flag:

```json title="Edit call"
{
  "file_path": "src/auth/session.ts",
  "old_string": "session",
  "new_string": "userSession",
  "replace_all": true
}
```

Here the catch is visible too: such a replacement will also hit `db.sessions`, turning it into `db.userSessions`. The replacement is textual and knows nothing about the language's syntax. That is why, for renames across a whole project, the agent usually reaches for a language server tool instead of a text replacement.

**Rule three: read first, then edit.** At first this was strict: an edit to a file that had not been read in this conversation was rejected. The point is that the model should edit what is really on disk, not what it thinks is there. For the newest models the requirement is relaxed: if the contents are already known, from search output or from a `cat` command, a separate read is not required. On older models it is always required, and for Jupyter notebooks and for files that were read only partially, on any model.

One more protection follows from this. If the file changed on disk between the read and the edit, because you saved it in your editor or a formatter ran, the fragment from `old_string` may no longer be found, and the edit will honestly fail with a "not found" error instead of overwriting your changes.

**Several edits in one file** are several calls in a row. Each next one works with the already changed file. So the model takes care that the second edit does not look for text the first one has just replaced.

Why not diff. The diff format requires the model to count line numbers exactly, and models make mistakes in counting. The "find this text" replacement needs no numbers at all, and an error in it is always loud: either the fragment was found exactly once, or there is no edit.

#### Creating and overwriting: Write

`Write` takes a path and the full contents. If the file does not exist, it is created together with any missing folders. If it exists, it is overwritten completely.

```json title="Write call"
{
  "file_path": "src/auth/cleanup.ts",
  "content": "import { db } from '../db';\n\nexport function removeExpired() {\n  db.sessions.deleteWhere((s) => s.expiresAt < Date.now());\n}\n"
}
```

You cannot append to the end of a file with this tool: it always puts down the whole text. That is why `Edit` is almost always chosen for changing an existing file, and there are two reasons. First, cost: to change one line in a thousand-line file through `Write`, the model would have to type out all thousand lines again. Second, risk: while retyping a big file, the model can quietly lose or "improve" a piece it was not asked to touch. `Edit` physically cannot change anything except the named fragment.

`Write` stays for two cases: a new file, and a full rewrite when almost nothing is left of the old contents.

#### Deleting, renaming, moving

There are no separate tools for this. The agent can delete a file, rename it or move it to another folder only with a shell command: `rm`, `mv`, `git mv`. This matters for two reasons. Such actions go through the permissions for commands, not for edits. And rollback by checkpoints does not see them; more on that in the section about rollback.

#### What you see in the interface

The harness shows every edit as a familiar diff: removed lines in red, added lines in green. In Manual mode there is a question under it with three options: apply, apply and stop asking about edits in this session, or refuse and explain to the agent what is wrong. Refusing with an explanation is a normal working tool: the agent gets your text as the result of the call and does it differently.

If an IDE with the extension is open, the diff is shown in the editor window instead of the terminal.

And before every edit, the harness saves the previous version of the file; more on that in the section about rollback.

### Search: there is no index

Many people expect the agent to "index the project" on first launch: to build an embedding database or a code graph, as some editors do. Claude Code does not do that. It has no persistent index.

Instead, the agent searches the way a person would in a terminal, only faster and more persistently:

There are two search tools: one looks for files by name, the other by content.

**`Glob` is search by name.** It takes a path pattern and returns a list of files:

```json title="Glob call"
{
  "pattern": "**/*.ts"
}
```

```text languages="Glob response"
src/auth/session.ts
src/api/login.ts
src/api/profile.ts
tests/session.test.ts
```

Two asterisks mean "any nesting depth". The result is sorted by modification time, and at most a hundred files are returned. Typical patterns: `src/**/*.test.ts` for all tests, `**/package.json` for all packages of a monorepo, `**/*config*` for everything that looks like configuration.

**`Grep` is search by content.** It takes a regular expression. Inside, it is ripgrep, a very fast search utility. It has three modes, and the agent picks them in turn, from cheap to detailed.

The first mode is file names only. It is on by default and costs almost nothing in tokens. The question "where is this function used at all":

```json title="Grep call"
{
  "pattern": "findSession"
}
```

```text languages="Grep response"
Found 3 files
tests/session.test.ts
src/api/profile.ts
src/auth/session.ts
```

Note that the `dist` folder holds a bundle where this word is also present, but it did not make it into the results. The folder is listed in `.gitignore`, and `Grep` skips ignored files.

The second mode is the lines themselves, with numbers and neighboring lines for context. Here the search is also narrowed with a pattern: only source files, no tests. The parenthesis in the pattern is escaped because this is a regular expression:

```json title="Grep call"
{
  "pattern": "findSession\\(",
  "glob": "src/**/*.ts",
  "output_mode": "content",
  "-C": 1
}
```

```text languages="Grep response"
src/api/profile.ts-3-export function profile(token: string) {
src/api/profile.ts:4:  const session = findSession(token);
src/api/profile.ts-5-  return session ? { userId: session.userId } : null;
--
src/auth/session.ts-10-
src/auth/session.ts:11:export function findSession(token: string) {
src/auth/session.ts-12-  const session = db.sessions.find(token);
```

A line with colons is a match, lines with hyphens are the context around it. The parameter `-C: 1` means one line before and one after. This is often enough to understand the place without opening the file.

The third mode is the count. The question "how many times does this occur":

```json title="Grep call"
{
  "pattern": "return null",
  "output_mode": "count"
}
```

```text languages="Grep response"
src/auth/session.ts:2

Found 2 total occurrences across 1 file.
```

This is how the agent gauges the scale before starting work: fixing two places is one thing, fixing two hundred is another.

Then the agent reads what it found and, if needed, searches again, more precisely. On a real task this is a chain of several steps: find the definition of a function → find who calls it → read the calling code → find the tests.

This approach is called agentic search. It has a cost: every search is a step of the loop and tokens. And it has advantages: there is no index that goes stale, the result always matches the disk, and none of your code goes into a third-party database.

Two details that save time when the agent "can't find the obvious":

- `Grep` skips files from `.gitignore`. `Glob` does not skip them by default. So a file in an ignored folder is found by name but not by content.
- On macOS, Linux and in WSL, the toolset has no separate `Grep` and `Glob` tools: there the agent uses the `find` and `grep` commands through the shell, and Claude Code substitutes built-in fast implementations for them. On Windows they are separate tools. The behavior is the same, only the names in the logs differ.

If you want real semantics, "find all places where this method is called" rather than "find the text", there is the `LSP` tool. It connects a language server, the same one that runs in your IDE, and gives you go to definition, find references and type errors right after an edit. It is enabled by a plugin for a specific language; more on that in the section about plugins.

### Commands: Bash and PowerShell

`Bash` runs a shell command and returns the output. The agent does everything for which there is no separate tool through it: builds, tests, git, package managers, scripts.

How it behaves:

- **Every command is a separate process.** Environment variables do not carry over from one command to the next. The working folder does carry over while you stay inside the project; if you went outside it, the next command starts from the project again.
- **Your profile is picked up.** When a session starts, Claude Code takes a snapshot of your shell (aliases, functions, settings) and applies it to commands.
- **There is a timeout.** Two minutes by default; the model can ask for up to ten.
- **Long things go to the background.** The agent starts a build or a server in the background and keeps working; when the process finishes, the harness tells it. A command that did not fit into the timeout also moves to the background by itself.
- **Output is truncated.** The model gets about 30 thousand characters right away. The rest is saved to a file, and the agent reads the pieces it needs from it. This way a megabyte-sized build log does not eat the context.

A couple of examples. Here is what the working folder rule looks like. The agent went to a temporary directory outside the project and ran a command there:

```json title="Bash call"
{
  "command": "cd /tmp/build && ls"
}
```

```text languages="Bash response"
bundle.js
Shell cwd was reset to D:\projects\demo
```

The last line was added by the harness: the command ran, but the next one will start from the project folder again. This way the agent cannot "get lost" and accidentally run `rm` in the wrong place.

And here is a background launch. A dev server does not end on its own, so there is no point in waiting for its end:

```json title="Bash call"
{
  "command": "npm run dev",
  "run_in_background": true
}
```

The harness immediately returns control and the ID of the background task. The server's output is written to a file, and the agent reads it with a plain `Read` when it needs to see what happened there. The list of background tasks is shown by the `/tasks` command; you can also stop them there.

On Windows, `Bash` is Git Bash from Git for Windows. Next to it works the `PowerShell` tool; without Git installed, it is the only shell. This causes a typical confusion: the syntax is different, and a command written for one does not work in the other.

There is also `Monitor`: it starts a command in the background and passes its output to the agent line by line as it appears. This is handy for following a log or waiting for an event without polling in a loop.

You can also run a command yourself without leaving the session: a line that starts with `!` is run in the shell, and its output goes into the conversation.

### Web

`WebSearch` returns titles and addresses from Anthropic's search backend. It does not download the pages themselves.

`WebFetch` downloads a page, but it works more cleverly than it seems. It turns the HTML into Markdown and hands it to **another, separate** request to a small model together with the question. The main agent gets the answer to the question, not the raw page. There are two points to this: a big page does not clog the context, and harmful instructions hidden in the page text do not reach the main agent directly. The flip side: this is a retelling, and it sometimes mixes up exact numbers from a table. When word-for-word accuracy is needed, the agent had better download the page with `curl`.

For sites that need a login or JavaScript, these two tools do not work. For those you need a real browser; more on the options below.

### One task from start to finish

Now let's put the tools together. A task on the same demo project: "make a session live for a day, and make expired ones get deleted from the database". Here is what the agent does, step by step.

| Step | Call | Why | What came back |
|---|---|---|---|
| 1 | `Grep` for the word `TTL` | find where the lifetime is set | one file: the sessions module |
| 2 | `Read` of that file | see the whole code, it is short | twenty lines with numbers |
| 3 | `Grep` for `findSession` | understand who the change will affect | three files: the module itself, the profile handler, the test |
| 4 | `Read` of the handler and the test, two calls at once | check what they expect from the function | both files |
| 5 | `Edit`: the `TTL` line | a day instead of an hour | "updated successfully" |
| 6 | `Edit`: the condition with the expired session | add the deletion | "updated successfully" |
| 7 | `Bash`: run the tests | check the result | test output |
| 8 | a text reply | tell what was done | — |

Here is what is worth noticing.

**The agent started with a search, not by reading everything in a row.** In a project of a thousand files it would have read three, just the same.

**Step 3 was done before the edit.** Before changing the behavior of a function, the agent found out who uses it. If the profile handler had relied on an expired session staying in the database, that would have come out here, not afterwards.

**At step 4 two calls went in one reply.** The reads do not depend on each other, and the harness ran them at the same time.

**At step 6 it had to take two lines.** A single line `return null;` is not unique in the file: this is the very case from the section about editing.

**Step 7 closes the loop.** Without it, the agent would have stopped at "looks right". With it, it stops at "the tests passed". If a test had failed, the output would have gone back to the model, and the loop would have continued: read the error, fix it, run again.

In all, eight requests to the model. And each next one carried everything before it: by the eighth, the request held both searches, three files that were read, two edits and the test output. This is what the context consists of, which is the subject of the next section.

## Context: the window, compaction and cost

The context window is the limit on the size of a single request to the model. Everything has to fit in it: the system prompt, the instructions, the whole conversation, every file that was read and the output of every command.

For current models the window is a million tokens. That is enough for hours of work, and it is hard to hit the limit. But the window still fills up, and then **compaction** kicks in: Claude Code asks the model to summarize the conversation and replaces the history with that summary. Work continues, but with a short version of the past.

What matters here is what survives compaction and what does not.

| Survives | Does not survive as is |
|---|---|
| the system prompt and the output style | the exact wording of early messages |
| the root `CLAUDE.md` and rules not tied to paths: reread from disk | rules tied to paths and `CLAUDE.md` from subfolders: they come back when the agent touches a matching file again |
| auto memory: reread from disk | the contents of files read earlier, except the last few |
| the skill list | agreements and data that exist only in the chat |
| the bodies of recently invoked skills, with a size limit | |
| background commands and subagents: they keep running | |

The practical conclusion is simple. Everything that must apply for the whole session should live in a file, not in the chat. What you said in the chat may not survive compaction; what is written into the project instructions is reread from disk.

Four commands control this: `/context` shows what the window is occupied with; `/compact` compacts right now, and you can hint at what to keep; `/clear` starts the conversation from a clean slate, with the old one staying on disk; `/autocompact` sets the threshold at which compaction turns on by itself.

Now, the cost. Since every request carries the whole conversation, a long session would be very expensive. What saves it is the **prompt cache**: the server remembers the unchanged beginning of a request, and on a repeat counts it at roughly a tenth of the price. While you work without long pauses, the cache is warm and the conversation is cheap. After a pause the cache cools down, and the next request is paid in full. Hence a piece of advice that seems odd until you know the mechanism: unrelated tasks are cheaper to do in separate sessions than in one endless one.

## Sessions: where the conversation is stored and how to roll back

A session is one conversation. The harness writes it to disk as it works, as a plain text file in JSONL format: one line is one JSON record.

It lives in the home directory, in a folder named after the project:

```text
~/.claude/projects/D--PycharmProjects-My-Site-on-Astro/
├── 4e5a5be5-….jsonl          the conversation: messages, tool calls, results
├── 4e5a5be5-…/
│   ├── subagents/            conversations of this session's subagents
│   └── tool-results/         big tool outputs that did not fit into the request
└── memory/                   the project's auto memory
```

The folder name is the project path with everything except letters and digits replaced by hyphens. This is how `D:\PycharmProjects\My_Site_on_Astro` becomes `D--PycharmProjects-My-Site-on-Astro`.

Here is what one record looks like: your message. I kept the main fields and split the line for readability; in the file it is a single line:

```json
{
  "type": "user",
  "uuid": "0b6f2c1e-…",
  "parentUuid": "9d41a7f3-…",
  "sessionId": "4e5a5be5-…",
  "timestamp": "2026-11-19T08:55:12.431Z",
  "cwd": "D:\\projects\\demo",
  "gitBranch": "master",
  "version": "2.1.328",
  "message": {
    "role": "user",
    "content": "make the session live for a day"
  }
}
```

The `parentUuid` field links the record to the previous one. Thanks to this, the conversation is not just a list but a tree: when you roll back and go another way, the old branch stays in the file and the new one grows from the same point. A record of the model's reply is built the same way, except that `message` holds blocks: thinking, text, tool calls, and next to them information about the model and the token usage.

Inside the file there are records of different types: user and assistant messages, file snapshots, a mode change, the session title. The format is internal and changes between versions, but it is plain text: you can open it and search it. And an important thing follows from this: **conversations lie on disk unencrypted**. If the agent read a file with a password, the password is now in the session file too.

Sessions are kept for 30 days and then deleted by themselves; the period is changed with the `cleanupPeriodDays` setting. To delete everything Claude Code knows about one project, use the `claude purge` command.

What you can do with sessions:

- **Continue.** `claude --continue` opens the latest session in this folder, `claude --resume` shows a list. Inside a session, `/resume` does the same.
- **Branch.** `/branch` copies the conversation into a new session from the current point, and the original does not change. Handy for trying another path.
- **Name.** `/rename` or the `--name` flag: a session is easier to find later by name.

### Rollback: checkpoints

Before every file edit, the harness saves the file's previous version. These copies live in `~/.claude/file-history/`, one folder per session. Each of your messages creates a checkpoint.

The `/rewind` command (or Esc twice on an empty line) opens the list of points. For a chosen one you can restore the code, restore the conversation, or both. There is also "compact from here": the files are not touched, and the tail of the conversation is replaced with a summary.

Rollback has a limit that you must remember. It knows only about edits made by the `Edit` and `Write` tools. What a shell command did it will not undo: a file deleted with `rm`, a database migration, a `git push`, an installed package. Edits made by subagents and your own edits in the editor are not tracked either. Checkpoints are insurance inside a session, not a replacement for git.

## The project folder: what is in `.claude`

Now, how Claude Code is configured for a specific project. Almost everything lives in the `.claude` folder at the root of the repository and is committed together with the code, so that the agent behaves the same for the whole team.

```text
project/
├── CLAUDE.md                   project instructions, read in every session
├── CLAUDE.local.md             personal instructions, not committed to git
├── .mcp.json                   the project's MCP servers
├── .worktreeinclude            which files outside git to copy into worktrees
└── .claude/
    ├── settings.json           team settings: permissions, hooks, variables
    ├── settings.local.json     personal settings, not committed to git
    ├── rules/                  rules, one file per topic
    ├── skills/<name>/SKILL.md  skills
    ├── agents/                 subagent definitions
    ├── commands/               commands in the old format
    ├── output-styles/          output styles
    ├── workflows/              saved workflows with several agents
    ├── agent-memory/           subagent memory
    ├── hooks/                  hook scripts are usually kept here
    └── worktrees/              separate worktrees for parallel sessions
```

Below is each part: what it is, when it is loaded and how it differs from its neighbors.

### Instructions: `CLAUDE.md`

`CLAUDE.md` is a text file with what the agent must know in every session: how to build the project, how to run the tests, which non-obvious conventions apply here. The `/init` command helps create the first version.

There can be several files, and they add up. The loading order is this:

| Level | Where it lives | What it is for |
|---|---|---|
| Organization | a system folder: `C:\Program Files\ClaudeCode\`, `/etc/claude-code/`, `/Library/Application Support/ClaudeCode/` | company rules, set by an administrator |
| Personal | `~/.claude/CLAUDE.md` | your habits across all projects |
| Project | `CLAUDE.md` in the root or `.claude/CLAUDE.md` | shared project rules, in git |
| Personal in the project | `CLAUDE.local.md` | your notes on this project, not in git |

Besides these, the `CLAUDE.md` files from all folders above the working one are read. And files from subfolders are loaded on demand, when the agent reads or edits something in that subfolder. In a monorepo this lets each service keep its own instructions without loading them all at once.

Inside a file you can include other files with a line `@path/to/file`. Nesting goes up to four levels.

About `AGENTS.md`. This is a common instruction format that many agents read. Claude Code reads it only if the project has no `CLAUDE.md` of its own. The behavior can be changed in settings: it can read both.

The main advice about this file is to keep it short. The documentation names a guideline of two hundred lines, and the reason is not a limit but that long instructions are followed worse.

### Rules: `.claude/rules/`

Rules are the same instructions, only laid out in files, one per topic. A rule without a header is loaded at startup, like `CLAUDE.md`.

A more interesting one is a rule with a header that lists path patterns:

```markdown title=".claude/rules/api-endpoints.md"
---
paths:
  - "src/api/**/*.ts"
---

# API rules

- Every endpoint validates its input.
- Errors are returned in the common format.
```

Such a rule gets into the context only when the agent reads or touches a matching file. This way the rules for the database do not take up space while the work is on the layout.

Personal rules for all projects go into `~/.claude/rules/`.

### Auto memory

Instructions and rules are written by you. Auto memory is written by the agent itself. These are notes about what it learned while working and what will be useful in the following sessions: what you prefer, which decision was made, where a needed dashboard is.

It is stored not in the project but in the home directory: `~/.claude/projects/<project>/memory/`. Inside there is an index file `MEMORY.md` and separate files by topic. At the start of a session only the beginning of the index, the first two hundred lines, gets into the context. The agent opens the topic files when they are needed.

The index is just a list of links, one line per note:

```markdown title="memory/MEMORY.md"
- [Tests only through the container](tests-in-docker.md) — running tests locally fails, the database from docker compose is needed
- [Monitoring dashboard](grafana-dashboard.md) — where to look at API latency after a release
```

And the note itself is a file with a short header and one fact:

```markdown title="memory/tests-in-docker.md"
---
name: tests-in-docker
description: Run integration tests only in the container, they fail locally
metadata:
  type: feedback
---

Run integration tests with the command `docker compose run tests`.

**Why:** the tests need a database of a specific version, and it is not available locally.
**How to apply:** before running tests, do not try `npm test` directly.
```

There are four types of notes: about the user, about their remarks on the work, about the project, and links to external resources. From the description in the header, the agent decides whether to open the file.

What follows from this:

- Memory is **local to the machine and to you**. A colleague will not get it, and it does not exist on another computer. Everything that everyone must know goes into the project rules.
- These are ordinary Markdown files. You can read and edit them by hand; with the `/memory` command you can view and turn them off.
- The project is identified by the git repository, so all worktrees of one repository share the memory.
- Cleanup by retention period does not touch it.

To avoid confusion, here is how the three kinds of "memory" differ:

| | Who writes it | Where it lives | Visible to the team | When it is in context |
|---|---|---|---|---|
| `CLAUDE.md` and rules | you | in the repository | yes | always, or by path pattern |
| Auto memory | the agent | in the home directory | no | the index always, topics on demand |
| Session history | the harness | in the home directory | no | only in that session |

### Skills: knowledge on demand

A skill is a folder with a `SKILL.md` file: an instruction for how to do a certain job. For example, how to ship a release or how to read data from analytics. Helper files and scripts can lie next to it.

The key idea is gradual loading. In its dormant state, a skill takes only its name and description in the context. When a task fits the description, the agent calls the `Skill` tool, and the body of the file gets into the context. The files next to it are read only if they are referenced and became necessary. So a thousand-line reference costs almost nothing as a skill, while as a rule it would cost in every session.

```markdown title=".claude/skills/release/SKILL.md"
---
name: release
description: Shipping a new version. Use when asked to cut a release or bump the version.
disable-model-invocation: true
allowed-tools: Bash(npm version *), Bash(git tag *)
---

1. Make sure the working tree is clean.
2. Bump the version: `npm version $ARGUMENTS`.
3. Build the project and run the tests.
```

What matters here:

- `description` is what the agent uses to decide whether the skill fits. The description matters more than the body: a badly described skill will not be invoked.
- `disable-model-invocation: true` forbids the agent from starting the skill itself. Only the manual invocation with the command `/release 1.4.0` remains. This is how procedures with consequences are marked.
- `$ARGUMENTS` is replaced with what you wrote after the command name.
- `allowed-tools` allows the listed tools in advance for the time the skill runs.

A skill can also be run in a separate context (`context: fork`): then it runs as a subagent and returns only the result.

Skills and slash commands are the same thing. Any skill is invoked as `/name`. The old format, files in `.claude/commands/`, still works. Skills can be personal (`~/.claude/skills/`), project ones, from plugins, and built-in: `/code-review`, `/simplify`, `/doctor`, `/loop`, `/run` and others.

There is not much room in the context for the skill list: about one percent of the window. When there are many skills, the rarely used ones keep only the name. You can see what each one costs in `/skills`.

### Subagents

A subagent is a separate instance of the agent with its own clean context. The main agent gives it a task, the subagent works in its own loop and returns one final report.

Why this is needed. Imagine the task "find out how authorization works". To answer, twenty files have to be read. If the main agent reads them, all twenty stay in its context forever. If a subagent reads them, one page of conclusions comes back to the main context, and the twenty files vanish together with the subagent.

There is a cost to this, and it is often forgotten. The subagent has not seen your conversation. It knows only what the main agent wrote in the assignment. And the main agent sees only the final report, not how the subagent got there. Details are lost at every handoff. That is why subagents are good for reconnaissance and independent pieces of work, and bad for tasks where all the accumulated context matters.

There are several built-in subagents:

| Name | What it does |
|---|---|
| `Explore` | read-only: fast search through the codebase |
| `Plan` | read-only: prepares an implementation plan |
| `general-purpose` | all tools, for multi-step tasks |
| `claude-code-guide` | answers questions about Claude Code itself |

You define your own with files in `.claude/agents/` or `~/.claude/agents/`:

```markdown title=".claude/agents/test-runner.md"
---
name: test-runner
description: Runs the tests and analyzes failures. Use after changes to the code.
tools: Read, Grep, Glob, Bash
model: haiku
---

Run the tests, find the cause of each failure and return a short list:
test, cause, file and line.
```

The body of the file is the subagent's system prompt. The header sets which tools are available to it, which model it runs on, and in which permission mode. Simple mechanical work is worth giving to a cheap model.

Useful options:

- **Background.** A subagent can work in the background while the main agent is busy with something else; the result arrives as a notification.
- **Isolation.** With `isolation: worktree`, the subagent gets its own copy of the repository and does not interfere with edits in the main one.
- **Fork.** An ordinary subagent starts from a clean slate. A fork inherits the whole conversation; it is started by `/subtask`.
- **Its own memory.** With the `memory` field, the subagent gets a notes folder that survives sessions.
- **Nesting.** A subagent can start its own subagent, up to three levels deep.

And about cost. Five subagents in parallel cost roughly five sessions. Starting them for a task of three files is not worth it.

### Hooks

Everything listed above is text that the model reads and usually follows. A hook is different: it is your code, which the harness runs by itself at a certain moment, whatever the model decides.

There are more than thirty moments you can attach a hook to: session start, sending a message, before a tool call and after it, a permission request, the end of a turn, context compaction and so on. A hook receives JSON describing the event, and it can not only do something but also influence the course of work: forbid a tool call, add text to the context, send the agent back to work.

```json title=".claude/settings.json"
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "npm run lint" }]
      }
    ]
  }
}
```

This hook runs the linter after every file edit. The model was not asked to do it: the harness does it.

The rule of choice is this: what must always happen is done with a hook, not with a line in the instructions. Formatting after an edit, a ban on touching a certain folder, a sound at the end of a turn, writing to a log. In detail, with all the events and working examples, see the [article about hooks](/en/claude-code-hooks/).

### MCP: external tools

The built-in tools are enough for working with files and the terminal. But the agent sometimes needs something else: to look into a task tracker, a database, a library's documentation. For this there is MCP (Model Context Protocol), a standard by which an external server program declares its tools and the agent calls them. How the protocol itself works I wrote about in a [separate article](/en/mcp-webmcp/).

For Claude Code, an MCP server is just one more set of tools. It is connected with a command or a file:

```json title=".mcp.json"
{
  "mcpServers": {
    "docs": {
      "type": "http",
      "url": "https://mcp.example.com/mcp"
    },
    "local-db": {
      "command": "npx",
      "args": ["-y", "example-db-mcp"],
      "env": { "DB_URL": "${DB_URL}" }
    }
  }
}
```

The first server is remote, and the agent reaches it over HTTP. The second is local: Claude Code starts it as a process itself and talks to it through standard input and output.

The same is done with commands, without editing the file by hand:

```bash
claude mcp add --transport http docs https://mcp.example.com/mcp
claude mcp add local-db -e DB_URL=postgres://localhost/app -- npx -y example-db-mcp
claude mcp add --scope project --transport http docs https://mcp.example.com/mcp
```

The first command adds a remote server. The second adds a local one: everything after the two hyphens is the command that starts it. The third differs by the `--scope` flag: it decides who will see the server.

A server's tools get names of the form `mcp__<server>__<tool>`, for example `mcp__docs__search`. Under these names they appear in permission rules and in hooks.

A server can be connected at three levels, and the level determines where the entry is stored:

| Level | Who sees it | Where it is recorded |
|---|---|---|
| local (the default) | you, in this project | `~/.claude.json`, in the project's section |
| project | the whole team | `.mcp.json` at the repository root |
| user | you, in all projects | `~/.claude.json` |

Servers from `.mcp.json` require a one-time confirmation: someone else's repository must not silently launch programs on your machine.

An important detail about context. Previously every server put the full descriptions of all its tools into the context right away, and five servers could eat tens of thousands of tokens. Now the descriptions are deferred: only the names are in the context. When a tool is needed, the agent calls `ToolSearch` and gets its full schema. So many connected servers are no longer a problem.

And one more thing: if you signed in with a claude.ai account, the connectors set up there (mail, calendar, drive) are also available in Claude Code.

### Plugins, marketplaces and mods

A plugin is a package. Skills, subagents, hooks, MCP servers, output styles, themes and executables are collected into one folder, and all of it is installed with one command. This is how settings are shared between projects and teams.

A source of plugins is called a marketplace. It is a git repository or an address with a catalog file. Anthropic's official marketplace is connected by itself on first launch. It is managed with the `/plugin` command: see what is available, install, enable, disable.

Two kinds of plugins are worth singling out.

**Language server plugins.** They give the agent the `LSP` tool mentioned in the section about search. Ready-made ones exist for a dozen and a half languages, from TypeScript and Python to Kotlin and Rust. The language server itself must be installed on the system.

**Mods.** An ordinary plugin adds knowledge and tools to the agent. A mod changes Claude Code itself: its code runs inside the program. A mod can draw a panel next to the chat or a band above the input field, add a command that runs instantly without calling the model, or step into a tool call. Mods appeared in version 2.1.287. You can write your own simply by asking the agent.

Treat mods like any program you run: a mod's code works with your rights and outside the sandbox. If something broke after installing one, `claude --safe-mode` starts a session without any settings, plugins and hooks.

### Output styles, the status line, keys

Three small interface settings.

An **output style** changes the manner of the replies. The built-in ones are: default, concise, explanatory (adds explanations of why it was done this way) and learning (leaves you pieces to do on your own). You can add your own as files in `output-styles/`.

The **status line** is the bottom line of the interface. It is drawn by your script: the harness passes it JSON with the session data, and whatever the script prints appears on the screen. People put the git branch, the model, how full the context is and the limit usage there.

**Keys** are rebound in the file `~/.claude/keybindings.json`.

## Settings: where they live and which wins

Settings are stored in `settings.json` files. There are several, and the same setting can be set in more than one. The level with the higher priority wins.

| Priority | Level | File |
|---|---|---|
| 1, highest | Organization | `managed-settings.json` in the system folder, an OS policy or settings from a server |
| 2 | Launch | the `--settings` flag |
| 3 | Personal in the project | `.claude/settings.local.json` |
| 4 | Project | `.claude/settings.json` |
| 5 | Personal | `~/.claude/settings.json` |

Lists do not override each other but add up. Permission rules from the personal file and from the project file work together.

There is one more file that is constantly confused with settings: `~/.claude.json`. It lives not in the `.claude` folder but next to it, in the home directory. It is not settings but state: which account you are signed in to, which folders you trust, personal MCP servers, hint counters, caches. Claude Code writes to it itself. There is usually no need to touch it by hand.

The third mechanism is environment variables. They set the API key, the provider, the model, timeouts. They can be set in the shell or in the `env` block of a settings file.

Two commands help check what has actually been loaded: `/status` shows the sources of settings, `/doctor` finds broken files and contradictions. The full list of keys with examples is in the [reference](/en/claude-code-commands-and-settings/).

## What lives on disk outside the project

The project is only part of the picture. Most of Claude Code's data lives in the user's home directory. On Windows it is `C:\Users\<name>\.claude`, on macOS and Linux it is `~/.claude`.

Here is what is in there. Some of the folders appear only when you start using the matching feature.

```text
~/.claude/
├── settings.json          personal settings
├── CLAUDE.md              personal instructions for all projects
├── keybindings.json       your own key combinations
├── rules/  skills/  agents/  commands/  output-styles/  workflows/  themes/
│                          personal rules, skills, subagents and so on
├── .credentials.json      account sign-in data
├── history.jsonl          history of the messages you typed
├── projects/              conversations and auto memory, one folder per project
├── file-history/          file copies for rollback
├── sessions/              a small file for every running session
├── session-env/           session environments
├── shell-snapshots/       snapshots of shell settings
├── paste-cache/           big pastes from the clipboard
├── plans/                 plans from plan mode
├── tasks/                 task lists
├── plugins/               installed plugins and marketplaces
├── daemon/  jobs/         state of background sessions
├── ide/                   connection to running IDEs
├── chrome/                bridge to the browser extension
├── debug/                 debug logs
├── backups/               copies of the ~/.claude.json file
├── cache/                 model catalog, changelog
├── agent-memory/          memory of personal subagents
└── teams/                 mailboxes of agent teams
```

Let's go through what is important to understand.

**`projects/`** is the biggest and most valuable folder. All your conversations and all the auto memory are here. On my machine it has several dozen subfolders, one for every project where I have ever started Claude Code. If you move your work to another computer, this is the one to copy.

**`.credentials.json`** is the sign-in data. On Windows and Linux it is a file protected by the access rights of the user's profile. On macOS the sign-in data is in the system keychain, and the file is used as a fallback. This file must not be committed, forwarded or shown.

**`history.jsonl`** is what you typed into the input field. The up arrow and the Ctrl+R search work from it. It is not deleted by the retention period.

**`sessions/`** holds service files of running sessions: the process number, the working folder, the name, the status. Sessions find each other through them, and Claude Code uses them to tell that a session crashed.

**`file-history/`** holds copies of files before edits. Versions are named by a hash of the path with a number: the first edit, the second, the third.

**`shell-snapshots/`** holds snapshots of the aliases and functions of your shell. Because of them the agent's commands behave like yours.

**`ide/`** holds lock files with the port the extension in VS Code or JetBrains is listening on. A terminal session finds an open editor through them.

Cleanup works like this: conversations, file copies, plans, logs and pastes are deleted when they get older than the retention period, 30 days by default. Auto memory, input history and settings are not deleted.

Now what lives outside `~/.claude`:

| What | Where on Windows | Where on macOS and Linux |
|---|---|---|
| State and personal MCP servers | `C:\Users\<name>\.claude.json` | `~/.claude.json` |
| The program itself | `C:\Users\<name>\.local\bin\claude.exe` | `~/.local/bin/claude` |
| Temporary session files | `%TEMP%\claude\<project>\<session>\` | the system temporary folder |
| Organization settings | `C:\Program Files\ClaudeCode\` | `/etc/claude-code/`, `/Library/Application Support/ClaudeCode/` |
| Bridge to the browser | `%APPDATA%\Claude Code\ChromeNativeHost` | the browser's settings folder |
| Cache | `%LOCALAPPDATA%\claude-cli-nodejs\` | the user's cache folder |

In the temporary folder every session has its own "scratch" directory. The agent puts one-off scripts and intermediate files there, so as not to litter the project.

Everything stored in `~/.claude` can be moved elsewhere with the `CLAUDE_CONFIG_DIR` variable. This is also a way to keep two accounts on one machine: each has its own configuration folder.

## Permissions: what the agent may do without asking

So far we have talked about what the agent can do. Now, about what it is allowed to do. This is a separate layer, and it works in the harness: the model can ask for anything, but the harness will carry out only what is permitted.

### Modes

The mode defines the default behavior. It is switched with Shift+Tab right during work.

| Mode | What it does without asking |
|---|---|
| Manual (`default`) | only reads; asks about edits and commands |
| `acceptEdits` | plus edits files and runs simple file commands in the working folder |
| `plan` | reads and investigates, writes a plan; does not touch the source |
| `auto` | everything, but a background classifier checks every action |
| `dontAsk` | what the rules allow; silently rejects everything else |
| `bypassPermissions` | everything without asking; deny rules stay in force |

The last mode is turned on with the `--dangerously-skip-permissions` flag, and the name is honest: it is meant for isolated environments, a container or a virtual machine with no access to anything valuable.

### Rules

On top of the mode, rules of three kinds apply: allow, ask, deny.

```json title=".claude/settings.json"
{
  "permissions": {
    "allow": ["Bash(npm run *)", "Edit(src/**)"],
    "ask": ["Bash(git push *)"],
    "deny": ["Read(./.env)", "Read(./secrets/**)"]
  }
}
```

A rule is a tool name and a refinement in parentheses. For commands it is the beginning of a command with an asterisk, for files a path pattern, for the web a domain.

Examples of rules and what they mean:

| Rule | What it covers |
|---|---|
| `Bash(npm run build)` | exactly this command |
| `Bash(npm run *)` | any command starting with `npm run` |
| `Bash(git log *)` | `git log` with any arguments, but not `git push` |
| `Edit(src/**)` | editing any files inside `src` |
| `Read(./.env)` | reading the `.env` file in the project root |
| `Read(~/.ssh/**)` | reading anything in the keys folder |
| `WebFetch(domain:docs.example.com)` | loading pages from this domain |
| `mcp__docs__*` | all tools of the MCP server `docs` |
| `Agent(Explore)` | starting the `Explore` subagent |
| `Bash` | the whole tool |

How this works in a live example. The agent wants to run `npm run test && git push origin main`. The harness splits the command into two parts. The first matches the allow rule `Bash(npm run *)`. The second matches the ask rule `Bash(git push *)`. The result: a question to you, and the whole command is visible in the question.

When you choose "don't ask again" in the dialog, the harness itself appends the rule to the project's personal settings, `.claude/settings.local.json`. You can view and clean up what has accumulated with the `/permissions` command.

Rules are checked in this order: first denies, then "ask", then allows. The first match wins, so a deny is always stronger than an allow. A deny on reading a file also works for search: such a file drops out of the results.

A few things make rules more reliable than they seem:

- A compound command is split into parts. `npm test && rm -rf build` is checked as two commands, and both must be allowed.
- Wrappers like `timeout` or `nohup` are stripped before the check.
- Redirecting output to a file is checked as an edit of that file.

And one thing because of which you must not rely on command rules as a wall: the same thing can be done in many ways. A deny on `Bash(curl *)` will not catch `/usr/bin/curl` or a Python script that makes the same request. Command denies protect against accidents, not against deliberate circumvention. The real boundary is set by the sandbox.

### Folder trust and protected paths

On the first launch in a new folder, Claude Code asks whether you trust it. This is not a formality. Project files can contain hooks and MCP servers, that is, code that will run on your machine. Until you confirm, allow rules from the project are not applied. Someone else's repository is worth looking at with your own eyes first.

In addition, there are protected paths, where writing requires confirmation even in the automatic edits mode: the `.git`, `.vscode`, `.idea`, `.claude` folders, shell settings files, `.mcp.json`. By changing them one can make arbitrary code run, so the harness guards them separately.

### Auto mode

Manual mode is safe but tiring: at the hundredth confirmation a person stops reading what they confirm. Auto mode solves this differently. There are no questions, but every action that the rules do not explicitly allow is checked by a separate classifier model.

What it sees: your messages, the tool calls and the project instructions. Tool results are not shown to it, so that text from a file or a web page that was read cannot talk it into something too.

What it blocks by default: downloading and immediately running a script from the network, sending secrets out, deploying to production, deleting data in the cloud, granting access rights, doing `git push --force` or `git reset --hard`. What it lets through: work with files in the project, installing declared dependencies, read requests, an ordinary push to a branch.

If the classifier blocked three actions in a row, auto mode pauses and the usual questions come back.

You write your own rules for the classifier as plain text in personal settings: which repositories and services to consider your own, what is always forbidden.

```json title="~/.claude/settings.json"
{
  "autoMode": {
    "environment": [
      "$defaults",
      "The example-org organization's repositories on GitHub are ours",
      "The example-staging bucket is for testing, writing to it is fine"
    ],
    "hard_deny": [
      "$defaults",
      "Any changes to the production database"
    ]
  }
}
```

These are not patterns but sentences in plain human language: the classifier model reads them. The `"$defaults"` line keeps the built-in rules; without it your list would replace them. This block is not read from project settings, otherwise someone else's repository could allow itself anything.

And the main thing to understand: auto mode saves confirmations, but Anthropic itself does not count it as a security boundary. It is an attentive observer, not a wall.

## Sandbox and isolation

Permissions decide what the agent will *ask* to do. Isolation decides what it will be *able* to do even if something goes wrong. There are several options, from light to strict.

### The sandbox for commands

The sandbox is an operating-system-level restriction on the commands the agent runs. The command and all the processes it spawns get cut-down access:

- **Writing** is allowed only to the working folder and the temporary directory.
- **Network**: there is no direct way out. All traffic goes through a local proxy that lets through only the allowed domains.
- **Reading**: by default almost the whole disk. Folders with keys have to be closed off explicitly.

```json title=".claude/settings.json"
{
  "sandbox": {
    "enabled": true,
    "network": {
      "allowedDomains": ["registry.npmjs.org", "*.githubusercontent.com"]
    },
    "filesystem": {
      "denyRead": ["~/.ssh", "~/.aws"]
    }
  }
}
```

On macOS the sandbox is built on the system mechanism Seatbelt, on Linux and in WSL2 on bubblewrap. **On Windows without WSL there is no sandbox**: commands run as usual. If you need it on Windows, run Claude Code inside WSL2.

By default the sandbox is off; you turn it on with the `/sandbox` command. It has a pleasant side effect: since a command cannot break anything outside the project, it can be run without asking. There are noticeably fewer confirmations.

What the sandbox does not cover, and you need to know this. It wraps only shell commands. The file reading and editing tools work outside it and are governed by permission rules. Local MCP servers, hooks and mods also run outside the sandbox, with your rights.

### Separate worktrees

The second job of isolation is so that parallel sessions do not interfere with each other. If two agents edit the same files in the same folder, you get a mess.

The solution is a git worktree. This is a standard git feature: a second working folder of the same repository, on its own branch. The history is shared, the files are separate.

```bash
claude --worktree feature-auth
```

The command creates a worktree in `.claude/worktrees/feature-auth/` on a new branch and starts a session in it. Background sessions and subagents with isolation do the same automatically. A worktree with no changes is deleted by itself on exit.

One practical detail: files that are not in git do not get into the new copy. If the project needs a `.env`, list it in the `.worktreeinclude` file, and it will be copied.

It is important not to confuse the two: a worktree protects your files from other agents, not the machine from the agent. This is isolation of work, not security.

### A container and a virtual machine

The most reliable isolation is to run the agent where there is nothing to break.

**A dev container.** Anthropic has a ready configuration: a container with Claude Code and a network firewall that lets through only the needed addresses. Inside, you can turn on the no-questions mode, because the agent can reach only the mounted project.

**A virtual machine.** The same, but the boundary is even harder. This option is covered in detail below, in the section about remote work.

**A cloud session.** Anthropic runs the agent on its own virtual machine. Your computer does not take part at all.

A summary to choose from:

| Method | What it protects against | What it does not cover |
|---|---|---|
| Permission rules | accidental actions | can be bypassed by another way of doing the same thing |
| Auto mode | clearly dangerous actions without questions | is not a security boundary |
| Sandbox | commands will not leave the project and the allowed domains | file tools, MCP, hooks; absent on Windows without WSL |
| Worktree | sessions do not interfere with each other | does not protect the machine |
| Container, VM | the agent does not see your system | whatever you mounted there yourself and whatever keys you gave |

## Models, effort and thinking

There is one harness, but several models behind it, and each has its knobs.

The **model** is chosen with the `/model` command or the `--model` flag. People usually write not the full identifier but the short name of a family: `fable`, `opus`, `sonnet`, `haiku`. Behind a short name there is always the newest model of the family. The senior models are smarter and more expensive, the junior ones are faster and cheaper. There is also a combined option, `opusplan`: the senior model plans, the middle one executes.

**Effort** is how much the model thinks and checks before it answers. There are five levels: `low`, `medium`, `high`, `xhigh`, `max`. Low suits small, clear edits, high is for when verification matters, and maximum is for truly hard tasks, with diminishing returns. It is set with the `/effort` command. Effort affects both speed and cost: on `max` the same task can cost several times more than on `medium`.

**Thinking** is the model's reasoning before the answer, which you see collapsed. In current models it is adaptive: the model decides where to think longer. The word `ultrathink` in a message raises the effort for that one turn.

**Fast mode** (`/fast`) is the same model, but the answer comes about two and a half times faster and costs more. Only for the senior models.

The **advisor** (`/advisor`) is a second, stronger model that the main one consults at key moments of a task. An experimental feature.

A **fallback model**: if the main one is overloaded, the session continues on the fallback. It is set with the `--fallback-model` flag.

**Ultracode** stands apart. It is not an effort level but a mode of work: for every substantial task the agent itself writes a workflow with several subagents and runs it. About workflows, see the section on how sessions interact. Token usage in this mode is noticeably higher.

The same knob exists for parts of the system. A subagent and a skill can be given their own model and their own effort in the header of the file. This way reconnaissance goes to a fast cheap model, and the main conversation is left to a strong one.

## Where Claude Code runs

The harness is one and the same engine with several faces.

| Where | What it is | Notes |
|---|---|---|
| Terminal | the `claude` program | the full set of features, where it all started |
| VS Code | an extension | edits are shown in the editor window, the agent sees the selected code |
| JetBrains | a plugin | viewing edits in the IDE, a session shared with the terminal |
| Desktop app | a program for macOS and Windows | several sessions side by side, diff viewing, a built-in browser, SSH connection |
| Web | claude.ai/code | cloud sessions, work without your computer |
| Phone | the Claude app | cloud sessions and control of sessions on your computer |
| Slack | `@Claude` in a channel | a task from a conversation goes to a cloud session |
| CI | GitHub Actions, GitLab CI/CD | started by an event, with no person |

The local surfaces share everything among themselves: settings, project instructions, MCP servers, session history. A conversation started in the terminal can be opened in the app with the `/desktop` command. Cloud sessions live separately: they have their own environment and cannot reach the files on your disk.

Installation. The main way is the native installer: one command for macOS and Linux, one for PowerShell. There are packages for Homebrew, WinGet and npm. Supported are macOS 13 and newer, Windows 10 and newer, and common Linux distributions; 4 GB of memory or more is required. A program installed this way updates itself, in the background. The update channel is selectable: the freshest or a stable one, with a delay of about a week.

On Windows there are two options. Running directly: everything works except the sandbox; it is better to install Git for Windows so the agent has Bash. Running in WSL2: this is a full Linux with all the features, including the sandbox, but without integration with the Chrome browser.

## The browser: what the options are

The agent often needs to look at the result of its work: open a page, press a button, read an error in the console. There are many ways, and it is easier to choose between them with three questions.

**Whose browser it is.** Your real one, with all your sign-ins to mail and work services, or a separate clean one, where the agent cannot reach anything of yours.

**How the agent sees the page.** There are three ways, and accuracy and token usage depend on them:

- *A screenshot.* A picture, the way a person sees it. Universal, but expensive in tokens, and hitting a button has to be done by coordinates.
- *The accessibility tree.* This is a structural description of the page, used by screen readers: button "Sign in", field "Email", link "Forgot password". The agent gets it as text where each element has a short number, and it clicks by number, not by coordinates. Cheaper and more accurate than a picture.
- *The browser's internals.* The console, network requests, styles, performance measurements: what you see in the developer tools.

**Whether a window is needed.** On a laptop there is a window. In a container, on a server and in CI there is none, and the browser has to work in a mode without an interface (headless).

A summary of all the options:

| Option | Whose browser | How it sees the page | Without a window | Made by |
|---|---|---|---|---|
| `WebFetch`, `WebSearch` | none | text as a retelling | yes | built in |
| Claude in Chrome | yours, with sign-ins | the page, screenshots, console, network | no | Anthropic |
| Desktop's built-in browser | clean, in the app | the page and screenshots | no | Anthropic |
| Playwright MCP | its own profile or your browser | accessibility tree, screenshots if wanted | yes | Microsoft |
| Playwright CLI | clean by default | accessibility tree, on request | yes, by default | Microsoft |
| Chrome DevTools MCP | its own or an already running Chrome | tree, screenshots, console, network, performance measurements | yes | the Chrome DevTools team |
| Firefox DevTools MCP | a separate Firefox profile | tree and screenshots | yes | Mozilla |
| Your own Playwright or Puppeteer script | any | whatever you write in the script | yes | you and the agent |
| A cloud browser | on the service's servers | depends on the service | yes | third-party paid services |
| Computer use | any, as a window on the screen | a screenshot | no | Anthropic |

Now, one by one.

### Built-in tools

`WebFetch` and `WebSearch` are not a browser. They are good for reading a public documentation page, and no good for anything that needs a sign-in, JavaScript or button presses. They are described above, in the section about tools.

### Claude in Chrome: your real browser

This is an extension for Chrome and Edge plus a bridge to Claude Code. It is turned on with the `claude --chrome` flag or the `/chrome` command. The agent works in a real window of your browser, in a new tab, and sees sites the way you see them: with your sign-ins to mail, control panels, trackers.

What it can do: navigate between pages, click and fill in forms, read page text, the console and network requests, take screenshots, record a GIF of the actions.

This is both its strength and its risk. The strength is that the agent can do something in a service where you already have an open session, without getting any passwords. The risk is the same thing. That is why access is granted in the extension for each site separately, and at an account sign-in and at a captcha the agent stops and waits for you.

How the connection works. The extension cannot talk to a program on the computer by itself, so on first enabling, Claude Code registers a small intermediary in the system (a native messaging host). Through it the extension and the terminal session exchange commands. On my machine it lives in `%APPDATA%\Claude Code\ChromeNativeHost`.

The limitations: a subscription and a sign-in with an account are required, it does not work with an API key; it does not work in WSL; there is no mode without a window; a system dialog with a question open on the page blocks control.

### The built-in browser of the Desktop app

The Desktop app has a browser panel next to the chat. Its profile is its own and clean, and your sign-ins are not there. It shows the project's running application and external sites, and the agent can act in it. Actions on external sites require confirmation.

For development this is calmer than the extension: the agent sees your site on a local server, but has no access to your mail.

### Playwright MCP

Playwright is Microsoft's library for browser automation; end-to-end tests are written with it. It has an MCP server that gives the agent tools for controlling a browser: open an address, click, type text, take a screenshot.

It is connected with one command:

```bash
claude mcp add playwright npx @playwright/mcp@latest
```

Or with a plugin from the official marketplace, which does the same thing:

```bash
claude plugin install playwright@claude-plugins-official
```

The main feature: by default the agent works with the accessibility tree, not a picture. It requests a snapshot of the page and gets text of roughly this form:

```yaml
- heading "Sign in" [level=1]
- textbox "Email" [ref=e12]
- textbox "Password" [ref=e13]
- button "Sign in" [ref=e15]
- link "Forgot your password?" [ref=e16]
```

Then it says "click `e15`", and the server presses exactly that button. The model does not need to guess coordinates, and noticeably fewer tokens are spent than on a picture. The coordinate mode exists too: it is turned on with the `--caps=vision` flag and is needed where the tree does not help, for example on a canvas with graphics.

What is configured with flags:

| Flag | What it does |
|---|---|
| `--browser` | which browser: Chrome, Edge, Firefox or WebKit |
| `--headless` | work without a window; by default a window is shown |
| `--isolated` | the profile lives only in memory, nothing is left after closing |
| `--user-data-dir` | your own path to the profile |
| `--storage-state` | load saved cookies into an isolated session |
| `--extension` | connect to your already open Chrome or Edge through the Playwright extension |
| `--cdp-endpoint` | connect to a browser started with a debugging port |

There is one thing to understand about the profile. By default it is persistent: the server creates its own profile folder and keeps sign-ins in it between launches. This is not your personal profile, but if you sign in to a service once in that window, the sign-in is kept. For tests that need cleanliness, `--isolated` is used.

The authors themselves warn about two things. The server is not a security boundary: allowlists of addresses do not cover redirects. And among the tools there is running arbitrary code in the browser, which is equivalent to full access to the page.

### Playwright CLI

The same Playwright has a second way, made specially for agents in the terminal: an ordinary command-line program instead of an MCP server.

```bash
npm install -g @playwright/cli@latest
playwright-cli install --skills
```

The second command installs skills for Claude Code: from them the agent learns which commands exist and how to use them. After that it simply calls the program through `Bash`:

```bash
playwright-cli open https://example.com
playwright-cli snapshot --depth=3
playwright-cli click e15
```

What differs from the MCP server. The MCP server returns the page tree after every action, and it settles in the context. The command-line program prints only what was requested: a snapshot of the needed depth, the result of an element search. The Playwright authors themselves write that for coding agents this way is more economical, and the MCP server is better where you need to explore a page for a long time while keeping state.

By default the browser here starts without a window and with a clean in-memory profile; a window is turned on with the `--headed` flag, and saving the profile with the `--persistent` flag.

### Chrome DevTools MCP

This server is made by the Chrome developer tools team. It can also click and type, but its point is different: it opens to the agent what you see in the developer panel.

- **Performance.** Record a trace of the page load and work out what slows it down.
- **Network.** The list of requests, headers and response bodies.
- **Console.** Messages and errors with a stack mapped back to the sources.
- **Styles.** Which CSS rules were actually applied to an element.
- **Audit.** A Lighthouse check.
- **Memory.** Heap snapshots for finding leaks.

It is installed as a plugin:

```bash
claude plugin marketplace add ChromeDevTools/chrome-devtools-mcp
claude plugin install chrome-devtools-mcp@chrome-devtools-plugins
```

It can start its own Chrome or connect to one that is already running. For that, Chrome is launched with a debugging port and a separate profile folder, and the address is passed to the server:

```bash
chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug
npx -y chrome-devtools-mcp@latest --browser-url http://127.0.0.1:9222
```

The choice between it and Playwright is simple. "Go through the form and check that an order is created" is Playwright. "The page loads in four seconds, find out why" is Chrome DevTools. It works only with Chrome. And by default it sends usage statistics to Google; this is turned off with the `--no-usage-statistics` flag.

### Firefox DevTools MCP

Mozilla has its own official server, still in an early version:

```bash
claude mcp add firefox-devtools npx @mozilla/firefox-devtools-mcp@latest
```

It is built similarly: a snapshot of the page with element numbers, clicking and typing by number, screenshots, a mode without a window. It is needed when a bug reproduces specifically in Firefox. The authors advise creating a separate profile for it and not connecting your main one.

For Safari I did not find a separate server. The WebKit engine, on which it is built, is available through Playwright: the `--browser webkit` flag.

### Your own script

The simplest way is often forgotten: no servers, the agent writes an ordinary Playwright or Puppeteer script and runs it through `Bash`.

```javascript title="check-login.mjs"
import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('http://localhost:3000/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByRole('button', { name: 'Sign in' }).click();
console.log(await page.getByRole('alert').textContent());
await page.screenshot({ path: 'login.png' });
await browser.close();
```

The agent runs the script, reads the printed text, and opens the screenshot with the `Read` tool and looks at it as a picture.

This way has three merits. Only what the script printed gets into the context. The script stays in the repository and turns into a test. And it works the same on a laptop, in a container and in CI. There is one drawback: it is not a dialogue with the page. Every "and what is there now" is a new run.

If the project already has end-to-end tests, this is the best way of checking: the agent adds a test and runs it. The built-in skills `/run` and `/verify` are built on the same idea: they determine the project type themselves, start the application and look at the result, and `/run-skill-generator` writes the launch recipe it found into a project skill.

### Cloud browsers and data collection services

A separate class is the services where the browser runs on someone else's servers and the agent controls it through MCP. All of them are third-party and either paid or with a limited free tier.

| Service | What it is for |
|---|---|
| Browserbase | browsers in the cloud; control by describing the action in words |
| browser-use | controls your local Chrome or the service's cloud browser |
| Firecrawl | not control but collection: a page or a whole site is turned into Markdown |
| Bright Data | data collection and a browser that gets around bot protection |

They are needed where a local browser is not enough: hundreds of pages in parallel, sites with protection against automation, a different country in the address. For checking your own application they are not needed. And remember that the pages and the data you enter then pass through a third party's servers.

### How to choose

- **Check your own site on a local server:** the Desktop built-in browser or Playwright; in a project with tests, your own script.
- **Do something in a service where you are already signed in:** Claude in Chrome. Or Playwright with the `--extension` flag.
- **Find out why a page is slow or what fails in the console:** Chrome DevTools MCP.
- **Work on a server, in a container, in CI:** Playwright CLI, Playwright MCP with `--headless`, or your own script. The Chrome extension does not work there.
- **A bug in only one browser:** Playwright with the right `--browser`, or the Mozilla server.
- **Mass data collection:** the cloud services.

Two warnings for all the options at once. The content of a page is someone else's text, and it can contain instructions addressed to the agent; the more of your sign-ins the browser has, the more a mistake costs. And every browser MCP server runs outside the sandbox, with your rights.

## Desktop and mobile apps

The browser is clear. But what if the program you need is not a website? A desktop application, a layout editor, a development environment, a phone simulator. There are several ways to reach them too, and the general principle is the same as with the browser: the narrower and more precise the tool, the better. Looking at the screen and moving the mouse is the last resort.

Claude Code itself goes through the options in this order: a ready connector or the program's MCP server → a command in the terminal → the browser → the simulator panel → screen control. Let's go through them in the same order.

### Don't touch the window: files and the command line

The most reliable way to work with a program is not to open it at all.

**Files.** A Word document, an Excel spreadsheet, a presentation are files of known formats. The agent reads and creates them with libraries, with a small script, and there are ready skills for this. The Office application is not started.

**The command line.** Many desktop programs have a mode without a window. Blender renders a scene from the command line, Android Studio builds a project through Gradle, Xcode through `xcodebuild`, Docker Desktop is controlled with the `docker` command. The `Bash` tool is enough for the agent.

### Scripting interfaces of the operating system

The next level: the program is running, but it is controlled not with the mouse but through a programming interface the system provides. The agent reaches them with ordinary shell commands.

| System | Interface | What it can do |
|---|---|---|
| Windows | PowerShell and COM | control Office applications as objects: open a workbook, fill cells, save |
| Windows | UI Automation | read the element tree of any window and click the elements; this is the interface for screen readers |
| macOS | AppleScript, JXA | send commands to applications that support scripting: Finder, Mail, Safari, Notes |
| Linux | xdotool, ydotool | imitate the keyboard and mouse, move windows |

An example for Windows. This is how the agent writes a value into an open Excel spreadsheet without seeing its window:

```powershell
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$book = $excel.Workbooks.Open("C:\reports\sales.xlsx")
$book.Sheets.Item(1).Range("B2").Value2 = 1250
$book.Save()
$excel.Quit()
```

And this is how on macOS it asks Finder to show a folder:

```bash
osascript -e 'tell application "Finder" to open folder "Documents" of home'
```

The difference from mouse control is fundamental. The command "write 1250 into cell B2" either ran or returned an error. It is not bothered by the screen resolution, a window that popped up on top, or a changed theme.

On macOS such scripts require permissions in the system settings: "Automation" for commands to applications and "Accessibility" for controlling the interface. On Linux `xdotool` works only under X11; Wayland needs `ydotool`.

### MCP servers of programs

Many programs now give agents an official entry themselves: an MCP server. This is the most convenient path: the program declares clear tools instead of making you guess where to click.

| Program | Server | What it gives |
|---|---|---|
| Figma | official, from Figma | design context, variables, screenshots, writing to the canvas |
| JetBrains IDEs | built into the IDE since version 2025.2 | build, errors in a file, running configurations, search and refactoring |
| Xcode | an official plugin from Apple | build and tests, SwiftUI previews, simulators, build logs |
| Unity | an official plugin and community servers | scenes, objects, scripts, tests |
| Blender | from the community | running Python inside Blender, rendering a scene |
| iOS, Android simulator | from the community | the screen's element tree, taps, screenshots |

Such a server is connected like any other. For example, Figma:

```bash
claude mcp add --transport http figma https://mcp.figma.com/mcp
```

With IDEs it is a separate story: besides the MCP server, JetBrains and VS Code have their own integration with Claude Code. Through it the agent sees the open file, the selected fragment and the errors the editor shows, and the edits appear in the comparison window.

There are also general-purpose servers that open the whole desktop to the agent: for Windows, a community server that reads the element tree of windows through UI Automation, clicks, types and runs PowerShell; for macOS, a server that executes AppleScript scripts. This is powerful and therefore dangerous: in essence, full access to the system. The authors themselves warn about this. Community servers should be treated like any other third-party program with such rights: look at the code, look at what it sends outside.

### Electron applications

Many desktop programs, Slack, VS Code, Discord, Notion, are written on Electron. Inside, it is a Chromium browser, and everything from the section about browsers applies to it.

If it is your own application, Playwright has Electron support, still experimental: a script starts the application, gets its windows and works with them as with pages.

```javascript title="check-app.mjs"
import { _electron as electron } from 'playwright';

const app = await electron.launch({ args: ['main.js'] });
const window = await app.firstWindow();
await window.getByRole('button', { name: 'New document' }).click();
await window.screenshot({ path: 'app.png' });
await app.close();
```

The second way is to start the application with a debugging port, the `--remote-debugging-port` flag, and connect Chrome DevTools MCP to that port the same way as to an ordinary Chrome.

### Mobile applications

**iOS.** The Desktop app on macOS has an iOS simulator panel. The agent builds the app, installs it in the simulator, taps, types text and takes screenshots. Screen control is not used for this: the panel works through Apple's standard tools, so system permissions for screen recording are not needed. It works only with the simulator, not with a real phone.

From the terminal the same is done with the `xcrun simctl` command and MCP servers for the simulator.

**Android.** Here everything rests on `adb`, the standard Android utility. Through it the agent installs a build on an emulator or a connected phone, starts a screen, reads logs, takes a screenshot, taps by coordinates:

```bash
adb install -r app/build/outputs/apk/debug/app-debug.apk
adb shell am start -n com.example.app/.MainActivity
adb logcat -d -t 200
adb exec-out screencap -p > screen.png
```

There are also MCP servers for mobile devices that give the screen's element tree instead of coordinates, the same way Playwright does for pages.

### Computer use: when nothing else fit

Computer use is when the agent works with the machine like a person: it looks at a screenshot, moves the mouse, presses keys. This way you can reach what has neither a command line nor a programming interface: an old corporate program, an equipment control panel, a proprietary tool.

Where it is available. In the Desktop app, on macOS and on Windows. In the terminal, only on macOS, turned on through `/mcp`. The feature is marked as preview and requires a personal subscription.

How it works from the security point of view:

- Access is granted per application. The agent asks for permission for a specific program, and you give it for the session.
- Applications have different levels. Browsers: view only. Terminals and code editors: view and click, but not type, since otherwise it would be full shell access bypassing all the rules. Everything else: full control.
- Only one session can work at a time. The other programs are hidden for the duration of the turn, and the terminal with Claude Code itself does not get into the screenshots.
- Esc interrupts the work from anywhere.

Why it is the last resort. It is the slowest: every action is a screenshot and a request to the model. It is the most fragile: a button moved and the agent missed. And there is no sandbox here: the agent acts on a real desktop, with your rights, and the screen content is one more channel through which someone else's text with instructions can get into it.

Next to it stands Dispatch, the ability to give a task from your phone to the Desktop app on your computer. It starts a session itself, and you get a notification when the work is done or a confirmation is needed.

### How to choose

| What you need | What to use |
|---|---|
| Create or change a document, spreadsheet, presentation | working with the file, without starting the program |
| Build, run, render | the program's command line |
| Control an Office application on Windows | PowerShell and COM |
| Commands to applications on macOS | AppleScript |
| Designs, an IDE, a game engine, a 3D editor | that program's MCP server |
| Your own Electron application | Playwright |
| An iOS application | the simulator panel in Desktop or `xcrun simctl` |
| An Android application | `adb` |
| A program with no programming entry of any kind | computer use |

## Working without a person

Everything described above is about the interactive mode, where you sit next to it. But the same engine also runs without an interface.

```bash
claude -p "Find the cause of the crash in the logs and describe it in one paragraph" --output-format json
```

The `-p` flag means: do the task, print the result and exit. The output comes in three kinds: plain text, a single JSON with the result, the cost and the session identifier, or a stream of JSON events as the work goes. You can set a schema, and then the answer comes in a strictly given structure.

What matters in this mode:

- **There is nobody to ask.** Everything that would need confirmation is rejected. The needed actions are allowed in advance: with the `--allowedTools` flag or a permission mode.
- **The folder trust dialog is not shown.** So it is worth running this way only in folders you trust.
- **There is a budget limiter**: `--max-budget-usd` stops the work when the given sum has been spent.
- **There is a "bare" mode**, `--bare`: without hooks, plugins, memory and the automatic reading of instructions. It gives a predictable result in scripts where the machine's environment must not affect the answer.

Ready integrations are built on this mode: an action for GitHub Actions and a template for GitLab CI that run the agent on an event in the repository: a new pull request, a failed build, a mention in a comment.

And if you need to embed the agent into your own program, there is the **Agent SDK** for Python and TypeScript. It is the same loop, the same tools and the same handling of context, only as a library: you call a function and get a stream of events.

## Background sessions

An interactive session occupies the terminal. If a task takes an hour and there is no need to watch it, the session can be sent to the background.

```bash
claude --bg "Update the dependencies and fix whatever breaks"
claude agents
```

The first command starts a session in the background and returns control at once. The second opens a screen with a list of all background sessions, sorted by state: waiting for your reply, working, finished. From the list you can enter any of them, look, and go back out without stopping it. A session that is already running is sent to the background by the `/background` command.

How it works inside. Background sessions are watched by a service process, a supervisor. It starts by itself, keeps the list of sessions, restarts the ones that crashed and stops the ones that have sat idle for an hour with nobody looking. Its state lives in the `daemon` and `jobs` folders of the home directory. Sessions survive the computer going to sleep, but not a reboot: after it they are marked as stopped and continue when you enter them.

So that background sessions do not get in your way or in each other's, each one moves into its own worktree of the repository before its first edit. They do not push to the main branch and do not merge anything themselves.

## How sessions and agents interact

There are now four ways to make several agents work together. They solve different problems, and it is easier to choose between them when you see them side by side.

| | Subagents | Workflows | Agent teams | Messages between sessions |
|---|---|---|---|---|
| Who manages | the main agent | a script | the lead agent | you or the agents themselves |
| Talk to each other | no, only a report to the main one | no, the script collects the results | yes, directly | yes |
| Context | each has its own, clean | each has its own | each has its own | each session has its own |
| Number | a handful | up to hundreds | several | as many sessions as are open |
| When to use | reconnaissance, an independent piece of work | big work of one kind | a task where the participants need to argue and agree | sessions that are already running must exchange information |

**Subagents** are described above: the main agent hands out tasks and gets reports. They do not talk to each other.

**Workflows** (dynamic workflows). When many subagents are needed, managing them from the conversation becomes inconvenient: every report lands in the main agent's context. A workflow solves this differently. The agent writes a small JavaScript script, and the harness executes it: it starts agents in parallel or in a chain and passes results from step to step. Intermediate results stay in the script's variables and take no context. A typical example is to check twenty files against five criteria and have every finding double-checked by a separate agent. It is started by the word `ultracode` in a message or by a request such as "use a workflow". Before launch, the harness asks for confirmation, because dozens of agents mean dozens of sessions in cost.

**Agent teams** are an experimental feature, off by default. Here the participants are more equal: there is a lead and several teammates, a shared task list and mailboxes. Teammates write to each other directly, take tasks from the shared list and mark what is done. This suits work that needs discussion: one investigates a hypothesis, another tries to refute it.

**Messages between sessions.** Ordinary independent sessions, in neighboring terminals or in the background, can also correspond. The agent sees a list of available counterparts and sends a message by session name. On one machine messages go directly, through a local channel, bypassing servers. Between machines they go through Anthropic's servers, and an account sign-in is required.

There is a protection built in here that is worth understanding. A message from another session arrives as ordinary text with a note of who it is from. It cannot confirm a permission request, change settings or run a command. Another session can ask, but not order. And in settings you can choose what to do with incoming messages: deliver, hold or reject.

## Scheduling

You can run an agent on a schedule at three levels.

**Inside a session.** The command `/loop 5m check whether the build has finished` repeats the task while the session is open. Without an interval the agent picks the pause between checks itself. This works only while the session is alive and idle.

**On your machine.** The Desktop app can run tasks on a schedule locally, with access to your files. The computer has to be turned on.

**In the cloud.** The `/schedule` command creates a task that runs on Anthropic's servers. Your computer can be off. It is started on a schedule (no more often than once an hour), by an API request or by an event in GitHub, for example when a pull request is opened.

## Remote work

The last big topic: how to work with an agent that is not where you are. There are four options, and they differ in where the code runs.

### Remote Control

The agent runs on your computer, and you control it from a phone or from a browser on another machine.

```bash
claude remote-control
```

After this command the session appears on claude.ai/code and in the phone app. From there you can write messages, watch what the agent does, confirm permissions.

How the connection works. Your computer itself connects to Anthropic's servers with an outgoing HTTPS request and waits for messages. It opens no incoming ports, and nothing needs to be forwarded. The code, the files, the tools and the MCP servers stay on your machine; only the correspondence goes through the servers: messages, replies and information about tool calls.

What it needs: a sign-in with an account with a subscription; it does not work with an API key. And the process must keep running: close the terminal and the control is gone.

### Cloud sessions

Here the agent works on Anthropic's virtual machine. Your computer is not needed at all.

```bash
claude --cloud "Add a phone number format check to the sign-up form"
```

The same is done from the claude.ai/code site and from the phone. The machine gets your repository from GitHub, the agent works in a separate branch and at the end offers a pull request.

What is worth knowing about this environment:

- **The environment is configurable.** You can set a setup script that installs the needed packages, environment variables and the level of network access: none, limited (package registries and GitHub) or full.
- **GitHub keys do not get into the machine.** They stay on Anthropic's servers, and requests to GitHub go through a proxy that adds them itself.
- **The machine falls asleep.** After several minutes of idleness it is paused; background processes are not preserved.
- **You can take a session over to your side.** The `/teleport` command moves a cloud conversation and its branch into your terminal. In the other direction, from the terminal to the cloud, a running session cannot be moved.

### Connecting over SSH from the app

In the Desktop app the list of environments has an SSH item. You give the address of a machine, the app installs Claude Code on it itself and starts a session there. The interface stays with you, while the code runs on the remote machine. Permanent connections are described in settings:

```json title="~/.claude/settings.json"
{
  "sshConfigs": [
    {
      "id": "dev-vm",
      "name": "Dev VM",
      "sshHost": "deploy@dev.example.com",
      "sshPort": 22
    }
  ]
}
```

### A virtual machine on the network: how to set one up yourself

Now a common practical case. You have your own virtual machine, in the cloud or on a local network, and you want the agent to work on it. There are usually two reasons. The first is isolation: the machine has none of your personal files and keys, and the agent can be allowed more. The second is continuity: the machine does not fall asleep along with the laptop.

Claude Code is an ordinary Linux program, so there are several ways.

**Way one: SSH and tmux.** You log in to the machine over SSH, start `tmux`, and in it `claude`. tmux is needed so that the session survives a dropped connection: you disconnect, connect again, and return to the same terminal. This is the simplest option, and it works everywhere.

**Way two: Remote Control from the machine.** On the machine, in tmux, you start `claude remote-control` and then work with it from a phone or from a browser. SSH is needed only for the first launch. No incoming ports need to be opened, because the machine connects outward by itself. `claude remote-control` has a server mode: one such command accepts several sessions, and each can be started in its own worktree of the repository.

**Way three: background sessions.** On the machine you start tasks with `claude --bg` and watch them with `claude agents`. The supervisor keeps them going without an open terminal.

**Way four: the Desktop app over SSH**, described above. Convenient if you want a graphical interface and diffs rather than a terminal.

**Way five: without an interface.** A script or a scheduler on the machine calls `claude -p` with a task. Suitable for nightly runs and processing a queue.

A question common to all the ways is how to sign in to an account on a machine with no browser. The options are:

| Sign-in method | What it gives | What it does not give |
|---|---|---|
| Normal sign-in (`/login`) | everything that is in the subscription | requires opening a link once in a browser on another device |
| A long-lived token (`claude setup-token`) | requests to the model under the subscription, convenient for scripts | Remote Control and the browser |
| An API key | requests to the model paid by tokens | everything tied to the subscription: Remote Control, cloud sessions |

And a couple of tips from practice. If the machine is dedicated to the agent, turn on the sandbox on it: this is Linux, where it works fully. Give the machine a separate access key to the repository with minimal rights, not your personal one. And remember that isolating the machine protects your system, but not whatever the machine itself can reach over the network.

For organizations there is one more option: their own environments for cloud sessions. You run an executor process on your own infrastructure, it connects to Anthropic's servers with an outgoing connection, and cloud sessions from the web interface run on your machines, inside your network. This is a beta for enterprise plans.

## Providers and local models

Where the model comes from. There are two main paths: a Claude subscription, or an API key paid by tokens. For companies there is a third: Claude models through a cloud, Amazon Bedrock, Google Cloud or Microsoft Foundry. It is chosen with an environment variable.

It is important to understand that some features are tied specifically to the subscription and Anthropic's servers. Through a cloud provider or with an API key, Remote Control, cloud sessions, the browser extension, computer use and the Desktop app do not work. The agent loop itself, the tools, memory, skills, hooks and MCP work the same everywhere.

Can Claude Code be run on someone else's or a local model? Officially, no: Anthropic does not support such a mode. Technically the API address is swapped with the `ANTHROPIC_BASE_URL` variable, and some vendors document connecting their models this way. But Claude Code's system prompt and tools are designed for Claude models, and the quality with others is noticeably lower. If you need to work on your own models, it is better to take a harness made for that.

## Limits and cost

On a subscription, usage is limited by windows: a five-hour one and a weekly one, plus separate weekly limits for the senior models. They are shared by the whole account: the terminal, the app, cloud sessions and the ordinary chat spend one quota. `/usage` shows how much is left; it also shows what exactly is using up the limit: which skills, subagents and MCP servers.

With an API key there are no window limits, and you pay for tokens. For orientation: the documentation gives an average figure of about 13 dollars per developer per active day.

From the design described above it follows directly what is expensive:

- **A long session after a pause.** The cache has cooled down, and the whole conversation is paid for again.
- **Parallel agents.** Each subagent, teammate or background session is a separate conversation with its own context.
- **High effort and a senior model** where the task does not need them.
- **Scheduled tasks.** Every run sends the full context.
- **Bloated instructions.** They are paid for in every request of every session.

## What leaves your machine

A short but important part.

**What is sent.** What goes to Anthropic's servers is what got into the request: your messages, the contents of the files that were read, the output of commands, the model's replies. Files the agent did not read are not sent anywhere.

**Training.** On personal plans, using your data to train models is a switch in the privacy settings. On enterprise plans and through the API, data is not used for training by default.

**Storage on the servers.** By default 30 days; if training is allowed on a personal plan, up to five years.

**Storage on your side.** Conversations lie in the home directory in plain text for 30 days. This is worth remembering when the agent reads files with secrets.

**Telemetry.** Usage metrics and error reports are turned off with environment variables; one variable switches off all the optional traffic at once.

**Protection against harmful instructions.** Text that the agent read on a web page, in a file or in a tool's response can contain commands addressed to it. Several layers work against this at once: permission requests, retelling of web pages by a separate model, the trust dialog for a new folder, confirmation for a project's MCP servers. No single layer gives a guarantee. That is why with untrusted content, someone else's repository or unfamiliar sites, it is wise to work in an isolated environment.

## How Claude Code differs from similar tools

All modern coding harnesses are built on one scheme: a loop, tools, project instructions, permissions. They differ in decisions of detail. Briefly about the main ones; a detailed comparison of more than forty tools is in a [separate article](/en/ai-agent-harnesses/).

| | Claude Code | Codex | Cursor | GitHub Copilot | OpenCode |
|---|---|---|---|---|---|
| Made by | Anthropic | OpenAI | Anysphere | GitHub | community, the SST team |
| Source code | closed | the CLI is open | closed | the CLI is closed, the extension is open | open |
| Main form | terminal | terminal and cloud | its own editor | editor and GitHub | terminal |
| Models | Claude only | OpenAI models | many vendors | many vendors | any, including local |
| Instructions | `CLAUDE.md`, rules by path | `AGENTS.md` | `.cursor/rules` | `copilot-instructions.md` | `AGENTS.md` |
| Code search | agentic, no index | agentic | an embedding index plus agentic | an index plus agentic | agentic |
| Sandbox | optional; absent on Windows without WSL | on by default on three OSes | on in macOS and Linux | optional | none |
| Cloud mode | yes | yes | yes | yes | no |

What follows from this in practice.

**The strengths of Claude Code** are depth of configuration and work without supervision. Four levels of instructions, rules tied to paths, skills, subagents with their own model, three dozen events for hooks, mods, workflows with dozens of agents, background and cloud sessions. Nobody else has such a set in full.

**The weaknesses** are closed code and being tied to one vendor. You can work only with Claude models, and the subscription is valid only in Anthropic's products. The sandbox is not on by default and does not work on Windows without WSL, while Codex has it on from the start and on all three systems.

**What carries over.** Files from the `.claude` folder have become something like a common format: skills, rules and hooks are partly read by Cursor, Copilot, OpenCode and others. And `AGENTS.md`, which almost everyone understands, Claude Code reads if there is no instruction file of its own. The `/import` command moves settings in the other direction, from Codex, Gemini CLI and Cursor.

## In short

- Claude Code is a harness: a program on your computer that gives the model tools and controls what the model sees. The model thinks, the harness acts.
- The work goes in a loop: the model asks to call a tool, the harness runs it and returns the result, and so on until a reply with no calls. Every request carries the whole conversation.
- A file edit is an exact replacement of a unique fragment. Search is ordinary search over files, with no index.
- The context compacts by itself. What survives compaction is what is written into files: instructions, rules, memory. What was said only in the chat can be lost.
- Knowledge is passed in three ways: instructions and rules (always in the context), skills (on demand), auto memory (written by the agent itself, stored in the home directory).
- A subagent is a separate context for a separate task. It saves the main context, but loses details in the handoff and costs as much as one more session.
- A hook is code that the harness runs itself. Everything that must always happen is done with a hook, not with a line in the instructions.
- Conversations, memory and file copies lie in `~/.claude` in plain text. The project's settings are in `.claude` in the repository.
- Permissions and auto mode protect against accidents. The real boundary is given by the sandbox, a container and a virtual machine.
- One engine works in the terminal, the editor, the app, the cloud and without an interface. On your own virtual machine it starts as an ordinary Linux program, and you can control it from a phone without opening ports.

## Sources

- [How Claude Code works](https://code.claude.com/docs/en/how-claude-code-works): the agent loop, context, sessions.
- [Tools reference](https://code.claude.com/docs/en/tools-reference): all built-in tools and their behavior.
- [Explore the context window](https://code.claude.com/docs/en/context-window): what is loaded into the context and what survives compaction.
- [Explore the .claude directory](https://code.claude.com/docs/en/claude-directory): the files of the project and the home directory.
- [Memory](https://code.claude.com/docs/en/memory), [Skills](https://code.claude.com/docs/en/skills), [Subagents](https://code.claude.com/docs/en/sub-agents), [Hooks](https://code.claude.com/docs/en/hooks), [MCP](https://code.claude.com/docs/en/mcp).
- [Permission modes](https://code.claude.com/docs/en/permission-modes), [Permissions](https://code.claude.com/docs/en/permissions), [Sandboxing](https://code.claude.com/docs/en/sandboxing), [Security](https://code.claude.com/docs/en/security), [Data usage](https://code.claude.com/docs/en/data-usage).
- [Checkpointing](https://code.claude.com/docs/en/checkpointing), [Worktrees](https://code.claude.com/docs/en/worktrees), [Development containers](https://code.claude.com/docs/en/devcontainer).
- [Claude in Chrome](https://code.claude.com/docs/en/chrome), [Computer use](https://code.claude.com/docs/en/computer-use), [Desktop](https://code.claude.com/docs/en/desktop).
- [Remote Control](https://code.claude.com/docs/en/remote-control), [Claude Code on the web](https://code.claude.com/docs/en/claude-code-on-the-web), [Self-hosted environments](https://code.claude.com/docs/en/self-hosted-environments).
- [Headless mode](https://code.claude.com/docs/en/headless), [Agent view](https://code.claude.com/docs/en/agent-view), [Agent teams](https://code.claude.com/docs/en/agent-teams), [Workflows](https://code.claude.com/docs/en/workflows), [Cross-session messaging](https://code.claude.com/docs/en/cross-session-messaging).
- [Model configuration](https://code.claude.com/docs/en/model-config), [Costs](https://code.claude.com/docs/en/costs), [Feature availability](https://code.claude.com/docs/en/feature-availability).
