Guardrails II โ€” Permissions, Modes, and Sandboxing

Lesson 6: Guardrails II โ€” Permissions, Modes, and Sandboxing

Hooks let you express policy. Permissions are how that policy becomes an enforceable decision. They are two layers of the same mechanism, and knowing which layer to use is most of the skill.

Two layers, one gate

onPreToolUse policy ยท conditional logic onPermissionRequest decision ยท approvals execute or not enforced by the CLI "ask" allow/deny short-circuit "allow" and "deny" end the decision here โ€” the permission handler is never called "ask" is the only bridge between the two layers

When you supply onPermissionRequest, it is called before the agent executes each tool โ€” file writes, shell commands, MCP calls, custom tools alike โ€” and returns a decision. Two properties govern the whole system:

  • If onPreToolUse returns "allow" or "deny", the permission handler is not consulted for that call.
  • If no onPermissionRequest handler is registered at all, permission requests are emitted as permission.requested events and left pending for a consumer to resolve with the pending-permission RPC.

The request tells you what is being asked

import type { PermissionRequest, PermissionRequestResult } from "@github/copilot-sdk";

const session = await client.createSession({
  model: "gpt-5",
  onPermissionRequest: (request: PermissionRequest, invocation): PermissionRequestResult => {
    if ("managedApprovalRequired" in request && request.managedApprovalRequired === true) {
      // Leave it pending for the host's human-facing confirmation flow.
      return { kind: "no-result" };
    }

    // request.kind โ€” what type of operation is being requested:
    //   "shell"       โ€” executing a shell command
    //   "write"       โ€” writing or editing a file
    //   "read"        โ€” reading a file
    //   "mcp"         โ€” calling an MCP tool
    //   "custom-tool" โ€” calling one of your registered tools
    //   "url"         โ€” fetching a URL
    //   "memory"      โ€” storing or retrieving persistent session memory
    //   "hook"        โ€” invoking a server-side hook or integration
    //   (additional kinds may be added; include a default case in handlers)

    if (request.kind === "shell") {
      return { kind: "reject", feedback: "Shell commands are not allowed." };
    }

    return { kind: "approve-once" };
  },
});
FieldAvailable forUse
kindAlwaysThe coarse category of operation
toolCallIdTool-driven requestsJoin to tool.execution_* events and your own logs
toolNamecustom-tool, mcpName-based policy
fileNamewritePath-based policy
fullCommandTextshellCommand inspection โ€” the single most important field to validate
managedApprovalRequiredManaged sessionsCheck before any automatic approval
Always include a default case. The runtime reserves the right to add kinds โ€” url, memory, and hook are all examples of categories that exist beyond the obvious file/shell pair. A handler with an exhaustive switch over today's kinds silently mis-approves tomorrow's.

The decision ladder

Approval scopes are present-tense: they describe the decision to apply, not the outcome reported back on session events. Choose the narrowest that keeps your product usable.

DecisionMeaningExtra fieldsRisk
"approve-once"Allow this single requestโ€”โœ… Lowest
"approve-for-session"Allow, and remember for the rest of the sessionapproval? (rule to remember), domain? (URL approvals)Medium โ€” a resumed session may keep it
"approve-for-location"Allow and persist for this project location (git root or cwd)approval, locationKeyHigh โ€” survives restarts
"approve-permanently"Allow and persist across sessions (currently URL domains)domainโš ๏ธ Highest โ€” audit these
"reject"Deny the requestfeedback? โ€” surfaced to the agentSafe; feedback helps recovery
"user-not-available"Deny because no human is present to confirmโ€”Safe โ€” the right answer for headless runs
"no-result"Suppress this client's answer so another connected client can answerโ€”Only for multi-client hosts
reject beats silence. A rejection with feedback goes back to the model as information: "Shell commands are not allowed" lets the agent choose a different approach and finish the task. A bare denial teaches it nothing, so it retries the same thing โ€” you get the same refusal, more turns, and a confused user. Always explain the refusal.

Approve-all, and the one place it breaks

import { CopilotClient, approveAll } from "@github/copilot-sdk";

const session = await client.createSession({
  model: "gpt-5",
  onPermissionRequest: approveAll,
});

Fine for local development and for sessions where your hooks already gate everything. The trap: when enableManagedSettings is true for the session, approveAll throws. Managed sessions exist precisely so an organisation's policy cannot be bypassed by application code. For those, write a custom handler โ€” and note that request-level managedApprovalRequired remains available as the signal for a human-facing confirmation step.

Do not reach for approveAll in a server deployment just because it makes things work. It converts every guardrail into a suggestion. If your design is "hooks decide, permissions rubber-stamp", write onPermissionRequest: async () => ({ kind: "approve-once" }) โ€” same effect, but the intent is legible in review, and it will not silently start auto-approving a category you forgot to handle in the hook.

Session modes: copilot-cli vs empty

The client's mode decides how much ambient capability exists before your configuration is applied. This is the most consequential single setting in multi-user deployments.

mode: "copilot-cli" (default)mode: "empty"
ToolsAmbient CLI tools โ€” filesystem, search, shellExplicit only. Nothing is exposed unless your app registers or allows it
Built-in skillsAmbientAll runtime-bundled skills excluded โ€” the SDK sends an empty includedBuiltinSkills list
PluginsAmbientEmpty installedPlugins list โ€” none loaded implicitly
Host filesystemReachable through ambient toolsNot exposed unless you disclose it
Intended forCLI-like coding agents on a workstationMulti-user servers, shared runtimes, tenants
import { CopilotClient, RuntimeConnection } from "@github/copilot-sdk";

const client = new CopilotClient({
  mode: "empty",
  connection: RuntimeConnection.forUri(process.env.COPILOT_RUNTIME_URL!),
});

const session = await client.createSession({
  sessionId: `user-${user.id}-${crypto.randomUUID()}`,
  model: "gpt-5.4",
  availableTools: ["custom:lookupOrder", "custom:createTicket"],
  gitHubToken: user.githubToken,
  onPermissionRequest: permissionHandler,
});

You can still opt back in selectively: includedBuiltinSkills allows particular bundled skills the same way availableTools allows particular bundled tools, and your own custom skills remain usable regardless.

Token angle: mode: "empty" is the rare change that improves security and cost simultaneously. Ambient tool definitions and bundled skill descriptions are prompt content on every turn. In copilot-cli mode a session pays for a capability surface it may never use; in empty mode it pays only for what you named.

Agent modes: interactive, plan, autopilot, shell

Separately from the client's mode, an agent mode governs how much autonomy the loop assumes. You will see it as the agentMode field in session events, with four values:

Agent modeBehaviourYou shouldโ€ฆ
"interactive"Normal chat. No nudge for task_complete.Keep a human in the loop; expect no completion signal
"plan"The agent plans and asks to exit plan mode before actingHandle exit_plan_mode.requested and choose an exit action
"autopilot"Autonomous. The CLI nudges for task_complete when the loop ends without it.Budget for extra turns; rely on session.idle
"shell"Shell-oriented agent modeGate shell permission requests hard

Plan mode is worth understanding because it is where human approval composes with autonomy. When the model proposes exiting plan mode, you receive exit_plan_mode.requested (carrying requestId, summary, planContent, and the available actions) and you reply with an exit action:

type ExitPlanModeAction =
  | "exit_only"
  | "interactive"
  | "autopilot"
  /** Exit plan mode and continue with parallel autonomous workers. */
  | "autopilot_fleet";

Use autopilot_fleet when the approved plan already contains independent work items โ€” it hands off directly to parallel workers (Lesson 8). Use autopilot for a single autonomous worker, and interactive when the human should stay in the loop.

Managed network policy for client-owned browsers

If your agent can drive a browser, URL navigation becomes a permission surface. The SDK exposes a pure, sessionless evaluation API for organisation policy so you can check a destination before opening it:

// A reusable policy context โ€” from account/device policy, or the session's retained policy
const permissionsContext =
  (await client.rpc.managedSettings.resolve({ selectionId })).permissionsContext;
// or, for the session's retained policy:
// const { permissionsContext } = await session.rpc.managedSettings.get();

const { results, failClosed } = await client.rpc.managedSettings.permissions.evaluate({
  context: permissionsContext,
  operations: [{ kind: "url", url: "https://docs.example.com/guide" }],
});
VerdictMeaning
denyBlocks navigation
askRequires approval
allowApproved under managed policy
unmanagedNo managed rule โ€” your normal permission flow still applies

Operational details that matter more than they look: the call performs no policy discovery, I/O, prompting, or sandbox changes โ€” so reuse an in-memory context for repeated checks and refresh it when managed policy changes. Results come back one per operation, in input order. An invalid URL rejects the batch. Unknown policy either rejects or returns failClosed: true with everything denied.

Check every navigation, redirect, and new-window destination โ€” and treat errors as denials. Do not navigate on an error, and treat an absent permissionsContext from an older runtime as unsupported evaluation, not as "unmanaged, so go ahead". Also keep the distinction straight: these APIs evaluate permission rules, they do not replace browser security, user permissions, or sandbox policy. In particular permissions.limitTo neither enables the sandbox nor changes sandbox.userPolicy.network โ€” configure network restrictions explicitly.

Defence in depth: what each layer actually stops

LayerMechanismStops
1. Capabilitymode: "empty" + availableTools allowlistThe tool never exists, so it can never be called
2. Scopetools per custom agent, defaultAgent.excludedToolsWrong agent gets the wrong capability
3. Path containmentworkingDirectory, workspace-relative APIs, path-jail hookReads/writes outside the intended root
4. PolicyonPreToolUse โ€” allow/deny/ask, modifiedArgsDangerous arguments, conditional violations
5. ApprovalonPermissionRequest decision ladderUnreviewed actions; gives humans a seam
6. EgressonPostToolUse redactionSecrets and PII reaching history and the model
7. NetworkManaged network policy evaluationNavigating to a disallowed destination
8. BudgetsessionLimits.maxAiCreditsRunaway spend (Lesson 9)
Layer 1 is the only layer that is not code you can get wrong. A tool excluded from the session is unavailable even if every hook has a bug. This is why mode: "empty" plus availableTools is the backbone of the multi-tenant story, and why the docs say plainly: do not use mode: "copilot-cli" for multi-user server mode.

Where approvals live on disk (and why it matters for tenants)

Runtime-owned durable permission choices use the session filesystem when you configure one, under the provider's sessionStatePath:

FileContains
permissions.jsonTop-level locations map with tool_approvals and allowed_directories
settings.jsonTop-level allowedUrls and sandbox
config.jsonTop-level trustedFolders

Session-filesystem approval operations deliberately do not import or fall back to the host's permissions-config.json, URL or sandbox settings, or folder trust โ€” and they do not write back to those host files, even when the provider errors. A provider error is not permission to use host consent. URL deny rules stay authoritative, and folder trust uses provider paths without host Git discovery.

The isolation boundary is yours to enforce. The runtime does not add session-ID partitions to these files, and sessions sharing a provider namespace share remembered grants. Use distinct namespaces per tenant, authorise access to each, and reconnect resumed sessions to their original namespace. Protect transcripts โ€” including durable permission events โ€” with the same tenant isolation you apply to approval metadata.

๐Ÿง  Knowledge Check

1. Your onPreToolUse returns "allow". Does onPermissionRequest still run for that call?

2. A session sets enableManagedSettings: true. What happens if you pass onPermissionRequest: approveAll?

3. In mode: "empty", what must your application do that it did not have to do in copilot-cli mode?

Further Reading