[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75TATHGFMCVTZ3C7NHRT4TW":3,"skill-same:01M75TATHGFMCVTZ3C7NHRT4TW":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":26,"commitSha":27,"skillDirectory":5,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M75TATHGFMCVTZ3C7NHRT4TW","email-triage",null,"Morning voice inbox briefing — fetch, prioritize, reply, and archive emails from R1 without looking at a screen","ajohnsonnow\u002Fr1-warren","ajohnsonnow","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F8867891?v=4","01M75T7TQ3B5VRHJF6X2Q7AWWW","Anthony Johnson","01M75T7TQPJG8YZTAVCH4SQW27",0,"MIT","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Femail-triage\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: email-triage\ndescription: Morning voice inbox briefing — fetch, prioritize, reply, and archive emails from R1 without looking at a screen\nversion: 1.0.0\nauthor: rabbit-r1-skillz\n---\n\n# EmailTriage — OpenClaw Skill\n\nEmailTriage uses your local machine as the mail backend for voice-driven inbox management on the R1. The skill connects to Gmail (or IMAP), fetches your unread emails, has an LLM flag urgency, and handles send\u002Farchive\u002Fbatch commands dispatched from the R1 app.\n\n## How it works\n\n1. R1 opens and sends `fetch_inbox` to this skill via the OpenClaw shared-storage bridge\n2. The skill fetches unread emails, runs LLM urgency classification, and returns a prioritized list\n3. R1 announces the count and reads summaries aloud — you scroll and tap with one hand\n4. Dictated replies are sent via `send_reply`; archive, skip, and star commands via `batch_action`\n5. Handled email IDs are persisted in R1 storage so the app stays in sync across sessions\n\n## Prerequisites\n\n### Required\n\n- **Node.js 20+** on your local machine\n- **OpenClaw CLI** installed and running (`openclaw serve`)\n- An **Anthropic API key** for urgency classification (or OpenAI key)\n- A **Gmail account** with OAuth2 credentials configured (see step 2), or an IMAP\u002FSMTP server\n\n### Optional\n\n- **Nodemailer** for SMTP-based sending (included in deps)\n- **node-imap** for non-Gmail IMAP accounts\n- **Gmail API** via `googleapis` (recommended — faster and no IMAP needed)\n\n## Local setup\n\n### 1. Install dependencies\n\n```bash\ncd ~\u002F.openclaw\u002Fskills\u002Femail-triage\nnpm install @anthropic-ai\u002Fsdk googleapis nodemailer dotenv\n```\n\n### 2. Configure Gmail OAuth2\n\nFollow the [Gmail API Quickstart](https:\u002F\u002Fdevelopers.google.com\u002Fgmail\u002Fapi\u002Fquickstart\u002Fnodejs) to create OAuth2 credentials:\n\n1. Create a project in Google Cloud Console\n2. Enable the Gmail API\n3. Create OAuth2 credentials (Desktop app type)\n4. Run the one-time auth flow to generate a refresh token:\n\n```bash\nnode auth-setup.js\n```\n\nWhere `auth-setup.js` is the standard OAuth2 token exchange script — see the Gmail API quickstart linked above.\n\n### 3. Configure environment\n\nCreate `~\u002F.openclaw\u002Fskills\u002Femail-triage\u002F.env`:\n\n```env\n# Required — LLM for urgency classification\nANTHROPIC_API_KEY=sk-ant-...\n\n# Gmail OAuth2 (recommended)\nGMAIL_CLIENT_ID=...apps.googleusercontent.com\nGMAIL_CLIENT_SECRET=...\nGMAIL_REFRESH_TOKEN=...\nGMAIL_USER=you@gmail.com\n\n# Alternative: IMAP\u002FSMTP (if not using Gmail API)\nIMAP_HOST=imap.example.com\nIMAP_PORT=993\nIMAP_USER=you@example.com\nIMAP_PASS=yourpassword\nSMTP_HOST=smtp.example.com\nSMTP_PORT=587\nSMTP_USER=you@example.com\nSMTP_PASS=yourpassword\n\n# Optional — use OpenAI instead of Anthropic\nOPENAI_API_KEY=sk-...\n\n# Tuning\nMAX_EMAILS=20\nFETCH_DAYS=1\n```\n\n### 4. Register the skill\n\nAdd to `~\u002F.openclaw\u002Fopenclaw.config.json`:\n\n```json\n{\n  \"skills\": [\n    {\n      \"name\": \"email-triage\",\n      \"path\": \"~\u002F.openclaw\u002Fskills\u002Femail-triage\u002Fskill.js\",\n      \"description\": \"Morning voice inbox — fetch, prioritize, reply, archive via R1\"\n    }\n  ]\n}\n```\n\n### 5. Create the skill file\n\nCreate `~\u002F.openclaw\u002Fskills\u002Femail-triage\u002Fskill.js`:\n\n```javascript\n\"use strict\";\nrequire(\"dotenv\").config({ path: __dirname + \"\u002F.env\" });\n\nconst { google }   = require(\"googleapis\");\nconst Anthropic    = require(\"@anthropic-ai\u002Fsdk\");\nconst nodemailer   = require(\"nodemailer\");\n\nconst MAX_EMAILS  = parseInt(process.env.MAX_EMAILS  || \"20\", 10);\nconst FETCH_DAYS  = parseInt(process.env.FETCH_DAYS  || \"1\",  10);\nconst anthropic   = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n\n\u002F\u002F ── Gmail client ───────────────────────────────────────────\nfunction getGmailClient() {\n  const auth = new google.auth.OAuth2(\n    process.env.GMAIL_CLIENT_ID,\n    process.env.GMAIL_CLIENT_SECRET\n  );\n  auth.setCredentials({ refresh_token: process.env.GMAIL_REFRESH_TOKEN });\n  return google.gmail({ version: \"v1\", auth });\n}\n\n\u002F\u002F ── Entry point ────────────────────────────────────────────\nmodule.exports = async function emailTriage(command, params, storage) {\n  switch (command) {\n    case \"fetch_inbox\":   return fetchInbox();\n    case \"send_reply\":    return sendReply(params);\n    case \"batch_action\":  return batchAction(params);\n    default:\n      return { error: `Unknown command: ${command}` };\n  }\n};\n\n\u002F\u002F ── FETCH INBOX ────────────────────────────────────────────\nasync function fetchInbox() {\n  try {\n    const gmail  = getGmailClient();\n    const cutoff = new Date();\n    cutoff.setDate(cutoff.getDate() - FETCH_DAYS);\n    const after  = Math.floor(cutoff.getTime() \u002F 1000);\n\n    const listResp = await gmail.users.messages.list({\n      userId:  \"me\",\n      q:       `is:unread after:${after}`,\n      maxResults: MAX_EMAILS,\n    });\n\n    const messageList = listResp.data.messages || [];\n    if (messageList.length === 0) {\n      return { emails: [] };\n    }\n\n    const rawEmails = await Promise.all(\n      messageList.map(m => fetchMessage(gmail, m.id))\n    );\n\n    const filtered = rawEmails.filter(Boolean);\n    const emails   = await classifyUrgency(filtered);\n\n    \u002F\u002F Sort: urgent first, then today, then normal\n    emails.sort((a, b) => {\n      const rank = { urgent: 0, today: 1, normal: 2 };\n      return (rank[a.urgency] ?? 2) - (rank[b.urgency] ?? 2);\n    });\n\n    return { emails };\n\n  } catch (err) {\n    console.error(\"fetch_inbox error:\", err.message);\n    return { error: err.message };\n  }\n}\n\nasync function fetchMessage(gmail, id) {\n  try {\n    const msg    = await gmail.users.messages.get({ userId: \"me\", id, format: \"full\" });\n    const headers = msg.data.payload?.headers || [];\n    const get    = name => headers.find(h => h.name.toLowerCase() === name)?.value || \"\";\n\n    const sender      = parseSenderName(get(\"from\"));\n    const senderEmail = parseSenderEmail(get(\"from\"));\n    const subject     = get(\"subject\") || \"(no subject)\";\n    const date        = get(\"date\");\n    const snippet     = msg.data.snippet || \"\";\n    const body        = extractBody(msg.data.payload);\n    const time        = formatEmailTime(date);\n\n    return { id, sender, senderEmail, subject, snippet, body, time, urgency: \"normal\" };\n  } catch (err) {\n    console.error(\"fetchMessage error:\", id, err.message);\n    return null;\n  }\n}\n\nfunction parseSenderName(from) {\n  const match = from.match(\u002F^([^\u003C]+)\u003C\u002F);\n  return match ? match[1].trim().replace(\u002F^\"|\"$\u002Fg, \"\") : from.split(\"@\")[0];\n}\n\nfunction parseSenderEmail(from) {\n  const match = from.match(\u002F\u003C([^>]+)>\u002F);\n  return match ? match[1] : from;\n}\n\nfunction extractBody(payload) {\n  if (!payload) return \"\";\n  const tryDecode = data => {\n    try { return Buffer.from(data, \"base64\").toString(\"utf-8\"); } catch (_) { return \"\"; }\n  };\n\n  if (payload.mimeType === \"text\u002Fplain\" && payload.body?.data) {\n    return tryDecode(payload.body.data).slice(0, 1200);\n  }\n\n  if (payload.parts) {\n    for (const part of payload.parts) {\n      if (part.mimeType === \"text\u002Fplain\" && part.body?.data) {\n        return tryDecode(part.body.data).slice(0, 1200);\n      }\n    }\n    \u002F\u002F Fall back to HTML part stripped of tags\n    for (const part of payload.parts) {\n      if (part.mimeType === \"text\u002Fhtml\" && part.body?.data) {\n        const html = tryDecode(part.body.data);\n        return html.replace(\u002F\u003C[^>]+>\u002Fg, \" \").replace(\u002F\\s+\u002Fg, \" \").trim().slice(0, 1200);\n      }\n    }\n  }\n\n  return payload.body?.data ? tryDecode(payload.body.data).slice(0, 1200) : \"\";\n}\n\nfunction formatEmailTime(dateStr) {\n  if (!dateStr) return \"\";\n  const d = new Date(dateStr);\n  if (isNaN(d.getTime())) return \"\";\n  const now     = new Date();\n  const isToday = d.toDateString() === now.toDateString();\n  return isToday\n    ? d.toLocaleTimeString(\"en-US\", { hour: \"2-digit\", minute: \"2-digit\" })\n    : d.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\" });\n}\n\n\u002F\u002F ── URGENCY CLASSIFICATION ─────────────────────────────────\nasync function classifyUrgency(emails) {\n  if (emails.length === 0) return emails;\n\n  const today = new Date().toDateString();\n\n  const summaries = emails.map((e, i) =>\n    `${i}: From: ${e.sender} | Subject: ${e.subject} | Snippet: ${e.snippet.slice(0, 120)}`\n  ).join(\"\\n\");\n\n  const prompt = `You are an email urgency classifier. Today is ${today}.\n\nFor each email, return one of three urgency levels:\n- \"urgent\": Requires a response or action today — deadlines, direct questions from people you know, time-sensitive requests, calendar conflicts\n- \"today\":  Should be reviewed today but not immediately — project updates, FYIs, newsletters with today-specific content\n- \"normal\": Can wait — newsletters, marketing, automated notifications, CC'd threads, GitHub notifications\n\nClassify these emails and return a JSON array of objects with fields \"index\" (number) and \"urgency\" (string).\nReturn only valid JSON, no other text.\n\nEmails:\n${summaries}`;\n\n  try {\n    const msg = await anthropic.messages.create({\n      model:      \"claude-haiku-4-5-20251001\",\n      max_tokens: 512,\n      messages:   [{ role: \"user\", content: prompt }],\n    });\n\n    const text   = msg.content[0]?.text?.trim() || \"[]\";\n    const parsed = JSON.parse(text);\n\n    if (Array.isArray(parsed)) {\n      parsed.forEach(({ index, urgency }) => {\n        if (emails[index] && [\"urgent\", \"today\", \"normal\"].includes(urgency)) {\n          emails[index].urgency = urgency;\n        }\n      });\n    }\n  } catch (err) {\n    console.error(\"classifyUrgency error:\", err.message);\n    \u002F\u002F Non-fatal — emails keep urgency \"normal\"\n  }\n\n  return emails;\n}\n\n\u002F\u002F ── SEND REPLY ─────────────────────────────────────────────\nasync function sendReply(params) {\n  const { emailId, body, subject } = params;\n\n  if (!body || !emailId) {\n    return { error: \"Missing emailId or body\" };\n  }\n\n  try {\n    const gmail   = getGmailClient();\n    const original = await gmail.users.messages.get({ userId: \"me\", id: emailId, format: \"metadata\" });\n    const headers  = original.data.payload?.headers || [];\n    const get      = name => headers.find(h => h.name.toLowerCase() === name)?.value || \"\";\n\n    const to        = parseSenderEmail(get(\"from\"));\n    const threadId  = original.data.threadId;\n    const messageId = get(\"message-id\");\n\n    const rawMessage = [\n      `From: ${process.env.GMAIL_USER}`,\n      `To: ${to}`,\n      `Subject: ${subject || \"Re: \" + get(\"subject\")}`,\n      `In-Reply-To: ${messageId}`,\n      `References: ${messageId}`,\n      \"Content-Type: text\u002Fplain; charset=utf-8\",\n      \"\",\n      body,\n    ].join(\"\\r\\n\");\n\n    const encoded = Buffer.from(rawMessage).toString(\"base64url\");\n\n    await gmail.users.messages.send({\n      userId: \"me\",\n      requestBody: { raw: encoded, threadId },\n    });\n\n    \u002F\u002F Archive (move to All Mail, remove INBOX label)\n    await gmail.users.messages.modify({\n      userId:      \"me\",\n      id:          emailId,\n      requestBody: { removeLabelIds: [\"INBOX\", \"UNREAD\"] },\n    });\n\n    return { ok: true, confirmation: \"Reply sent and email archived.\" };\n\n  } catch (err) {\n    console.error(\"send_reply error:\", err.message);\n    return { error: err.message };\n  }\n}\n\n\u002F\u002F ── BATCH ACTIONS ──────────────────────────────────────────\nasync function batchAction(params) {\n  const { action, emailIds = [], params: actionParams = {} } = params;\n\n  try {\n    const gmail = getGmailClient();\n\n    switch (action) {\n      case \"archive_skipped\":\n      case \"archive_newsletters\":\n      case \"mark_all_read\": {\n        const removals = action === \"mark_all_read\"\n          ? [\"UNREAD\"]\n          : [\"INBOX\", \"UNREAD\"];\n\n        await Promise.all(\n          emailIds.map(id =>\n            gmail.users.messages.modify({\n              userId:      \"me\",\n              id,\n              requestBody: { removeLabelIds: removals },\n            })\n          )\n        );\n\n        const verb = action === \"mark_all_read\" ? \"marked read\" : \"archived\";\n        return {\n          ok:           true,\n          confirmation: `${emailIds.length} email${emailIds.length !== 1 ? \"s\" : \"\"} ${verb}.`,\n        };\n      }\n\n      case \"star_sender\": {\n        await Promise.all(\n          emailIds.map(id =>\n            gmail.users.messages.modify({\n              userId:      \"me\",\n              id,\n              requestBody: { addLabelIds: [\"STARRED\"] },\n            })\n          )\n        );\n        return {\n          ok:           true,\n          confirmation: `Starred ${emailIds.length} email${emailIds.length !== 1 ? \"s\" : \"\"} from ${actionParams.senderName || \"sender\"}.`,\n        };\n      }\n\n      case \"filter_priority\":\n        \u002F\u002F Archive everything not from priority senders (done locally on R1, no-op here)\n        return { ok: true, confirmation: \"Priority filter applied.\" };\n\n      default:\n        return { error: `Unknown batch action: ${action}` };\n    }\n\n  } catch (err) {\n    console.error(\"batch_action error:\", err.message);\n    return { error: err.message };\n  }\n}\n```\n\n### 6. Start OpenClaw\n\n```bash\nopenclaw serve\n```\n\nYou should see `email-triage` listed in the registered skills output.\n\n## Command reference\n\n### `fetch_inbox`\n\nSent on app open. No params required.\n\n**Response:**\n\n| Field | Type | Description |\n|---|---|---|\n| `emails` | array | Prioritized email objects (see below) |\n| `error` | string\\|null | Error message if fetch failed |\n\n**Email object:**\n\n| Field | Type | Description |\n|---|---|---|\n| `id` | string | Gmail message ID |\n| `sender` | string | Display name |\n| `senderEmail` | string | Email address |\n| `subject` | string | Email subject |\n| `snippet` | string | Short preview text |\n| `body` | string | Full plain-text body (up to 1200 chars) |\n| `urgency` | `\"urgent\"` \\| `\"today\"` \\| `\"normal\"` | LLM-classified priority |\n| `time` | string | Human-readable receive time |\n\n### `send_reply`\n\nSent when the user confirms a dictated reply.\n\n| Field | Type | Description |\n|---|---|---|\n| `emailId` | string | Gmail message ID being replied to |\n| `body` | string | Dictated reply text |\n| `subject` | string | Reply subject (prefixed with `Re:`) |\n\n**Response:**\n\n| Field | Type | Description |\n|---|---|---|\n| `ok` | boolean | True if send succeeded |\n| `confirmation` | string | Human-readable confirmation for TTS |\n| `error` | string\\|null | Error if failed |\n\n### `batch_action`\n\nSent when the user selects and confirms a batch operation.\n\n| Field | Type | Description |\n|---|---|---|\n| `action` | string | One of `archive_skipped`, `archive_newsletters`, `star_sender`, `mark_all_read`, `filter_priority` |\n| `emailIds` | string[] | IDs to act on |\n| `params` | object | Action-specific params (e.g. `{senderEmail, senderName}` for star_sender) |\n\n**Response:**\n\n| Field | Type | Description |\n|---|---|---|\n| `ok` | boolean | True if action succeeded |\n| `confirmation` | string | Spoken confirmation text |\n| `error` | string\\|null | Error if failed |\n\n## Urgency classification logic\n\nThe skill uses `claude-haiku-4-5-20251001` to classify each email as `urgent`, `today`, or `normal` based on sender, subject, and snippet. Classification is batch-processed in a single API call for all emails in the fetch. Failures are non-fatal — emails default to `normal` urgency.\n\n**Urgent signals:** deadlines, direct questions, calendar invites, meeting requests, \"ASAP\", \"today\", \"by EOD\", replies from known contacts.\n\n**Today signals:** project updates, newsletters with time-sensitive content, FYI threads you are directly addressed in.\n\n**Normal signals:** marketing, automated notifications, GitHub\u002FJira bot messages, CC'd threads, newsletters.\n\n## Troubleshooting\n\n**R1 shows \"Connection failed\" on open**\n- Confirm `openclaw serve` is running on the same network as the R1\n- Check that the skill is registered in `openclaw.config.json`\n- Verify your `.env` file is in `~\u002F.openclaw\u002Fskills\u002Femail-triage\u002F`\n\n**Red LED immediately — no emails loaded**\n- The Gmail OAuth2 refresh token may have expired — re-run `auth-setup.js`\n- Confirm the Gmail API is enabled for your project in Google Cloud Console\n- Check `GMAIL_USER` matches the authenticated account\n\n**Urgency classification always \"normal\"**\n- Verify `ANTHROPIC_API_KEY` is valid and has quota\n- Check the Haiku model ID (`claude-haiku-4-5-20251001`) is correct for your account\n- Switch to `claude-sonnet-4-6` for more accurate classification on complex inboxes\n\n**Send reply fails**\n- Confirm the refresh token has `gmail.send` scope (requires re-auth if it was created without it)\n- Check that the original message ID exists and has not been permanently deleted\n\n**Batch archive does nothing**\n- Verify the R1 app is passing the correct `emailIds` array\n- Gmail API requires `gmail.modify` scope — re-run auth if the token predates that scope\n\n## Security notes\n\n- OAuth2 refresh tokens grant full Gmail access. Store `.env` securely and never commit it to version control.\n- The skill runs only on your local machine. Email content is sent only to the Anthropic API for urgency classification (snippet + subject, not full body). Full email bodies are sent to the R1 for reading aloud but never to any third party.\n- OpenClaw communicates over localhost by default. Do not expose the OpenClaw port to the internet without authentication.\n- Reply templates and priority sender lists are stored in R1 on-device storage only — they do not leave the device.\n","# EmailTriage — OpenClaw Skill\n\nEmailTriage uses your local machine as the mail backend for voice-driven inbox management on the R1. The skill connects to Gmail (or IMAP), fetches your unread emails, has an LLM flag urgency, and handles send\u002Farchive\u002Fbatch commands dispatched from the R1 app.\n\n## How it works\n\n1. R1 opens and sends `fetch_inbox` to this skill via the OpenClaw shared-storage bridge\n2. The skill fetches unread emails, runs LLM urgency classification, and returns a prioritized list\n3. R1 announces the count and reads summaries aloud — you scroll and tap with one hand\n4. Dictated replies are sent via `send_reply`; archive, skip, and star commands via `batch_action`\n5. Handled email IDs are persisted in R1 storage so the app stays in sync across sessions\n\n## Prerequisites\n\n### Required\n\n- **Node.js 20+** on your local machine\n- **OpenClaw CLI** installed and running (`openclaw serve`)\n- An **Anthropic API key** for urgency classification (or OpenAI key)\n- A **Gmail account** with OAuth2 credentials configured (see step 2), or an IMAP\u002FSMTP server\n\n### Optional\n\n- **Nodemailer** for SMTP-based sending (included in deps)\n- **node-imap** for non-Gmail IMAP accounts\n- **Gmail API** via `googleapis` (recommended — faster and no IMAP needed)\n\n## Local setup\n\n### 1. Install dependencies\n\n```bash\ncd ~\u002F.openclaw\u002Fskills\u002Femail-triage\nnpm install @anthropic-ai\u002Fsdk googleapis nodemailer dotenv\n```\n\n### 2. Configure Gmail OAuth2\n\nFollow the [Gmail API Quickstart](https:\u002F\u002Fdevelopers.google.com\u002Fgmail\u002Fapi\u002Fquickstart\u002Fnodejs) to create OAuth2 credentials:\n\n1. Create a project in Google Cloud Console\n2. Enable the Gmail API\n3. Create OAuth2 credentials (Desktop app type)\n4. Run the one-time auth flow to generate a refresh token:\n\n```bash\nnode auth-setup.js\n```\n\nWhere `auth-setup.js` is the standard OAuth2 token exchange script — see the Gmail API quickstart linked above.\n\n### 3. Configure environment\n\nCreate `~\u002F.openclaw\u002Fskills\u002Femail-triage\u002F.env`:\n\n```env\n# Required — LLM for urgency classification\nANTHROPIC_API_KEY=sk-ant-...\n\n# Gmail OAuth2 (recommended)\nGMAIL_CLIENT_ID=...apps.googleusercontent.com\nGMAIL_CLIENT_SECRET=...\nGMAIL_REFRESH_TOKEN=...\nGMAIL_USER=you@gmail.com\n\n# Alternative: IMAP\u002FSMTP (if not using Gmail API)\nIMAP_HOST=imap.example.com\nIMAP_PORT=993\nIMAP_USER=you@example.com\nIMAP_PASS=yourpassword\nSMTP_HOST=smtp.example.com\nSMTP_PORT=587\nSMTP_USER=you@example.com\nSMTP_PASS=yourpassword\n\n# Optional — use OpenAI instead of Anthropic\nOPENAI_API_KEY=sk-...\n\n# Tuning\nMAX_EMAILS=20\nFETCH_DAYS=1\n```\n\n### 4. Register the skill\n\nAdd to `~\u002F.openclaw\u002Fopenclaw.config.json`:\n\n```json\n{\n  \"skills\": [\n    {\n      \"name\": \"email-triage\",\n      \"path\": \"~\u002F.openclaw\u002Fskills\u002Femail-triage\u002Fskill.js\",\n      \"description\": \"Morning voice inbox — fetch, prioritize, reply, archive via R1\"\n    }\n  ]\n}\n```\n\n### 5. Create the skill file\n\nCreate `~\u002F.openclaw\u002Fskills\u002Femail-triage\u002Fskill.js`:\n\n```javascript\n\"use strict\";\nrequire(\"dotenv\").config({ path: __dirname + \"\u002F.env\" });\n\nconst { google }   = require(\"googleapis\");\nconst Anthropic    = require(\"@anthropic-ai\u002Fsdk\");\nconst nodemailer   = require(\"nodemailer\");\n\nconst MAX_EMAILS  = parseInt(process.env.MAX_EMAILS  || \"20\", 10);\nconst FETCH_DAYS  = parseInt(process.env.FETCH_DAYS  || \"1\",  10);\nconst anthropic   = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });\n\n\u002F\u002F ── Gmail client ───────────────────────────────────────────\nfunction getGmailClient() {\n  const auth = new google.auth.OAuth2(\n    process.env.GMAIL_CLIENT_ID,\n    process.env.GMAIL_CLIENT_SECRET\n  );\n  auth.setCredentials({ refresh_token: process.env.GMAIL_REFRESH_TOKEN });\n  return google.gmail({ version: \"v1\", auth });\n}\n\n\u002F\u002F ── Entry point ────────────────────────────────────────────\nmodule.exports = async function emailTriage(command, params, storage) {\n  switch (command) {\n    case \"fetch_inbox\":   return fetchInbox();\n    case \"send_reply\":    return sendReply(params);\n    case \"batch_action\":  return batchAction(params);\n    default:\n      return { error: `Unknown command: ${command}` };\n  }\n};\n\n\u002F\u002F ── FETCH INBOX ────────────────────────────────────────────\nasync function fetchInbox() {\n  try {\n    const gmail  = getGmailClient();\n    const cutoff = new Date();\n    cutoff.setDate(cutoff.getDate() - FETCH_DAYS);\n    const after  = Math.floor(cutoff.getTime() \u002F 1000);\n\n    const listResp = await gmail.users.messages.list({\n      userId:  \"me\",\n      q:       `is:unread after:${after}`,\n      maxResults: MAX_EMAILS,\n    });\n\n    const messageList = listResp.data.messages || [];\n    if (messageList.length === 0) {\n      return { emails: [] };\n    }\n\n    const rawEmails = await Promise.all(\n      messageList.map(m => fetchMessage(gmail, m.id))\n    );\n\n    const filtered = rawEmails.filter(Boolean);\n    const emails   = await classifyUrgency(filtered);\n\n    \u002F\u002F Sort: urgent first, then today, then normal\n    emails.sort((a, b) => {\n      const rank = { urgent: 0, today: 1, normal: 2 };\n      return (rank[a.urgency] ?? 2) - (rank[b.urgency] ?? 2);\n    });\n\n    return { emails };\n\n  } catch (err) {\n    console.error(\"fetch_inbox error:\", err.message);\n    return { error: err.message };\n  }\n}\n\nasync function fetchMessage(gmail, id) {\n  try {\n    const msg    = await gmail.users.messages.get({ userId: \"me\", id, format: \"full\" });\n    const headers = msg.data.payload?.headers || [];\n    const get    = name => headers.find(h => h.name.toLowerCase() === name)?.value || \"\";\n\n    const sender      = parseSenderName(get(\"from\"));\n    const senderEmail = parseSenderEmail(get(\"from\"));\n    const subject     = get(\"subject\") || \"(no subject)\";\n    const date        = get(\"date\");\n    const snippet     = msg.data.snippet || \"\";\n    const body        = extractBody(msg.data.payload);\n    const time        = formatEmailTime(date);\n\n    return { id, sender, senderEmail, subject, snippet, body, time, urgency: \"normal\" };\n  } catch (err) {\n    console.error(\"fetchMessage error:\", id, err.message);\n    return null;\n  }\n}\n\nfunction parseSenderName(from) {\n  const match = from.match(\u002F^([^\u003C]+)\u003C\u002F);\n  return match ? match[1].trim().replace(\u002F^\"|\"$\u002Fg, \"\") : from.split(\"@\")[0];\n}\n\nfunction parseSenderEmail(from) {\n  const match = from.match(\u002F\u003C([^>]+)>\u002F);\n  return match ? match[1] : from;\n}\n\nfunction extractBody(payload) {\n  if (!payload) return \"\";\n  const tryDecode = data => {\n    try { return Buffer.from(data, \"base64\").toString(\"utf-8\"); } catch (_) { return \"\"; }\n  };\n\n  if (payload.mimeType === \"text\u002Fplain\" && payload.body?.data) {\n    return tryDecode(payload.body.data).slice(0, 1200);\n  }\n\n  if (payload.parts) {\n    for (const part of payload.parts) {\n      if (part.mimeType === \"text\u002Fplain\" && part.body?.data) {\n        return tryDecode(part.body.data).slice(0, 1200);\n      }\n    }\n    \u002F\u002F Fall back to HTML part stripped of tags\n    for (const part of payload.parts) {\n      if (part.mimeType === \"text\u002Fhtml\" && part.body?.data) {\n        const html = tryDecode(part.body.data);\n        return html.replace(\u002F\u003C[^>]+>\u002Fg, \" \").replace(\u002F\\s+\u002Fg, \" \").trim().slice(0, 1200);\n      }\n    }\n  }\n\n  return payload.body?.data ? tryDecode(payload.body.data).slice(0, 1200) : \"\";\n}\n\nfunction formatEmailTime(dateStr) {\n  if (!dateStr) return \"\";\n  const d = new Date(dateStr);\n  if (isNaN(d.getTime())) return \"\";\n  const now     = new Date();\n  const isToday = d.toDateString() === now.toDateString();\n  return isToday\n    ? d.toLocaleTimeString(\"en-US\", { hour: \"2-digit\", minute: \"2-digit\" })\n    : d.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\" });\n}\n\n\u002F\u002F ── URGENCY CLASSIFICATION ─────────────────────────────────\nasync function classifyUrgency(emails) {\n  if (emails.length === 0) return emails;\n\n  const today = new Date().toDateString();\n\n  const summaries = emails.map((e, i) =>\n    `${i}: From: ${e.sender} | Subject: ${e.subject} | Snippet: ${e.snippet.slice(0, 120)}`\n  ).join(\"\\n\");\n\n  const prompt = `You are an email urgency classifier. Today is ${today}.\n\nFor each email, return one of three urgency levels:\n- \"urgent\": Requires a response or action today — deadlines, direct questions from people you know, time-sensitive requests, calendar conflicts\n- \"today\":  Should be reviewed today but not immediately — project updates, FYIs, newsletters with today-specific content\n- \"normal\": Can wait — newsletters, marketing, automated notifications, CC'd threads, GitHub notifications\n\nClassify these emails and return a JSON array of objects with fields \"index\" (number) and \"urgency\" (string).\nReturn only valid JSON, no other text.\n\nEmails:\n${summaries}`;\n\n  try {\n    const msg = await anthropic.messages.create({\n      model:      \"claude-haiku-4-5-20251001\",\n      max_tokens: 512,\n      messages:   [{ role: \"user\", content: prompt }],\n    });\n\n    const text   = msg.content[0]?.text?.trim() || \"[]\";\n    const parsed = JSON.parse(text);\n\n    if (Array.isArray(parsed)) {\n      parsed.forEach(({ index, urgency }) => {\n        if (emails[index] && [\"urgent\", \"today\", \"normal\"].includes(urgency)) {\n          emails[index].urgency = urgency;\n        }\n      });\n    }\n  } catch (err) {\n    console.error(\"classifyUrgency error:\", err.message);\n    \u002F\u002F Non-fatal — emails keep urgency \"normal\"\n  }\n\n  return emails;\n}\n\n\u002F\u002F ── SEND REPLY ─────────────────────────────────────────────\nasync function sendReply(params) {\n  const { emailId, body, subject } = params;\n\n  if (!body || !emailId) {\n    return { error: \"Missing emailId or body\" };\n  }\n\n  try {\n    const gmail   = getGmailClient();\n    const original = await gmail.users.messages.get({ userId: \"me\", id: emailId, format: \"metadata\" });\n    const headers  = original.data.payload?.headers || [];\n    const get      = name => headers.find(h => h.name.toLowerCase() === name)?.value || \"\";\n\n    const to        = parseSenderEmail(get(\"from\"));\n    const threadId  = original.data.threadId;\n    const messageId = get(\"message-id\");\n\n    const rawMessage = [\n      `From: ${process.env.GMAIL_USER}`,\n      `To: ${to}`,\n      `Subject: ${subject || \"Re: \" + get(\"subject\")}`,\n      `In-Reply-To: ${messageId}`,\n      `References: ${messageId}`,\n      \"Content-Type: text\u002Fplain; charset=utf-8\",\n      \"\",\n      body,\n    ].join(\"\\r\\n\");\n\n    const encoded = Buffer.from(rawMessage).toString(\"base64url\");\n\n    await gmail.users.messages.send({\n      userId: \"me\",\n      requestBody: { raw: encoded, threadId },\n    });\n\n    \u002F\u002F Archive (move to All Mail, remove INBOX label)\n    await gmail.users.messages.modify({\n      userId:      \"me\",\n      id:          emailId,\n      requestBody: { removeLabelIds: [\"INBOX\", \"UNREAD\"] },\n    });\n\n    return { ok: true, confirmation: \"Reply sent and email archived.\" };\n\n  } catch (err) {\n    console.error(\"send_reply error:\", err.message);\n    return { error: err.message };\n  }\n}\n\n\u002F\u002F ── BATCH ACTIONS ──────────────────────────────────────────\nasync function batchAction(params) {\n  const { action, emailIds = [], params: actionParams = {} } = params;\n\n  try {\n    const gmail = getGmailClient();\n\n    switch (action) {\n      case \"archive_skipped\":\n      case \"archive_newsletters\":\n      case \"mark_all_read\": {\n        const removals = action === \"mark_all_read\"\n          ? [\"UNREAD\"]\n          : [\"INBOX\", \"UNREAD\"];\n\n        await Promise.all(\n          emailIds.map(id =>\n            gmail.users.messages.modify({\n              userId:      \"me\",\n              id,\n              requestBody: { removeLabelIds: removals },\n            })\n          )\n        );\n\n        const verb = action === \"mark_all_read\" ? \"marked read\" : \"archived\";\n        return {\n          ok:           true,\n          confirmation: `${emailIds.length} email${emailIds.length !== 1 ? \"s\" : \"\"} ${verb}.`,\n        };\n      }\n\n      case \"star_sender\": {\n        await Promise.all(\n          emailIds.map(id =>\n            gmail.users.messages.modify({\n              userId:      \"me\",\n              id,\n              requestBody: { addLabelIds: [\"STARRED\"] },\n            })\n          )\n        );\n        return {\n          ok:           true,\n          confirmation: `Starred ${emailIds.length} email${emailIds.length !== 1 ? \"s\" : \"\"} from ${actionParams.senderName || \"sender\"}.`,\n        };\n      }\n\n      case \"filter_priority\":\n        \u002F\u002F Archive everything not from priority senders (done locally on R1, no-op here)\n        return { ok: true, confirmation: \"Priority filter applied.\" };\n\n      default:\n        return { error: `Unknown batch action: ${action}` };\n    }\n\n  } catch (err) {\n    console.error(\"batch_action error:\", err.message);\n    return { error: err.message };\n  }\n}\n```\n\n### 6. Start OpenClaw\n\n```bash\nopenclaw serve\n```\n\nYou should see `email-triage` listed in the registered skills output.\n\n## Command reference\n\n### `fetch_inbox`\n\nSent on app open. No params required.\n\n**Response:**\n\n| Field | Type | Description |\n|---|---|---|\n| `emails` | array | Prioritized email objects (see below) |\n| `error` | string\\|null | Error message if fetch failed |\n\n**Email object:**\n\n| Field | Type | Description |\n|---|---|---|\n| `id` | string | Gmail message ID |\n| `sender` | string | Display name |\n| `senderEmail` | string | Email address |\n| `subject` | string | Email subject |\n| `snippet` | string | Short preview text |\n| `body` | string | Full plain-text body (up to 1200 chars) |\n| `urgency` | `\"urgent\"` \\| `\"today\"` \\| `\"normal\"` | LLM-classified priority |\n| `time` | string | Human-readable receive time |\n\n### `send_reply`\n\nSent when the user confirms a dictated reply.\n\n| Field | Type | Description |\n|---|---|---|\n| `emailId` | string | Gmail message ID being replied to |\n| `body` | string | Dictated reply text |\n| `subject` | string | Reply subject (prefixed with `Re:`) |\n\n**Response:**\n\n| Field | Type | Description |\n|---|---|---|\n| `ok` | boolean | True if send succeeded |\n| `confirmation` | string | Human-readable confirmation for TTS |\n| `error` | string\\|null | Error if failed |\n\n### `batch_action`\n\nSent when the user selects and confirms a batch operation.\n\n| Field | Type | Description |\n|---|---|---|\n| `action` | string | One of `archive_skipped`, `archive_newsletters`, `star_sender`, `mark_all_read`, `filter_priority` |\n| `emailIds` | string[] | IDs to act on |\n| `params` | object | Action-specific params (e.g. `{senderEmail, senderName}` for star_sender) |\n\n**Response:**\n\n| Field | Type | Description |\n|---|---|---|\n| `ok` | boolean | True if action succeeded |\n| `confirmation` | string | Spoken confirmation text |\n| `error` | string\\|null | Error if failed |\n\n## Urgency classification logic\n\nThe skill uses `claude-haiku-4-5-20251001` to classify each email as `urgent`, `today`, or `normal` based on sender, subject, and snippet. Classification is batch-processed in a single API call for all emails in the fetch. Failures are non-fatal — emails default to `normal` urgency.\n\n**Urgent signals:** deadlines, direct questions, calendar invites, meeting requests, \"ASAP\", \"today\", \"by EOD\", replies from known contacts.\n\n**Today signals:** project updates, newsletters with time-sensitive content, FYI threads you are directly addressed in.\n\n**Normal signals:** marketing, automated notifications, GitHub\u002FJira bot messages, CC'd threads, newsletters.\n\n## Troubleshooting\n\n**R1 shows \"Connection failed\" on open**\n- Confirm `openclaw serve` is running on the same network as the R1\n- Check that the skill is registered in `openclaw.config.json`\n- Verify your `.env` file is in `~\u002F.openclaw\u002Fskills\u002Femail-triage\u002F`\n\n**Red LED immediately — no emails loaded**\n- The Gmail OAuth2 refresh token may have expired — re-run `auth-setup.js`\n- Confirm the Gmail API is enabled for your project in Google Cloud Console\n- Check `GMAIL_USER` matches the authenticated account\n\n**Urgency classification always \"normal\"**\n- Verify `ANTHROPIC_API_KEY` is valid and has quota\n- Check the Haiku model ID (`claude-haiku-4-5-20251001`) is correct for your account\n- Switch to `claude-sonnet-4-6` for more accurate classification on complex inboxes\n\n**Send reply fails**\n- Confirm the refresh token has `gmail.send` scope (requires re-auth if it was created without it)\n- Check that the original message ID exists and has not been permanently deleted\n\n**Batch archive does nothing**\n- Verify the R1 app is passing the correct `emailIds` array\n- Gmail API requires `gmail.modify` scope — re-run auth if the token predates that scope\n\n## Security notes\n\n- OAuth2 refresh tokens grant full Gmail access. Store `.env` securely and never commit it to version control.\n- The skill runs only on your local machine. Email content is sent only to the Anthropic API for urgency classification (snippet + subject, not full body). Full email bodies are sent to the R1 for reading aloud but never to any third party.\n- OpenClaw communicates over localhost by default. Do not expose the OpenClaw port to the internet without authentication.\n- Reply templates and priority sender lists are stored in R1 on-device storage only — they do not leave the device.\n",{"name":5,"author":24,"version":25,"description":7},"rabbit-r1-skillz","1.0.0","main","734489c70f6293d3b800cd956559034acaa9f563","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren","https:\u002F\u002Fgithub.com\u002Fajohnsonnow","structuredforgrowth.com","2026-09-04 21:06:25",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add ajohnsonnow\u002Fr1-warren --skill email-triage",{"tool":38,"command":39},"bunx","bunx skills add ajohnsonnow\u002Fr1-warren --skill email-triage",{"tool":41,"command":42},"pnpm","pnpm dlx skills add ajohnsonnow\u002Fr1-warren --skill email-triage","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Femail-triage\u002FSKILL.md",true,[46,52,56],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"card.jpg","ASSET","资产文件",20490,"https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Femail-triage\u002Fcard.jpg",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"icon.png",11202,"https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Femail-triage\u002Ficon.png",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"index.html","REFERENCE","参考文档",48566,"https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Femail-triage\u002Findex.html",[63,70,77,84,91,98],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M75THZJQ1XYR8QDWB9RXC9QV","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.","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Fwhisper-quiz\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M75THW5BJRSQQM3QP6M568FT","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 \u002F Anchor, Podbean, Buzzsprout, RSS.com, or any FTP-accessible feed).","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Fwalk-cast\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M75THTANZTS2AMDDBP615RTA","voice-novel","Local machine skill for VoiceNovel — handles story export to disk.","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Fvoice-novel\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M75THQ175ZRJ3E0GPFW7QKM8","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\u002Fvehicles\u002Ffood\u002Fhazards\u002Fexits), performs 360° scans, retrieves GPS position, and sends emergency SMS alerts — all via audio feedback with zero screen dependency.","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Fvoice-guide\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M75THKAJR69WV7QQYJ26X95C","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.","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Fvoice-draft\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M75THGKGY2JY59MM9PREXCXX","voice-commit","Hands-free git and CI workflow voice controller for the Rabbit R1. Speak git\u002FCI commands and hear results — commit, push, status, PR management, test runs, and deploy, all voice-driven via OpenClaw.","https:\u002F\u002Fgithub.com\u002Fajohnsonnow\u002Fr1-warren\u002Fblob\u002Fmain\u002Fvoice-commit\u002FSKILL.md",[],[]]