apoc
Unrestricted process control and durable execution for LLM agents.
apoc (apocalypse) replaces shell-shaped process inspection, PID bookkeeping,
background-job glue, and one-off supervisors with one typed control plane. It
gives agents fresh process state, exact process identities, durable executions,
bounded concurrency, resource ownership, causal history, and JavaScript
composition through the same command graph.
It is built for workloads where independent operations run concurrently, long-lived work must survive the initiating call, and later agents need to inspect exact outcomes without reconstructing state from terminal transcripts.
Install · Quick start · Execution model · MCP · Security · Operations · Reference
Core guarantees
| Capability | Contract |
|---|---|
| Process identity | Mutations target boot ID, PID, and nanosecond start time to prevent PID-reuse mistakes. |
| Durable execution | Accepted commands retain specifications, attempts, bounded logs, events, ownership, and terminal results. |
| Exact arguments | Direct argv is the default; shell parsing requires explicit --shell. |
| Replay safety | Caller-supplied idempotency keys prevent repeated operating-system mutations. |
| One command graph | CLI, MCP, and Code Mode share schemas, validation, history, and execution state. |
| Local-first operation | No account, telemetry service, or required remote control plane. |
Status and scope
| Property | Current contract |
|---|---|
| Release | 0.4.0 |
| Platform | Supported: macOS |
| Minimum Rust version | 1.95 |
| Interfaces | CLI, MCP stdio, and Code Mode JavaScript |
| Compatibility | SemVer releases with versioned durable schemas and pre-migration database backups |
| Release gates | rustfmt, Clippy with warnings denied, workspace tests, package contents, and publish dry-run on macOS CI |
| State | Local SQLite database, execution logs, and content-addressed artifacts |
| Authority | The operating-system permissions of the user who starts apoc |
| License | MIT |
The 0.x line is actively evolving. Breaking public-interface changes receive
a minor version bump; durable state changes use explicit schema migrations.
Security and trust model
apoc is not a sandbox, policy engine, confirmation layer, or embedded model. It exposes destructive operations and their metadata directly, using the authority of the user who starts it. The calling agent remains responsible for selecting the correct target and action.
apoc has no telemetry, account service, update checker, or automatic network access. Network requests occur only when the user configures and invokes an HTTP, MCP, or OpenAPI provider.
Purpose and agent narration
Every executable apoc command requires a one-line purpose of at most 120
characters with no secrets. In an agentic thread, the LLM writes that exact
sentence immediately before the call. The parameter itself has no ordering
requirement.
A useful purpose states the intended decision or proof. Treat each purpose as
one narrative beat. When prior evidence matters, carry forward the relevant
observed state. Never invent an observation or result. For example, after
identifying a port owner, prefer
Port 5173 belongs to Vite; I’m reading its context before deciding whether to stop it. over Read process context. This is a content requirement, not a
runtime grammar.
Purposes are stored with native invocation history and can be found with
apoc history search. Framework discovery such as help, schema, and --llms
does not execute a command and is exempt.
Install
apoc skill install writes the embedded operator contract to
~/.agents/skills/apoc and links the Codex and Claude skill roots to that
canonical copy. Run it again after an upgrade. A successful status reports
"ready": true.
Each crates.io release contains the complete MIT-licensed source. Development happens in a private repository; the crates.io package and docs.rs source view are the public source distribution.
Quick start
Run one exact-argv command and receive its durable result:
The response has one stable envelope. This abridged example omits timestamps, the full execution specification, attempts, and log-tail metadata:
Use the returned execution ID to inspect or control the work later:
Choose the smallest execution surface
| Work | Preferred surface |
|---|---|
| One process query or mutation | apoc process ... |
| One managed command | apoc execution command or start |
| Repeat a command or typed apoc operation until an outcome | apoc poll run or start |
| Known independent commands | apoc execution batch |
| A native stdout pipeline | apoc execution pipeline |
| Heterogeneous concurrent tools | apoc code run |
| Agent-host integration | apoc --mcp |
| External MCP, OpenAPI, or macOS action | apoc provider ... and apoc action ... |
| Prior apoc use in this worktree | apoc history ... |
Every surface resolves through the same typed graph and durable lifecycle:
CLI MCP Code Mode
| | |
+----------+-------------+
|
typed command graph
|
per-user daemon
/ | \
executions events ownership
|
macOS processes and providers
All commands support TOON, JSON, YAML, Markdown, and JSONL output. Use
--schema for one command's JSON Schema and --llms for the compact
LLM-readable command manifest. Use --filter-output when an agent needs only a
few fields from a CLI response. Code Mode programs should return a compact
synthesis instead of complete nested execution envelopes.
Process discovery and control
apoc resolves a selector from a fresh native snapshot before every mutation.
The durable identity is BOOT_ID:PID@STARTED_AT_NS, so PID reuse cannot redirect
an operation to a different process.
Selectors are pid:, name:, match: regular expressions, pgid:, port:
with optional /tcp or /udp, and all. A bare integer is a PID.
Structured queries combine process fields, regular expressions, socket ownership, and recorded apoc ownership:
The causal journal answers relationship questions from recorded evidence:
Process mutations accept caller-supplied idempotency keys. Repeating the same
normalized request and key returns the original receipt without another
operating-system call. Empty selections fail unless --allow-empty is explicit.
These commands can stop or suspend host processes. Resolve and inspect the selector before mutating a target when its identity is not already known.
Durable execution contract
execution is the public lifecycle abstraction. Direct argv is the default.
Place apoc options before the first literal --, then pass each exact child
argv value after it. That first separator belongs to apoc; every later --
belongs to the child. Structured MCP and Code Mode calls use the same arg
array. Use --shell only when the program intentionally requires zsh parsing.
An execution records its versioned specification, working directory, repository and worktree state, attempts, exact process identities, output paths, parent, session, lease, progress time, and terminal result.
- An omitted working directory inherits the caller's current directory through the CLI, MCP, and Code Mode.
- A relative
--cwdresolves from that directory. apoc validates and canonicalizes it before accepting the execution. command,batch, andpipelinereturn{ execution, replayed, logs }.- The CLI exit status matches the managed result while structured stdout remains available to the caller.
- Inline stdout and stderr are bounded 32 KiB tails with explicit truncation
flags. Full logs remain available through
execution logs. - Launch failures, nonzero exits, timeouts, and cancellations are terminal execution results after acceptance. They are not transport failures.
- Reusing an idempotency key for a different normalized request fails before launching work.
Secret environment values use NAME=env:VARIABLE. apoc stores the reference
and resolves the value only when the process launches. Literal environment
values are part of the durable execution specification and are stored locally.
Poll commands and typed apoc operations
Use poll run when one observation must be repeated until it matches or reaches
a bound. Use poll start to return the durable parent execution immediately.
Both forms use the existing execution get, wait, and cancel lifecycle.
Poll options are named arguments and have no ordering requirement before --.
The separator preserves exact command argv. Interval behavior uses these request
arguments; it does not use interval subcommands.
--interval-mode |
Arguments | Behavior |
|---|---|---|
fixed-delay |
--interval-ms |
Wait after each unmatched observation. |
backoff |
--initial-interval-ms, --multiplier, --max-interval-ms |
Increase the delay to the cap. |
fixed-rate |
--interval-ms |
Use acceptance-based ticks, skip missed ticks, and never overlap. |
Conditions include repeated --until-exit-code, stdout or stderr regex,
--until-json-pointer with --until-json-equals, and a pure boolean
--until-js expression over observation. Select one condition family. A poll
without a condition must include --max-iterations or --duration-ms and
completes as bounded sampling. A condition that reaches a bound fails with
POLL_CONDITION_NOT_MET.
Poll the shared typed graph with apoc as the target. This does not spawn a
nested apoc CLI process:
The parent result stays compact. Expand only the evidence needed for diagnosis:
Run independent commands concurrently
Use one batch when the agent already knows the independent commands. apoc bounds
concurrency, records each child, and returns a compact failure-oriented parent.
max_parallel defaults to the logical CPU count and is limited to 256.
Use a pipeline only when stdout must flow between stages. apoc creates native pipes, starts every stage before waiting, keeps each child's stderr separate, captures final stdout on the parent, and enables pipefail by default.
Compose heterogeneous work in Code Mode
Code Mode runs generated JavaScript in isolated QuickJS actors. The worker pool
defaults to min(logical CPUs, 8); set APOC_CODE_WORKERS to override it.
Separate programs use separate actors, and one program can issue independent
host calls concurrently with Promise.all.
Code Mode persists source, immutable capabilities, ordered calls, replay state, result, events, and oversized artifacts. Provider mutations record intent before dispatch. Replay skips operations that already have a durable applied receipt.
Do not fan out shell strings that each invoke apoc through a host tool's
Promise.all. Use one execution batch for known commands or one Code Mode
program with typed apoc.* calls. Avoid concatenating large source trees with
cat; use targeted searches, bounded reads, or a compact Code Mode synthesis.
After apoc accepts a managed execution, an unsuccessful terminal status resolves
normally inside JavaScript. Inspect execution.status and throw explicitly when
the surrounding program must fail.
Coordinate agents and resources
A session groups one agent's executions under a heartbeat. Its root lease is
session/SESSION_ID. When the heartbeat expires, the daemon releases the lease,
cancels session-owned executions, and releases their reservations.
Reservations provide atomic apoc-local ownership for ports, paths, exact
processes, devices, and custom keys. Port reservations also report native socket
conflicts. reservation wait waits for up to 30 seconds.
Extend the capability graph
Providers add Streamable HTTP MCP, supervised MCP stdio, or OpenAPI operations
to the same graph. Their names become Code Mode namespaces. Secret configuration
uses PROVIDER:REFERENCE and resolves only when a client connects or a child
starts.
From an unpacked apoc source package, build the standalone macOS provider before registering its release binary.
action run and action start use the durable Code Mode lifecycle. Calls with
the same stable resource identity are ordered. Independent resources can run
concurrently. Every mutation stores an intent followed by an applied, failed, or
unknown receipt.
The packaged macOS provider covers app, window, Accessibility, input, pasteboard, capture, Shortcuts, URL, AppleScript, and JXA operations without adding platform dependencies to apoc core.
Use apoc through MCP
The built-in command graph serves MCP stdio with apoc --mcp. Register the
absolute installed path so the agent host does not depend on shell startup
configuration:
APOC_BIN=
The MCP, CLI, and Code Mode surfaces share command schemas, execution state, idempotency behavior, and output contracts.
Configure a durable environment
Use one implicit environment per Git worktree or canonical directory. Pass
--global for values that every workspace should inherit. Literal values are
durable. Secret values are not: env secret stores an unresolved reference and
resolves it only when apoc constructs a process or provider transport.
Precedence is daemon inheritance, global apoc environment, local apoc
environment, execution --env or --secret-env, then a batch or pipeline
unit's environment. env list and env doctor return destination names,
scopes, generations, and resolution status. They never return literal secret
values or provider references. Every environment mutation requires
--idempotency-key.
Search invocation history
apoc records each typed CLI, MCP, and Code Mode invocation in its local SQLite
database. Queries are local by default: every directory in one Git worktree
shares a scope, while a directory outside Git has its own exact canonical scope.
Use --global only when the task needs history from every recorded workspace.
Normalized arguments and options are stored and searchable. Secret-bearing
fields keep only their destination names; values, providers, and references are
removed before normalized input, search text, and pattern signatures are
written. Literal environment and header values remain recordable, so use
structured secret options for credentials.
list and search return bounded reverse-chronological pages with
invocations and next_cursor. They accept exact filters for source,
surface, command, status, actor, and linked execution, plus since-ms
and until-ms. --global and --cwd cannot be combined. A local query does
not include imported records whose original working directory is unknown.
timeline returns complete sanitized records oldest-first. Its opaque cursor
holds a stable acceptance snapshot, so calls accepted after the first page do
not appear later in the same traversal. The default limit is 100 and the
maximum is 500.
history query runs one read-only SQL statement against an isolated in-memory
history table, never against apoc's durable database. The table exposes
id, purpose, started_at, updated_at, status, command_path, source,
surface, actor, execution_id, and error_code for filtering and ordering,
but results may contain only id and purpose. The CLI returns compact
columns plus positional rows, defaults to 20 rows, and hard-caps at 100 even
when the SQL asks for more. Use history get ID only after a purpose identifies
something worth expanding.
Native capture is automatic and does not call DevSQL. Historical shell and agent transcripts can contain literal credentials, so inspect their retention and access before importing them. The following explicit command runs DevSQL once, imports only shell segments that invoke apoc, redacts recognized secret flags, preserves source provenance, and skips records already imported:
Imported records have source: "devsql". Ordinary capture and every later
history query remain independent of DevSQL.
Build a temporary command namespace
Use recipes when repeated commands should become a small composable interface
without creating a standalone binary. Dotted names form the namespace. A recipe
is local to the current Git worktree, or the exact current directory outside
Git, unless you pass --global. Local definitions shadow global definitions
with the same name.
apoc resolves the complete declared dependency graph before execution. Missing,
expired, cyclic, deeper-than-16, and larger-than-64 graphs fail before Code Mode
runs. The resolved functions execute inside one Code Mode program. Draft
2020-12 input and output schemas validate the top-level recipe boundary. Repeat
--require-env NAME on recipe put when a recipe must fail before Code Mode if
a literal or secret value cannot resolve. Portable bundles include required key
names, never values or references.
The caller LLM can propose a recipe from exact chronological evidence without making it executable. apoc stores the candidate and rationale; it does not run an embedded model or infer candidates with built-in heuristics.
Suggestions remain separate from lookup, dependency resolution, execution
tools, and bundles. Adoption atomically creates the exact candidate and links
the suggestion. The default adopted lifetime is 604800000 ms (7 days); pass a
positive --ttl-ms to override it. A different existing generation is a
conflict unless you pass --replace.
Expired recipes remain durable but are hidden and cannot run. recipe pin
clears one expiry, and recipe prune deletes expired recipes in the selected
scope. Both commands require --idempotency-key.
recipe export writes RecipeBundleV1 and includes transitive dependencies.
The bundle excludes scope, expiry, timestamps, receipts, and resolved secrets.
recipe import validates the whole bundle before one atomic database write and
rejects conflicts unless you pass --replace.
Inspect events and state
apoc appends monotonically ordered lifecycle events. Repeated large payloads are content-addressed and deduplicated; event metadata remains after payload pruning.
Commands that need durable ownership automatically start one detached daemon per user.
| State | Default macOS path |
|---|---|
| Database | ~/Library/Application Support/apoc/apoc.sqlite3 |
| Execution logs | ~/Library/Application Support/apoc/runs/ |
| Daemon log | ~/Library/Application Support/apoc/daemon.log |
| Socket | $TMPDIR/apoc-<effective-user-id>/apoc.sock |
Ordinary consumer work uses the installed per-user controller without setting
APOC_HOME or APOC_RUNTIME_DIR. Set both only for apoc tests and integration
fixtures, or for an explicitly bounded isolation task. Return to the default
controller after a temporary compatibility workaround is no longer needed;
never carry a dated temporary runtime into later ordinary work.
Set both APOC_HOME and APOC_RUNTIME_DIR to run a bounded isolated instance. apoc
backs up a non-empty database before each schema migration. The runtime directory
uses mode 0700; the Unix socket uses mode 0600. $TMPDIR represents the
platform temporary directory returned to the process and is commonly under
/var/folders/.../T on macOS. <effective-user-id> is the numeric effective
user ID returned by the operating system.
Upgrade and verify
The next durable command starts the current daemon build. apoc version reports
the client version and public execution schema. apoc daemon status reports the
daemon build and schema when it is running.
Reference
There is no public issue tracker or support channel. The structured CLI help, JSON Schemas, embedded operator skill, and packaged source are the public product contract.
License
apoc is available under the MIT License.