# Permissions from Go

> Choose the permission mode, write rules, limit the tools a session is offered and the modes it may switch to.

[Permissions](/concepts/permissions/) explains how zelk decides whether a
tool call runs, asks a person or is refused. This page is what a host
passes to make those decisions. Everything here is fixed when you build the
agent and recorded in each session when it starts, so a session reopened
later decides the way it did before.

## The mode

`WithPermissionMode` is required. It is the mode every new session starts
in, and the only one it may use unless you say more:

| Constant | Runs without asking |
|---|---|
| `permission.ModePlan` | reads only; the rest is refused |
| `permission.ModeDefault` | reads; the rest asks |
| `permission.ModeAcceptEdits` | reads and file edits in the workspace |
| `permission.ModeAuto` | what a reviewer model allows; see [auto mode](/concepts/permissions/#auto-mode) |
| `permission.ModeDontAsk` | reads; whatever would ask is refused |
| `permission.ModeBypass` | everything a rule doesn't deny, except protected paths |

Choosing `ModeBypass` is your authorization to act unattended. A service
that serves other people's requests starts in `ModeDefault` or `ModePlan`
and lets rules open what it means to allow.

"Asks" needs somebody to ask. With no input callback a session answers
every request itself by denying it, so a headless host does only what its
rules allow; [Approvals and questions](/go/approvals/) shows how to route a
request to a person instead.

## Rules

`WithRules` adds rules to the policy sessions start with. A rule is a tool
name and, optionally, a pattern for what it acts on. `permission.MustRule`
parses one and panics on a malformed rule, which suits rules that are
written in the program; `permission.ParseRule` returns the error for rules
that come from a file or a user.

```go
// core/guide_permissions_example_test.go
var deployed []string
deploy, err := tool.Define("Deploy", "Deploys the named service.", func(_ context.Context, in struct {
	Service string `json:"service"`
}) (tool.Result, error) {
	deployed = append(deployed, in.Service)
	return tool.Text("deployed " + in.Service), nil
})
if err != nil {
	panic(err)
}
p, err := replay.New(provider.Caps{},
	replay.ToolCalls(
		history.ToolCall{ID: "d1", Name: "Deploy", Input: json.RawMessage(`{"service":"web"}`)},
		history.ToolCall{ID: "d2", Name: "Deploy", Input: json.RawMessage(`{"service":"prod-db"}`)}),
	replay.Reported("met", "Done."))
if err != nil {
	panic(err)
}
ctx := context.Background()
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithTools(deploy),
	zelk.WithPermissionMode(permission.ModeDefault),
	zelk.WithRules(permission.Rules{
		Allow: []permission.Rule{permission.MustRule(`Deploy(*"service":"web"*)`)},
		Deny:  []permission.Rule{permission.MustRule(`Deploy(*"service":"prod-db"*)`)},
	}))
if err != nil {
	panic(err)
}
defer a.Close(ctx)
s, err := a.Session(ctx, "ops-3")
if err != nil {
	panic(err)
}
x, err := s.Start(ctx, zelk.WithCommands(zelk.UserMessage("Deploy web and prod-db.")))
if err != nil {
	panic(err)
}
if _, err := x.Wait(ctx); err != nil {
	panic(err)
}
fmt.Println("deployed:", deployed)
// Output: deployed: [web]
```

There are four kinds in `permission.Rules`, and the strongest rule that
matches decides: `Deny` over `Human` (always a person, even in `auto`) over
`Ask` over `Allow`. A deny rule wins in every mode, bypass included. Several
`WithRules` calls combine.

A custom tool is named like any other, so `order_status` allows or refuses
it whole, and a pattern matches its input as JSON, as in the example.
Built-in tools take the patterns the [permissions concept page](/concepts/permissions/#rules)
lists, such as `Bash(npm test *)` or `Edit(src/**)`. A tool from an MCP
server is `mcp__server__tool`.

Rules a person grants during a session, by answering "always", are added to
that session's own record; they never change the agent's.

`WithProtectedPaths` adds your own patterns to the writes that always need a
person: a pattern with a slash is a glob relative to the workspace, one
without matches base names anywhere. The built-in ones, such as `.git/` and
`.zelk/`, stay.

## Limit the tools

Rules decide calls. `WithAllowedTools` decides what the model is offered at
all. It is a ceiling: the tools you name, built in or your own, and the
`ReportOutcome` tool a run needs to end. Nothing else is offered, and no
later rule or command widens it. Naming a tool the agent doesn't have makes
`New` fail.

```go
// core/guide_permissions_example_test.go
lookup, err := tool.Define("order_status", "Look up an order's status.",
	func(_ context.Context, _ struct {
		ID string `json:"id"`
	}) (tool.Result, error) {
		return tool.Text("shipped"), nil
	}, tool.WithReadOnly())
if err != nil {
	panic(err)
}
refund, err := tool.Define("refund", "Refund an order.",
	func(_ context.Context, _ struct {
		ID string `json:"id"`
	}) (tool.Result, error) {
		return tool.Text("refunded"), nil
	})
if err != nil {
	panic(err)
}
p, err := replay.New(provider.Caps{})
if err != nil {
	panic(err)
}
ctx := context.Background()
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModeDefault),
	zelk.WithTools(lookup, refund),
	zelk.WithAllowedTools("order_status"))
if err != nil {
	panic(err)
}
defer a.Close(ctx)
var names []string
for _, t := range a.Tools() {
	names = append(names, t.Name)
}
slices.Sort(names)
fmt.Println(names)
// Output: [ReportOutcome order_status]
```

`WithWithheldTools` is the softer kind. It hides tools from sessions
started from now on, such as worktree tools in a directory that isn't a
repository, but a session that already recorded one keeps it.

## Limit the modes

A host or a user can switch a running session's mode with the
`zelk.SetPermissionMode` command. `WithAllowedModes` lists the modes it may
switch to; the starting mode is always allowed, and without the option it is
the only one. A command for another mode is refused when it is accepted, and
the session stays where it was:

```go
// core/guide_permissions_example_test.go
p, err := replay.New(provider.Caps{})
if err != nil {
	panic(err)
}
ctx := context.Background()
a, err := zelk.New(ctx, p, zelk.WithModel("m"), zelk.WithPermissionMode(permission.ModePlan),
	zelk.WithAllowedModes(permission.ModeDefault))
if err != nil {
	panic(err)
}
defer a.Close(ctx)
s, err := a.Session(ctx, "review-2")
if err != nil {
	panic(err)
}
for _, mode := range []permission.Mode{permission.ModeDefault, permission.ModeBypass} {
	x, ack, err := s.Send(ctx, zelk.SetPermissionMode(mode))
	if err != nil {
		panic(err)
	}
	_, err = ack.Wait(ctx)
	fmt.Println(mode, "accepted:", err == nil)
	_, _ = x.Wait(ctx)
}
status, err := s.Status(ctx)
if err != nil {
	panic(err)
}
fmt.Println("now in", status.Mode)
// Output:
// default accepted: true
// bypass accepted: false
// now in default
```

The same list limits what an approved plan may switch to, and a subagent
never has more authority than its parent
([Skills and subagents](/go/skills-subagents/)). `Session.Status` reports a
session's mode, the modes it may use and the rules it recorded.

A `Reconfigure` that changes the rules reaches a session that already exists
when an execution next starts on it: the session takes the agent's current
policy if its own differs, and keeps the rules a user granted in it. An
execution that is already running keeps its rules until you send it the new
ones. Build the command from the agent the reconfiguration prepared, after
`Commit`: `pending.Agent().RulesCommand()`. The old agent handle still gives
the old rules. The command applies once no tool call is running. An approval
a person already answered is bound to the action as they saw it, including
the session's policy revision, so a change in between makes it a different
action and it is decided again. [Running zelk in a service](/go/service/)
shows reconfiguring.

## Next

Rules limit what the model may ask for; [Sandboxing from Go](/go/sandboxing/)
limits what a command can reach once it runs.
