Exported functions in state/lib/bridge.ts. .md file to compare - side-by-side diff against bridge
bridge
What it does for you
Lets your assistant run trusted actions on your Mac with the right permissions.
What it produces
A recent result, so you can see the kind of work it returns.
loading…
How to get it
These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.
For developers how this skill is built, graded, and how it runs
at a glance- the short version
what's inside - the parts that make up a skill 3/4 present
A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.
state/skills/bridge/SKILL.md
present
state/lib/bridge.ts
present
state/bin/bridge/
not present
state/skills/bridge/AGENTS.md
present
how it's graded - what counts as a good run 3 criteria · 1 deterministic · 2 judge
Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.
how it runs - the shared frame every skill uses 5/5 present
Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.
State/lint/library-shape.ts (mechanical -- the lib must state/log/evals.ndjson what it has learned - fixes written back in over time sample
When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.
- Loading feedback rows…
how the work flows- who makes it, who checks it
SKILL.md- the skill, written out in plain English
bridge
A thin client for the openclaw helper daemon at ~/.openclaw/helper/server.js, listening on 127.0.0.1:18790 with Bearer-token auth. The daemon is the long-running process that holds the macOS TCC grants (Screen Recording, Accessibility) the agent's own child-process tree does not.
Backed by state/lib/bridge.ts. Local-loopback only. NOT MCP -- this is the same shape every other snappy-os HTTP integration takes (the head-screen server on :3147, the eval endpoint, etc).
When to use
- Any shell call that touches a TCC-restricted primitive:
screencapture -x,
peekaboo image|paste|press|click, osascript keystroke, cliclick. Spawned from Claude Code, those return permission errors or zero-byte artifacts. Routed through the bridge, they actually run.
- File operations on paths the agent's process can't read or write directly
(e.g. things under ~/Library, /var/log, or another user's home).
- Long-running shell commands that benefit from the daemon's stable PID
rather than a per-turn child spawn.
When NOT to use
- File reads inside the agent's working tree -- use the local
Readtool. - Internal commands the agent can already run fine (
git,npm,npx tsx,
most CLI tools that don't touch the GUI). Adding a hop just adds latency.
- Anything where the local context already works -- if the in-process call
succeeds, don't relay it through the bridge.
Steps
bridgeAvailable()-- seestate/lib/bridge.tsbridgeExec(command, opts?)-- seestate/lib/bridge.tsbridgeReadFile(filePath)-- seestate/lib/bridge.tsbridgeWriteFile(filePath, content)-- seestate/lib/bridge.ts
Library API
bridgeAvailable(): Promise<boolean>
Pings GET /health. Returns true when the daemon answers within 2s with ok: true. Cached for 60s in module-local state -- a tight loop of captureWindow() calls only pays the probe once. Never throws (network failure collapses to false).
import { bridgeAvailable, bridgeExec } from "../lib/bridge.ts";
if (await bridgeAvailable()) {
await bridgeExec("screencapture -x /tmp/x.png");
}
bridgeExec(command, opts?): Promise<BridgeExecResult>
POSTs { command, timeout } to /exec. Returns { ok, output } on success or { ok: false, error, stderr? } on failure. Default timeout 30s; pass { timeout: 60_000 } for slow captures. The command runs in the daemon's environment, NOT the caller's cwd -- pass absolute paths.
const { ok, output, error } = await bridgeExec("/opt/homebrew/bin/peekaboo image --mode window --app SnappyChat --path /tmp/sc.png");
if (!ok) throw new Error(`capture failed: ${error}`);
bridgeReadFile(filePath): Promise<string>
POST /read-file. Returns the file contents. Throws on ok: false.
bridgeWriteFile(filePath, content): Promise<void>
POST /write-file. Throws on failure.
Configuration
Read from .env.cache at the repo root (or process env, which wins):
OPENCLAW_BRIDGE_URL(defaulthttp://127.0.0.1:18790)OPENCLAW_BRIDGE_TOKEN(no default -- throws on first auth attempt if
missing)
The token is the Bearer credential hardcoded in ~/.openclaw/helper/server.js:7. It is NOT secret in the cryptographic sense (anything with read access to either file gets it), but it gates the daemon from accepting requests from random local processes that haven't been told the value. Treat it like a session cookie -- don't log it, don't ship it off-machine.
Failure modes
- Daemon down:
bridgeAvailable()returns false. Callers should fall back
to direct exec when graceful degradation is appropriate (the desktop skill does this) or fail fast when the bridge is the only path that works.
- Token missing: every call throws on the first auth attempt. The fix is
to add OPENCLAW_BRIDGE_TOKEN=... to .env.cache.
- Command fails inside the daemon:
bridgeExecreturns `{ ok: false,
error, stderr } with the same shape regardless of whether the failure was a non-zero exit, a timeout, or a transport error. Inspect error` to discriminate.
Eval
Actor: the exported functions in state/lib/bridge.ts. Auditor: state/lint/library-shape.ts (mechanical -- the lib must exist with named exports). Behavioral correctness is verified by the consuming skill (e.g. desktop), not here -- a relay can't grade its own payload.
| Outcome | Score |
|---|---|
| Bridge probe passes, all four exports importable | 1.0 |
| Lib present but contract drifts (missing export) | 0.5 |
| Lib missing or empty | 0.0 |
Rubric
criteria:
- name: lib_exists_and_exports
kind: deterministic
check: "'state/lib/bridge.ts' exists and exports bridgeAvailable, bridgeExec, bridgeReadFile, bridgeWriteFile."
- name: token_not_logged
kind: judge
check: "No code path writes OPENCLAW_BRIDGE_TOKEN to stdout, stderr, eval rows, or any log file outside .env.cache."
- name: loopback_only
kind: judge
check: "Default bridge URL is 127.0.0.1; no production code path constructs a non-loopback URL."AGENTS.md- what the AI loads when this skill comes up
bridge - loader
Per-turn rules for bridge. TCC-grants relay for screen capture, keystroke, click, file ops. Full reference: state/skills/bridge/SKILL.md. Do not skip Critical Rules.
Critical Rules
- NEVER log
OPENCLAW_BRIDGE_TOKEN. Not to stdout, stderr, eval rows, or any file outside.env.cache. The token gates arbitrary shell exec on the daemon. - LOOPBACK ONLY. Default
OPENCLAW_BRIDGE_URLishttp://127.0.0.1:18790. Never construct a non-loopback URL or expose the daemon over the network - anyone with the token can run anything as the user. - The bridge is the actor; the bridge response is NOT the auditor. After a
bridgeExecthat mutates GUI state, verify with a follow-up that doesn't trust the bridge return alone (e.g.captureWindowto confirm visual change). CONSTITUTION invariant #3. - Don't relay commands the local context can already run. Adding a hop costs latency. The bridge is for TCC-restricted ops (screen capture, keystroke, click), not for
git status. - If
bridgeAvailable()returns false, the daemon is down. Restart withlaunchctl kickstart -k gui/$(id -u)/ai.openclaw.helper. Do NOT try to start~/.openclaw/helper/server.jsdirectly (it's a launchd-managed process and direct node invocation won't bind the port cleanly). Do NOT curl in a loop. - HTTP 500 from bridge = daemon error state, not a transient failure. Restart the daemon (same launchctl command as above). Retrying the same request will keep returning 500.
- BridgeEvalWatcher hash-nav. To drive snappy-chat to a specific route from shell:
echo "__snappyNav('#/chat/customize/themes', 'chat')" > /tmp/snappy-eval.js(or via bridgeExec). The BridgeEvalWatcher in SnappyChat polls/tmp/snappy-eval.jsand executes the nav. Verify nav landed with a follow-up screenshot. Registered bridge events:bundle.state,bundle.mounted,config.elevenlabs,agent.select.
Commands
| ui dashboard | state/skills/bridge/resources/ui.openui |
| operation | command | |||
|---|---|---|---|---|
| import (TS) | import { bridgeAvailable, bridgeExec, bridgeReadFile, bridgeWriteFile } from "./state/lib/bridge.ts" | |||
| invoke | bridgeAvailable() · bridgeExec(command, opts?) · bridgeReadFile(path) · bridgeWriteFile(path, content) | |||
| CLI | `npx tsx state/lib/bridge.ts [health\ | exec\ | read\ | write] ...` |
| daemon restart | launchctl kickstart -k gui/$(id -u)/ai.openclaw.helper | |||
| daemon | ~/.openclaw/helper/server.js (external to snappy-os; managed by launchd) | |||
| hash-nav | echo "__snappyNav('#/chat/customize/themes', 'chat')" > /tmp/snappy-eval.js | |||
| config | .env.cache: OPENCLAW_BRIDGE_TOKEN, OPENCLAW_BRIDGE_URL (default http://127.0.0.1:18790) | |||
| verify | bridgeAvailable() returns true; for exec, trust ok field + independent observation (file exists, screenshot diff) - never bridge response alone | |||
| reference | state/skills/bridge/SKILL.md | |||
| eval log | state/log/evals.ndjson (skill: bridge) |
Daemon endpoints (127.0.0.1:18790, Bearer auth)
GET /health→{ ok, service, uptime }POST /execbody{ command, timeout? }→{ ok, output }or{ ok: false, error, stderr? }POST /read-filebody{ file_path }→{ ok, content }POST /write-filebody{ file_path, content }→{ ok, written }
The body field is command, NOT cmd. {"cmd":"..."} returns {"ok":false,"error":"command required"}. Canonical raw-curl shape:
TOKEN=$(grep '^OPENCLAW_BRIDGE_TOKEN=' .env.cache | cut -d= -f2-)
curl -s -X POST http://127.0.0.1:18790/exec \
-H "Authorization: Bearer $TOKEN" \
-H "content-type: application/json" \
-d '{"command":"echo hello"}'
OpenUI Resource
- Skill-owned OpenUI Lang resource:
state/skills/bridge/resources/ui.openui. Read it before rendering or editing this skill's generated component surface. - Treat this resource as a first-class artifact of the skill, not a generic chat response. Improve it when the skill's user-facing output needs to become richer.
- System resources compose OpenUI primitives and inherit SnappyChat tokens. Use
ui_contract: brandedin SKILL.md only for deliberate platform or client visuals.
Known Pitfalls
- Commands run in the daemon's environment, NOT the caller's cwd. Pass absolute paths (
/opt/homebrew/bin/peekaboo, notpeekaboo). bridgeAvailable()is cached for 60s. CallbridgeResetCache()in tests if the daemon was just started.- Token source of truth:
~/.openclaw/helper/server.js:7(lineconst TOKEN = '...')..env.cache(OPENCLAW_BRIDGE_TOKEN) must match. Read either with:grep '^OPENCLAW_BRIDGE_TOKEN=' ~/projects/snappy-os/.env.cache | cut -d= -f2-ORnode -e "const s=require('fs').readFileSync(process.env.HOME+'/.openclaw/helper/server.js','utf8'); console.log(s.match(/TOKEN = '([^']+)'/)[1])". If they disagree, update.env.cacheto matchserver.js(the daemon wins). Current token rotated 2026-05-01 - old literalsnappy-openclawis invalid. - Default
bridgeExectimeout is 30s. Slow GUI ops (e.g.peekaboo imageon a buried window) may need{ timeout: 60_000 }. - Async render race on inject-control / theme changes. When you inject a UI state change via the
/dispatch/chatinject-control endpoint (e.g.theme:light), the HTTP 204 response confirms the queue consumed the command - but WKWebView renders asynchronously. A screenshot taken immediately after will race and likely capture the pre-change state. Insert a 500ms+ delay before screenshotting, or poll until the visual state settles. (2026-04-29: light-mode verification captured dark state because the peekaboo call followed the inject curl with no delay.) peekaboowindow-IDs rotate per call.peekaboo list windowsreturns a freshID:each invocation; using--window-id <n>from a previous list call fails withWindow not found: window_id <n>. For capture, prefer--app "Snappy Chat"(note the space). For positioning math, usepeekaboo list windows --app "Snappy Chat"immediately before the click/move and compute screen coords from the window'sPosition: (x, y)+Size: WxHfields. Window-reltop: 50%lands aty = window.y + height/2in screen coords.- Hover-only chrome won't show in unattended captures. Elements with
opacity: 0until.app:hover(e.g..panel-toggle) require the cursor to be inside the app window before the screenshot. Usepeekaboo move <x>,<y>to position the cursor over the app first (positional, not--coords), then capture. Without this, hover-styled elements render as transparent and look "missing."
Self-Test
An agent reading this should correctly:
- [ ] Never log
OPENCLAW_BRIDGE_TOKENanywhere? - [ ] Construct only loopback URLs (127.0.0.1 or localhost)?
- [ ] Verify
bridgeExecresults via independent observation, not response payload? - [ ] Skip bridge for commands local context can already run fine?
- [ ] Restart daemon (not work around) when
bridgeAvailable()is false? - [ ] Use JSON body field
command(notcmd) in raw curl? - [ ] Add 500ms+ delay before screenshot after inject-control theme changes?
- [ ] Know peekaboo window IDs rotate per call - always list first?
- [ ] Know hover-only chrome needs cursor-in-app before screenshot?
<!-- kernel-ok: historical attribution for the PID-loader pattern. -->
Self-correcting loader (PID feedback)
This is the rule that makes loaders learn. Ported from snappy-kernel, where it demonstrably worked: the snappy-dom-cartographer skill mapped Skool admin UI once, every later ship-agent inherited the full map for free.
Before you finish, do two things:
1. Fix gaps (P - proportional). MANDATORY. If this loader didn't cover your case - if you had to read another file, run an undocumented command, work around a wrong selector, or discover a quirk - you MUST attempt an Edit to this AGENTS.md before you log.
- Default action: edit this file. Surgical. Add the missing line, table
row, or code example where it belongs. No restructuring.
- Only
LOGGEDis allowed when: the fix needs >10 lines, spans multiple
files, or requires a structural rewrite. In that case the state/regen/drain.sh queue picks it up asynchronously.
- "I didn't have time" / "it's minor" / "the next agent will figure it out"
are NOT valid reasons. Minor gaps compound - that's the whole point of this loop.
- Concrete example of a valid P-fix: discover
agent-browser screenshot
takes path positionally not as --output <path>. One line in a table. Edit it in. Do not just log it.
- The goal: the next agent never has to leave the loader.
2. Log the result.
echo "[$(date -u +%FT%TZ)] bridge: <what was missing or fixed> [FIXED|LOGGED] action_kind=<kind>" >> state/log/loader-feedback.log
<slug>MUST be the literal folder name of this loader
(state/skills/<slug>/AGENTS.md). The class token between [ts] and : is the producer slug, the writeback class, AND the grade class - they must be equal so state/lib/controller-tune.ts can pair the brief.
FIXED= you patched this loader inline (P-fix).LOGGED= too large for inline; the PostToolUse enqueue + Stop-hook drain
will rewrite the loader from scratch on next session-end.
action_kindis the SECOND pairing predicate (added 2026-04-27, task #327).
Pick the value that describes what you actually did - same slug, different action_kind means the writeback satisfies a different brief layer:
shape-ok- only frontmatter-shape verification passed (rare from
a human; usually emitted by the lint, not a loader echo)
skill-ran- the skill ran end-to-end and an eval row landed
in state/log/evals.ndjson
loader-rewritten- you EDITED this AGENTS.md inline (the FIXED case),
OR the regen drain rewrote it
pattern-elevated- you promoted a recurring failure to a Critical Rule
(rule fix or new-skill scaffold) If you LOGGED (couldn't fix inline), omit action_kind - the inferrer will pick it up from your body keywords.
Do not skip this. Every agent run must leave the system better than it found it. The loader is the setpoint; you are the sensor; the gap is the error signal; closing the gap is the correction.
api.ts- the code it can call
#!/usr/bin/env npx tsx
/**
* snappy-bridge/api.ts -- TCC-grants-intact shell relay client.
*
* Thin client for the openclaw helper daemon (`~/.openclaw/helper/server.js`,
* loopback on 127.0.0.1:18790). The daemon is the long-running process that
* holds the macOS TCC grants (Screen Recording, Accessibility) the agent's
* own child-process tree does not.
*
* Why this exists: shell commands spawned from inside Claude Code (or any
* other agent runtime that didn't pass through System Settings → Privacy)
* fail silently on TCC-restricted operations -- `screencapture -x` produces
* a zero-byte file, `osascript keystroke` no-ops, `peekaboo image` returns
* a permission error. Routing the same command through this daemon lets it
* inherit the daemon's grants, so the operation actually runs.
*
* Local-loopback only. Bearer-token auth. Never expose to the network --
* the daemon trusts every authenticated request to run arbitrary shell.
*
* Usage:
* import { bridgeAvailable, bridgeExec, bridgeReadFile, bridgeWriteFile }
* from "./bridge.ts";
*
* if (await bridgeAvailable()) {
* const { ok, output } = await bridgeExec("screencapture -x /tmp/x.png");
* }
*
* Or as CLI:
* npx tsx api.ts health
* npx tsx api.ts exec "<command>"
* npx tsx api.ts read /tmp/foo
* npx tsx api.ts write /tmp/foo "contents"
*/
import { realpathSync } from "fs";
import { env } from "./env.ts";
const DEFAULT_URL = "http://127.0.0.1:18790";
function bridgeUrl(): string {
return process.env.OPENCLAW_BRIDGE_URL || env("OPENCLAW_BRIDGE_URL", false) || DEFAULT_URL;
}
function bridgeToken(): string {
// Required. The daemon refuses every request without a Bearer token, so a
// missing token is a fast, loud failure -- not a silent fallback to local.
const tok = process.env.OPENCLAW_BRIDGE_TOKEN || env("OPENCLAW_BRIDGE_TOKEN", false);
if (!tok) {
throw new Error(
"[bridge] OPENCLAW_BRIDGE_TOKEN missing. Set it in .env.cache or env. " +
"The token is the Bearer credential for ~/.openclaw/helper/server.js.",
);
}
return tok;
}
function authHeaders(): Record<string, string> {
return {
"content-type": "application/json",
authorization: `Bearer ${bridgeToken()}`,
};
}
// --- Availability cache ---
//
// Pinging /health on every call would add 5-10ms per primitive. Cache the
// boolean for 60s in module-local state -- short enough that a daemon
// restart is noticed within a minute, long enough that a tight loop of
// captureWindow() calls only pays the probe once.
let _availCache: { value: boolean; expiresAt: number } | null = null;
const AVAIL_TTL_MS = 60_000;
/**
* Probe /health. Returns true if the daemon answers within the timeout
* with `ok: true`. Cached for 60s. Never throws -- a network failure is
* "not available", which is the same boolean shape as "explicitly down".
*/
export async function bridgeAvailable(): Promise<boolean> {
const now = Date.now();
if (_availCache && now < _availCache.expiresAt) return _availCache.value;
let ok = false;
try {
const res = await fetch(`${bridgeUrl()}/health`, {
method: "GET",
headers: authHeaders(),
signal: AbortSignal.timeout(2000),
});
if (res.ok) {
const body = (await res.json()) as { ok?: boolean };
ok = Boolean(body?.ok);
}
} catch {
ok = false;
}
_availCache = { value: ok, expiresAt: now + AVAIL_TTL_MS };
return ok;
}
/** Reset the cached availability probe; useful in tests. */
export function bridgeResetCache(): void {
_availCache = null;
}
export interface BridgeExecResult {
ok: boolean;
output?: string;
error?: string;
stderr?: string;
}
/**
* POST /exec -- run a shell command on the daemon, inheriting its TCC
* grants. The command runs in the daemon's environment (NOT this agent's
* cwd or env) -- pass absolute paths and explicit env when the call
* depends on them.
*
* The daemon returns `{ ok, output }` on success and `{ ok: false, error,
* stderr }` on failure. We surface that shape unchanged so the caller can
* decide whether to throw, fall back, or retry.
*
* Default timeout is 30s -- long enough for `peekaboo image` window
* captures of slow apps, short enough that a hung daemon doesn't block a
* skill indefinitely.
*/
export async function bridgeExec(
command: string,
opts: { timeout?: number } = {},
): Promise<BridgeExecResult> {
const timeout = opts.timeout ?? 30_000;
try {
const res = await fetch(`${bridgeUrl()}/exec`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({ command, timeout }),
signal: AbortSignal.timeout(timeout + 2000),
});
if (!res.ok) {
return { ok: false, error: `bridge http ${res.status}` };
}
const body = (await res.json()) as BridgeExecResult;
return body;
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
return { ok: false, error: `bridge transport: ${msg}` };
}
}
/**
* POST /read-file -- read a file via the daemon's filesystem grants.
* Useful for paths that live outside the agent's working tree (e.g. log
* files in /var, user config in ~/Library).
*
* Throws on `ok: false` -- callers that want to tolerate missing files
* should wrap in try/catch.
*/
export async function bridgeReadFile(filePath: string): Promise<string> {
const res = await fetch(`${bridgeUrl()}/read-file`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({ file_path: filePath }),
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) throw new Error(`[bridge] read-file http ${res.status}`);
const body = (await res.json()) as { ok: boolean; content?: string; error?: string };
if (!body.ok) {
throw new Error(`[bridge] read-file failed: ${body.error ?? "unknown error"}`);
}
return body.content ?? "";
}
/**
* POST /write-file -- write a file via the daemon. Same caveat as read:
* paths are interpreted on the daemon side, not the caller's cwd.
*
* Throws on failure rather than returning a tuple -- callers should fail
* loudly when a write doesn't land.
*/
export async function bridgeWriteFile(filePath: string, content: string): Promise<void> {
const res = await fetch(`${bridgeUrl()}/write-file`, {
method: "POST",
headers: authHeaders(),
body: JSON.stringify({ file_path: filePath, content }),
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) throw new Error(`[bridge] write-file http ${res.status}`);
const body = (await res.json()) as { ok: boolean; written?: number; error?: string };
if (!body.ok) {
throw new Error(`[bridge] write-file failed: ${body.error ?? "unknown error"}`);
}
}
// --- CLI ---
if ((() => { try { return import.meta.url === `file://${realpathSync(process.argv[1])}`; } catch { return false; } })()) {
(async () => {
const [, , cmd, ...args] = process.argv;
switch (cmd) {
case "health": {
const ok = await bridgeAvailable();
console.log(JSON.stringify({ available: ok, url: bridgeUrl() }));
if (!ok) process.exit(1);
break;
}
case "exec": {
const command = args.join(" ");
if (!command) { console.error("Usage: api.ts exec <command>"); process.exit(2); }
const r = await bridgeExec(command);
console.log(JSON.stringify(r, null, 2));
if (!r.ok) process.exit(1);
break;
}
case "read": {
const path = args[0];
if (!path) { console.error("Usage: api.ts read <path>"); process.exit(2); }
process.stdout.write(await bridgeReadFile(path));
break;
}
case "write": {
const path = args[0];
const content = args.slice(1).join(" ");
if (!path) { console.error("Usage: api.ts write <path> <content>"); process.exit(2); }
await bridgeWriteFile(path, content);
console.log(`wrote ${path}`);
break;
}
default:
console.log("Usage: npx tsx api.ts [health|exec|read|write] ...");
}
})();
}
scripts- helper scripts it can run
prose-only skill - 3 inline code blocks live in SKILL.md above (no state/bin/ sidecar yet).
how we check it- the checks, plus the last 3 runs
| timestamp | verb | score | primary_issue | artifact |
|---|---|---|---|---|
| 2026-04-29 03:08Z | - | 1.00 | - | - |
| 2026-04-29 03:08Z | - | 1.00 | - | - |
| 2026-04-29 03:08Z | - | 1.00 | - | - |