AGENT SKILL

context-bridge

Compress, store, and inject conversation context blocks between AI sessions — decisions, open questions, next actions, and people — from the R1 to your local machine

License 许可
MIT
最近更新
2026-09-04
Stars
★ 0
Forks
0

01 前言 Front Matter

name
context-bridge
author
rabbit-r1-skillz
version
1.0.0
description
Compress, store, and inject conversation context blocks between AI sessions — decisions, open questions, next actions, and people — from the R1 to your local machine

02 资源文件 3

03 SKILL.md 正文

ContextBridge — OpenClaw Skill

ContextBridge lets you end any AI session by speaking your key decisions, open questions, and next steps into the R1. The R1 compresses the transcript via LLM, stores a named context block locally, and later injects that block as a structured preamble into your next AI conversation — eliminating copy-paste and context loss between sessions.

How it works

  1. Capture — At the end of a session, press PTT on the R1. Scroll to choose a context name (Project Alpha, Client Call, etc.), then speak your decisions, open questions, and next steps.
  2. Compress — R1 sends the transcript to this skill, which uses an LLM to extract structured fields: decisions made, open questions, next actions, people involved, and topic tags.
  3. Store — The compressed context block is returned to the R1 and saved in named context storage (up to 10 contexts, with optional expiry).
  4. Browse — Scroll through saved contexts on the R1 home screen. PTT to open a card view showing date, tags, and bullet previews.
  5. Inject — From the card view, press PTT to inject the context. This skill formats it as a structured block and sends it to your configured target (clipboard, Notion, or Obsidian) so your next AI conversation starts with full context.
  6. Merge — Double-tap PTT on the home screen to open merge mode. Select two contexts; this skill (or local merge logic) combines them into one.

Prerequisites

Required

  • Node.js 20+ on your local machine
  • OpenClaw CLI installed and running (openclaw serve)
  • An Anthropic API key for LLM-powered compression and merging

Optional (for injection targets)

  • xclip / pbcopy or Windows clipboard access — for clipboard injection
  • Notion integration token and a target page/database ID — for Notion injection
  • Obsidian vault path — for Obsidian injection (writes a new note in a _context-bridge/ folder)

Local setup

1. Install dependencies

cd ~/.openclaw/skills/context-bridge
npm install @anthropic-ai/sdk dotenv

2. Configure environment

Create ~/.openclaw/skills/context-bridge/.env:

# Required
ANTHROPIC_API_KEY=sk-ant-...

# Optional — Notion injection
NOTION_TOKEN=secret_...
NOTION_PAGE_ID=...

# Optional — Obsidian injection
OBSIDIAN_VAULT_PATH=/Users/you/Documents/MyVault

# Injection target override (clipboard | notion | obsidian)
# R1 app sends this per-inject, but this is the server-side fallback
DEFAULT_INJECT_TARGET=clipboard

3. Register the skill

Add to ~/.openclaw/openclaw.config.json:

{
  "skills": [
    {
      "name": "context-bridge",
      "path": "~/.openclaw/skills/context-bridge/skill.js",
      "description": "Compress and inject conversation context blocks between AI sessions"
    }
  ]
}

4. Create the skill file

Create ~/.openclaw/skills/context-bridge/skill.js:

"use strict";
require("dotenv").config({ path: __dirname + "/.env" });
const Anthropic = require("@anthropic-ai/sdk");
const fs        = require("fs");
const path      = require("path");
const { exec }  = require("child_process");
const { promisify } = require("util");
const execAsync = promisify(exec);

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });

// ── Entry point called by OpenClaw ──────────────────────────
module.exports = async function contextBridge(command, params, storage) {
  switch (command) {
    case "compress": return compress(params);
    case "inject":   return inject(params);
    case "merge":    return merge(params);
    default:         return { error: `Unknown command: ${command}` };
  }
};

// ── COMPRESS — LLM extracts structured fields from transcript ──
async function compress({ transcript, name, expiryDays }) {
  if (!transcript || !transcript.trim()) {
    return {
      decisions: [],
      questions: [],
      actions:   [],
      people:    [],
      tags:      [],
      error:     null,
    };
  }

  const prompt =
    "You are a context compression assistant. Extract structured information from the spoken context below.\n" +
    "Return a JSON object with these fields:\n" +
    "  decisions: string[]  — key decisions made (max 3, each under 70 chars)\n" +
    "  questions: string[]  — open questions remaining (max 3, each under 70 chars)\n" +
    "  actions:   string[]  — concrete next action items (max 3, each under 70 chars)\n" +
    "  people:    string[]  — people mentioned by name (max 4)\n" +
    "  tags:      string[]  — 1-2 short topic tags, no spaces or # (e.g. [\"api-design\", \"auth\"])\n" +
    "If a field has no content, use an empty array. Return only valid JSON, no other text.\n\n" +
    "Spoken context:\n" + transcript.slice(0, 4000);

  try {
    const msg = await anthropic.messages.create({
      model:      "claude-haiku-4-5-20251001",
      max_tokens: 512,
      messages:   [{ role: "user", content: prompt }],
    });

    const text   = msg.content[0]?.text?.trim() || "{}";
    const match  = text.match(/\{[\s\S]*\}/);
    const parsed = match ? JSON.parse(match[0]) : {};

    return {
      decisions: toStringArray(parsed.decisions, 3),
      questions: toStringArray(parsed.questions, 3),
      actions:   toStringArray(parsed.actions,   3),
      people:    toStringArray(parsed.people,     4),
      tags:      toStringArray(parsed.tags,       2),
      error:     null,
    };
  } catch (e) {
    return { error: e.message, decisions: [], questions: [], actions: [], people: [], tags: [] };
  }
}

// ── INJECT — deliver a context block to configured target ──────
async function inject({ contextBlock, name, target }) {
  const dest = target || process.env.DEFAULT_INJECT_TARGET || "clipboard";

  try {
    if (dest === "clipboard") {
      await writeToClipboard(contextBlock);
    } else if (dest === "notion") {
      await writeToNotion(name, contextBlock);
    } else if (dest === "obsidian") {
      await writeToObsidian(name, contextBlock);
    }
    return { ok: true, target: dest, error: null };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

// ── MERGE — combine two context blocks with LLM deduplication ──
async function merge({ contextA, contextB, mergedName }) {
  const combined = {
    decisions: dedup([...contextA.decisions, ...contextB.decisions]),
    questions: dedup([...contextA.questions, ...contextB.questions]),
    actions:   dedup([...contextA.actions,   ...contextB.actions  ]),
    people:    dedup([...contextA.people,    ...contextB.people   ]),
    tags:      dedup([...contextA.tags,      ...contextB.tags     ]),
  };

  // If entries fit within limits, skip LLM and return local merge
  const totalItems =
    combined.decisions.length + combined.questions.length + combined.actions.length;

  if (totalItems <= 9) {
    return {
      decisions: combined.decisions.slice(0, 3),
      questions: combined.questions.slice(0, 3),
      actions:   combined.actions.slice(0, 3),
      people:    combined.people.slice(0, 4),
      tags:      combined.tags.slice(0, 2),
      error:     null,
    };
  }

  // LLM dedup/consolidation for over-full merges
  const prompt =
    "Merge and deduplicate these two context blocks into one. " +
    "Keep the most important items in each category (max 3 per category). " +
    "Return JSON with fields: decisions, questions, actions, people (max 4), tags (max 2). " +
    "Each item max 70 chars. Return only valid JSON.\n\n" +
    "Context A (" + contextA.name + "):\n" + JSON.stringify(contextA, null, 2) + "\n\n" +
    "Context B (" + contextB.name + "):\n" + JSON.stringify(contextB, null, 2);

  try {
    const msg = await anthropic.messages.create({
      model:      "claude-haiku-4-5-20251001",
      max_tokens: 512,
      messages:   [{ role: "user", content: prompt }],
    });

    const text   = msg.content[0]?.text?.trim() || "{}";
    const match  = text.match(/\{[\s\S]*\}/);
    const parsed = match ? JSON.parse(match[0]) : combined;

    return {
      decisions: toStringArray(parsed.decisions, 3),
      questions: toStringArray(parsed.questions, 3),
      actions:   toStringArray(parsed.actions,   3),
      people:    toStringArray(parsed.people,     4),
      tags:      toStringArray(parsed.tags,       2),
      error:     null,
    };
  } catch (e) {
    return {
      ...combined,
      decisions: combined.decisions.slice(0, 3),
      questions: combined.questions.slice(0, 3),
      actions:   combined.actions.slice(0, 3),
      error:     null,
    };
  }
}

// ── CLIPBOARD ──────────────────────────────────────────────────
async function writeToClipboard(text) {
  const platform = process.platform;
  if (platform === "darwin") {
    const proc = require("child_process").spawn("pbcopy");
    proc.stdin.write(text);
    proc.stdin.end();
    await new Promise(r => proc.on("close", r));
  } else if (platform === "linux") {
    const proc = require("child_process").spawn("xclip", ["-selection", "clipboard"]);
    proc.stdin.write(text);
    proc.stdin.end();
    await new Promise(r => proc.on("close", r));
  } else if (platform === "win32") {
    const proc = require("child_process").spawn("clip");
    proc.stdin.write(text);
    proc.stdin.end();
    await new Promise(r => proc.on("close", r));
  } else {
    throw new Error("Clipboard not supported on this platform");
  }
}

// ── NOTION ─────────────────────────────────────────────────────
async function writeToNotion(name, contextBlock) {
  if (!process.env.NOTION_TOKEN || !process.env.NOTION_PAGE_ID) {
    throw new Error("NOTION_TOKEN and NOTION_PAGE_ID required");
  }

  const https   = require("https");
  const body    = JSON.stringify({
    parent: { page_id: process.env.NOTION_PAGE_ID },
    properties: {
      title: { title: [{ text: { content: name + " — " + new Date().toLocaleDateString() } }] },
    },
    children: [{
      object: "block",
      type: "code",
      code: {
        rich_text: [{ type: "text", text: { content: contextBlock } }],
        language: "plain text",
      },
    }],
  });

  await new Promise((resolve, reject) => {
    const req = https.request({
      hostname: "api.notion.com",
      path:     "/v1/pages",
      method:   "POST",
      headers: {
        Authorization:    "Bearer " + process.env.NOTION_TOKEN,
        "Notion-Version": "2022-06-28",
        "Content-Type":   "application/json",
        "Content-Length": Buffer.byteLength(body),
      },
    }, res => {
      let data = "";
      res.on("data", d => { data += d; });
      res.on("end", () => {
        if (res.statusCode >= 200 && res.statusCode < 300) resolve(data);
        else reject(new Error("Notion error " + res.statusCode + ": " + data.slice(0, 200)));
      });
    });
    req.on("error", reject);
    req.write(body);
    req.end();
  });
}

// ── OBSIDIAN ───────────────────────────────────────────────────
async function writeToObsidian(name, contextBlock) {
  const vaultPath = process.env.OBSIDIAN_VAULT_PATH;
  if (!vaultPath) throw new Error("OBSIDIAN_VAULT_PATH not configured");

  const folder   = path.join(vaultPath, "_context-bridge");
  if (!fs.existsSync(folder)) fs.mkdirSync(folder, { recursive: true });

  const safeTitle = name.replace(/[^a-zA-Z0-9 _-]/g, "").slice(0, 60);
  const date      = new Date().toISOString().split("T")[0];
  const filename  = path.join(folder, `${date} ${safeTitle}.md`);

  const content   = `# ${name}\n_Captured ${new Date().toLocaleString()}_\n\n\`\`\`\n${contextBlock}\n\`\`\`\n`;
  fs.writeFileSync(filename, content, "utf8");
}

// ── HELPERS ────────────────────────────────────────────────────
function toStringArray(val, max) {
  if (!Array.isArray(val)) return [];
  return val.filter(s => typeof s === "string" && s.trim()).slice(0, max);
}

function dedup(arr) {
  const seen = new Set();
  return arr.filter(s => {
    const key = s.toLowerCase().trim();
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}

5. Start OpenClaw

openclaw serve

Confirm you see context-bridge listed among registered skills.

Command reference

compress

Sent automatically when the R1 finishes a capture session.

Field Type Description
transcript string Raw STT transcript from the R1
name string Context name chosen by the user
expiryDays number Configured decay: 7, 30, or 0 (never)

Response:

Field Type Description
decisions string[] Key decisions extracted (max 3)
questions string[] Open questions (max 3)
actions string[] Next action items (max 3)
people string[] People mentioned (max 4)
tags string[] Topic tags (max 2)
error string|null Error message if compression failed

inject

Sent when the user presses PTT on a context card.

Field Type Description
contextId string Internal context ID
name string Context name
contextBlock string Pre-formatted structured text block
target string clipboard, notion, or obsidian

Response:

Field Type Description
ok boolean Whether injection succeeded
target string Which target was used
error string|null Error message on failure

If injection fails, the R1 app falls back to reading the context aloud via TTS — you can dictate or type it into your AI tool manually.


merge

Sent when the user confirms a merge of two contexts.

Field Type Description
contextA object First context record
contextB object Second context record
mergedName string Auto-generated merged name

Response: Same structure as compress response, representing the merged context.


Injection workflow example

After injecting a context named "API Design Review" to clipboard:

  1. Open your AI tool (Claude.ai, ChatGPT, etc.)
  2. Start a new conversation
  3. Paste the clipboard content — it looks like:
=== Context: API Design Review [Jun 14, 2026] ===
DECISIONS:
  • Use JWT for auth, not session cookies
  • Rate limit at API gateway layer, not service level
  • Versioning via URL prefix /v1/
OPEN QUESTIONS:
  • How to handle token refresh in mobile clients?
  • Should pagination be cursor-based or offset?
NEXT ACTIONS:
  • Draft OpenAPI spec for auth endpoints
  • Benchmark gateway throughput under load
  • Review OWASP API Top 10 against current design
PEOPLE: Sarah, Marcus, Dev team
=== End Context ===

The AI immediately has full context from your previous session without any copy-paste from previous chat history.

Troubleshooting

R1 shows "OpenClaw timeout" and falls back to voice delivery

  • Confirm openclaw serve is running
  • Both the R1 device and your machine must be on the same network
  • Check ~/.openclaw/logs/ for connection errors

Compression returns generic or empty fields

  • Speak more explicitly: name decisions as "we decided to...", questions as "open question:", actions as "next step is..."
  • Increase your Anthropic API quota if you hit rate limits

Clipboard injection not working on Linux

  • Install xclip: sudo apt install xclip
  • Alternatively, switch inject target to obsidian or notion

Obsidian file not appearing

  • Confirm OBSIDIAN_VAULT_PATH points to the vault root (the folder containing your .obsidian/ directory)
  • Files land in <vault>/_context-bridge/ — check that folder in the Obsidian file explorer

Notion injection returns 401

  • Verify the integration has been added to the target page: open the Notion page → ··· → Add connections → select your integration
  • Confirm NOTION_PAGE_ID is the bare UUID from the page URL, not the full URL

Security notes

  • Context blocks may contain sensitive session content. Treat ANTHROPIC_API_KEY as a secret — never commit .env.
  • The skill runs exclusively on your local machine. No context data is sent anywhere except the LLM provider (for compression/merge) and your chosen injection target.
  • OpenClaw communicates over localhost by default. Do not expose the OpenClaw port over the internet without authentication.
  • If using Notion injection, ensure the integration has minimum required permissions (insert content only).

04 同仓库更多 Skills

ajohnsonnow
ajohnsonnow/r1-warren

whisper-quiz

WhisperQuiz — voice-answered trivia game for Rabbit R1. Generates questions via the R1's built-in LLM, captures spoken answers via STT, and evaluates correctness with flexible LLM-based matching.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

walk-cast

Walking podcast production skill. Receives raw audio metadata and transcript from the R1, removes long pauses, applies noise reduction and normalization, generates AI chapter titles and episode metadata via LLM, and uploads the final episode to your configured podcast RSS host (Spotify for Podcasters / Anchor, Podbean, Buzzsprout, RSS.com, or any FTP-accessible feed).

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

voice-novel

Local machine skill for VoiceNovel — handles story export to disk.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

voice-guide

Environment description and navigation assistant for blind and low-vision users. Analyzes camera frames via a vision LLM, reads visible text, identifies scene categories (people/vehicles/food/hazards/exits), performs 360° scans, retrieves GPS position, and sends emergency SMS alerts — all via audio feedback with zero screen dependency.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

voice-draft

Voice-driven document drafting for the Rabbit R1. Dictate stream-of-consciousness speech; the R1 formats it into Email, Blog Post, Report, Proposal, Meeting Notes, Creative Writing, Code Comments, Cover Letter, or Tweet Thread — then saves the result to a configured folder on your local machine via OpenClaw.

★ 0
ajohnsonnow
ajohnsonnow/r1-warren

voice-commit

Hands-free git and CI workflow voice controller for the Rabbit R1. Speak git/CI commands and hear results — commit, push, status, PR management, test runs, and deploy, all voice-driven via OpenClaw.

★ 0