# AI Agent & Script Plugins: Guardrails for a Self-Extending Clipboard

> How Deck embeds an AI agent directly into clipboard workflows—multi-provider routing, 22 scoped tools, jsc subprocess isolation, JavaScriptCore sandboxing, and Smart Rule automation.

Engineering · 2026-12-02 · 5 min read

Most AI integrations in desktop utilities are chat sidebars bolted onto an existing window. They cannot inspect your history reliably, execute transformations deterministically, or extend themselves with new capabilities.

[Deck](https://deckclip.app/) treats AI as a tool-using agent operating inside explicit permission boundaries. When you press `⌥⇧Space` and ask *"Format the JSON I just copied"*, the agent searches your recent clipboard history, checks whether a matching JavaScript plugin already exists under `~/.deck/scripts/`, generates and preflights one if needed, asks for your confirmation in the native approval UI, runs the transform in an isolated JavaScriptCore runtime, and writes the formatted output back into your history.

## Beyond a Bolted-On Chat Box

Building a reliable desktop agent means separating two very different responsibilities:

- **Non-deterministic reasoning:** Understanding what the user wants, translating natural language into structured `/app:` or `/date:` filters, chaining read-only lookups, and synthesizing JavaScript transforms or automation rules.
- **Deterministic guardrails:** Enforcing approval gates before mutations, bounding snippet sizes (`maxToolSnippetCharacters = 2500`), validating plugin syntax before presenting diffs, isolating `JavaScriptCore` VM memory in child processes, and blocking private-network SSRF attempts.

Every request runs through a streaming loop in [`AIService.swift`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/AI/AIService.swift#L8-L60) that emits incremental text deltas and structured tool calls until the task is complete.

## Multi-Provider Model Routing

Deck avoids vendor lock-in through [`AIProviderProtocol`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Models/AIProvider.swift#L5-L58). Switching providers requires changing one setting; the 22-tool runtime, streaming loop, and Smart Rule engine work identically across all backends:

| Provider | Configuration | Transport / Notes |
|---|---|---|
| ChatGPT Subscription | OAuth sign-in (`chatgpt`) | Uses your existing ChatGPT account |
| OpenAI API | API key in macOS Keychain (`openai_api`) | Configurable base URL and model |
| Anthropic API | API key in macOS Keychain (`anthropic`) | Direct Messages API support |
| Local AI | `ollama`, `lmStudio`, `openAICompatible` | Runs offline against `localhost:11434`, `1234`, or custom endpoints |

API keys are stored in the macOS Keychain rather than plain `UserDefaults`, and clipboard data is sent to a model only when you explicitly invoke the AI assistant or trigger an AI Smart Rule.

## Twenty-Two Tools and Approval Boundaries

An agent is defined by its tool surface and the boundaries around mutating actions. [`AIToolService.swift`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/AI/AIToolService.swift#L192-L200) exposes **22 tools** partitioned into read-only/low-risk tools (which execute concurrently when independent) and approval-gated mutations (which run serially after native UI confirmation):

| Category | Tools | Approval Required |
|---|---|---|
| Clipboard | `search_clipboard`, `write_clipboard`, `delete_clipboard` | `write_clipboard`, `delete_clipboard` |
| Script Plugins | `list_script_plugins`, `read_script_plugin`, `run_script_transform`, `generate_script_plugin`, `modify_script_plugin`, `delete_script_plugin` | `generate`, `modify`, `delete`, and first-time network `run_script_transform` |
| Smart Rules | `list_smart_rules`, `read_smart_rule`, `generate_smart_rule`, `modify_smart_rule`, `delete_smart_rule` | `generate`, `modify`, `delete` |
| Skills & Web | `read_skill_detail`, `web_search`, `web_fetch` | Autonomous (external web text treated as untrusted data) |
| Long-Term Memory | `record_memory`, `delete_memory` | Autonomous (`record_memory` capped at 30 chars, 1 call per turn) |
| Session Context | `save_session_context`, `read_session_context`, `delete_session_context` | Autonomous (encrypted long-form notes indexed by title/source only) |

Splitting short user preferences (`AIMemoryService`) from encrypted long-form project notes (`AIContextNoteService`) prevents prompt bloat: turn-by-turn prompts inject only compact memories and an index of context titles, while full bodies are fetched on demand via `read_session_context`.

## Sandboxed JavaScript Plugins and Subprocess Isolation

Each script plugin lives in `~/.deck/scripts/<plugin-id>/` with a `manifest.json` (capped at `64 KB`) and a JavaScript entry point (capped at `1 MB`) exporting `transform(input)`.

```javascript
// ~/.deck/scripts/json-format/main.js
function transform(input) {
    try {
        return JSON.stringify(JSON.parse(input), null, 2);
    } catch (e) {
        return "Invalid JSON: " + e.message;
    }
}
```

### Keeping JavaScriptCore Gigacage Memory Out of the App

Creating a `JSVirtualMachine` inside a long-lived macOS menu bar app carries a subtle memory penalty: WebKit's `JavaScriptCore` reserves a large virtual-memory Gigacage region that stays mapped for the lifetime of the host process.

For offline plugins (`requiresNetwork == false`), [`ScriptPluginService.executeScriptInSubprocess`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Plugins/ScriptPluginService.swift#L1397-L1470) delegates execution to macOS's built-in `jsc` shell helper (`/System/Library/Frameworks/JavaScriptCore.framework/.../Helpers/jsc --destroy-vm`). When the transform finishes—or is terminated at the `5.0s` deadline—the child process exits and its entire virtual memory reservation disappears with it.

### In-Process Timeout and Outbound Network Guardrails

Plugins that declare `requiresNetwork: true` run in a dedicated `JSContext` with two defense layers:

- **Hard 5-second CPU timeout:** Because public `JavaScriptCore` headers omit an execution timeout API, [`JSExecutionTimeLimiter`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Plugins/ScriptPluginService.swift#L18-L37) resolves `JSGlobalContextGetGroup` and `JSContextGroupSetExecutionTimeLimit` via `dlopen` / `dlsym` to terminate runaway loops cleanly.
- **Ephemeral, SSRF-checked networking:** Authorized network plugins receive a synchronous `fetch` bridge backed by an ephemeral `URLSession` (no cookies, no cache, 2 MB response cap) and gated by [`DeckOutboundNetworkPolicy`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Core/Security/DeckOutboundNetworkPolicy.swift#L6-L100). It enforces `http`/`https` only and resolves DNS before connecting to block `localhost`, `.local`, loopback, RFC 1918 private subnets, link-local addresses (`169.254.0.0/16`), CGNAT (`100.64.0.0/10`), and IPv6 ULA/multicast ranges—even across redirects. Network authorization is bound to the plugin's SHA-256 script hash.

## Self-Extending Plugins with Native Preflight

Deck's agent does not blindly write JavaScript to `~/.deck/scripts/`. Before the host app even presents an approval card for `generate_script_plugin` or `modify_script_plugin`, [`AIPluginGeneratorService`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/AI/AIPluginGeneratorService.swift#L7-L100) runs native preflight diagnostics on a staging copy:

1. Validates plugin IDs, manifest fields, file sizes, and symlinks within `~/.deck/scripts/`.
2. Applies `apply_patch`-style incremental diffs for modifications rather than rewriting entire files from scratch.
3. Evaluates the JavaScript source and checks that `transform(input)` is defined and passes syntax verification.

If preflight fails, diagnostics flow straight back to the model so it fixes the bug before asking you to approve installation.

## Smart Rules and Scoped Background Automation

Interactive chat is user-initiated; **Smart Rules** in [`SmartRuleService.swift`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search/SmartRuleService.swift#L80-L189) run automatically the moment you copy something.

Rules combine six condition primitives (`contentContains`, `contentMatches` regex, `contentType`, `sourceApp`, `contentLength`, and `hasCustomTitle`) with `.all` or `.any` logic, and trigger six action types (`addTag`, `markSensitive`, `autoDelete`, `transform` built-in or script plugin, `aiPrompt`, or `ignore`).

When a rule fires `aiPrompt` in the background, [`AIService.runSmartRuleAutomation`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/AI/AIService.swift#L688-L745) tightens the agent's capability perimeter via [`smartRuleToolDefinitions()`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/AI/AIToolService.swift#L454-L467):

- Background AI runs are scoped to **9 tools** (`search_clipboard`, `write_clipboard`, `delete_clipboard`, `list_script_plugins`, `read_script_plugin`, `read_skill_detail`, `run_script_transform`, `web_search`, `web_fetch`).
- Self-modification tools (`generate_script_plugin`, `modify_script_plugin`, `delete_script_plugin`, and all Smart Rule mutation tools) are **stripped completely** from background automation.

Giving an agent the ability to extend your toolset while denying autonomous background rules the ability to create or mutate plugins keeps automation predictable. You can browse the full AI and plugin subsystems on [GitHub](https://github.com/yuzeguitarist/Deck/tree/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/AI) or [download Deck for macOS](https://deckclip.app/download).

---

- HTML: https://deckclip.app/newsroom/ai-agent-plugins
- 中文: https://deckclip.app/zh-cn/newsroom/ai-agent-plugins.md

© 2026 Yuze Pan
