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
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
onPreToolUsereturns"allow"or"deny", the permission handler is not consulted for that call. - If no
onPermissionRequesthandler is registered at all, permission requests are emitted aspermission.requestedevents 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" };
},
});
| Field | Available for | Use |
|---|---|---|
kind | Always | The coarse category of operation |
toolCallId | Tool-driven requests | Join to tool.execution_* events and your own logs |
toolName | custom-tool, mcp | Name-based policy |
fileName | write | Path-based policy |
fullCommandText | shell | Command inspection โ the single most important field to validate |
managedApprovalRequired | Managed sessions | Check before any automatic approval |
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.
| Decision | Meaning | Extra fields | Risk |
|---|---|---|---|
"approve-once" | Allow this single request | โ | โ Lowest |
"approve-for-session" | Allow, and remember for the rest of the session | approval? (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, locationKey | High โ survives restarts |
"approve-permanently" | Allow and persist across sessions (currently URL domains) | domain | โ ๏ธ Highest โ audit these |
"reject" | Deny the request | feedback? โ surfaced to the agent | Safe; 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.
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" | |
|---|---|---|
| Tools | Ambient CLI tools โ filesystem, search, shell | Explicit only. Nothing is exposed unless your app registers or allows it |
| Built-in skills | Ambient | All runtime-bundled skills excluded โ the SDK sends an empty includedBuiltinSkills list |
| Plugins | Ambient | Empty installedPlugins list โ none loaded implicitly |
| Host filesystem | Reachable through ambient tools | Not exposed unless you disclose it |
| Intended for | CLI-like coding agents on a workstation | Multi-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.
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 mode | Behaviour | You 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 acting | Handle 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 mode | Gate 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" }],
});
| Verdict | Meaning |
|---|---|
deny | Blocks navigation |
ask | Requires approval |
allow | Approved under managed policy |
unmanaged | No 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.
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
| Layer | Mechanism | Stops |
|---|---|---|
| 1. Capability | mode: "empty" + availableTools allowlist | The tool never exists, so it can never be called |
| 2. Scope | tools per custom agent, defaultAgent.excludedTools | Wrong agent gets the wrong capability |
| 3. Path containment | workingDirectory, workspace-relative APIs, path-jail hook | Reads/writes outside the intended root |
| 4. Policy | onPreToolUse โ allow/deny/ask, modifiedArgs | Dangerous arguments, conditional violations |
| 5. Approval | onPermissionRequest decision ladder | Unreviewed actions; gives humans a seam |
| 6. Egress | onPostToolUse redaction | Secrets and PII reaching history and the model |
| 7. Network | Managed network policy evaluation | Navigating to a disallowed destination |
| 8. Budget | sessionLimits.maxAiCredits | Runaway spend (Lesson 9) |
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:
| File | Contains |
|---|---|
permissions.json | Top-level locations map with tool_approvals and allowed_directories |
settings.json | Top-level allowedUrls and sandbox |
config.json | Top-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.
๐ง 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?