
Hooks System - Functional hooks adapted from Claude Code's React hooks. Includes permission checking, status management, inbox polling, typeahead, and more. Use when [hooks system] is needed.
# Hook Types Skill Hook类型系统 - Discriminated hook output + Zod validation + Event-specific output + Async/Sync type guard。 ## 功能概述 从Claude Code的Hook Types提取的hook类型模式,用于OpenClaw的hook系统。 ## 核心机制 ### Discriminated Hook Output ```typescript hookSpecificOutput: z.union([ z.object({ hookEventName: z.literal('PreToolUse'), permissionDecision, updatedInput }), z.object({ hookEventName: z.literal('UserPromptSubmit'), additionalContext }), z.object({ hookEventName: z.literal('SessionStart'), in
Score Analyzer - 分数趋势分析,判断 IMPROVING/STAGNANT/DECLINING,推荐 REFINE/PIVOT 策略。适用多轮迭代场景,指导下一步行动。
Triage GitHub issues through label-based state machine with interactive grilling sessions. Use when user wants to triage issues, review incoming bugs, prepare issues for AFK agent, or manage issue workflow.
# Git Worktree Main Repo Detection Pattern ## Source Claude Code: `utils/sandbox/sandbox-adapter.ts` (detectWorktreeMainRepoPath) ## Pattern Detect git worktree and resolve main repo path once at initialization - cached for session. ## Code Example ```typescript // Cached main repo path for worktrees // undefined = not yet resolved; null = not a worktree let worktreeMainRepoPath: string | null | undefined /** * Detect if cwd is a git worktree and resolve the main repo path. * In a worktree
Git worktree support for isolated agent workspaces. Each agent gets its own worktree branch, preventing conflicts in parallel multi-agent work. Use when: - Multiple agents working on the same repo simultaneously - Need isolated branch per agent task - Parallel feature development without conflicts - Agent needs clean working directory Keywords: worktree, git branch, isolated workspace, parallel agents, multi-agent git
# Git Root Walker Pattern Skill Git Root Walker Pattern - findGitRootImpl + memoizeWithLRU + parent walk + statSync check + .git directory or file + GIT_ROOT_NOT_FOUND symbol + normalize NFC + stat count + dirname parent loop + root directory check + realpathSync。 ## 功能概述 从Claude Code的utils/git.ts提取的Git root walker模式,用于OpenClaw的Git根目录查找。 ## 核心机制 ### findGitRootImpl ```typescript const findGitRootImpl = memoizeWithLRU( (startPath: string): string | typeof GIT_ROOT_NOT_FOUND => { const
# Fuzzy Picker Skill Fuzzy Picker - PickerAction + previewPosition + direction (down/up) + CHROME_ROWS + visibleCount动态计算。 ## 功能概述 从Claude Code的FuzzyPicker提取的模糊选择器模式,用于OpenClaw的搜索/选择界面。 ## 核心机制 ### PickerAction Type ```typescript type PickerAction<T> = { /** Hint label shown in the byline, e.g. "mention" → "Tab to mention". */ action: string handler: (item: T) => void } onTab?: PickerAction<T> onShiftTab?: PickerAction<T> // Action + handler pair // Hint label for byline // Tab gets
File system operations abstraction. FsOperations type (cwd/existsSync/stat/readdir/unlink/rmdir/rm/mkdir/readFile/rename/readFileSync/writeFileSync/mkdirSync) + safeResolvePath + UNC path blocking + FIFO/Socket blocking + Type safety + Alternative implementations. Use when [fs operations] is needed.
Forked Subagent 创建模式。创建独立的子Agent处理特定任务,避免主会话上下文污染。Use when task needs isolated execution context.
# File Write Tool Skill 文件写入工具 - Atomic RMW + LSP notify + Mtime staleness + Skill discovery。 ## 功能概述 从Claude Code的FileWriteTool提取的文件写入模式,与FileEditTool类似但有独立机制。 ## 核心机制 ### Atomic RMW Pattern ```typescript // Load current state and confirm no changes since last read. // Please avoid async operations between here and writing to disk. let meta = readFileSyncWithMetadata(fullFilePath) if (meta !== null) { const lastWriteTime = getFileModificationTime(fullFilePath) const lastRead = readFil
Track file modification history with snapshots. Maintain up to 100 backups for diff comparison, change statistics, and version recovery. Use when checking file history, checkpointing changes, or rolling back edits.
飞书交互强制防止重复消息 Use when [feishu no repeat] is needed.
Rate limit cooldown mechanism. Switch to alternative mode when rate limit hit. Track cooldown state with expiration. Auto-recovery after cooldown period. Use when [fast mode cooldown] is needed.
# ExitPlanMode Scanner Stateful Classifier Pattern ## Source Claude Code: `utils/ultraplan/ccrSession.ts` (ExitPlanModeScanner) ## Pattern Stateful classifier for CCR event stream - ingest SDKMessage[] batches + precedence order + rescan after rejection. ## Code Example ```typescript export type ScanResult = | { kind: 'approved'; plan: string } | { kind: 'teleport'; plan: string } | { kind: 'rejected'; id: string } | { kind: 'pending' } | { kind: 'terminated'; subtype: string } |
# Env Truthy/Falsy Pattern Skill Env Truthy/Falsy Pattern - isEnvTruthy + isEnvDefinedFalsy + ['1','true','yes','on'] truthy + ['0','false','no','off'] falsy + boolean return + memoize getClaudeConfigHomeDir + CLAUDE_CONFIG_DIR key + normalize().trim().toLowerCase() + hasNodeOption split + parseEnvVars KEY=VALUE。 ## 功能概述 从Claude Code的utils/envUtils.ts提取的Env truthy/falsy模式,用于OpenClaw的环境变量解析。 ## 核心机制 ### isEnvTruthy ```typescript export function isEnvTruthy(envVar: string | boolean | undefin
# Enhanced Telemetry Feature Gate Pattern ## Source Claude Code: `utils/telemetry/sessionTracing.ts` (isEnhancedTelemetryEnabled) ## Pattern Feature gate check: env var override > ant build > GrowthBook gate. ## Code Example ```typescript import { feature } from 'bun:bundle' import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js' /** * Check if enhanced telemetry is enabled. * Priority: env var override > ant build > GrowthBook gate */ export function
# Entrypoint Truncation Pattern Skill Entrypoint Truncation Pattern - MAX_ENTRYPOINT_LINES=200 + MAX_ENTRYPOINT_BYTES=25000 + Line AND Byte caps + truncateEntrypointContent + Line-truncates first + Byte-truncates at newline。 ## 功能概述 从Claude Code的memdir/memdir.ts提取的截断模式,用于OpenClaw的文件大小限制。 ## 核心机制 ### MAX_ENTRYPOINT_LINES ```typescript export const ENTRYPOINT_NAME = 'MEMORY.md' export const MAX_ENTRYPOINT_LINES = 200 // ~125 chars/line at 200 lines // Line cap for entrypoint ``` ### MAX_ENT
# Duration Format Pattern Skill Duration Format Pattern - formatDuration + ms threshold branches + <60s formatSeconds + rounding carry-over + 60s→minutes++ + 24h→days++ + hideTrailingZeros + mostSignificantOnly + days/hours/minutes/seconds cascade + formatSecondsShort decimal + formatNumber Intl.NumberFormat compact + cached formatter。 ## 功能概述 从Claude Code的utils/format.ts提取的Duration format模式,用于OpenClaw的时长格式化。 ## 核心机制 ### formatDuration ```typescript export function formatDuration( ms: nu
# DOM Element Type Skill DOM Element Type - DOMElement comprehensive type + Scroll State + Event Handlers + dirty flag + yogaNode LayoutNode + scrollTop/pendingScrollDelta + scrollClamp pattern。 ## 功能概述 从Claude Code的ink/dom.ts提取的DOM元素类型定义,用于OpenClaw的终端UI渲染。 ## 核心机制 ### DOMElement Type ```typescript export type DOMElement = { nodeName: ElementNames attributes: Record<string, DOMNodeAttribute> childNodes: DOMNode[] textStyles?: TextStyles // Internal properties onComputeLayout?:
# Diff Optimizer Pattern Skill Diff Optimizer Pattern - optimize single pass + merge cursorMove + remove no-op (0,0) + concat styleStr + dedupe hyperlinks + cancel hide/show pairs + result array + len counter。 ## 功能概述 从Claude Code的ink/optimizer.ts提取的Diff优化模式,用于OpenClaw的终端渲染优化。 ## 核心机制 ### optimize Function ```typescript export function optimize(diff: Diff): Diff { if (diff.length <= 1) { return diff // Single patch: no optimization needed } const result: Diff = [] let len = 0
Track file diagnostics before/after edits Use when [diagnostic tracking] is needed.
Classify module dependencies into 4 categories for architectural decisions. Use when analyzing module dependencies, planning deep modules, or discussing test strategies.
# DECSTBM Scroll Optimization Skill DECSTBM Scroll Optimization - ScrollHint type + DECSTBM scroll region + hardware scroll (SU/SD) + top/bottom rows + delta direction + scrollTop change detection + CSI n S/CSI n T pattern。 ## 功能概述 从Claude Code的ink/render-node-to-output.ts提取的DECSTBM滚动优化模式,用于OpenClaw的终端滚动性能优化。 ## 核心机制 ### ScrollHint Type ```typescript // DECSTBM scroll optimization hint. When a ScrollBox's scrollTop changes // between frames (and nothing else moved), log-update.ts can emit
上下文可视化组件。展示上下文token使用情况,帮助用户理解当前状态。Use when displaying context usage to user.
上下文管理参考文档。Context压缩策略参考,详解4层压缩方法和阈值。Use when implementing context compression.
# Commit Command Skill Git提交命令 - Allowed tools限制 + Shell execution + Attribution。 ## 功能概述 从Claude Code的commit.ts提取的提交模式,用于OpenClaw的Git操作。 ## 核心机制 ### Allowed Tools ```typescript const ALLOWED_TOOLS = [ 'Bash(git add:*)', 'Bash(git status:*)', 'Bash(git commit:*)', ] // 只允许git add/status/commit ``` ### Prompt内容 ```typescript function getPromptContent(): string { const { commit: commitAttribution } = getAttributionTexts() return ` ## Context - Current git status: !\`git status
Beta headers support. 15+ beta headers. Provider-specific headers (1P/3P). Bedrock extra params. Vertex count tokens allowed betas. Feature gating. Use when [beta headers] is needed.
# Bare Git Repo Security Scrub Pattern ## Source Claude Code: `utils/sandbox/sandbox-adapter.ts` (bareGitRepoScrubPaths, scrubBareGitRepoFiles) ## Pattern Scrub planted bare-repo files after sandboxed command - prevent git config escape. ## Code Example ```typescript // SECURITY: Git's is_git_directory() treats cwd as a bare repo if it has: // HEAD + objects/ + refs/. An attacker planting these (plus config with // core.fsmonitor) escapes the sandbox when Claude's unsandboxed git runs. // Pa
Background Task UI - Integrate background task visualization with Feishu cards. Shows running tasks, progress, and completion status. Use when [background task ui] is needed.
Background memory consolidation service. Fires /dream prompt as forked subagent when time-gate (24h) AND session-gate (5 sessions) pass. Uses lock to prevent concurrent consolidation. Use when: - Implementing automatic memory consolidation - Running background dream/consolidation tasks - Checking if auto-dream should fire Keywords: auto-dream, memory consolidation, background consolidation, dream prompt, session gate
--- name: auto-compact-service description: "| Use when context pressure high, needs compaction, or approaching token limits." Auto compact service. Constants: - MAX_OUTPUT_TOKENS_FOR_SUMMARY: 20_000 Functions: - getEffectiveContextWindowSize(model): Context window minus max output Features: - CLAUDE_CODE_AUTO_COMPACT_WINDOW override - Session memory compaction - Post compact cleanup Keywords: - Service reference - auto compact metadata: openclaw: emoji: "
Ask users multiple choice questions via Feishu interactive cards. Use when: gathering preferences, clarifying ambiguity, making decisions, offering choices.
# App State Provider Skill 应用状态管理 - React Context + Zustand-like store。 ## 功能概述 从Claude Code的AppState.tsx提取的状态管理模式,用于OpenClaw的UI状态管理。 ## 核心机制 ### Provider结构 ```typescript type Props = { children: React.ReactNode initialState?: AppState onChangeAppState?: (args: { newState, oldState }) => void } export function AppStateProvider({ children, initialState, onChangeAppState }) { const [store] = useState(() => createStore(initialState ?? getDefaultAppState(), onChangeAppState)) // ...
Agent context management using AsyncLocalStorage. SubagentContext + TeammateAgentContext. Concurrent agent isolation. Context precedence. Use when spawning agents, managing concurrent sessions, or needing context isolation.
Activity time tracking for user vs CLI operations. Deduplicate overlapping activities. Track active time with timeout. Singleton instance. Use when managing user activity, tracking idle time, or handling away/return states.
--- name: coding-agent description: | Interactive coding assistant with Claude Code integration. Provides TUI-based code editing, git operations, AI-powered code review, LSP support, and Vim mode. Use when: user wants to edit code with AI assistance, create git commits, review code changes, diagnose coding issues, or use Vim motions in the editor. metadata: openclaw: emoji: 🤖 requires: bins: [node, git] node_modules: [ink, react, @anthropic-ai/sdk, chalk, diff, vsc
# BTW Command Skill 快速旁路问题命令 - forked agent处理side question,不中断主对话。 ## 功能概述 从Claude Code的btw.ts提取的旁路问题模式,用于OpenClaw的快速查询。 ## 核心机制 ### 命令结构 ```typescript { type: 'local-jsx', name: 'btw', description: 'Ask a quick side question without interrupting the main conversation', immediate: true, argumentHint: '<question>', load: () => import('./btw.js') } ``` ### 关键字段 | 字段 | 说明 | |------|------| | immediate | true - 立即执行,不等待turn end | | argumentHint | 用户问题提示 | ### 执行模式 - **Forked ag
# Buddy Companion Pattern Skill Buddy Companion Pattern - Mulberry32 PRNG + Rarity Roll + hashString + rollCache + CompanionBones vs CompanionSoul + Shiny chance 1%。 ## 功能概述 从Claude Code的buddy/companion.ts提取的伙伴系统模式,用于OpenClaw的趣味性功能。 ## 核心机制 ### Mulberry32 PRNG ```typescript // Mulberry32 — tiny seeded PRNG, good enough for picking ducks function mulberry32(seed: number): () => number { let a = seed >>> 0 return function () { a |= 0 a = (a + 0x6d2b79f5) | 0 let t = Math.imul
# CLI Hints Protocol Skill **优先级**: P29 **来源**: Claude Code `claudeCodeHints.ts` **适用场景**: Feishu卡片协议、CLI/SDK通信 --- ## 概述 CLI Hints Protocol允许SDK/CLI通过stderr发送自关闭XML标签 `<claude-code-hint />`,harness扫描处理后将stripped output传给model。hints是harness-only side channel,model不感知。 --- ## 核心功能 ### 1. Hint标签解析 ```typescript type ClaudeCodeHintType = 'plugin' | 'card' | 'progress' type ClaudeCodeHint = { v: number // Spec version type: ClaudeCodeHintType value: string // nam
Memory命令模式。管理记忆系统,查看、提取和压缩持久记忆。Use when managing memory via commands.
Claude Code 多代理协调模式,管理 Worker 工具权限和会话模式切换 Use when [coordinator mode] is needed.
Dynamic tool discovery via ToolSearchTool. Defer loading MCP and heavy tools until needed, reducing upfront context token usage. Use when: - Many MCP tools available but rarely all needed - Context window is tight and tool definitions take too many tokens - Need to discover tools by semantic search at runtime Keywords: tool search, deferred tools, dynamic tools, MCP tools, tool discovery
Effort levels for task complexity. Low/Medium/High/Max effort corresponds to task difficulty and model capability. Helps match task complexity with appropriate effort. Use when [effort] is needed.
Edit and improve articles by restructuring sections, improving clarity, and tightening prose. Use when user wants to edit, revise, or improve article draft.
# Feature Conditional Import Skill Feature Conditional Import - feature() + require() + null fallback + Dead Code Elimination + External Build Protection。 ## 功能概述 从Claude Code的多个文件提取的Feature Conditional Import模式,用于OpenClaw的条件导入。 ## 核心机制 ### feature() Check ```typescript import { feature } from 'bun:bundle' const proactiveModule = feature('PROACTIVE') || feature('KAIROS') ? require('../proactive/index.js') : null // Bun feature flag // Conditional import // null fallback ``` ### Dead
# Fixed-Size Circular Buffer Skill Fixed-Size Circular Buffer - CircularBuffer class + modulo arithmetic + head pointer + size tracking + add/getRecent/toArray + capacity fixed + oldest evict + rolling window + capacity constructor + buffer array。 ## 功能概述 从Claude Code的utils/CircularBuffer.ts提取的Fixed-size circular buffer模式,用于OpenClaw的滚动窗口数据存储。 ## 核心机制 ### CircularBuffer Class ```typescript export class CircularBuffer<T> { private buffer: T[] private head = 0 private size = 0 constr
Browser Test - Playwright 自动化测试,启动 dev server + headless Chromium,执行操作(click/fill/wait/evaluate),截图保存。适用 Web 应用测试场景。
Lifecycle hooks system for custom shell commands at various points. Execute user-defined hooks at PreToolUse, PostToolUse, Notification, Stop events. Use when [hooks] is needed.
Planner Agent - 将 1-4句话需求扩展为完整产品规格(spec.md),包含 Features/User Stories/Technical Stack/Design Direction。适用产品规划场景,自动生成规格文档。
# Bridge Kick Command Skill Bridge调试命令 - Ant-only + 故障注入 + Recovery测试。 ## 功能概述 从Claude Code的bridge-kick.ts提取的bridge调试模式,用于OpenClaw的远程控制故障测试。 ## 核心机制 ### Ant-only限制 ```typescript isEnabled: () => process.env.USER_TYPE === 'ant' // 只有Ant(内部)用户可用 // 生产环境不显示 ``` ### 故障注入 ```typescript // WebSocket close h.fireClose(code) // 1002, 1006等 // Poll failure h.injectFault({ method: 'pollForWork', kind: 'fatal', status: 404 }) // Register failure h.injectFault({ method: 'registerBridgeEnvironment
# Brief Mode Command Skill Brief模式命令 - Entitlement check + UserMsgOptIn同步 + MetaMessages。 ## 功能概述 从Claude Code的brief.ts提取的brief模式,用于OpenClaw的精简输出控制。 ## 核心机制 ### 双Gate控制 ```typescript isEnabled: () => { if (feature('KAIROS') || feature('KAIROS_BRIEF')) { return getBriefConfig().enable_slash_command } return false } // Feature flag + GrowthBook config双层控制 ``` ### Entitlement Check ```typescript // on-transition需要entitlement if (newState && !isBriefEntitled()) { logEvent('tengu_
Bridge Service - Remote collaboration system with connection management, session handling, messaging, permission callbacks, and capacity wake. Use when [bridge service] is needed.
Send messages to users with proactive vs normal status. Proactive: background task finished, blocker surfaced. Normal: replying to user request. Use when [brief] is needed.
Guide for analyzing chess positions from images and determining optimal moves. This skill should be used when asked to find the best move, checkmate, or tactical solution from a chess board image. It provides structured approaches for image-based chess analysis, piece detection calibration, position validation, and move verification.
Claude AI 使用量限制追踪系统,5h/7d 限额 + Early Warning Use when [claude ai limits] is needed.
# ClusteredChar Precompute Skill ClusteredChar Precompute - ClusteredChar type + precomputed width + styleId cached + hyperlink string + charCache session-lived + setCellAt hot loop optimization + StylePool interning。 ## 功能概述 从Claude Code的ink/output.ts提取的预计算优化模式,用于OpenClaw的终端渲染性能优化。 ## 核心机制 ### ClusteredChar Type ```typescript /** * A grapheme cluster with precomputed terminal width, styleId, and hyperlink. * Built once per unique line (cached via charCache), so the per-char hot loop *
Code indexing tool detection. CodeIndexingTool (30+ tools: Sourcegraph/Cody/Aider/Cursor/GitHub Copilot/Codeium/Tabnine/Windsurf/Amazon Q/Gemini) + CLI_COMMAND_MAPPING + MCP_SERVER_PATTERNS + detectCodeIndexingFromCommand + detectCodeIndexingFromMcp + Analytics tracking. Use when [code indexing detection] is needed.
# Color Discriminated Union Skill Color Discriminated Union - Color type union + type discriminant + named/indexed/rgb/default variants + NamedColor enum + TextStyle type + defaultStyle function + UnderlineStyle enum + comprehensive text attributes。 ## 功能概述 从Claude Code的ink/termio/types.ts提取的Color discriminated union模式,用于OpenClaw的ANSI样式类型定义。 ## 核心机制 ### Color Type Union ```typescript /** Color specification - can be named, indexed (256), or RGB */ export type Color = | { type: 'named'; n
Compact命令模式。执行上下文压缩,清理冗余内容以释放token空间。Use when compressing context via commands.
# Commands Registry Pattern Skill Commands Registry Pattern - getCommands + filterCommandsForRemoteMode + Dead code elimination imports + memoize + Command type + Non-interactive variants。 ## 功能概述 从Claude Code的commands.ts提取的命令注册模式,用于OpenClaw的命令系统。 ## 核心机制 ### getCommands ```typescript export function getCommands(): Command[] { return [ addDir, autofixPr, backfillSessions, btw, goodClaude, issue, feedback, clear, color, commit, copy, desktop
# Command Types Skill 命令类型系统 - Discriminated command kind + Availability array + Lazy load module + Immediate bypass queue。 ## 功能概述 从Claude Code的Command Types提取的命令类型模式,用于OpenClaw的命令系统。 ## 核心机制 ### Discriminated Command Kind ```typescript type LocalCommand = { type: 'local', load: () => Promise<LocalCommandModule> } type LocalJSXCommand = { type: 'local-jsx', load: () => Promise<LocalJSXCommandModule> } type PromptCommand = { type: 'prompt', getPromptForCommand(...), source, context, agent
Commit/PR attribution text generation. Model name sanitization. Internal vs external repo detection. Co-authored-by format. Use when [commit attribution] is needed.
# Compact Summary Skill Compact Summary - summarizeMetadata + direction (up_to/from_this_point) + userContext + BLACK_CIRCLE indicator。 ## 功能概述 从Claude Code的CompactSummary提取的压缩摘要模式,用于OpenClaw的会话压缩显示。 ## 核心机制 ### summarizeMetadata ```typescript const metadata = message.summarizeMetadata if (metadata) { return ( <Box> <Text>{BLACK_CIRCLE}</Text> <Text bold>Summarized conversation</Text> <Text dimColor>Summarized {metadata.messagesSummarized} messages {metadata.direct
Collapse repetitive read/search tool calls into summary lines to reduce context token usage. Use when: - Multiple consecutive file reads or searches in a session - Context window is getting large - Repeated bash/grep/glob operations - Hook summaries need aggregation Keywords: collapse, context, token, summarize reads, fold messages
Cron-based scheduled task system. Create, list, delete recurring or one-shot scheduled prompts. Use when: - User asks to schedule a recurring task ("every morning at 9am...") - User asks for a one-shot reminder ("remind me in 20 minutes") - User wants to automate periodic checks or reports - Managing existing scheduled tasks Keywords: schedule, cron, recurring, reminder, every day, every hour, loop, /loop
# Dream Detail Dialog Skill Dream Detail Dialog - Visible turns limit + Hidden turn collapse + Keyboard shortcuts + Elapsed time hook。 ## 功能概述 从Claude Code的DreamDetailDialog提取的dream任务详情模式,用于OpenClaw的长期任务展示。 ## 核心机制 ### Visible Turns Limit ```typescript const VISIBLE_TURNS = 6 const visibleTurns = task.turns.filter(isVisible) const shown = visibleTurns.slice(-VISIBLE_TURNS) const hidden = visibleTurns.length - shown.length // Render last 6 turns // Earlier turns collapse to count ``` ### H
--- name: extract-memories-service description: "| Use when [extract memories service] is needed." Extract memories service. Functions: - initExtractMemories() - extractMemories() - opener(newMessageCount, existingMemories) Strategy: - Turn 1: All FILE_READ calls in parallel - Turn 2: All FILE_WRITE/FILE_EDIT calls in parallel - No interleaved reads/writes Keywords: - Service reference - extract memories metadata: openclaw: emoji: "🧠" source: claude-code
# File Read Tool Skill 文件读取工具 - Dedup mtime + Blocked devices + Token budget + Multi-format。 ## 功能概述 从Claude Code的FileReadTool提取的文件读取模式,用于OpenClaw的文件读取。 ## 核心机制 ### Dedup by Mtime ```typescript const existingState = dedupKillswitch ? undefined : readFileState.get(fullFilePath) if (existingState && !existingState.isPartialView && existingState.offset !== undefined) { const rangeMatch = existingState.offset === offset && existingState.limit === limit if (rangeMatch) { const mtimeMs =
This skill provides guidance for XSS filter bypass tasks where the goal is to craft HTML payloads that execute JavaScript despite sanitization filters. Use this skill when tasks involve bypassing HTML sanitizers (like BeautifulSoup), exploiting parser differentials between server-side sanitizers and browsers, or security testing/CTF challenges involving XSS filter evasion.
Block dangerous git commands before execution. Use when user wants git safety, mentions dangerous git operations, or to prevent accidental pushes.
Git utilities. findGitRoot + resolveCanonicalRoot + getCachedBranch + getCachedRemoteUrl + getCachedHead + getWorktreeCountFromFs + LRU cache (50 entries) + Security validation + memoizeWithLRU. Use when [git utils] is needed.
Guidance for implementing neural network inference (like GPT-2) under extreme code size constraints. This skill should be used when tasks require implementing ML model inference in minimal code (code golf), parsing model checkpoints in constrained environments, or building transformer architectures in low-level languages like C with strict size limits.
# absoluteRects Tracking Skill absoluteRects Tracking - absoluteRectsPrev/Cur arrays + position:absolute tracking + ScrollBox blit+shift repair + three recording paths + full-render nodeCache.set + blit early-return + blitEscapingAbsoluteDescendants + clean-overlay consecutive scrolls。 ## 功能概述 从Claude Code的ink/render-node-to-output.ts提取的absoluteRects追踪模式,用于OpenClaw的滚动渲染修复。 ## 核心机制 ### absoluteRectsPrev/Cur Arrays ```typescript // Rects of position:absolute nodes from the PREVIOUS frame, us
# Allowed/Denied MCP Server Entry Pattern ## Source Claude Code: `utils/settings/types.ts` (AllowedMcpServerEntrySchema, DeniedMcpServerEntrySchema) ## Pattern MCP server allowlist/denylist with mutually exclusive matching fields + Zod refine validation. ## Code Example ```typescript export const AllowedMcpServerEntrySchema = lazySchema(() => z.object({ serverName: z.string() .regex(/[a-zA-Z0-9_-]+/, 'Server name: letters, numbers, hyphens, underscores') .optional() .d
上下文分析模式。分析消息历史,提取关键信息,识别用户意图。Use when analyzing conversation context.
Background memory consolidation. Periodically runs /dream prompt to extract and organize memories from recent sessions. Runs when enough sessions accumulated. Use when sessionCount >= 5, consolidation needed, or reviewing recent sessions.
# Auto Mode Module-Scope State Skill Auto Mode Module-Scope State - autoModeActive boolean + autoModeFlagCli boolean + autoModeCircuitBroken boolean + setAutoModeActive/isActive + setAutoModeFlagCli/getFlagCli + setAutoModeCircuitBroken/isCircuitBroken + _resetForTesting test helper + feature('TRANSCRIPT_CLASSIFIER') conditional require + circuit breaker disabled state + kick-out detection。 ## 功能概述 从Claude Code的utils/permissions/autoModeState.ts提取的Auto mode module-scope state,用于OpenClaw的auto
# Away Summary Skill **优先级**: P32 **来源**: Claude Code `awaySummary.ts` **适用场景**: 用户离开后返回摘要生成 --- ## 概述 Away Summary生成"While you were away"摘要,用于用户长时间未交互后返回时快速了解进度。使用最近30条消息 + session memory,调用small fast model生成1-3句摘要。 --- ## 核心功能 ### 1. 消息窗口 ```typescript const RECENT_MESSAGE_WINDOW = 30 export async function generateAwaySummary( messages: readonly Message[], signal: AbortSignal ): Promise<string | null> { if (messages.length === 0) return null const recent = messages.slice(-R
# Backend Detection Cached Result Pattern ## Source Claude Code: `utils/swarm/backends/registry.ts` (detectAndGetBackend) ## Pattern Cache detection result for process lifetime + priority flow + fallback handling. ## Code Example ```typescript let cachedBackend: PaneBackend | null = null let cachedDetectionResult: BackendDetectionResult | null = null let inProcessFallbackActive = false /** * Detection priority flow: * 1. If inside tmux, always use tmux (even in iTerm2) * 2. If in iTerm2 w
# Abort-Safe Sleep Pattern Skill Abort-Safe Sleep Pattern - sleep function + AbortSignal responsive + signal?.aborted check BEFORE timer + throwOnAbort option + abortError custom + unref timer + removeEventListener cleanup + setTimeout unref + withTimeout race + Promise.race pattern。 ## 功能概述 从Claude Code的utils/sleep.ts提取的Abort-safe sleep模式,用于OpenClaw的响应式延迟。 ## 核心机制 ### sleep Function ```typescript export function sleep( ms: number, signal?: AbortSignal, opts?: { throwOnAbort?: boolea
Agent摘要服务。生成Agent工作摘要报告,总结活动统计。Use when generating agent activity summary.
# Auto Mode Circuit Breaker Pattern Skill Auto Mode Circuit Breaker Pattern - verifyAutoModeGateAccess async check + getDynamicConfig_BLOCKS_ON_INIT enabled/disabled/opt-in + setAutoModeCircuitBroken kick-out + isAutoModeGateEnabled sync check + getAutoModeEnabledStateIfCached cold start + kickOutOfAutoIfNeeded transform function + carouselAvailable vs canEnterAuto + hasAutoModeOptInAnySource + modelSupportsAutoMode + disableFastMode breaker。 ## 功能概述 从Claude Code的utils/permissions/permissionS
# Backward-Compatible Schema Pattern ## Source Claude Code: `utils/settings/types.ts` (header comment + SettingsSchema) ## Pattern Zod schema designed for backward compatibility - new fields optional, old fields preserved. ## Code Example ```typescript /** * ⚠️ BACKWARD COMPATIBILITY NOTICE ⚠️ * * ✅ ALLOWED CHANGES: * - Adding new optional fields (always use .optional()) * - Adding new enum values (keeping existing ones) * - Adding new properties to objects * - Making validation more p
Combined abort signal utilities. createCombinedAbortSignal + signalB + timeoutMs options + cleanup function (remove listeners + clear timer) + Bun memory optimization (setTimeout > AbortSignal.timeout). Use when combining abort signals, adding timeout controls, or managing cleanup.
A/B测试管理技能 功能: - 创建A/B测试 - 分析测试结果 - 自动停止测试 - 生成测试报告 - 素材版本管理 Use when: - 创建广告素材A/B测试 - 分析测试效果 - 选择最优版本 - 管理素材版本 Keywords: - A/B测试, 素材测试, 效果对比, 版本管理
Systematic academic paper review workflow with structure extraction, methodology critique, and contribution assessment. Use when reviewing academic papers, analyzing research methodology, or evaluating paper contributions.
# Advisor Command Skill 顾问模型配置 - Feature-gated启用 + Model validation。 ## 功能概述 从Claude Code的advisor.ts提取的顾问模型模式,用于OpenClaw的辅助模型配置。 ## 核心机制 ### 命令结构 ```typescript { type: 'local', name: 'advisor', description: 'Configure the advisor model', argumentHint: '[<model>|off]', isEnabled: () => canUserConfigureAdvisor(), get isHidden() { return !canUserConfigureAdvisor() }, supportsNonInteractive: true, load: () => Promise.resolve({ call }) } ``` ### Feature-gated Visibility
Deterministic agent ID system. Agent IDs (agentName@teamName). Request IDs (requestType-timestamp@agentId). formatAgentId/parseAgentId. @ separator. Use when [agent id system] is needed.
Agent记忆系统。管理Agent的持久记忆,存储重要信息。Use when storing and retrieving agent memories.
--- name: agent-summary-services-directory description: "| Use when [agent summary services directory] is needed." Agent Summary services directory. Features: - Periodic background summarization for coordinator sub-agents - Forks conversation every ~30s - 1-2 sentence progress summary - Stored on AgentProgress for UI Constants: - SUMMARY_INTERVAL_MS: 30_000 Prompt Rules: - Present tense (-ing) - Name file/function, not branch - 3-5 words - No tools Good Ex
# Agent Tool Skill Agent执行工具 - Fork + Background + Worktree + Progress tracking。 ## 功能概述 从Claude Code的AgentTool提取的agent执行模式,用于OpenClaw的多agent管理。 ## 核心机制 ### Auto-background Threshold ```typescript function getAutoBackgroundMs(): number { if (isEnvTruthy('CLAUDE_AUTO_BACKGROUND_TASKS') || getFeatureValue('tengu_auto_background_agents', false)) { return 120_000 // 2 minutes } return 0 // disabled } // GrowthBook gate + env override // 长时间任务自动后台化 ``` ### Fork Execution ``
--- name: agent-tool-complete description: "| Use when [agent tool complete] is needed." Complete AgentTool implementation (15 files). Files: - AgentTool.tsx - Main component - agentColorManager.ts - Color management - agentDisplay.ts - Display logic - agentMemory.ts - Memory handling - agentMemorySnapshot.ts - Snapshot - agentToolUtils.ts - Utilities - built-in/ - Built-in agents - builtInAgents.ts - Built-in definitions - constants.ts - Constants - forkSubagent.ts -
Analytics & Telemetry - Session tracing, event logging, and analytics reporting. Performance monitoring and usage statistics. Use when tracking session events, monitoring performance, or reporting usage statistics.
Classifier approvals tracking with CLASSIFIER_APPROVALS map and CLASSIFIER_CHECKING set. setClassifierApproval/getClassifierApproval/setYoloClassifierApproval. Signal subscription. Use when [classifier approvals] is needed.
焦虑检测机制,识别模型"提前收工"信号并触发reset。集成到Agent循环中,检测assistant消息中的焦虑模式。适用所有长任务场景,防止Agent因上下文焦虑而假完成。
API limits constants. Image limits (5MB base64, 2000px). PDF limits (20MB, 100 pages). Media limits (100 per request). Client-side validation. Use when checking rate limits, managing API quotas, or preventing throttling.
API call retry strategy with exponential backoff, 429/529 handling, OAuth token refresh, and model fallback. Use when: - API calls fail with rate limit (429) or overload (529) - OAuth token expired (401) or revoked (403) - Network connection reset (ECONNRESET/EPIPE) - Need to implement resilient API calls Keywords: retry, rate limit, 429, 529, backoff, API error, token refresh, fallback
# AppState Store Skill 应用状态存储 - Zustand-style store + onChange hook + Selector pattern + External metadata sync。 ## 功能概述 从Claude Code的AppState系统提取的状态管理模式,用于OpenClaw的全局状态管理。 ## 核心机制 ### Zustand-style Store ```typescript export type Store<T> = { getState: () => T setState: (updater: (prev: T) => T) => void subscribe: (listener: Listener) => () => void } export function createStore<T>(initialState: T, onChange?: OnChange<T>): Store<T> { let state = initialState const listeners = ne
Argument substitution for skill/command prompts. substituteArguments + parseArguments + parseArgumentNames + $ARGUMENTS/$ARGUMENTS[0]/$0/$foo named args + generateProgressiveArgumentHint + shell-quote parsing. Use when substituting arguments, binding parameters, or resolving placeholders.
# Ask User Question Tool Skill 用户提问工具 - MultiSelect + Preview + Uniqueness validation + Chip width。 ## 功能概述 从Claude Code的AskUserQuestionTool提取的交互式问答模式,用于OpenClaw的用户交互。 ## 核心机制 ### MultiSelect Support ```typescript multiSelect: z.boolean().default(false).describe( 'Set to true to allow selecting multiple options. Use when choices are not mutually exclusive.' ) // 单选或多选 // 非互斥选项支持多选 ``` ### Preview Content ```typescript preview: z.string().optional().describe( 'Optional preview content
Background task execution system with worker threads, status tracking, and timeout handling. Submit, monitor, and manage async tasks for long-running operations. Use when executing background tasks, monitoring async operations, or delegating heavy computations.
# Auto Dream Service Skill 自动记忆整合服务模式 - 双门控触发forked subagent进行后台记忆整合。 ## 功能概述 从Claude Code的autoDream.ts提取的智能触发模式,用于OpenClaw的记忆整合自动化。 ## 核心机制 ### 双门控(Gate Order) 按成本从低到高检查: ``` 1. Time Gate: hoursSinceLast >= minHours (默认24h) 2. Session Gate: transcripts >= minSessions (默认5) 3. Lock Gate: 无其他进程正在整合 ``` ### 扫描节流 防止时间门通过但session门未通过时每turn重复扫描: ```typescript SESSION_SCAN_INTERVAL_MS = 10 * 60 * 1000 // 10分钟 ``` ### 状态管理 - `lastConsolidatedAt`: 上次整合时间戳(单次stat读取) - `priorMtime`: 锁文件原始mtim
# Auto Mode Allowlist Pattern Skill Auto Mode Allowlist Pattern - SAFE_YOLO_ALLOWLISTED_TOOLS Set + read-only file ops + search tools + task management + plan mode UI + swarm coordination + misc safe + ant-only conditional spread + feature DCE + isAutoModeAllowlistedTool + YOLO_CLASSIFIER_TOOL_NAME。 ## 功能概述 从Claude Code的utils/permissions/classifierDecision.ts提取的Auto mode allowlist模式,用于OpenClaw的auto mode安全工具列表。 ## 核心机制 ### SAFE_YOLO_ALLOWLISTED_TOOLS Set ```typescript const SAFE_YOLO_ALLOWL
Auto mode denials tracking with AutoModeDenial type. recordAutoModeDenial/getAutoModeDenials. MAX_DENIALS=20. RecentDenialsTab in /permissions. Use when [auto mode denials] is needed.
# Auto Mode Dialog Skill Auto Mode Dialog - 三选项模式 + Analytics logEvent + Settings updateForSource + 法律审核文案。 ## 功能概述 从Claude Code的AutoModeOptInDialog提取的自动模式对话框模式,用于OpenClaw的权限模式切换。 ## 核心机制 ### 三选项模式 ```typescript const onChange = (value) => { switch (value) { case "accept": { logEvent("tengu_auto_mode_opt_in_dialog_accept", {}) updateSettingsForSource("userSettings", { skipAutoPermissionPrompt: true }) onAccept() break } case "accept-default": { l
用户离开期间摘要生成服务。检测用户离开时间,生成'while you were away'摘要,发送飞书卡片。Use when user returns after > 30min absence.
# Backend Type Discriminated Union Pattern ## Source Claude Code: `utils/swarm/backends/types.ts` ## Pattern BackendType + PaneBackendType discriminated union + isPaneBackend type guard. ## Code Example ```typescript export type BackendType = 'tmux' | 'iterm2' | 'in-process' export type PaneBackendType = 'tmux' | 'iterm2' // Subset without in-process export type PaneId = string // Opaque identifier for pane export type CreatePaneResult = { paneId: PaneId isFirstTeammate: boolean //
# Background Task Skill Background Task - Type discriminant + Activity limit truncate + Diamond icon status + Remote session progress。 ## 功能概述 从Claude Code的BackgroundTask提取的后台任务模式,用于OpenClaw的任务显示。 ## 核心机制 ### Type Discriminant ```typescript switch (task.type) { case "local_bash": { return <ShellProgress shell={task} /> } case "remote_agent": { return <RemoteSessionProgress session={task} /> } } // task.type as discriminant // Different render per type ``` ### Activity Limi
Navigate between background tasks with keyboard shortcuts Use when [background task navigation] is needed.
Visualize background tasks (memory maintenance, insights analysis, etc.) via Feishu cards. Shows what's happening behind the scenes to build user trust. Use when spawning background work, managing long-running tasks, or checking task status.
# Bash Tool Skill Shell执行工具 - Search/Read分类 + Sandbox + Permission rules。 ## 功能概述 从Claude Code的BashTool.tsx提取的shell执行模式,用于OpenClaw的命令执行。 ## 核心机制 ### Command Classification ```typescript const BASH_SEARCH_COMMANDS = new Set(['find', 'grep', 'rg', 'ag', 'ack']) const BASH_READ_COMMANDS = new Set(['cat', 'head', 'tail', 'less', 'wc', 'jq']) const BASH_LIST_COMMANDS = new Set(['ls', 'tree', 'du']) const BASH_SILENT_COMMANDS = new Set(['mv', 'cp', 'rm', 'mkdir', 'chmod']) export function isSea
# benchmark-analyzer ## Description Analyze benchmark test results with failure classification, statistics reporting, and retry command generation. ## Usage This skill is used to analyze Terminal-Bench 2.0 or other benchmark test results, classify failures, generate statistics, and provide retry recommendations. ## How It Works ### Failure Classification The analyzer classifies failures into these categories: | Type | Description | |------|-------------| | `rate_limit` | API rate limit e
# Bootstrap State Skill Bootstrap State - 全局状态单例 + 1758行 + DO NOT ADD MORE STATE原则 + createSignal信号 + Counter类型 + platform detection。 ## 功能概述 从Claude Code的bootstrap/state.ts提取的全局状态管理模式,用于OpenClaw的核心状态管理。 ## 核心机制 ### DO NOT ADD MORE STATE原则 ```typescript // DO NOT ADD MORE STATE HERE - BE JUDICIOUS WITH GLOBAL STATE // 1758 lines of state definitions // Strict discipline on additions // Global state is expensive ``` ### State Type Definition ```typescript type State = { originalCwd: str
# Branch Command Skill 对话分支命令 - 从当前点创建分支对话。 ## 功能概述 从Claude Code的branch.ts提取的对话分支模式,用于OpenClaw的对话fork。 ## 核心机制 ### 命令结构 ```typescript { type: 'local-jsx', name: 'branch', aliases: feature('FORK_SUBAGENT') ? [] : ['fork'], description: 'Create a branch of the current conversation at this point', argumentHint: '[name]', load: () => import('./branch.js') } ``` ### Alias条件化 ```typescript aliases: feature('FORK_SUBAGENT') ? [] : ['fork'] // fork别名只在FORK_SUBAGENT feature未启用时可用 // 避
# Branded IDs Skill 品牌化ID类型 - Branded type + Compile-time safety + Pattern validation + Cast functions。 ## 功能概述 从Claude Code的Branded ID系统提取的类型安全模式,用于OpenClaw的ID管理。 ## 核心机制 ### Branded Type Pattern ```typescript export type SessionId = string & { readonly __brand: 'SessionId' } export type AgentId = string & { readonly __brand: 'AgentId' } // Nominal typing via brand // Compile-time safety // 防止ID混用 ``` ### Cast Functions ```typescript export function asSessionId(id: string): SessionId {
# Brief Tool Skill 消息发送工具 - Entitlement check + Activation gate + GB kill-switch + Optional field evolution。 ## 功能概述 从Claude Code的BriefTool提取的用户消息发送模式,用于OpenClaw的可见输出通道。 ## 核心机制 ### Entitlement Check (是否允许使用) ```typescript export function isBriefEntitled(): boolean { return feature('KAIROS') || feature('KAIROS_BRIEF') ? getKairosActive() || isEnvTruthy(process.env.CLAUDE_CODE_BRIEF) || getFeatureValue_CACHED_WITH_REFRESH('tengu_kairos_brief', false, KAIROS_BRIEF_REFRESH_MS)
虚拟伙伴系统,游戏化用户体验 Use when [buddy companion] is needed.
Buffered writer for batch writes. createBufferedWriter + write/flush/dispose. flushIntervalMs=1000 default. maxBufferSize/maxBufferBytes limits. Deferred flush with setImmediate. Use when [buffered writer] is needed.
--- name: builtin-plugins-system description: "| Use when [builtin plugins system] is needed." Built-in plugins system. Features: - BUILTIN_PLUGINS Map - BUILTIN_MARKETPLACE_NAME = 'builtin' - registerBuiltinPlugin() - isBuiltinPluginId() Plugin IDs format: - `{name}@builtin` for built-in - `{name}@{marketplace}` for marketplace Differences from bundled skills: - Appear in /plugin UI - User can enable/disable - Can provide multiple components Keywords: -
捆绑插件目录管理。管理内置插件列表,自动加载核心插件。Use when managing built-in OpenClaw plugins.
# Bundled Skills Pattern Skill Bundled Skills Pattern - BundledSkillDefinition + registerBundledSkill + files extraction + Closure-local memoization + extractionPromise + prependBaseDir。 ## 功能概述 从Claude Code的skills/bundledSkills.ts提取的bundled skills模式,用于OpenClaw的内置技能。 ## 核心机制 ### BundledSkillDefinition Type ```typescript export type BundledSkillDefinition = { name: string description: string aliases?: string[] whenToUse?: string argumentHint?: string allowedTools?: string[] mo
# Bun Native YAML Pattern Skill Bun Native YAML Pattern - parseYaml + typeof Bun !== 'undefined' guard + Bun.YAML.parse zero-cost + require('yaml') fallback + lazy-require non-Bun branch + ~270KB yaml parser avoided + native builds never load npm package + built-in YAML parser。 ## 功能概述 从Claude Code的utils/yaml.ts提取的Bun native YAML模式,用于OpenClaw的YAML解析。 ## 核心机制 ### parseYaml ```typescript export function parseYaml(input: string): unknown { if (typeof Bun !== 'undefined') { return Bun.YA
Guidance for building and training with the Caffe deep learning framework on CIFAR-10 dataset. This skill applies when tasks involve compiling Caffe from source, training convolutional neural networks on image classification datasets, or working with legacy deep learning frameworks that have compatibility issues with modern systems.
# Chalk Level Boost/Clamp Skill Chalk Level Boost/Clamp - boostChalkLevelForXtermJs + clampChalkLevelForTmux + COLORTERM detection + tmux terminal-overrides + level 2 fallback。 ## 功能概述 从Claude Code的ink/colorize.ts提取的颜色级别调整模式,用于OpenClaw的终端颜色适配。 ## 核心机制 ### boostChalkLevelForXtermJs ```typescript /** * xterm.js (VS Code, Cursor, code-server, Coder) has supported truecolor * since 2017, but code-server/Coder containers often don't set * COLORTERM=truecolor. chalk's supports-color doesn't r
Change detector with chokidar FSWatcher. FILE_STABILITY_THRESHOLD_MS=1000, MDM_POLL_INTERVAL_MS=30min. settingsChanged signal. pendingDeletions map. Internal write suppression. Use when [change detector] is needed.
# Change Detector with Deletion Grace Pattern ## Source Claude Code: `utils/settings/changeDetector.ts` (415 lines) ## Pattern Chokidar file watcher with deletion grace period + MDM polling + ConfigChange hooks. ## Code Example ```typescript // Constants const FILE_STABILITY_THRESHOLD_MS = 1000 // Wait for write to stabilize const FILE_STABILITY_POLL_INTERVAL_MS = 500 const INTERNAL_WRITE_WINDOW_MS = 5000 // Suppress own writes const DELETION_GRACE_MS = 1200 // > stability thr
# CharPool Interming Skill CharPool Interming - CharPool class + strings array + stringMap + ascii Int32Array fast-path + intern/get methods + Index 0 space + Index 1 empty spacer + shared pool across screens + blitRegion copy IDs + diffEach compare IDs。 ## 功能概述 从Claude Code的ink/screen.ts提取的CharPool interning模式,用于OpenClaw的字符池内存优化。 ## 核心机制 ### CharPool Class ```typescript export class CharPool { private strings: string[] = [' ', ''] // Index 0 = space, 1 = empty (spacer) private string
上下文警告检查模式。检测上下文异常,发送警告通知。Use when detecting context anomalies.
Circuit breaker for LLM API calls with failure threshold and automatic recovery. Protects against cascading failures and API rate limits. Use when experiencing repeated LLM failures or configuring API resilience.
Guide for implementing combinational/sequential logic circuits using gate-level descriptions in text-based simulators. This skill applies when building circuits for mathematical functions like integer
Circular buffer for fixed-size rolling window. CircularBuffer<T> + add/addAll/getRecent/toArray/clear/length. Automatically evicts oldest items when full. Use when [circular buffer] is needed.
Cleanup registry for graceful shutdown. cleanupFunctions Set + registerCleanup + runCleanupFunctions + Unregister function return + Async cleanup support + Graceful shutdown integration. Use when [cleanup registry] is needed.
Handle user clarification requests gracefully. Use when the agent needs to ask the user for clarification before proceeding - missing info, ambiguous requirements, approach choices, or risk confirmations. Implements DeerFlow's ClarificationMiddleware pattern.
# Classifier Denial Tracking Pattern Skill Classifier Denial Tracking Pattern - DenialTrackingState consecutiveDenials/totalDenials + DENIAL_LIMITS maxConsecutive:3/maxTotal:20 + recordDenial increment + recordSuccess reset consecutive + shouldFallbackToPrompting limits check + consecutive≥3 OR total≥20 fallback + immutable state update + classifier retry budget。 ## 功能概述 从Claude Code的utils/permissions/denialTracking.ts提取的Classifier denial tracking模式,用于OpenClaw的分类器拒绝计数。 ## 核心机制 ### DenialTra
# Cleanup Registry Pattern Skill Cleanup Registry Pattern - cleanupFunctions Set + registerCleanup + unregister return + runCleanupFunctions + Promise.all + global registry + graceful shutdown support + circular dependency avoidance + async cleanup + Set.add/delete。 ## 功能概述 从Claude Code的utils/cleanupRegistry.ts提取的Cleanup registry模式,用于OpenClaw的清理函数管理。 ## 核心机制 ### cleanupFunctions Set ```typescript const cleanupFunctions = new Set<() => Promise<void>>() // Global registry for cleanup functio
Message collapsing utilities. collapseBackgroundBashNotifications + collapseHookSummaries + collapseTeammateShutdowns + N background commands completed + Parallel tool calls hook summary + Aggregation (hookCount/hookInfos/hookErrors). Use when [collapse utils] is needed.
Context命令模式。管理上下文相关命令,查看和压缩上下文以控制token使用。Use when managing context via commands.
# Combined Abort Signal Pattern Skill Combined Abort Signal Pattern - createCombinedAbortSignal + signal + signalB + timeoutMs + cleanup function + setTimeout + clearTimeout cleanup + removeEventListener cleanup + unref timer + Bun AbortSignal.timeout memory leak avoid + multi-source abort。 ## 功能概述 从Claude Code的utils/combinedAbortSignal.ts提取的Combined abort signal模式,用于OpenClaw的多源Abort组合。 ## 核心机制 ### createCombinedAbortSignal ```typescript export function createCombinedAbortSignal( signal:
Insights命令模式。生成用户行为洞察报告,分析使用模式和偏好。Use when generating user behavior insights.
# Command Lifecycle Skill **优先级**: P29 **来源**: Claude Code `commandLifecycle.ts` **适用场景**: 命令状态追踪 --- ## 概述 Command Lifecycle提供命令生命周期状态追踪,支持 `started` | `completed` 状态通知。监听器回调用于追踪命令执行状态。 --- ## 核心功能 ### 1. 状态定义 ```typescript type CommandLifecycleState = 'started' | 'completed' | 'failed' type CommandLifecycleListener = ( uuid: string, state: CommandLifecycleState ) => void ``` ### 2. 监听器管理 ```typescript let listener: CommandLifecycleListener | null = null export function setComma
PR评论命令模式。生成Pull Request评论,自动化代码审查。Use when generating automated PR comments.
# Commit Push PR Command Skill 组合命令 - Allowed tools + Shell execution + Slack集成。 ## 功能概述 从Claude Code的commit-push-pr.ts提取的组合命令,用于OpenClaw的Git工作流。 ## 核心机制 ### Allowed Tools白名单 ```typescript const ALLOWED_TOOLS = [ 'Bash(git checkout --branch:*)', 'Bash(git checkout -b:*)', 'Bash(git add:*)', 'Bash(git status:*)', 'Bash(git push:*)', 'Bash(git commit:*)', 'Bash(gh pr create:*)', 'Bash(gh pr edit:*)', 'Bash(gh pr view:*)', 'Bash(gh pr merge:*)', 'ToolSearch', 'mcp__sla
Group conversation messages at API-round boundaries for compact/summarization. One group per API round-trip, split at new assistant response IDs. Use when: - Preparing messages for compact/summarization - Splitting conversation into logical API rounds - Identifying safe split points for context reduction Keywords: compact, message grouping, API round, conversation split, context reduction
# Compact Service Skill 对话压缩服务核心逻辑 - 生成摘要保留recent history,PTL重试作为安全阀。 ## 功能概述 从Claude Code的compact.ts提取的对话压缩模式,用于OpenClaw的长对话管理。 ## 核心机制 ### 预处理 ```typescript stripImagesFromMessages(messages) // [image]/[document]标记 stripReinjectedAttachments(messages) // 移除skill_discovery/skill_listing ``` ### PTL Retry(Prompt Too Long Escape Hatch) CC-1180的最后防线 - 当compact请求本身超长时truncate最老内容: ```typescript truncateHeadForPTLRetry(messages, ptlResponse): // 按API-round分组 // 计算tokenGap从PTL error
--- name: compact-services-directory description: "| Use when [compact services directory] is needed." Compact services directory (11 files). Files: - apiMicrocompact.ts: API microcompact with context management strategies - autoCompact.ts: Auto compact with context window sizing - compact.ts: Compact conversation - compactWarningHook.ts: Compact warning hook - compactWarningState.ts: Compact warning state - grouping.ts: Grouping utilities - microCompact.ts: Micro compact
压缩警告钩子服务。检测上下文压力,发送压缩警告通知。Use when context size approaches thresholds.
Guidance for building CompCert, a formally verified C compiler. This skill applies when tasks involve compiling CompCert from source, setting up Coq/OCaml environments with opam, or building software with strict proof assistant dependencies. Use for CompCert compilation, Coq-dependent project builds, or formal verification toolchain setup.
Concurrent session registry. registerSession + SessionKind (interactive/bg/daemon/daemon-worker) + SessionStatus (busy/idle/waiting) + PID file (process.pid.json) + isBgSession + claude ps. Use when [concurrent sessions] is needed.
# Config Command Skill 配置命令 - Alias别名 + 面板打开。 ## 功能概述 从Claude Code的config/index.ts提取的配置模式,用于OpenClaw的设置管理。 ## 核心机制 ### 命令结构 ```typescript { aliases: ['settings'], type: 'local-jsx', name: 'config', description: 'Open config panel', load: () => import('./config.js') } ``` ### Alias Support ```typescript aliases: ['settings'] // 用户可以用/config或/settings // 提升discoverability ``` ### Panel Opening ```typescript type: 'local-jsx' // React组件渲染配置面板 // load按需加载 ``` ## 实现建议 ### OpenCl
# Config Tool Skill 配置工具 - Kill switch + Kill switch validation + AppState sync。 ## 功能概述 从Claude Code的ConfigTool提取的配置管理模式,用于OpenClaw的设置管理。 ## 核心机制 ### Kill Switch Check ```typescript if (feature('VOICE_MODE') && setting === 'voiceEnabled') { const { isVoiceGrowthBookEnabled } = await import('...') if (!isVoiceGrowthBookEnabled()) { return { success: false, error: 'Unknown setting' } } } // Runtime gate检查 // Kill switch关时不暴露设置 ``` ### Coerce Boolean ```typescript if (config.type
Analyze current conversation context token distribution. Shows which tools/files are consuming the most tokens, duplicate reads, and optimization opportunities. Use when: - User asks "how much context is left" or "why is context full" - Context usage > 70% - User asks "what's taking up context" - Before compaction to understand what to keep Keywords: - "context", "tokens", "上下文", "token 分布", "context full", "context usage"
# Context Command Skill 上下文可视化命令 - 双版本(Interactive + NonInteractive)。 ## 功能概述 从Claude Code的context/index.ts提取的上下文可视化模式,用于OpenClaw的token使用显示。 ## 核心机制 ### 双命令结构 ```typescript // Interactive version export const context: Command = { name: 'context', description: 'Visualize current context usage as a colored grid', isEnabled: () => !getIsNonInteractiveSession(), type: 'local-jsx', load: () => import('./context.js') } // NonInteractive version export const contextNonInteractive: Comm
Automatic context optimization suggestions. Detect bloat, large tool results, memory usage issues. Warn users and suggest actions to optimize context. Use when [context suggestions] is needed.
Context window utilities. MODEL_CONTEXT_WINDOW_DEFAULT (200k) + COMPACT_MAX_OUTPUT_TOKENS (20k) + is1mContextDisabled + has1mContext + modelSupports1M + getContextWindowForModel + calculateContextPercentages + getModelMaxOutputTokens + CAPPED_DEFAULT_MAX_TOKENS (8k) + ESCALATED_MAX_TOKENS (64k). Use when [context utils] is needed.
# Context Visualization Skill Context Visualization - SOURCE_DISPLAY_ORDER + groupBySource + CollapseStatus + RESERVED_CATEGORY_NAME + isMeta placeholders。 ## 功能概述 从Claude Code的ContextVisualization提取的上下文可视化模式,用于OpenClaw的token使用展示。 ## 核心机制 ### SOURCE_DISPLAY_ORDER ```typescript // Order for displaying source groups: Project > User > Managed > Plugin > Built-in const SOURCE_DISPLAY_ORDER = ['Project', 'User', 'Managed', 'Plugin', 'Built-in'] // Display priority order // Project settings high
# Coordinator Mode Pattern Skill Coordinator Mode Pattern - isCoordinatorMode + matchSessionMode + INTERNAL_WORKER_TOOLS + isScratchpadGateEnabled + Session Mode Switch + Worker Whitelist + Task Notification XML。 ## 功能概述 从Claude Code的coordinator/coordinatorMode.ts提取的协调模式,用于OpenClaw的多Agent协调。 ## 核心机制 ### isCoordinatorMode ```typescript export function isCoordinatorMode(): boolean { if (feature('COORDINATOR_MODE')) { return isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE) } re
# Coordinator Task Panel Skill Coordinator Task Panel - EvictAfter deadline + 1s tick eviction + Agent name registry + View/steer pattern。 ## 功能概述 从Claude Code的CoordinatorAgentStatus提取的任务面板模式,用于OpenClaw的后台任务展示。 ## 核心机制 ### EvictAfter Deadline ```typescript export function getVisibleAgentTasks(tasks: AppState['tasks']): LocalAgentTaskState[] { return Object.values(tasks).filter((t): t is LocalAgentTaskState => isPanelAgentTask(t) && t.evictAfter !== 0 ).sort((a, b) => a.startTime -
# Cost Tracker Pattern Skill Cost Tracker Pattern - StoredCostState + addToTotalCostState + ModelUsage + formatCost + resetCostState + calculateUSDCost。 ## 功能概述 从Claude Code的cost-tracker.ts提取的成本追踪模式,用于OpenClaw的使用统计。 ## 核心机制 ### StoredCostState ```typescript type StoredCostState = { totalCostUSD: number totalAPIDuration: number totalAPIDurationWithoutRetries: number totalToolDuration: number totalLinesAdded: number totalLinesRemoved: number lastDuration: number | undefined m
This skill provides guidance for cracking 7z archive password hashes. It should be used when tasks involve extracting hashes from password-protected 7z archives, selecting appropriate cracking tools, and recovering passwords through dictionary or brute-force attacks. Applicable to password recovery, security testing, and CTF challenges involving encrypted 7z files.
# Cron Create Tool Skill Cron任务创建 - Recurring/One-shot + Durable persistence + Validation。 ## 功能概述 从Claude Code的CronCreateTool提取的cron调度模式,用于OpenClaw的定时任务。 ## 核心机制 ### Input Schema ```typescript z.strictObject({ cron: z.string().describe('Standard 5-field: "M H DoM Mon DoW"'), prompt: z.string().describe('The prompt to enqueue'), recurring: semanticBoolean().describe('true=fire every match, false=once'), durable: semanticBoolean().describe('true=persist to disk, false=in-memory') })
Parse and evaluate 5-field cron expressions. Compute next run time, validate expressions, convert to human-readable format. Use when: - Creating or validating cron scheduled tasks - Computing next fire time for a cron expression - Converting cron to human-readable description - Checking if a cron task should fire now Keywords: cron, schedule, next run, cron expression, parse cron, cron validation
Cron scheduler core. CronSchedulerOptions + CronScheduler (start/stop/getNextFireTime) + createCronScheduler + isRecurringTaskAged + CHECK_INTERVAL_MS=1000 + FILE_STABILITY_MS=300 + LOCK_PROBE_INTERVAL_MS=5000 + Assistant mode bypass + Missed task handling + Lock identity + PID. Use when [cron scheduler core] is needed.
# CSI Parse Pattern Skill CSI Parse Pattern - parseCSI function + finalByte extraction + privateMode prefix + intermediate bytes + paramStr parsing + params array + p0/p1 defaults + cursor movement cases + erase/insert/delete cases + SGR handling + Action type return。 ## 功能概述 从Claude Code的ink/termio/parser.ts提取的CSI解析模式,用于OpenClaw的ANSI序列语义解析。 ## 核心机制 ### parseCSI Function ```typescript function parseCSI(rawSequence: string): Action | null { const inner = rawSequence.slice(2) // Remove ES
# CSI Sequence Generator Skill CSI Sequence Generator - CSI_PREFIX + csi() function + parameter byte ranges + isCSIParam/Intermediate/Final checks + cursor movement constants + erase/insert/delete commands + DECSTBM scroll region + SU/SD scroll commands + single arg raw body pattern。 ## 功能概述 从Claude Code的ink/termio/csi.ts提取的CSI序列生成模式,用于OpenClaw的终端控制序列。 ## 核心机制 ### CSI_PREFIX ```typescript import { ESC, ESC_TYPE, SEP } from './ansi.js' export const CSI_PREFIX = ESC + String.fromCharCode(ESC
# Dangerous Files Auto-Edit Protection Skill Dangerous Files Auto-Edit Protection - DANGEROUS_FILES .gitconfig/.bashrc/.zshrc/.claude.json + DANGEROUS_DIRECTORIES .git/.vscode/.idea/.claude + normalizeCaseForComparison lowercase + getClaudeSkillScope skill directory + .claude/worktrees/ exception + isDangerousFilePathToAutoEdit UNC/dangerous check + isClaudeConfigFilePath + isSessionPlanFile + isScratchpadPath + isSessionMemoryPath + isProjectDirPath。 ## 功能概述 从Claude Code的utils/permissions/fi
Detect dangerous patterns in commands and tool inputs. Use when: - System needs to protect against destructive operations - Permission system validates commands - Safety check before execution NOT for: - Direct user invocation (internal service) - Already-safe commands - Read-only operations Auto-trigger conditions: - Automatically invoked before tool execution - Part of permission pipeline Dangerous patterns: - File deletion: rm -rf, rmdir -p - Disk operations: dd, mkfs, fdisk - Permission changes: chmod 777, chown - Network exposure: nc -l, netcat -l - System control: reboot, shutdown - Process kill: kill -9, killall Keywords: - Internal service - auto-activated by safety checks
# Dangerous Permission Detection Skill Dangerous Permission Detection - isDangerousBashPermission python:* + isDangerousPowerShellPermission iex:* + isDangerousTaskPermission Agent allow + findDangerousClassifierPermissions + DANGEROUS_BASH_PATTERNS + CROSS_PLATFORM_CODE_EXEC + stripDangerousPermissionsForAutoMode + restoreDangerousPermissions stash + transitionPermissionMode。 ## 功能概述 从Claude Code的utils/permissions/permissionSetup.ts提取的Dangerous permission detection模式,用于OpenClaw的auto mode危险权限
Middleware to fix dangling tool calls in message history. Detects AIMessages with tool_calls that lack corresponding ToolMessages (due to interruption/cancellation) and inserts synthetic error ToolMessages to ensure correct message format. Use when [dangling tool call] is needed.
Guide for recovering data from SQLite Write-Ahead Log (WAL) files that may be corrupted, encrypted, or inaccessible through standard methods. This skill should be used when tasks involve SQLite database recovery, WAL file analysis, encrypted database files, or discrepancies between tool outputs and filesystem access.
Deep module = small interface + large implementation. The key architectural concept from John Ousterhout's "A Philosophy of Software Design". Use when designing interfaces, planning refactors, or discussing architecture.
--- name: deep-research description: "Use this skill instead of WebSearch for ANY question requiring web research. Trigger on queries like "what is X", "explain X", "compare X and Y", "research X", or before content generation tasks. Provides systematic multi-angle research methodology instead of single superficial searches. Use this proactively when the user's question needs online information. Use when [deep research] is needed." --- # Deep Research Skill ## Overview This skill provides a s
# Deferred Flush BufferedWriter Skill Deferred Flush BufferedWriter - createBufferedWriter + flushIntervalMs + maxBufferSize + maxBufferBytes + flushDeferred setImmediate + pendingOverflow coalesce + immediateMode bypass + buffer array + writeFn inject + flush clearTimer + dispose drain + overflow detach。 ## 功能概述 从Claude Code的utils/bufferedWriter.ts提取的Deferred flush bufferedWriter模式,用于OpenClaw的批量写入优化。 ## 核心机制 ### createBufferedWriter ```typescript export function createBufferedWriter({ w
Middleware for deferred tool loading optimization. When enabled, MCP tools are not loaded into context directly but discoverable via tool_search at runtime, reducing context usage and improving tool selection accuracy for large MCP catalogs. Use when [deferred tool filter] is needed.
Deferred tool loading configuration for OpenClaw. Reduces context usage by listing MCP tools by name in prompt and making them discoverable via tool_search at runtime. Use when [deferred tool loading] is needed.
延迟工具Delta服务。跟踪延迟工具调用的变化,管理待执行工具队列。Use when tracking deferred tool execution.
Generate multiple radically different interface designs using parallel sub-agents. Use when user wants to design an API, explore interface options, or mentions "design it twice".
# Diag Logger Wrapper Pattern ## Source Claude Code: `utils/telemetry/logger.ts` (ClaudeCodeDiagLogger) ## Pattern OpenTelemetry DiagLogger interface wrapper - error/warn only, info/debug silenced. ## Code Example ```typescript import type { DiagLogger } from '@opentelemetry/api' export class ClaudeCodeDiagLogger implements DiagLogger { error(message: string, ..._: unknown[]) { logError(new Error(message)) logForDebugging(`[3P telemetry] OTEL diag error: ${message}`, { level: 'erro
# Diagnostic Logs Skill **优先级**: P29 **来源**: Claude Code `diagLogs.ts` **适用场景**: 监控日志、诊断追踪 --- ## 概述 Diagnostic Logs将诊断信息写入JSONL日志文件,用于容器内监控和问题追踪。支持计时包装函数,自动记录started/completed/failed事件。 --- ## 核心功能 ### 1. JSONL日志写入 ```typescript type DiagnosticLogLevel = 'debug' | 'info' | 'warn' | 'error' type DiagnosticLogEntry = { timestamp: string level: DiagnosticLogLevel event: string data: Record<string, unknown> } export function logForDiagnosticsNoPII( level: DiagnosticLogLevel, e
# Direct Member Message Skill **优先级**: P29 **来源**: Claude Code `directMemberMessage.ts` **适用场景**: 飞书群聊@成员消息语法 --- ## 概述 Direct Member Message解析 `@agent-name message` 语法,直接发送消息给团队成员,绕过model处理。可用于飞书群聊中直接回复特定用户。 --- ## 核心功能 ### 1. 语法解析 ```typescript export function parseDirectMemberMessage(input: string): { recipientName: string message: string } | null { const match = input.match(/^@([\w-]+)\s+(.+)$/s) if (!match) return null const [, recipientName, message] = match if (!rec
# Display Tags Stripper Skill **优先级**: P29 **来源**: Claude Code `displayTags.ts` **适用场景**: 飞书卡片标题、XML标签剥离 --- ## 概述 Display Tags Stripper从文本中剥离XML-like标签块,用于UI标题显示。只匹配小写标签名,大写标签(JSX/HTML)保留。可用于飞书卡片标题显示。 --- ## 核心功能 ### 1. XML标签剥离 ```typescript // 匹配任何XML-like <tag>...</tag>块 const XML_TAG_BLOCK_PATTERN = /<([a-z][\w-]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>\n?/g export function stripDisplayTags(text: string): string { const result = text.replace(XML_TAG_BLOCK_PATTERN, '').trim() return result |
Guidance for finding probability distributions that satisfy specific statistical constraints such as KL divergence targets, entropy requirements, or moment conditions. This skill should be used when tasks involve constructing discrete or continuous probability distributions with specified divergence measures, entropy values, or other distributional properties through numerical optimization.
# djb2 Hash Pattern Skill djb2 Hash Pattern - djb2Hash function + signed 32-bit int + hash << 5 - hash + charCode | 0 + fast non-cryptographic + deterministic cross-runtime + Bun.hash fallback + hashContent + hashPair seed-chain + wyhash vs SHA-256。 ## 功能概述 从Claude Code的utils/hash.ts提取的djb2 hash模式,用于OpenClaw的快速哈希计算。 ## 核心机制 ### djb2Hash Function ```typescript export function djb2Hash(str: string): number { let hash = 0 for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - ha
Project diagnostics: installation type detection, dependency status, ripgrep check, multiple installations warning. Diagnose project environment and configuration issues. Use when [doctor] is needed.
# Edges Function Overloads Skill Edges Function Overloads - edges() function + 4 overload signatures + uniform edges + axis edges + individual edges + function implementation + edges(a,b?,c?,d?) + ZERO_EDGES constant + resolveEdges partial + addEdges addition + Rectangle union + clampRect bounds。 ## 功能概述 从Claude Code的ink/layout/geometry.ts提取的Edges function overloads模式,用于OpenClaw的边距处理。 ## 核心机制 ### edges() Function Overloads ```typescript export function edges(all: number): Edges // Uniform
# Effort Command Skill Effort配置命令 - Getter immediate + Argument hint。 ## 功能概述 从Claude Code的effort/index.ts提取的effort模式,用于OpenClaw的模型effort设置。 ## 核心机制 ### 命令结构 ```typescript { type: 'local-jsx', name: 'effort', description: 'Set effort level for model usage', argumentHint: '[low|medium|high|max|auto]', get immediate() { return shouldInferenceConfigCommandBeImmediate() }, load: () => import('./effort.js') } ``` ### Effort Levels ``` low | medium | high | max | auto // 控制模型
# End-Truncating Accumulator Pattern Skill End-Truncating Accumulator Pattern - EndTruncatingAccumulator class + maxSize limit + append truncation from end + isTruncated flag + totalBytesReceived tracking + toString truncation marker + truncation marker KB + MAX_STRING_LENGTH 2^25 + safeJoinLines + firstLineOf indexOf + countCharInString indexOf jumps。 ## 功能概述 从Claude Code的utils/stringUtils.ts提取的End-truncating accumulator模式,用于OpenClaw的大字符串处理。 ## 核心机制 ### EndTruncatingAccumulator Class ```t
# Enter Plan Mode Tool Skill Plan mode切换工具 - Permission transition + Interview phase + MetaMessages injection。 ## 功能概述 从Claude Code的EnterPlanModeTool提取的plan模式,用于OpenClaw的探索-计划模式。 ## 核心机制 ### Permission Transition ```typescript handlePlanModeTransition(mode, 'plan') context.setAppState(prev => ({ ...prev, toolPermissionContext: applyPermissionUpdate( prepareContextForPlanMode(prev.toolPermissionContext), { type: 'setMode', mode: 'plan', destination: 'session' } ) })) // 切换perm
# Enter Worktree Tool Skill Worktree切换工具 - Canonical root + Cache clear + State persistence。 ## 功能概述 从Claude Code的EnterWorktreeTool提取的worktree模式,用于OpenClaw的repo隔离。 ## 核心机制 ### Canonical Root Resolution ```typescript const mainRepoRoot = findCanonicalGitRoot(getCwd()) if (mainRepoRoot && mainRepoRoot !== getCwd()) { process.chdir(mainRepoRoot) setCwd(mainRepoRoot) } // 从当前worktree定位到main repo // 确保worktree creation正确 ``` ### Worktree Creation ```typescript const worktreeSession = awai
# Environment Detection Module-Load Capture Pattern ## Source Claude Code: `utils/swarm/backends/detection.ts` (ORIGINAL_USER_TMUX, ORIGINAL_TMUX_PANE) ## Pattern Capture environment variables at module load time before Shell.ts overrides. ## Code Example ```typescript /** * Captured at module load time to detect if user started Claude from within tmux. * Shell.ts may override TMUX env var later, so we capture the original value. */ // eslint-disable-next-line custom-rules/no-process-env-t
Environment utilities. getClaudeConfigHomeDir memoize + isEnvTruthy 4 values (1/true/yes/on) + isEnvDefinedFalsy 4 values (0/false/no/off) + isBareMode + parseEnvVars KEY=VALUE + getAWSRegion. Use when [environment utils] is needed.
# Env Timeout Constants Pattern Skill Env Timeout Constants Pattern - getDefaultBashTimeoutMs + getMaxBashTimeoutMs + env parameter injection + EnvLike type + parseInt NaN check > 0 + Math.max ensure max >= default + DEFAULT_TIMEOUT_MS 120_000 + MAX_TIMEOUT_MS 600_000 + configurable constants。 ## 功能概述 从Claude Code的utils/timeouts.ts提取的Env timeout constants模式,用于OpenClaw的超时配置。 ## 核心机制 ### getDefaultBashTimeoutMs ```typescript export function getDefaultBashTimeoutMs(env: EnvLike = process.env)
# Error Classification Pattern Skill Error Classification Pattern - isAbortError multiple checks + instanceof + Error.name === 'AbortError' + getErrnoCode + isENOENT + isFsInaccessible + classifyAxiosError + kind bucket + status optional + TelemetrySafeError + shortErrorStack + errorMessage + toError。 ## 功能概述 从Claude Code的utils/errors.ts提取的Error classification模式,用于OpenClaw的错误分类处理。 ## 核心机制 ### isAbortError Multiple Checks ```typescript export function isAbortError(e: unknown): boolean { r
ErrorGuidance错误指导,12个预置错误模式(command not found/permission denied/timeout等),提供具体修复建议,防止重复相同指导。适用所有命令执行失败场景。
Error handling utilities. ClaudeError + MalformedCommandError + AbortError + ConfigParseError + ShellError + TeleportOperationError + TelemetrySafeError + isAbortError + hasExactErrorMessage + toError + errorMessage + getErrnoCode + isENOENT + getErrnoPath. Use when [errors utils] is needed.
# Exit Plan Mode V2 Tool Skill 退出计划模式工具 - Leader approval + Gate fallback + Mode restore + Plan snapshot。 ## 功能概述 从Claude Code的ExitPlanModeV2Tool提取的计划模式退出模式,用于OpenClaw的计划执行。 ## 核心机制 ### Leader Approval Request ```typescript if (isTeammate() && isPlanModeRequired()) { const approvalRequest = { type: 'plan_approval_request', from: agentName, planFilePath: filePath, planContent: plan, requestId } await writeToMailbox('team-lead', { from: agentName, text: jsonStringif
# Exit Worktree Tool Skill 退出Worktree工具 - Change count fail-closed + Session scope guard + Project root restore + Hooks snapshot restore。 ## 功能概述 从Claude Code的ExitWorktreeTool提取的worktree退出模式,用于OpenClaw的git worktree管理。 ## 核心机制 ### Change Count Fail-Closed ```typescript async function countWorktreeChanges(worktreePath: string, originalHeadCommit: string | undefined): Promise<ChangeSummary | null> { const status = await execFileNoThrow('git', ['-C', worktreePath, 'status', '--porcelain'])
Extract durable memories from session transcripts Use when [extract memories] is needed.
Guidance for extracting text-based game commands, moves, or inputs from video recordings using OCR and frame analysis. This skill applies when extracting user inputs from screen recordings of text-based games (Zork, interactive fiction), terminal sessions, or any video where typed commands need to be recovered. It covers OCR preprocessing, region-of-interest extraction, domain-aware validation, and deduplication strategies.
# Fast Command Skill 快速模式命令 - Feature-gated + Availability限制。 ## 功能概述 从Claude Code的fast/index.ts提取的快速模式,用于OpenClaw的轻量模型切换。 ## 核心机制 ### 命令结构 ```typescript { type: 'local-jsx', name: 'fast', get description() { return `Toggle fast mode (${FAST_MODE_MODEL_DISPLAY} only)` }, availability: ['claude-ai', 'console'], isEnabled: () => isFastModeEnabled(), get isHidden() { return !isFastModeEnabled() }, argumentHint: '[on|off]', get immediate() { return shouldInferenceConfigCo
Fast mode system. isFastModeEnabled + getFastModeModel + FAST_MODE_MODEL_DISPLAY + getFastModeUnavailableReason + FastModeDisabledReason + CLAUDE_CODE_DISABLE_FAST_MODE + orgStatus + feature gates. Use when enabling fast mode, reducing thinking, or optimizing simple queries.
This skill provides guidance for FEAL cipher linear cryptanalysis tasks. It should be used when recovering encryption keys from FEAL-encrypted data using known plaintext-ciphertext pairs, implementing linear approximation attacks on block ciphers, or solving cryptanalysis challenges involving the FEAL cipher family. The skill emphasizes mathematical analysis over brute-force approaches.
Feishu interactive card builder for OpenClaw Use when [feishu card builder] is needed.
飞书云文档操作技能 功能: - 创建/编辑文档 - 表格操作 - 多维表格操作 - 文档协作 Use when: - 创建飞书云文档 - 编辑表格内容 - 操作多维表格 Keywords: - 飞书文档, 飞书表格, 多维表格 - feishu doc, feishu sheet
Feishu integration hub for OpenClaw services Use when [feishu integration] is needed.
Handle Feishu interactive card callbacks Use when [feishu interaction] is needed.
Feishu notification service for OpenClaw Use when [feishu notifications] is needed.
# File Edit Tool Skill 文件编辑工具 - Atomic RMW + Staleness check + LSP notify + Skill discovery。 ## 功能概述 从Claude Code的FileEditTool提取的文件编辑模式,用于OpenClaw的文件修改。 ## 核心机制 ### Atomic Read-Modify-Write ```typescript // CRITICAL SECTION - no async between staleness check and write const lastWriteTime = getFileModificationTime(absoluteFilePath) const lastRead = readFileState.get(absoluteFilePath) if (lastWriteTime > lastRead.timestamp) { throw new Error(FILE_UNEXPECTEDLY_MODIFIED_ERROR) } // ... immed
File edit checkpointing and rollback. Automatically snapshot files before edits, enable per-messageId rewind. Use when: - Before making file edits (auto-snapshot) - User asks to undo/revert changes - Comparing current state to before a specific message - Recovering from bad edits Keywords: undo, revert, checkpoint, file history, rollback, restore, snapshot
In-memory file content cache with mtime-based invalidation. 1000 entries max. Encoding detection. Cache statistics. Reduce redundant reads. Use when [file read cache] is needed.
Fast file search using glob patterns and grep regex. Glob for filename patterns, Grep for content search. Use when: finding files, searching code, pattern matching.
Scan memory directory and find files relevant to the current query. Use when: - Starting a new conversation and need to recall relevant context - User asks about something that might be in memory files - Before answering questions about prior work, decisions, or preferences - When memory_search returns low confidence results NOT for: - MEMORY.md (already loaded in system prompt) - Simple Q&A that doesn't need memory context - When memory directory is empty Keywords: - "recall", "remember", "what did we", "previous", "last time", "相关记忆", "回忆"
# First Source Wins Policy Pattern ## Source Claude Code: `utils/settings/mdm/settings.ts` + `settings.ts` ## Pattern Policy settings use "first source wins" - highest priority source provides ALL settings. ## Code Example ```typescript // Policy priority: remote > HKLM/plist > file > HKCU export function getSettingsForSource(source: SettingSource): SettingsJson | null { if (source === 'policySettings') { // First source wins - return first that has content const remoteSettings = ge
# Focus Manager Skill Focus Manager - FocusManager class + MAX_FOCUS_STACK + deduplicate stack + handleNodeRemoved + activeElement tracking + FocusEvent dispatch。 ## 功能概述 从Claude Code的ink/focus.ts提取的焦点管理模式,用于OpenClaw的UI焦点管理。 ## 核心机制 ### FocusManager Class ```typescript export class FocusManager { activeElement: DOMElement | null = null private enabled = true private focusStack: DOMElement[] = [] constructor(dispatchFocusEvent: (target, event) => boolean) { this.dispatchFocus
Forked Agent Cache Sharing - Share prompt cache between parent session and forked subagents. Reduces token usage for background tasks. Use when [forked agent cache] is needed.
# Format Utils Skill **优先级**: P29 **来源**: Claude Code `format.ts` **适用场景**: 文件大小、时长、数字格式化 --- ## 概述 Format Utils提供显示格式化函数:文件大小(KB/MB/GB)、时长(1.2s、1d 2h)、数字(1.3k)、相对时间。NumberFormat缓存避免重复创建。 --- ## 核心功能 ### 1. 文件大小 ```typescript export function formatFileSize(sizeInBytes: number): string { const kb = sizeInBytes / 1024 if (kb < 1) return `${sizeInBytes} bytes` if (kb < 1024) return `${kb.toFixed(1).replace(/\.0$/, '')}KB` const mb = kb / 1024 if (mb < 1024) return `${mb.toFixed(1)
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
转化漏斗分析技能 功能: - 转化漏斗构建 - 转化率计算 - 漏斗可视化 - 漏斗优化建议 - A/B测试漏斗对比 Use when: - 分析用户转化路径 - 计算转化率 - 优化转化漏斗 - 对比不同漏斗 Keywords: - 转化漏斗, 转化率, 用户路径, 漏斗优化, 转化分析
Fyber (DT Exchange) 开通SOP 功能: - 开通入口 - 注册要求 - 审核流程 - 开通 checklist Use when: - 开通Fyber账号 - 欧洲市场变现 Keywords: - Fyber开通, Fyber注册, DT Exchange, 欧洲变现
Decode and interpret text content from G-code files by analyzing toolpath geometry and coordinate patterns. This skill should be used when extracting text, letters, or symbols that are encoded as movement commands in G-code files (e.g., 3D printing, CNC engraving, laser cutting). Applies to tasks like identifying what text a G-code file will print/engrave, reverse-engineering embossed or engraved text from toolpaths, or visualizing G-code geometry to reveal hidden content.
Automatically inject Git context into system prompt for better code awareness. Use when: - System needs current Git state - Code context needs branch info - User working in Git repository - Automatic Git status awareness NOT for: - Non-Git projects - User explicitly disables - Privacy-sensitive repos Auto-trigger conditions: - Automatically at session start - Periodic refresh via heartbeat Injected context: - Current branch - Default branch (main/master) - Git status (modified, added, deleted) - Recent commits (last 5) - User name Keywords: - Internal service - auto-activated at session start
Conduct multi-round deep research on any GitHub Repo. Use when users request comprehensive analysis, timeline reconstruction, competitive analysis, or in-depth investigation of GitHub. Produces structured markdown reports with executive summaries, chronological timelines, metrics analysis, and Mermaid diagrams. Triggers on Github repository URL or open source projects.
# Git Repo Sync Check Pattern ## Source Claude Code: `utils/memory/versions.ts` (projectIsInGitRepo) ## Pattern Sync git repo check via findGitRoot filesystem walk (no subprocess). ## Code Example ```typescript import { findGitRoot } from '../git.js' // Note: This is used to check git repo status synchronously // Uses findGitRoot which walks the filesystem (no subprocess) // Prefer `dirIsInGitRepo()` for async checks export function projectIsInGitRepo(cwd: string): boolean { return findGit
# Glob Tool Skill 文件查找工具 - Truncated flag + Duration tracking + Path relativize。 ## 功能概述 从Claude Code的GlobTool提取的glob模式,用于OpenClaw的文件查找。 ## 核心机制 ### Truncated Flag ```typescript const limit = globLimits?.maxResults ?? 100 const { files, truncated } = await glob(input.pattern, path, { limit, offset: 0 }) return { filenames, truncated, // true if > 100 ... } // 默认100结果限制 // truncated=true表示有更多 ``` ### Duration Tracking ```typescript const start = Date.now() const { files, truncated
Google Ads API技能 功能: - 创建广告账户 - 创建广告系列 - 创建广告组 - 创建广告素材 - 查询广告数据 - 管理预算 - 关键词管理 Use when: - 创建Google广告 - 查询Google广告效果 - 管理Google广告预算 - 管理关键词 Keywords: - Google Ads, UAC, App Campaigns, 广告投放, 关键词
# Google Play自动安装器 自动从Google Play商店下载并安装应用到Android手机。 --- ## 功能 1. 通过ADB打开Google Play应用详情页面 2. 自动定位安装按钮 3. 模拟点击安装 4. 等待安装完成 5. 验证安装成功 --- ## 使用方法 ### CLI方式 ```bash node ~/.openclaw/workspace-dispatcher/impl/bin/google-play-installer.js install <package_id> [device_id] ``` ### Skill方式 ``` 用户请求: "帮我安装 https://play.google.com/store/apps/details?id=com.wordconnect.cash.game" Agent: 调用 google-play-installer skill ``` --- ## 技术细节 ### 1. 打开应用详情页面 ```bash adb shell am start -a android.intent.
Google Play商店上架技能 功能: - APP上架流程 - 审核要求 - Store页面优化 - 常见拒绝原因 Use when: - 上架APP到Google Play - 查看审核要求 - 优化Store页面 Keywords: - Google Play, 上架, 审核 - Store listing, ASO
# Graceful Exit Reason Pattern Skill Graceful Exit Reason Pattern - ExitReason type + gracefulShutdown function + reason string + 'user-interrupt'/'normal'/'error'/'timeout'/'drain-scroll' + code mapping + exitMessage + logEvent analytics + forceExit fallback + retry shutdown + setTimeout delay + lastRequest wait + session persistence。 ## 功能概述 从Claude Code的utils/gracefulShutdown.ts提取的Graceful exit reason模式,用于OpenClaw的退出原因追踪。 ## 核心机制 ### ExitReason Type ```typescript type ExitReason = | '
Graceful shutdown mechanism: cleanup terminal modes, execute SessionEnd hooks, flush analytics, print resume hint. Failsafe timer with SIGKILL fallback. Use when shutting down, cleaning up resources, or handling SIGTERM/SIGINT.
# Grapheme Width Calculation Skill Grapheme Width Calculation - graphemeWidth function + hasMultipleCodepoints check + isEmoji detection + isEastAsianWide detection + codePoint extraction + width 1 or 2 return + segmentGraphemes generator + Intl.Segmenter usage。 ## 功能概述 从Claude Code的ink/termio/parser.ts提取的Grapheme宽度计算模式,用于OpenClaw的终端字符宽度计算。 ## 核心机制 ### graphemeWidth Function ```typescript function graphemeWidth(grapheme: string): 1 | 2 { if (hasMultipleCodepoints(grapheme)) return 2 //
# Grep Tool Skill 搜索工具 - Head_limit pagination + VCS exclusion + Mtime sort + Path relativize。 ## 功能概述 从Claude Code的GrepTool提取的搜索模式,用于OpenClaw的文件内容搜索。 ## 核心机制 ### Head Limit Pagination ```typescript const DEFAULT_HEAD_LIMIT = 250 function applyHeadLimit<T>(items: T[], limit?: number, offset = 0) { if (limit === 0) return { items: items.slice(offset), appliedLimit: undefined } const effectiveLimit = limit ?? DEFAULT_HEAD_LIMIT const sliced = items.slice(offset, offset + effectiveLimi
Interview the user relentlessly about a plan or design until reaching shared understanding. Use when user wants to stress-test a plan, get grilled on their design, or mentions "grill me".
Pre-tool-call authorization for security (borrowed from DeerFlow) Use when [guardrails] is needed.
Builder Agent - 按 spec.md 写代码,处理 QA 反馈,支持 REFINE/PIVOT 策略。适用代码构建场景,创建实际源代码文件(HTML/CSS/JS/TS)。
Evaluator Agent - 用 Playwright 实际操作页面并打分(Design/Originality/Craft/Functionality),输出 feedback.md。适用 QA 测试场景,严格评估应用质量。
# Hash Utils Skill **优先级**: P29 **来源**: Claude Code `hash.ts` **适用场景**: 内容hash、缓存key生成 --- ## 概述 Hash Utils提供快速非加密hash函数。djb2 hash用于缓存key,hashContent用于内容变化检测。支持Bun.hash(快)和SHA-256(兼容)。 --- ## 核心功能 ### 1. djb2 Hash ```typescript /** * djb2 string hash — fast non-cryptographic hash * 返回signed 32-bit int */ export function djb2Hash(str: string): number { let hash = 0 for (let i = 0; i < str.length; i++) { hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0 } return hash } ```
This skill provides guidance for implementing headless terminal interfaces that programmatically control shell sessions. Use this skill when implementing terminal emulation, pseudo-terminal wrappers,
--- metadata: openclaw: source: claude-code-pattern category: heartbeat tags: [heartbeat, executor, automation] --- # HEARTBEAT 任务执行器 执行 HEARTBEAT.md 中定义的定期任务。 ## 任务列表 ### 1. task-visualizer (30m, high) 检查活动任务,发送飞书卡片通知。 ### 2. memory-compact (24h, low) 压缩 MEMORY.md,节省 tokens。 ### 3. memory-maintenance (2h) 读取 daily notes,更新 MEMORY.md AUTO_UPDATE 区块。 ### 4. insights-analysis (6h) 分析用户工作模式,更新 User Profile。 ### 5. auto-dream (24h) 后台记忆合并,提取持久记忆。 ### 6. prompt-suggestion (on-e
Visualize background tasks during heartbeat checks. Send Feishu cards to show task status, progress, and results. Use when visualizing heartbeat tasks, showing active work, or monitoring health.
# History Pattern Skill History Pattern - MAX_HISTORY_ITEMS=100 + PastedContent Reference + parseReferences + expandPastedTextRefs + lockfile + MAX_PASTED_CONTENT_LENGTH=1024。 ## 功能概述 从Claude Code的history.ts提取的历史管理模式,用于OpenClaw的输入历史。 ## 核心机制 ### MAX_HISTORY_ITEMS ```typescript const MAX_HISTORY_ITEMS = 100 // Bounded history size // Prevent unbounded growth // 100 items max ``` ### MAX_PASTED_CONTENT_LENGTH ```typescript const MAX_PASTED_CONTENT_LENGTH = 1024 // Inline content threshold
# Hooks Command Skill Hooks配置命令 - Immediate模式查看配置。 ## 功能概述 从Claude Code的hooks/index.ts提取的hooks查看模式,用于OpenClaw的事件钩子管理。 ## 核心机制 ### 命令结构 ```typescript { type: 'local-jsx', name: 'hooks', description: 'View hook configurations for tool events', immediate: true, load: () => import('./hooks.js') } ``` ### Immediate Execution ```typescript immediate: true // 立即执行,不等待turn end // 查看配置不需要延迟 ``` ### Tool Events ``` PostToolUse, PreToolUse等事件 // Deterministic shell commands on tool even
# HyperlinkPool Pattern Skill HyperlinkPool Pattern - HyperlinkPool class + strings array + stringMap + Index 0 no hyperlink + intern(hyperlink) + get(id) + undefined handling + 5-minute reset + OSC8 hyperlink interning。 ## 功能概述 从Claude Code的ink/screen.ts提取的HyperlinkPool模式,用于OpenClaw的OSC8超链接池管理。 ## 核心机制 ### HyperlinkPool Class ```typescript export class HyperlinkPool { private strings: string[] = [''] // Index 0 = no hyperlink private stringMap = new Map<string, number>() // strings
IAA固定日报分析模板 功能: - 固定字段模板(可直接贴每天数据) - 自动输出总盘结论 - 自动输出美加澳/日韩结论 - 自动给出加量/降量/停投建议 - 适配文件修复/清理两类产品 Use when: - 需要固定日报格式 - 每天复盘渠道表现 - 给运营团队出统一结论 Keywords: - 固定模板, 日报模板, ROI模板, IAA日报, 运营模板
IAA日报分析模型 功能: - 渠道日报自动分析 - 小时级+日级ROI联动判断 - 按地区输出加量/降量/停投建议 - 按产品类型输出阈值 - 自动识别利润区/观察区/止损区 Use when: - 分析每天投放数据 - 生成运营日报结论 - 判断是否加量/降量/停投 - 对比美加澳/日韩表现 Keywords: - 日报模型, 投放日报, 加量, 降量, 停投, ROI日报, 分地区分析
IAA 日报飞书输出能力。 支持把固定 CSV 模板一键转换成: - 中文运营结论 - 飞书卡片 JSON - 飞书发送载荷 Use when: - 需要把 IAA 日报直接发到飞书 - 需要从 CSV 一键生成运营日报