openvole 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +62 -19
- package/dist/cli.js +63 -13
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +54 -11
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config/index.ts","../src/core/bus.ts","../src/core/logger.ts","../src/skill/resolver.ts","../src/core/task.ts","../src/core/scheduler.ts","../src/core/vault.ts","../src/tool/registry.ts","../src/paw/manifest.ts","../src/skill/loader.ts","../src/skill/registry.ts","../src/tool/core-tools.ts","../src/cli.ts","../src/index.ts","../src/context/types.ts","../src/core/errors.ts","../src/core/loop.ts","../src/core/hooks.ts","../src/core/rate-limiter.ts","../src/paw/registry.ts","../src/paw/loader.ts","../src/core/ipc.ts","../src/paw/sandbox.ts","../src/io/tty.ts"],"sourcesContent":["import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport type { PawConfig } from '../paw/types.js'\n\n/** Rate limit configuration */\nexport interface RateLimits {\n\t/** Max LLM (Brain) calls per minute */\n\tllmCallsPerMinute?: number\n\t/** Max LLM (Brain) calls per hour */\n\tllmCallsPerHour?: number\n\t/** Max tool executions per single task */\n\ttoolExecutionsPerTask?: number\n\t/** Max tasks per hour, keyed by source */\n\ttasksPerHour?: Record<string, number>\n}\n\n/** Loop configuration */\nexport interface LoopConfig {\n\tmaxIterations: number\n\tconfirmBeforeAct: boolean\n\ttaskConcurrency: number\n\t/** Max messages before triggering compact hooks (0 = disabled) */\n\tcompactThreshold: number\n\t/** Rate limits (undefined = no limits) */\n\trateLimits?: RateLimits\n}\n\n/** Tool profile — restricts which tools a task source can use */\nexport interface ToolProfile {\n\t/** Tools allowed (if set, only these tools can be used) */\n\tallow?: string[]\n\t/** Tools denied (if set, these tools are blocked) */\n\tdeny?: string[]\n}\n\n/** Heartbeat configuration */\nexport interface HeartbeatConfig {\n\tenabled: boolean\n\tintervalMinutes: number\n\t/** If true, run heartbeat immediately on startup (default: false) */\n\trunOnStart?: boolean\n}\n\n/** Security configuration */\nexport interface SecurityConfig {\n\t/** If true, paws can only access files inside .openvole/ directory. Default: true */\n\tsandboxFilesystem?: boolean\n\t/** Additional paths paws are allowed to access outside .openvole/ */\n\tallowedPaths?: string[]\n}\n\n/** The full OpenVole configuration */\nexport interface VoleConfig {\n\tbrain?: string\n\tpaws: Array<PawConfig | string>\n\tskills: string[]\n\tloop: LoopConfig\n\theartbeat: HeartbeatConfig\n\t/** Tool profiles per task source — restrict which tools can be used */\n\ttoolProfiles?: Record<string, ToolProfile>\n\t/** Security settings */\n\tsecurity?: SecurityConfig\n}\n\n/** CLI-managed lock file — tracks installed paws and skills */\nexport interface VoleLock {\n\tpaws: Array<{\n\t\tname: string\n\t\tversion: string\n\t\tallow?: PawConfig['allow']\n\t}>\n\tskills: Array<{\n\t\tname: string\n\t\tversion: string\n\t}>\n}\n\n/** Default configuration values */\nconst DEFAULT_LOOP_CONFIG: LoopConfig = {\n\tmaxIterations: 10,\n\tconfirmBeforeAct: true,\n\ttaskConcurrency: 1,\n\tcompactThreshold: 50,\n\trateLimits: undefined,\n}\n\nconst DEFAULT_HEARTBEAT_CONFIG: HeartbeatConfig = {\n\tenabled: false,\n\tintervalMinutes: 30,\n}\n\n/** Normalize a Paw entry (string shorthand → full config) */\nexport function normalizePawConfig(entry: PawConfig | string): PawConfig {\n\tif (typeof entry === 'string') {\n\t\treturn { name: entry }\n\t}\n\treturn entry\n}\n\n/** Create a VoleConfig with defaults applied */\nexport function defineConfig(config: Partial<VoleConfig>): VoleConfig {\n\treturn {\n\t\tbrain: config.brain,\n\t\tpaws: config.paws ?? [],\n\t\tskills: config.skills ?? [],\n\t\tloop: {\n\t\t\t...DEFAULT_LOOP_CONFIG,\n\t\t\t...config.loop,\n\t\t},\n\t\theartbeat: {\n\t\t\t...DEFAULT_HEARTBEAT_CONFIG,\n\t\t\t...config.heartbeat,\n\t\t},\n\t\ttoolProfiles: config.toolProfiles,\n\t\tsecurity: config.security,\n\t}\n}\n\n/** Load configuration — merges vole.config.{ts,mjs,js} with vole.lock.json */\nexport async function loadConfig(configPath: string): Promise<VoleConfig> {\n\tconst userConfig = await loadUserConfig(configPath)\n\tconst lockPath = path.join(path.dirname(configPath), '.openvole', 'vole.lock.json')\n\tconst lock = await loadLockFile(lockPath)\n\n\treturn mergeConfigWithLock(userConfig, lock)\n}\n\n/** Load the user-authored config file */\nasync function loadUserConfig(configPath: string): Promise<VoleConfig> {\n\t// Try JSON first (preferred), then fall back to JS/MJS\n\tconst dir = path.dirname(configPath)\n\tconst jsonPath = path.join(dir, 'vole.config.json')\n\n\t// Try JSON\n\ttry {\n\t\tconst raw = await fs.readFile(jsonPath, 'utf-8')\n\t\tconst config = JSON.parse(raw)\n\t\treturn {\n\t\t\tbrain: config.brain,\n\t\t\tpaws: config.paws ?? [],\n\t\t\tskills: config.skills ?? [],\n\t\t\tloop: {\n\t\t\t\t...DEFAULT_LOOP_CONFIG,\n\t\t\t\t...config.loop,\n\t\t\t},\n\t\t\theartbeat: {\n\t\t\t\t...DEFAULT_HEARTBEAT_CONFIG,\n\t\t\t\t...config.heartbeat,\n\t\t\t},\n\t\t\ttoolProfiles: config.toolProfiles,\n\t\t\tsecurity: config.security,\n\t\t}\n\t} catch {\n\t\t// JSON not found or invalid, try JS candidates\n\t}\n\n\t// Fall back to JS/MJS/TS imports\n\tconst candidates = [configPath]\n\tif (configPath.endsWith('.ts')) {\n\t\tcandidates.push(configPath.replace(/\\.ts$/, '.mjs'))\n\t\tcandidates.push(configPath.replace(/\\.ts$/, '.js'))\n\t}\n\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst module = await import(candidate)\n\t\t\tconst config = module.default ?? module\n\t\t\treturn {\n\t\t\t\tbrain: config.brain,\n\t\t\t\tpaws: config.paws ?? [],\n\t\t\t\tskills: config.skills ?? [],\n\t\t\t\tloop: {\n\t\t\t\t\t...DEFAULT_LOOP_CONFIG,\n\t\t\t\t\t...config.loop,\n\t\t\t\t},\n\t\t\t\theartbeat: {\n\t\t\t\t\t...DEFAULT_HEARTBEAT_CONFIG,\n\t\t\t\t\t...config.heartbeat,\n\t\t\t\t},\n\t\t\t\ttoolProfiles: config.toolProfiles,\n\t\tsecurity: config.security,\n\t\t\t}\n\t\t} catch {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tconsole.warn(`[config] No config found (tried: ${jsonPath}, ${candidates.join(', ')}), using defaults`)\n\treturn defineConfig({})\n}\n\n/** Load the CLI-managed lock file */\nasync function loadLockFile(lockPath: string): Promise<VoleLock> {\n\ttry {\n\t\tconst raw = await fs.readFile(lockPath, 'utf-8')\n\t\treturn JSON.parse(raw) as VoleLock\n\t} catch {\n\t\treturn { paws: [], skills: [] }\n\t}\n}\n\n/**\n * Merge user config with lock file.\n * Lock file entries are added if not already present in user config.\n * User config takes precedence (can override permissions, add hooks, etc.)\n */\nfunction mergeConfigWithLock(userConfig: VoleConfig, lock: VoleLock): VoleConfig {\n\tconst userPawNames = new Set(\n\t\tuserConfig.paws.map((p) => (typeof p === 'string' ? p : p.name)),\n\t)\n\tconst userSkillNames = new Set(userConfig.skills)\n\n\t// Add lock file paws not already in user config\n\tconst mergedPaws: Array<PawConfig | string> = [...userConfig.paws]\n\tfor (const lockPaw of lock.paws) {\n\t\tif (!userPawNames.has(lockPaw.name)) {\n\t\t\tmergedPaws.push(\n\t\t\t\tlockPaw.allow\n\t\t\t\t\t? { name: lockPaw.name, allow: lockPaw.allow }\n\t\t\t\t\t: lockPaw.name,\n\t\t\t)\n\t\t}\n\t}\n\n\t// Add lock file skills not already in user config\n\tconst mergedSkills = [...userConfig.skills]\n\tfor (const lockSkill of lock.skills) {\n\t\tif (!userSkillNames.has(lockSkill.name)) {\n\t\t\tmergedSkills.push(lockSkill.name)\n\t\t}\n\t}\n\n\treturn {\n\t\t...userConfig,\n\t\tpaws: mergedPaws,\n\t\tskills: mergedSkills,\n\t}\n}\n\n// === Lock file management (used by CLI) ===\n\n/** Read the lock file */\nexport async function readLockFile(projectRoot: string): Promise<VoleLock> {\n\tconst lockPath = path.join(projectRoot, '.openvole', 'vole.lock.json')\n\ttry {\n\t\tconst raw = await fs.readFile(lockPath, 'utf-8')\n\t\treturn JSON.parse(raw) as VoleLock\n\t} catch {\n\t\treturn { paws: [], skills: [] }\n\t}\n}\n\n/** Write the lock file */\nexport async function writeLockFile(\n\tprojectRoot: string,\n\tlock: VoleLock,\n): Promise<void> {\n\tconst openvoleDir = path.join(projectRoot, '.openvole')\n\tawait fs.mkdir(openvoleDir, { recursive: true })\n\tconst lockPath = path.join(openvoleDir, 'vole.lock.json')\n\tawait fs.writeFile(lockPath, JSON.stringify(lock, null, 2) + '\\n', 'utf-8')\n}\n\n/** Add a Paw to the lock file */\nexport async function addPawToLock(\n\tprojectRoot: string,\n\tname: string,\n\tversion: string,\n\tallow?: PawConfig['allow'],\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tconst existing = lock.paws.findIndex((p) => p.name === name)\n\tconst entry = { name, version, allow }\n\n\tif (existing >= 0) {\n\t\tlock.paws[existing] = entry\n\t} else {\n\t\tlock.paws.push(entry)\n\t}\n\n\tawait writeLockFile(projectRoot, lock)\n}\n\n/** Remove a Paw from the lock file */\nexport async function removePawFromLock(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tlock.paws = lock.paws.filter((p) => p.name !== name)\n\tawait writeLockFile(projectRoot, lock)\n}\n\n/** Add a Skill to the lock file */\nexport async function addSkillToLock(\n\tprojectRoot: string,\n\tname: string,\n\tversion: string,\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tconst existing = lock.skills.findIndex((s) => s.name === name)\n\tconst entry = { name, version }\n\n\tif (existing >= 0) {\n\t\tlock.skills[existing] = entry\n\t} else {\n\t\tlock.skills.push(entry)\n\t}\n\n\tawait writeLockFile(projectRoot, lock)\n}\n\n/** Remove a Skill from the lock file */\nexport async function removeSkillFromLock(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tlock.skills = lock.skills.filter((s) => s.name !== name)\n\tawait writeLockFile(projectRoot, lock)\n}\n\n// === vole.config.json management ===\n\n/** Read the raw vole.config.json */\nexport async function readConfigFile(\n\tprojectRoot: string,\n): Promise<Record<string, unknown>> {\n\tconst configPath = path.join(projectRoot, 'vole.config.json')\n\ttry {\n\t\tconst raw = await fs.readFile(configPath, 'utf-8')\n\t\treturn JSON.parse(raw)\n\t} catch {\n\t\treturn {}\n\t}\n}\n\n/** Write the vole.config.json */\nexport async function writeConfigFile(\n\tprojectRoot: string,\n\tconfig: Record<string, unknown>,\n): Promise<void> {\n\tconst configPath = path.join(projectRoot, 'vole.config.json')\n\tawait fs.writeFile(configPath, JSON.stringify(config, null, 2) + '\\n', 'utf-8')\n}\n\n/** Add a Paw to vole.config.json if not already present */\nexport async function addPawToConfig(\n\tprojectRoot: string,\n\tname: string,\n\tallow?: PawConfig['allow'],\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst paws = (config.paws ?? []) as Array<PawConfig | string>\n\tconst existing = paws.find((p) =>\n\t\ttypeof p === 'string' ? p === name : p.name === name,\n\t)\n\tif (existing) return\n\n\tpaws.push(allow ? { name, allow } : name)\n\tconfig.paws = paws\n\tawait writeConfigFile(projectRoot, config)\n}\n\n/** Remove a Paw from vole.config.json */\nexport async function removePawFromConfig(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst paws = (config.paws ?? []) as Array<PawConfig | string>\n\tconfig.paws = paws.filter((p) =>\n\t\ttypeof p === 'string' ? p !== name : p.name !== name,\n\t)\n\tawait writeConfigFile(projectRoot, config)\n}\n\n/** Add a Skill to vole.config.json if not already present */\nexport async function addSkillToConfig(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst skills = (config.skills ?? []) as string[]\n\tif (skills.includes(name)) return\n\n\tskills.push(name)\n\tconfig.skills = skills\n\tawait writeConfigFile(projectRoot, config)\n}\n\n/** Remove a Skill from vole.config.json */\nexport async function removeSkillFromConfig(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst skills = (config.skills ?? []) as string[]\n\tconfig.skills = skills.filter((s) => s !== name)\n\tawait writeConfigFile(projectRoot, config)\n}\n","import mitt, { type Emitter } from 'mitt'\n\n/** Events emitted on the message bus */\nexport type BusEvents = {\n\t'tool:registered': { toolName: string; pawName: string }\n\t'tool:unregistered': { toolName: string; pawName: string }\n\t'paw:registered': { pawName: string }\n\t'paw:unregistered': { pawName: string }\n\t'paw:crashed': { pawName: string; error?: unknown }\n\t'task:queued': { taskId: string }\n\t'task:started': { taskId: string }\n\t'task:completed': { taskId: string; result?: string }\n\t'task:failed': { taskId: string; error?: unknown }\n\t'task:cancelled': { taskId: string }\n\t'rate:limited': { bucket: string; source?: string }\n}\n\nexport type MessageBus = Emitter<BusEvents>\n\n/** Create a new message bus instance */\nexport function createMessageBus(): MessageBus {\n\treturn mitt<BusEvents>()\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nconst LEVELS = { error: 0, warn: 1, info: 2, debug: 3, trace: 4 } as const\ntype Level = keyof typeof LEVELS\n\nlet logStream: fs.WriteStream | undefined\n\n/** Initialize file logging from VOLE_LOG_FILE env var */\nfunction getLogStream(): fs.WriteStream | undefined {\n\tif (logStream) return logStream\n\tconst logFile = process.env.VOLE_LOG_FILE\n\tif (!logFile) return undefined\n\tconst dir = path.dirname(logFile)\n\tfs.mkdirSync(dir, { recursive: true })\n\tlogStream = fs.createWriteStream(logFile, { flags: 'a' })\n\treturn logStream\n}\n\n/** Close the log file stream (called on shutdown) */\nexport function closeLogger(): void {\n\tlogStream?.end()\n\tlogStream = undefined\n}\n\nfunction currentLevel(): number {\n\tconst level = (process.env.VOLE_LOG_LEVEL ?? 'info').toLowerCase() as Level\n\treturn LEVELS[level] ?? LEVELS.info\n}\n\nfunction writeToFile(level: string, prefix: string, msg: string, args: unknown[]): void {\n\tconst stream = getLogStream()\n\tif (!stream) return\n\tconst timestamp = new Date().toISOString()\n\tconst argsStr = args.length > 0 ? ' ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ') : ''\n\tstream.write(`${timestamp} [${level.toUpperCase()}] ${prefix} ${msg}${argsStr}\\n`)\n}\n\nexport function createLogger(tag: string) {\n\tconst prefix = `[${tag}]`\n\treturn {\n\t\terror: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.error) console.error(prefix, msg, ...args)\n\t\t\twriteToFile('error', prefix, msg, args)\n\t\t},\n\t\twarn: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.warn) console.warn(prefix, msg, ...args)\n\t\t\twriteToFile('warn', prefix, msg, args)\n\t\t},\n\t\tinfo: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.info) console.info(prefix, msg, ...args)\n\t\t\twriteToFile('info', prefix, msg, args)\n\t\t},\n\t\tdebug: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.debug) console.debug(prefix, msg, ...args)\n\t\t\twriteToFile('debug', prefix, msg, args)\n\t\t},\n\t\ttrace: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.trace) console.debug(prefix, msg, ...args)\n\t\t\twriteToFile('trace', prefix, msg, args)\n\t\t},\n\t}\n}\n","import { execFileSync } from 'node:child_process'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { SkillInstance } from './types.js'\nimport type { ActiveSkill } from '../context/types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('skill-resolver')\n\n/**\n * Resolve Skill activation based on the current tool registry\n * and runtime requirements (env vars, binaries).\n *\n * A Skill is active if:\n * - All requiredTools are registered in the tool registry\n * - All requires.env vars are set in the environment\n * - All requires.bins are available on PATH\n * - At least one of requires.anyBins is available (if specified)\n */\nexport function resolveSkills(\n\tskills: SkillInstance[],\n\ttoolRegistry: ToolRegistry,\n): void {\n\tfor (const skill of skills) {\n\t\tconst missing: string[] = []\n\n\t\t// Check required tools\n\t\tfor (const toolName of skill.definition.requiredTools) {\n\t\t\tif (!toolRegistry.has(toolName)) {\n\t\t\t\tmissing.push(`tool:${toolName}`)\n\t\t\t}\n\t\t}\n\n\t\t// Check OpenClaw-compatible requirements\n\t\tconst requires = skill.definition.requires\n\t\tif (requires) {\n\t\t\t// Check env vars\n\t\t\tfor (const envVar of requires.env) {\n\t\t\t\tif (!process.env[envVar]) {\n\t\t\t\t\tmissing.push(`env:${envVar}`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check required binaries\n\t\t\tfor (const bin of requires.bins) {\n\t\t\t\tif (!isBinaryAvailable(bin)) {\n\t\t\t\t\tmissing.push(`bin:${bin}`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check anyBins — at least one must exist\n\t\t\tif (requires.anyBins.length > 0) {\n\t\t\t\tconst hasAny = requires.anyBins.some(isBinaryAvailable)\n\t\t\t\tif (!hasAny) {\n\t\t\t\t\tmissing.push(`anyBin:${requires.anyBins.join('|')}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst wasActive = skill.active\n\t\tskill.active = missing.length === 0\n\t\tskill.missingTools = missing\n\n\t\tif (skill.active && !wasActive) {\n\t\t\tconst providers = skill.definition.requiredTools\n\t\t\t\t.map((t) => toolRegistry.get(t)?.pawName)\n\t\t\t\t.filter(Boolean)\n\t\t\tconst providerInfo = providers.length > 0\n\t\t\t\t? ` (tools provided by: ${[...new Set(providers)].join(', ')})`\n\t\t\t\t: ''\n\t\t\tlogger.info(`Skill \"${skill.name}\" activated${providerInfo}`)\n\t\t} else if (!skill.active && wasActive) {\n\t\t\tlogger.warn(\n\t\t\t\t`Skill \"${skill.name}\" deactivated (missing: ${missing.join(', ')})`,\n\t\t\t)\n\t\t} else if (!skill.active) {\n\t\t\tlogger.debug(\n\t\t\t\t`Skill \"${skill.name}\" inactive (missing: ${missing.join(', ')})`,\n\t\t\t)\n\t\t}\n\t}\n}\n\n/** Build ActiveSkill entries for the AgentContext */\nexport function buildActiveSkills(\n\tskills: SkillInstance[],\n\ttoolRegistry: ToolRegistry,\n): ActiveSkill[] {\n\treturn skills\n\t\t.filter((s) => s.active)\n\t\t.map((s) => {\n\t\t\tconst satisfiedBy = s.definition.requiredTools\n\t\t\t\t.map((t) => toolRegistry.get(t)?.pawName)\n\t\t\t\t.filter((name): name is string => name != null)\n\n\t\t\treturn {\n\t\t\t\tname: s.name,\n\t\t\t\tdescription: s.definition.description,\n\t\t\t\tsatisfiedBy: [...new Set(satisfiedBy)],\n\t\t\t}\n\t\t})\n}\n\n/** Check if a binary is available on PATH */\nfunction isBinaryAvailable(name: string): boolean {\n\ttry {\n\t\tconst cmd = process.platform === 'win32' ? 'where' : 'which'\n\t\texecFileSync(cmd, [name], { stdio: 'ignore' })\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n","import * as crypto from 'node:crypto'\nimport type { MessageBus } from './bus.js'\nimport type { RateLimiter } from './rate-limiter.js'\nimport type { RateLimits } from '../config/index.js'\nimport { createLogger } from './logger.js'\n\n/** Task states */\nexport type TaskStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled'\n\n/** A discrete unit of work for the agent loop */\nexport interface AgentTask {\n\tid: string\n\tsource: 'user' | 'schedule' | 'heartbeat' | 'paw'\n\tinput: string\n\tstatus: TaskStatus\n\tcreatedAt: number\n\tstartedAt?: number\n\tcompletedAt?: number\n\tresult?: string\n\terror?: string\n\tsessionId?: string\n\tmetadata?: Record<string, unknown>\n}\n\nexport type TaskRunner = (task: AgentTask) => Promise<void>\n\nconst logger = createLogger('task-queue')\n\n/** FIFO task queue with configurable concurrency */\nexport class TaskQueue {\n\tprivate queue: AgentTask[] = []\n\tprivate running = new Map<string, AgentTask>()\n\tprivate completed: AgentTask[] = []\n\tprivate runner: TaskRunner | undefined\n\tprivate draining = false\n\n\tconstructor(\n\t\tprivate bus: MessageBus,\n\t\tprivate concurrency = 1,\n\t\tprivate rateLimiter?: RateLimiter,\n\t\tprivate rateLimits?: RateLimits,\n\t) {}\n\n\t/** Set the task runner function (called by the agent loop) */\n\tsetRunner(runner: TaskRunner): void {\n\t\tthis.runner = runner\n\t}\n\n\t/** Enqueue a new task */\n\tenqueue(\n\t\tinput: string,\n\t\tsource: 'user' | 'schedule' | 'heartbeat' | 'paw' = 'user',\n\t\toptions?: { sessionId?: string; metadata?: Record<string, unknown> },\n\t): AgentTask {\n\t\tconst task: AgentTask = {\n\t\t\tid: crypto.randomUUID(),\n\t\t\tsource,\n\t\t\tinput,\n\t\t\tstatus: 'queued',\n\t\t\tcreatedAt: Date.now(),\n\t\t\tsessionId: options?.sessionId,\n\t\t\tmetadata: options?.metadata,\n\t\t}\n\n\t\t// Check tasksPerHour rate limit (warn but still enqueue)\n\t\tif (this.rateLimiter && this.rateLimits?.tasksPerHour) {\n\t\t\tconst limit = this.rateLimits.tasksPerHour[source]\n\t\t\tif (limit != null) {\n\t\t\t\tconst bucket = `tasks:per-hour:${source}`\n\t\t\t\tif (!this.rateLimiter.tryConsume(bucket, limit, 3_600_000)) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`Rate limit warning: tasksPerHour for source \"${source}\" exceeded (limit: ${limit}). Task will still be enqueued.`,\n\t\t\t\t\t)\n\t\t\t\t\tthis.bus.emit('rate:limited', { bucket, source })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.queue.push(task)\n\t\tlogger.info(`Task ${task.id} queued (source: ${source})`)\n\t\tthis.bus.emit('task:queued', { taskId: task.id })\n\t\tthis.drain()\n\t\treturn task\n\t}\n\n\t/** Cancel a task by ID */\n\tcancel(taskId: string): boolean {\n\t\t// Cancel from queue\n\t\tconst queueIdx = this.queue.findIndex((t) => t.id === taskId)\n\t\tif (queueIdx !== -1) {\n\t\t\tconst task = this.queue.splice(queueIdx, 1)[0]\n\t\t\ttask.status = 'cancelled'\n\t\t\ttask.completedAt = Date.now()\n\t\t\tthis.completed.push(task)\n\t\t\tlogger.info(`Task ${taskId} cancelled (was queued)`)\n\t\t\tthis.bus.emit('task:cancelled', { taskId })\n\t\t\treturn true\n\t\t}\n\n\t\t// Cancel running task (mark it — the loop must check this)\n\t\tconst running = this.running.get(taskId)\n\t\tif (running) {\n\t\t\trunning.status = 'cancelled'\n\t\t\tlogger.info(`Task ${taskId} marked for cancellation (running)`)\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/** Get all tasks (queued + running + completed) */\n\tlist(): AgentTask[] {\n\t\treturn [\n\t\t\t...this.queue,\n\t\t\t...Array.from(this.running.values()),\n\t\t\t...this.completed.slice(-50), // keep last 50 completed\n\t\t]\n\t}\n\n\t/** Get a task by ID */\n\tget(taskId: string): AgentTask | undefined {\n\t\treturn (\n\t\t\tthis.queue.find((t) => t.id === taskId) ??\n\t\t\tthis.running.get(taskId) ??\n\t\t\tthis.completed.find((t) => t.id === taskId)\n\t\t)\n\t}\n\n\t/** Check if a task has been cancelled */\n\tisCancelled(taskId: string): boolean {\n\t\tconst task = this.running.get(taskId)\n\t\treturn task?.status === 'cancelled'\n\t}\n\n\tprivate async drain(): Promise<void> {\n\t\tif (this.draining) return\n\t\tthis.draining = true\n\n\t\ttry {\n\t\t\twhile (this.queue.length > 0 && this.running.size < this.concurrency) {\n\t\t\t\tif (!this.runner) {\n\t\t\t\t\tlogger.error('No task runner configured')\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tconst task = this.queue.shift()!\n\t\t\t\ttask.status = 'running'\n\t\t\t\ttask.startedAt = Date.now()\n\t\t\t\tthis.running.set(task.id, task)\n\n\t\t\t\tlogger.info(`Task ${task.id} started`)\n\t\t\t\tthis.bus.emit('task:started', { taskId: task.id })\n\n\t\t\t\t// Run task without blocking the drain loop for concurrency > 1\n\t\t\t\tthis.runTask(task)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.draining = false\n\t\t}\n\t}\n\n\tprivate async runTask(task: AgentTask): Promise<void> {\n\t\ttry {\n\t\t\tawait this.runner!(task)\n\t\t\tif (task.status !== 'cancelled') {\n\t\t\t\ttask.status = 'completed'\n\t\t\t}\n\t\t\ttask.completedAt = Date.now()\n\t\t\tlogger.info(`Task ${task.id} ${task.status}`)\n\t\t\tthis.bus.emit('task:completed', { taskId: task.id, result: task.result })\n\t\t} catch (err) {\n\t\t\ttask.status = 'failed'\n\t\t\ttask.completedAt = Date.now()\n\t\t\ttask.error = err instanceof Error ? err.message : String(err)\n\t\t\tlogger.error(`Task ${task.id} failed: ${task.error}`)\n\t\t\tthis.bus.emit('task:failed', { taskId: task.id, error: err })\n\t\t} finally {\n\t\t\tthis.running.delete(task.id)\n\t\t\tthis.completed.push(task)\n\t\t\t// Drain next tasks\n\t\t\tthis.drain()\n\t\t}\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport { Cron } from 'croner'\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('scheduler')\n\ninterface ScheduleEntry {\n\tid: string\n\tinput: string\n\t/** Cron expression (e.g. \"0 13 * * *\" for daily at 1 PM UTC) */\n\tcron: string\n\tjob: Cron\n\tcreatedAt: number\n}\n\n/** Persisted schedule data (no job handle) */\ninterface PersistedSchedule {\n\tid: string\n\tinput: string\n\tcron: string\n\tcreatedAt: number\n}\n\n/** Persistent store for recurring schedules using cron expressions */\nexport class SchedulerStore {\n\tprivate schedules = new Map<string, ScheduleEntry>()\n\tprivate savePath: string | undefined\n\tprivate tickHandler: ((input: string) => void) | undefined\n\n\t/** Set the file path for persistence */\n\tsetPersistence(filePath: string): void {\n\t\tthis.savePath = filePath\n\t}\n\n\t/** Set the handler called when a schedule ticks */\n\tsetTickHandler(handler: (input: string) => void): void {\n\t\tthis.tickHandler = handler\n\t}\n\n\t/** Load schedule data from disk without starting cron jobs (for read-only access). Never persists. */\n\tasync loadFromDisk(): Promise<void> {\n\t\tif (!this.savePath) return\n\t\tconst savedPath = this.savePath\n\t\t// Temporarily disable persistence so read-only access can't overwrite the file\n\t\tthis.savePath = undefined\n\t\ttry {\n\t\t\tconst raw = await fs.readFile(savedPath, 'utf-8')\n\t\t\tconst persisted = JSON.parse(raw) as PersistedSchedule[]\n\t\t\tfor (const s of persisted) {\n\t\t\t\tconst job = new Cron(s.cron, { timezone: 'UTC', paused: true }, () => {})\n\t\t\t\tthis.schedules.set(s.id, {\n\t\t\t\t\tid: s.id,\n\t\t\t\t\tinput: s.input,\n\t\t\t\t\tcron: s.cron,\n\t\t\t\t\tjob,\n\t\t\t\t\tcreatedAt: s.createdAt,\n\t\t\t\t})\n\t\t\t}\n\t\t} catch {\n\t\t\t// No file or invalid\n\t\t}\n\t\tthis.savePath = savedPath\n\t}\n\n\t/** Load persisted schedules from disk and restart their jobs */\n\tasync restore(): Promise<void> {\n\t\tif (!this.savePath || !this.tickHandler) return\n\n\t\ttry {\n\t\t\tconst raw = await fs.readFile(this.savePath, 'utf-8')\n\t\t\tconst persisted = JSON.parse(raw) as PersistedSchedule[]\n\n\t\t\tfor (const s of persisted) {\n\t\t\t\tthis.add(s.id, s.input, s.cron, () => {\n\t\t\t\t\tthis.tickHandler!(s.input)\n\t\t\t\t}, s.createdAt)\n\t\t\t}\n\n\t\t\tif (persisted.length > 0) {\n\t\t\t\tlogger.info(`Restored ${persisted.length} schedule(s) from disk`)\n\t\t\t}\n\t\t} catch {\n\t\t\t// No file or invalid — start fresh\n\t\t}\n\t}\n\n\t/** Create or replace a recurring schedule */\n\tadd(\n\t\tid: string,\n\t\tinput: string,\n\t\tcron: string,\n\t\tonTick: () => void,\n\t\tcreatedAt?: number,\n\t\timmediate = false,\n\t): void {\n\t\t// Cancel existing schedule with same ID (idempotent upsert)\n\t\tif (this.schedules.has(id)) {\n\t\t\tthis.cancel(id, true)\n\t\t}\n\n\t\tif (immediate) {\n\t\t\tsetTimeout(onTick, 0)\n\t\t}\n\n\t\tconst job = new Cron(cron, { timezone: 'UTC' }, onTick)\n\n\t\tthis.schedules.set(id, {\n\t\t\tid,\n\t\t\tinput,\n\t\t\tcron,\n\t\t\tjob,\n\t\t\tcreatedAt: createdAt ?? Date.now(),\n\t\t})\n\n\t\tconst next = job.nextRun()\n\t\tlogger.info(`Schedule \"${id}\" created — cron: ${cron} (next: ${next?.toISOString() ?? 'unknown'}): \"${input.substring(0, 80)}\"`)\n\t\tthis.persist()\n\t}\n\n\t/** Cancel a schedule by ID */\n\tcancel(id: string, skipPersist = false): boolean {\n\t\tconst entry = this.schedules.get(id)\n\t\tif (!entry) return false\n\n\t\tentry.job.stop()\n\t\tthis.schedules.delete(id)\n\t\tlogger.info(`Schedule \"${id}\" cancelled`)\n\t\tif (!skipPersist) this.persist()\n\t\treturn true\n\t}\n\n\t/** List all active schedules */\n\tlist(): Array<{ id: string; input: string; cron: string; nextRun?: string; createdAt: number }> {\n\t\treturn Array.from(this.schedules.values()).map(({ id, input, cron, job, createdAt }) => ({\n\t\t\tid,\n\t\t\tinput,\n\t\t\tcron,\n\t\t\tnextRun: job.nextRun()?.toISOString(),\n\t\t\tcreatedAt,\n\t\t}))\n\t}\n\n\t/** Clear all schedules (for shutdown) */\n\tclearAll(): void {\n\t\tfor (const entry of this.schedules.values()) {\n\t\t\tentry.job.stop()\n\t\t}\n\t\tthis.schedules.clear()\n\t\tlogger.info('All schedules cleared')\n\t}\n\n\t/** Save schedules to disk */\n\tprivate async persist(): Promise<void> {\n\t\tif (!this.savePath) return\n\n\t\t// Don't persist the heartbeat — it's recreated from config on startup\n\t\tconst toSave: PersistedSchedule[] = Array.from(this.schedules.values())\n\t\t\t.filter((s) => s.id !== '__heartbeat__')\n\t\t\t.map(({ id, input, cron, createdAt }) => ({\n\t\t\t\tid,\n\t\t\t\tinput,\n\t\t\t\tcron,\n\t\t\t\tcreatedAt,\n\t\t\t}))\n\n\t\ttry {\n\t\t\tawait fs.mkdir(path.dirname(this.savePath), { recursive: true })\n\t\t\tawait fs.writeFile(this.savePath, JSON.stringify(toSave, null, 2) + '\\n', 'utf-8')\n\t\t} catch (err) {\n\t\t\tlogger.error(`Failed to persist schedules: ${err}`)\n\t\t}\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport * as crypto from 'node:crypto'\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('vault')\n\nexport interface VaultEntry {\n\tvalue: string // encrypted if VOLE_VAULT_KEY is set, plain text otherwise\n\tsource: 'user' | 'tool' | 'brain'\n\tcreatedAt: number\n\t/** Optional metadata — context about the stored value (service, handle, url, etc.) */\n\tmeta?: Record<string, string>\n}\n\nexport class Vault {\n\tprivate entries: Map<string, VaultEntry> = new Map()\n\tprivate vaultPath: string\n\tprivate encryptionKey?: Buffer\n\n\tconstructor(vaultPath: string, encryptionKey?: string) {\n\t\tthis.vaultPath = vaultPath\n\t\tif (encryptionKey) {\n\t\t\t// Derive a 32-byte key from the provided string using SHA-256\n\t\t\tthis.encryptionKey = crypto.createHash('sha256').update(encryptionKey).digest()\n\t\t}\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (!this.encryptionKey) {\n\t\t\tlogger.debug('VOLE_VAULT_KEY not set — vault values will be stored in plain text')\n\t\t}\n\n\t\ttry {\n\t\t\tconst raw = await fs.readFile(this.vaultPath, 'utf-8')\n\t\t\tconst data = JSON.parse(raw) as Record<string, VaultEntry>\n\t\t\tthis.entries = new Map(Object.entries(data))\n\t\t} catch {\n\t\t\t// File doesn't exist or is invalid — start fresh\n\t\t\tthis.entries = new Map()\n\t\t}\n\t}\n\n\tasync store(key: string, value: string, source: string = 'brain', meta?: Record<string, string>): Promise<boolean> {\n\t\tif (this.entries.has(key)) {\n\t\t\treturn false // write-once\n\t\t}\n\n\t\tconst entry: VaultEntry = {\n\t\t\tvalue: this.encrypt(value),\n\t\t\tsource: source as VaultEntry['source'],\n\t\t\tcreatedAt: Date.now(),\n\t\t\t...(meta && Object.keys(meta).length > 0 ? { meta } : {}),\n\t\t}\n\t\tthis.entries.set(key, entry)\n\t\tawait this.save()\n\t\treturn true\n\t}\n\n\tasync get(key: string): Promise<string | null> {\n\t\tconst entry = this.entries.get(key)\n\t\tif (!entry) return null\n\t\treturn this.decrypt(entry.value)\n\t}\n\n\tasync list(): Promise<Array<{ key: string; source: string; createdAt: number; meta?: Record<string, string> }>> {\n\t\tconst result: Array<{ key: string; source: string; createdAt: number; meta?: Record<string, string> }> = []\n\t\tfor (const [key, entry] of this.entries) {\n\t\t\tresult.push({ key, source: entry.source, createdAt: entry.createdAt, meta: entry.meta })\n\t\t}\n\t\treturn result\n\t}\n\n\tasync delete(key: string): Promise<boolean> {\n\t\tif (!this.entries.has(key)) return false\n\t\tthis.entries.delete(key)\n\t\tawait this.save()\n\t\treturn true\n\t}\n\n\tprivate async save(): Promise<void> {\n\t\tconst dir = path.dirname(this.vaultPath)\n\t\tawait fs.mkdir(dir, { recursive: true })\n\t\tconst obj: Record<string, VaultEntry> = Object.fromEntries(this.entries)\n\t\tawait fs.writeFile(this.vaultPath, JSON.stringify(obj, null, 2) + '\\n', 'utf-8')\n\t}\n\n\tprivate encrypt(value: string): string {\n\t\tif (!this.encryptionKey) return value\n\n\t\tconst iv = crypto.randomBytes(12)\n\t\tconst cipher = crypto.createCipheriv('aes-256-gcm', this.encryptionKey, iv)\n\t\tconst encrypted = Buffer.concat([cipher.update(value, 'utf-8'), cipher.final()])\n\t\tconst authTag = cipher.getAuthTag()\n\n\t\treturn `${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted.toString('base64')}`\n\t}\n\n\tprivate decrypt(value: string): string {\n\t\tif (!this.encryptionKey) return value\n\n\t\t// Check if value looks like encrypted format (iv:authTag:encrypted)\n\t\tconst parts = value.split(':')\n\t\tif (parts.length !== 3) return value // not encrypted, return as-is\n\n\t\tconst [ivB64, authTagB64, encryptedB64] = parts\n\t\tconst iv = Buffer.from(ivB64, 'base64')\n\t\tconst authTag = Buffer.from(authTagB64, 'base64')\n\t\tconst encrypted = Buffer.from(encryptedB64, 'base64')\n\n\t\tconst decipher = crypto.createDecipheriv('aes-256-gcm', this.encryptionKey, iv)\n\t\tdecipher.setAuthTag(authTag)\n\t\treturn Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf-8')\n\t}\n}\n","import type { ToolDefinition, ToolRegistryEntry } from './types.js'\nimport type { ToolSummary } from '../context/types.js'\nimport type { MessageBus } from '../core/bus.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('tool-registry')\n\n/** Convert a Zod schema to a serializable JSON Schema object */\nfunction zodToJsonSchema(schema: unknown): Record<string, unknown> | undefined {\n\tif (!schema || typeof schema !== 'object') return undefined\n\n\ttry {\n\t\tconst zodSchema = schema as { _def?: { shape?: () => Record<string, unknown> }; shape?: Record<string, unknown> }\n\t\tconst shape = typeof zodSchema._def?.shape === 'function' ? zodSchema._def.shape() : zodSchema.shape\n\t\tif (!shape || typeof shape !== 'object') return undefined\n\n\t\tconst properties: Record<string, unknown> = {}\n\t\tconst required: string[] = []\n\n\t\tfor (const [key, val] of Object.entries(shape)) {\n\t\t\tconst field = val as { _def?: { typeName?: string; description?: string; innerType?: { _def?: { typeName?: string; values?: string[] } }; values?: string[] } }\n\t\t\tconst isOptional = field?._def?.typeName === 'ZodOptional' || field?._def?.typeName === 'ZodDefault'\n\t\t\tconst inner = isOptional ? field?._def?.innerType?._def : field?._def\n\t\t\tconst typeName = inner?.typeName\n\n\t\t\tlet type = 'string'\n\t\t\tif (typeName === 'ZodNumber') type = 'number'\n\t\t\telse if (typeName === 'ZodBoolean') type = 'boolean'\n\t\t\telse if (typeName === 'ZodRecord') type = 'object'\n\n\t\t\tconst prop: Record<string, unknown> = { type }\n\t\t\tconst description = field?._def?.description\n\t\t\tif (description) prop.description = description\n\t\t\tif (typeName === 'ZodEnum') {\n\t\t\t\tprop.enum = inner?.values\n\t\t\t}\n\n\t\t\tproperties[key] = prop\n\t\t\tif (!isOptional) required.push(key)\n\t\t}\n\n\t\treturn {\n\t\t\ttype: 'object',\n\t\t\tproperties,\n\t\t\t...(required.length > 0 ? { required } : {}),\n\t\t}\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nexport class ToolRegistry {\n\tprivate tools = new Map<string, ToolRegistryEntry>()\n\n\tconstructor(private bus: MessageBus) {}\n\n\t/** Register tools from a Paw. Skips tools with conflicting names. */\n\tregister(pawName: string, tools: ToolDefinition[], inProcess: boolean): void {\n\t\tfor (const tool of tools) {\n\t\t\tif (this.tools.has(tool.name)) {\n\t\t\t\tconst existing = this.tools.get(tool.name)!\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Tool name conflict: \"${tool.name}\" already registered by \"${existing.pawName}\", ` +\n\t\t\t\t\t\t`ignoring registration from \"${pawName}\"`,\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tthis.tools.set(tool.name, {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: tool.parameters,\n\t\t\t\tpawName,\n\t\t\t\tinProcess,\n\t\t\t\texecute: tool.execute,\n\t\t\t})\n\n\t\t\tlogger.debug(`Registered tool \"${tool.name}\" from \"${pawName}\"`)\n\t\t\tthis.bus.emit('tool:registered', { toolName: tool.name, pawName })\n\t\t}\n\t}\n\n\t/** Remove all tools owned by a specific Paw */\n\tunregister(pawName: string): void {\n\t\tconst toRemove: string[] = []\n\t\tfor (const [name, entry] of this.tools) {\n\t\t\tif (entry.pawName === pawName) {\n\t\t\t\ttoRemove.push(name)\n\t\t\t}\n\t\t}\n\n\t\tfor (const name of toRemove) {\n\t\t\tthis.tools.delete(name)\n\t\t\tlogger.info(`Unregistered tool \"${name}\" from \"${pawName}\"`)\n\t\t\tthis.bus.emit('tool:unregistered', { toolName: name, pawName })\n\t\t}\n\t}\n\n\t/** Get a tool entry by name */\n\tget(toolName: string): ToolRegistryEntry | undefined {\n\t\treturn this.tools.get(toolName)\n\t}\n\n\t/** List all registered tools */\n\tlist(): ToolRegistryEntry[] {\n\t\treturn Array.from(this.tools.values())\n\t}\n\n\t/** Check if a tool exists */\n\thas(toolName: string): boolean {\n\t\treturn this.tools.has(toolName)\n\t}\n\n\t/** Get tool summaries for AgentContext */\n\tsummaries(): ToolSummary[] {\n\t\treturn this.list().map((t) => ({\n\t\t\tname: t.name,\n\t\t\tdescription: t.description,\n\t\t\tpawName: t.pawName,\n\t\t\tparameters: zodToJsonSchema(t.parameters),\n\t\t}))\n\t}\n\n\t/** Get all tool names owned by a specific Paw */\n\ttoolsForPaw(pawName: string): string[] {\n\t\treturn this.list()\n\t\t\t.filter((t) => t.pawName === pawName)\n\t\t\t.map((t) => t.name)\n\t}\n\n\t/** Clear all tools (for shutdown) */\n\tclear(): void {\n\t\tthis.tools.clear()\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport { accessSync } from 'node:fs'\nimport * as path from 'node:path'\nimport { z } from 'zod'\nimport type { PawManifest } from './types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-manifest')\n\n/** Schema for vole-paw.json */\nconst pawManifestSchema = z.object({\n\tname: z.string().min(1),\n\tversion: z.string().min(1),\n\tdescription: z.string(),\n\tentry: z.string().min(1),\n\tbrain: z.boolean().default(false),\n\tinProcess: z.boolean().optional().default(false),\n\ttransport: z.enum(['ipc', 'stdio']).optional().default('ipc'),\n\ttools: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string().min(1),\n\t\t\t\tdescription: z.string(),\n\t\t\t}),\n\t\t)\n\t\t.default([]),\n\tpermissions: z\n\t\t.object({\n\t\t\tnetwork: z.array(z.string()).optional().default([]),\n\t\t\tlisten: z.array(z.number().int().positive()).optional().default([]),\n\t\t\tfilesystem: z.array(z.string()).optional().default([]),\n\t\t\tenv: z.array(z.string()).optional().default([]),\n\t\t})\n\t\t.optional()\n\t\t.default({}),\n})\n\n/** Resolve a Paw package path from its name */\nexport function resolvePawPath(name: string, projectRoot: string): string {\n\tif (name.startsWith('.') || name.startsWith('/')) {\n\t\treturn path.resolve(projectRoot, name)\n\t}\n\t// Try .openvole/paws/<name> first, then node_modules\n\tconst openvoleDir = path.resolve(projectRoot, '.openvole', 'paws', name)\n\ttry {\n\t\taccessSync(path.join(openvoleDir, 'vole-paw.json'))\n\t\treturn openvoleDir\n\t} catch {\n\t\t// Not found — fall through to node_modules\n\t}\n\treturn path.resolve(projectRoot, 'node_modules', name)\n}\n\n/** Read and validate a vole-paw.json manifest */\nexport async function readPawManifest(\n\tpawPath: string,\n): Promise<PawManifest | null> {\n\tconst manifestPath = path.join(pawPath, 'vole-paw.json')\n\n\ttry {\n\t\tconst raw = await fs.readFile(manifestPath, 'utf-8')\n\t\tconst parsed = JSON.parse(raw)\n\t\tconst result = pawManifestSchema.safeParse(parsed)\n\n\t\tif (!result.success) {\n\t\t\tlogger.error(\n\t\t\t\t'Invalid manifest at %s: %s',\n\t\t\t\tmanifestPath,\n\t\t\t\tresult.error.message,\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\n\t\treturn result.data as PawManifest\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\tlogger.error('Manifest not found: %s', manifestPath)\n\t\t} else {\n\t\t\tlogger.error('Failed to read manifest %s: %s', manifestPath, err)\n\t\t}\n\t\treturn null\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport { parse as parseYaml } from 'yaml'\nimport type { SkillDefinition } from './types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('skill-loader')\n\n/** Parse a SKILL.md file into a SkillDefinition */\nexport async function loadSkillFromDirectory(\n\tskillDir: string,\n): Promise<SkillDefinition | null> {\n\tconst skillMdPath = path.join(skillDir, 'SKILL.md')\n\n\ttry {\n\t\tconst raw = await fs.readFile(skillMdPath, 'utf-8')\n\t\treturn parseSkillMd(raw, skillMdPath)\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\tlogger.error('SKILL.md not found: %s', skillMdPath)\n\t\t} else {\n\t\t\tlogger.error('Failed to read SKILL.md at %s: %s', skillMdPath, err)\n\t\t}\n\t\treturn null\n\t}\n}\n\n/** Parse SKILL.md content (YAML frontmatter + markdown body) */\nfunction parseSkillMd(\n\tcontent: string,\n\tfilePath: string,\n): SkillDefinition | null {\n\tconst { frontmatter, body } = extractFrontmatter(content)\n\n\tif (!frontmatter) {\n\t\tlogger.error('No YAML frontmatter found in %s', filePath)\n\t\treturn null\n\t}\n\n\tlet meta: Record<string, unknown>\n\ttry {\n\t\tmeta = parseYaml(frontmatter) as Record<string, unknown>\n\t} catch (err) {\n\t\tlogger.error('Invalid YAML frontmatter in %s: %s', filePath, err)\n\t\treturn null\n\t}\n\n\tif (!meta.name || typeof meta.name !== 'string') {\n\t\tlogger.error('SKILL.md missing \"name\" in frontmatter: %s', filePath)\n\t\treturn null\n\t}\n\n\tif (!meta.description || typeof meta.description !== 'string') {\n\t\tlogger.error('SKILL.md missing \"description\" in frontmatter: %s', filePath)\n\t\treturn null\n\t}\n\n\tconst instructions = body.trim()\n\tif (!instructions) {\n\t\tlogger.error('SKILL.md has no instructions (empty body): %s', filePath)\n\t\treturn null\n\t}\n\n\t// Extract OpenClaw metadata if present\n\tconst openclaw = extractOpenClawMetadata(meta)\n\n\treturn {\n\t\tname: meta.name as string,\n\t\tdescription: meta.description as string,\n\t\tversion: typeof meta.version === 'string'\n\t\t\t? meta.version\n\t\t\t: typeof meta.version === 'number'\n\t\t\t\t? String(meta.version)\n\t\t\t\t: undefined,\n\t\trequiredTools: toStringArray(meta.requiredTools),\n\t\toptionalTools: toStringArray(meta.optionalTools),\n\t\tinstructions,\n\t\ttags: toStringArray(meta.tags),\n\t\t// OpenClaw compatibility fields\n\t\trequires: openclaw.requires,\n\t}\n}\n\n/**\n * Extract OpenClaw-specific metadata from frontmatter.\n *\n * OpenClaw skills use this structure:\n * metadata:\n * openclaw:\n * requires:\n * env: [TODOIST_API_KEY]\n * bins: [curl]\n * anyBins: [python3, python]\n * config: [browser.enabled]\n * primaryEnv: TODOIST_API_KEY\n * emoji: \"✅\"\n *\n * Or as inline JSON:\n * metadata: { \"openclaw\": { \"requires\": { \"bins\": [\"uv\"] } } }\n */\nfunction extractOpenClawMetadata(meta: Record<string, unknown>): {\n\trequires: SkillDefinition['requires']\n} {\n\tconst metadata = meta.metadata as Record<string, unknown> | undefined\n\tif (!metadata) return { requires: undefined }\n\n\t// Support both \"openclaw\" and \"clawdbot\" (legacy name)\n\tconst oc = (metadata.openclaw ?? metadata.clawdbot) as Record<string, unknown> | undefined\n\tif (!oc) return { requires: undefined }\n\n\tconst req = oc.requires as Record<string, unknown> | undefined\n\tif (!req) return { requires: undefined }\n\n\treturn {\n\t\trequires: {\n\t\t\tenv: toStringArray(req.env),\n\t\t\tbins: toStringArray(req.bins),\n\t\t\tanyBins: toStringArray(req.anyBins),\n\t\t},\n\t}\n}\n\n/** Extract YAML frontmatter and markdown body from a file */\nfunction extractFrontmatter(content: string): {\n\tfrontmatter: string | null\n\tbody: string\n} {\n\tconst match = content.match(/^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/)\n\tif (!match) {\n\t\treturn { frontmatter: null, body: content }\n\t}\n\treturn { frontmatter: match[1], body: match[2] }\n}\n\n/** Safely convert a value to string[] */\nfunction toStringArray(value: unknown): string[] {\n\tif (!value) return []\n\tif (Array.isArray(value)) return value.filter((v) => typeof v === 'string')\n\treturn []\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport type { MessageBus } from '../core/bus.js'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { SkillInstance } from './types.js'\nimport { loadSkillFromDirectory } from './loader.js'\nimport { resolveSkills } from './resolver.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('skill-registry')\n\n/**\n * Resolve a Skill directory path from its name.\n * Resolution order:\n * 1. Explicit path (./ or /) — use as-is\n * 2. skills/<name> — local skills\n * 3. skills/clawhub/<name> — ClawHub-installed skills\n * 4. node_modules/<name> — npm-installed skills\n */\nasync function resolveSkillPath(name: string, projectRoot: string): Promise<string> {\n\t// Explicit path (./ or /)\n\tif (name.startsWith('.') || name.startsWith('/')) {\n\t\treturn path.resolve(projectRoot, name)\n\t}\n\n\t// clawhub/<name> format → .openvole/skills/clawhub/<name>\n\tif (name.startsWith('clawhub/')) {\n\t\treturn path.resolve(projectRoot, '.openvole', 'skills', name)\n\t}\n\n\t// Try .openvole/skills/<name> (local skills)\n\tconst localPath = path.resolve(projectRoot, '.openvole', 'skills', name)\n\tif (await exists(path.join(localPath, 'SKILL.md'))) return localPath\n\n\t// Try .openvole/skills/clawhub/<name> (ClawHub-installed)\n\tconst clawHubPath = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', name)\n\tif (await exists(path.join(clawHubPath, 'SKILL.md'))) return clawHubPath\n\n\t// Fall back to node_modules\n\treturn path.resolve(projectRoot, 'node_modules', name)\n}\n\nasync function exists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(filePath)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Manages loaded Skills and their activation state */\nexport class SkillRegistry {\n\tprivate skills = new Map<string, SkillInstance>()\n\n\tconstructor(\n\t\tprivate bus: MessageBus,\n\t\tprivate toolRegistry: ToolRegistry,\n\t\tprivate projectRoot: string,\n\t) {\n\t\t// Re-run resolver when tools change\n\t\tthis.bus.on('tool:registered', () => this.resolve())\n\t\tthis.bus.on('tool:unregistered', () => this.resolve())\n\t}\n\n\t/** Load a Skill from a directory containing SKILL.md */\n\tasync load(nameOrPath: string): Promise<boolean> {\n\t\tconst skillDir = await resolveSkillPath(nameOrPath, this.projectRoot)\n\t\tconst definition = await loadSkillFromDirectory(skillDir)\n\n\t\tif (!definition) {\n\t\t\treturn false\n\t\t}\n\n\t\t// Use the config key as the registry key to avoid collisions\n\t\t// clawhub/summarize → \"clawhub/summarize\", email-triage → \"email-triage\"\n\t\tconst registryKey = nameOrPath.startsWith('.') || nameOrPath.startsWith('/')\n\t\t\t? definition.name\n\t\t\t: nameOrPath\n\n\t\tif (this.skills.has(registryKey)) {\n\t\t\tlogger.warn(`Skill \"${registryKey}\" is already loaded`)\n\t\t\treturn false\n\t\t}\n\n\t\tconst instance: SkillInstance = {\n\t\t\tname: registryKey,\n\t\t\tdefinition,\n\t\t\tpath: skillDir,\n\t\t\tactive: false,\n\t\t\tmissingTools: [...definition.requiredTools],\n\t\t}\n\n\t\tthis.skills.set(registryKey, instance)\n\t\tlogger.info(`Skill \"${registryKey}\" loaded from ${skillDir}`)\n\n\t\t// Run resolver to check activation\n\t\tthis.resolve()\n\t\treturn true\n\t}\n\n\t/** Unload a Skill */\n\tunload(name: string): boolean {\n\t\tif (!this.skills.has(name)) {\n\t\t\treturn false\n\t\t}\n\t\tthis.skills.delete(name)\n\t\tlogger.info(`Skill \"${name}\" unloaded`)\n\t\treturn true\n\t}\n\n\t/** Re-run the resolver against the current tool registry */\n\tresolve(): void {\n\t\tresolveSkills(Array.from(this.skills.values()), this.toolRegistry)\n\t}\n\n\t/** Get all Skill instances */\n\tlist(): SkillInstance[] {\n\t\treturn Array.from(this.skills.values())\n\t}\n\n\t/** Get active Skills only */\n\tactive(): SkillInstance[] {\n\t\treturn this.list().filter((s) => s.active)\n\t}\n\n\t/** Get a Skill by name */\n\tget(name: string): SkillInstance | undefined {\n\t\treturn this.skills.get(name)\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport { z } from 'zod'\nimport type { ToolDefinition } from './types.js'\nimport type { SchedulerStore } from '../core/scheduler.js'\nimport type { TaskQueue } from '../core/task.js'\nimport type { SkillRegistry } from '../skill/registry.js'\nimport type { Vault } from '../core/vault.js'\n\n/** Create the built-in core tools that are always available to the Brain */\nexport function createCoreTools(\n\tscheduler: SchedulerStore,\n\ttaskQueue: TaskQueue,\n\tprojectRoot: string,\n\tskillRegistry: SkillRegistry,\n\tvault: Vault,\n): ToolDefinition[] {\n\tconst heartbeatPath = path.resolve(projectRoot, '.openvole', 'HEARTBEAT.md')\n\tconst workspaceDir = path.resolve(projectRoot, '.openvole', 'workspace')\n\n\t/** Validate that a resolved path stays inside the workspace directory */\n\tfunction resolveWorkspacePath(relativePath: string): string | null {\n\t\tconst resolved = path.resolve(workspaceDir, relativePath)\n\t\tif (!resolved.startsWith(workspaceDir + path.sep) && resolved !== workspaceDir) {\n\t\t\treturn null\n\t\t}\n\t\treturn resolved\n\t}\n\n\treturn [\n\t\t// === Scheduling tools ===\n\t\t{\n\t\t\tname: 'schedule_task',\n\t\t\tdescription: 'Create a recurring scheduled task using a cron expression. Examples: \"0 13 * * *\" = daily at 1 PM UTC, \"*/30 * * * *\" = every 30 minutes, \"0 9 * * 1\" = every Monday at 9 AM UTC.',\n\t\t\tparameters: z.object({\n\t\t\t\tid: z.string().describe('Unique schedule ID (for cancellation)'),\n\t\t\t\tinput: z.string().describe('The task input to enqueue each time'),\n\t\t\t\tcron: z.string().describe('Cron expression in UTC (minute hour day month weekday). Examples: \"0 13 * * *\" for daily 1 PM, \"*/30 * * * *\" for every 30 min'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { id, input, cron } = params as {\n\t\t\t\t\tid: string\n\t\t\t\t\tinput: string\n\t\t\t\t\tcron: string\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tscheduler.add(id, input, cron, () => {\n\t\t\t\t\t\ttaskQueue.enqueue(input, 'schedule')\n\t\t\t\t\t})\n\t\t\t\t\tconst schedules = scheduler.list()\n\t\t\t\t\tconst entry = schedules.find((s) => s.id === id)\n\t\t\t\t\treturn { ok: true, id, cron, nextRun: entry?.nextRun }\n\t\t\t\t} catch (err) {\n\t\t\t\t\treturn { ok: false, error: `Invalid cron expression: ${err instanceof Error ? err.message : err}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'cancel_schedule',\n\t\t\tdescription: 'Cancel a previously created scheduled task',\n\t\t\tparameters: z.object({\n\t\t\t\tid: z.string().describe('Schedule ID to cancel'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { id } = params as { id: string }\n\t\t\t\tconst cancelled = scheduler.cancel(id)\n\t\t\t\treturn { ok: cancelled, id }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'list_schedules',\n\t\t\tdescription: 'List all active scheduled tasks with cron expression and next run time',\n\t\t\tparameters: z.object({}),\n\t\t\tasync execute() {\n\t\t\t\treturn scheduler.list()\n\t\t\t},\n\t\t},\n\n\t\t// === Heartbeat tools ===\n\t\t{\n\t\t\tname: 'heartbeat_read',\n\t\t\tdescription: 'Read the HEARTBEAT.md file containing recurring job definitions',\n\t\t\tparameters: z.object({}),\n\t\t\tasync execute() {\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(heartbeatPath, 'utf-8')\n\t\t\t\t\treturn { ok: true, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: true, content: '' }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'heartbeat_write',\n\t\t\tdescription: 'Update the HEARTBEAT.md file with new recurring job definitions',\n\t\t\tparameters: z.object({\n\t\t\t\tcontent: z.string().describe('The full content to write to HEARTBEAT.md'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { content } = params as { content: string }\n\t\t\t\tawait fs.writeFile(heartbeatPath, content, 'utf-8')\n\t\t\t\treturn { ok: true }\n\t\t\t},\n\t\t},\n\n\t\t// === Skill tools (on-demand loading) ===\n\t\t{\n\t\t\tname: 'skill_read',\n\t\t\tdescription: 'Read the full SKILL.md instructions for a skill by name. Use this when a skill is relevant to the current task.',\n\t\t\tparameters: z.object({\n\t\t\t\tname: z.string().describe('Skill name to read'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { name } = params as { name: string }\n\t\t\t\tconst skill = skillRegistry.get(name)\n\t\t\t\tif (!skill) {\n\t\t\t\t\treturn { ok: false, error: `Skill \"${name}\" not found` }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(\n\t\t\t\t\t\tpath.join(skill.path, 'SKILL.md'),\n\t\t\t\t\t\t'utf-8',\n\t\t\t\t\t)\n\t\t\t\t\treturn { ok: true, name, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `Failed to read SKILL.md for \"${name}\"` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'skill_read_reference',\n\t\t\tdescription: 'Read a reference file from a skill\\'s references/ directory. Use this for API docs, schemas, or detailed guides.',\n\t\t\tparameters: z.object({\n\t\t\t\tname: z.string().describe('Skill name'),\n\t\t\t\tfile: z.string().describe('File path relative to the skill\\'s references/ directory'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { name, file } = params as { name: string; file: string }\n\t\t\t\tconst skill = skillRegistry.get(name)\n\t\t\t\tif (!skill) {\n\t\t\t\t\treturn { ok: false, error: `Skill \"${name}\" not found` }\n\t\t\t\t}\n\t\t\t\t// Prevent path traversal\n\t\t\t\tconst resolved = path.resolve(skill.path, 'references', file)\n\t\t\t\tif (!resolved.startsWith(path.resolve(skill.path, 'references'))) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid file path' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(resolved, 'utf-8')\n\t\t\t\t\treturn { ok: true, name, file, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `File not found: references/${file}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'skill_list_files',\n\t\t\tdescription: 'List all files in a skill\\'s directory including scripts, references, and assets.',\n\t\t\tparameters: z.object({\n\t\t\t\tname: z.string().describe('Skill name'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { name } = params as { name: string }\n\t\t\t\tconst skill = skillRegistry.get(name)\n\t\t\t\tif (!skill) {\n\t\t\t\t\treturn { ok: false, error: `Skill \"${name}\" not found` }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst files = await listFilesRecursive(skill.path)\n\t\t\t\t\treturn { ok: true, name, files }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `Failed to list files for \"${name}\"` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\n\t\t// === Workspace tools ===\n\t\t{\n\t\t\tname: 'workspace_write',\n\t\t\tdescription: 'Write a file to the workspace scratch space (.openvole/workspace/). Creates parent directories automatically.',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('File path relative to the workspace directory'),\n\t\t\t\tfile: z.string().optional().describe('Alias for path'),\n\t\t\t\tcontent: z.string().describe('Content to write to the file'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst p = params as { path?: string; file?: string; content: string }\n\t\t\t\tconst relPath = p.path ?? p.file\n\t\t\t\tconst content = p.content\n\t\t\t\tif (!relPath) return { ok: false, error: 'Missing path or file parameter' }\n\t\t\t\tconst resolved = resolveWorkspacePath(relPath)\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\tawait fs.mkdir(path.dirname(resolved), { recursive: true })\n\t\t\t\tawait fs.writeFile(resolved, content, 'utf-8')\n\t\t\t\treturn { ok: true, path: relPath }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'workspace_read',\n\t\t\tdescription: 'Read a file from the workspace scratch space (.openvole/workspace/).',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('File path relative to the workspace directory'),\n\t\t\t\tfile: z.string().optional().describe('Alias for path'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst p = params as { path?: string; file?: string }\n\t\t\t\tconst relPath = p.path ?? p.file\n\t\t\t\tif (!relPath) return { ok: false, error: 'Missing path or file parameter' }\n\t\t\t\tconst resolved = resolveWorkspacePath(relPath)\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(resolved, 'utf-8')\n\t\t\t\t\treturn { ok: true, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `File not found: ${relPath}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'workspace_list',\n\t\t\tdescription: 'List files and directories in the workspace scratch space (.openvole/workspace/). Returns recursive listing with file sizes.',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('Subdirectory to list (relative to workspace root). Defaults to root.'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { path: relPath } = params as { path?: string }\n\t\t\t\tconst resolved = relPath ? resolveWorkspacePath(relPath) : workspaceDir\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst files = await listFilesWithSizes(resolved)\n\t\t\t\t\treturn { ok: true, files }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: true, files: [] }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'workspace_delete',\n\t\t\tdescription: 'Delete a file or directory from the workspace scratch space (.openvole/workspace/).',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('File or directory path relative to the workspace directory'),\n\t\t\t\tfile: z.string().optional().describe('Alias for path'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst p = params as { path?: string; file?: string }\n\t\t\t\tconst relPath = p.path ?? p.file\n\t\t\t\tif (!relPath) return { ok: false, error: 'Missing path or file parameter' }\n\t\t\t\tconst resolved = resolveWorkspacePath(relPath)\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait fs.rm(resolved, { recursive: true })\n\t\t\t\t\treturn { ok: true }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `Not found: ${relPath}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\n\t\t// === Vault tools ===\n\t\t{\n\t\t\tname: 'vault_store',\n\t\t\tdescription: 'Store a key-value pair in the secure vault with context metadata. Write-once: fails if key already exists (delete first to update).',\n\t\t\tparameters: z.object({\n\t\t\t\tkey: z.string().describe('Key name for the stored value'),\n\t\t\t\tvalue: z.string().describe('Value to store (will be encrypted if VOLE_VAULT_KEY is set)'),\n\t\t\t\tsource: z.enum(['user', 'tool', 'brain']).optional().describe('Who stored this value. Defaults to brain.'),\n\t\t\t\tmeta: z.record(z.string()).optional().describe('Context metadata — e.g. { \"service\": \"vibegigs\", \"handle\": \"bumblebee\", \"url\": \"https://vibegigs.com\" }'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { key, value, source, meta } = params as { key: string; value: string; source?: string; meta?: Record<string, string> }\n\t\t\t\tconst ok = await vault.store(key, value, source ?? 'brain', meta)\n\t\t\t\tif (!ok) {\n\t\t\t\t\treturn { ok: false, error: 'Key already exists' }\n\t\t\t\t}\n\t\t\t\treturn { ok: true, key }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'vault_get',\n\t\t\tdescription: 'Retrieve a value from the secure vault by key.',\n\t\t\tparameters: z.object({\n\t\t\t\tkey: z.string().describe('Key name to retrieve'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { key } = params as { key: string }\n\t\t\t\tconst value = await vault.get(key)\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn { ok: false, error: `Key not found: ${key}` }\n\t\t\t\t}\n\t\t\t\treturn { ok: true, value }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'vault_list',\n\t\t\tdescription: 'List all keys in the vault with their sources and creation dates. Never returns values.',\n\t\t\tparameters: z.object({}),\n\t\t\tasync execute() {\n\t\t\t\tconst entries = await vault.list()\n\t\t\t\treturn { ok: true, entries }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'vault_delete',\n\t\t\tdescription: 'Delete a key from the secure vault.',\n\t\t\tparameters: z.object({\n\t\t\t\tkey: z.string().describe('Key name to delete'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { key } = params as { key: string }\n\t\t\t\tconst ok = await vault.delete(key)\n\t\t\t\tif (!ok) {\n\t\t\t\t\treturn { ok: false, error: `Key not found: ${key}` }\n\t\t\t\t}\n\t\t\t\treturn { ok: true }\n\t\t\t},\n\t\t},\n\n\t\t// === Web tools ===\n\t\t{\n\t\t\tname: 'web_fetch',\n\t\t\tdescription: 'Fetch a URL and return its content as text. Use for APIs, web pages, JSON endpoints, or downloading text content. Much lighter than browser_navigate — use this when you just need the content, not browser interaction.',\n\t\t\tparameters: z.object({\n\t\t\t\turl: z.string().describe('The URL to fetch'),\n\t\t\t\tmethod: z.enum(['GET', 'POST', 'PUT', 'DELETE']).optional().describe('HTTP method. Defaults to GET.'),\n\t\t\t\theaders: z.record(z.string()).optional().describe('Request headers (e.g. { \"Authorization\": \"Bearer ...\" })'),\n\t\t\t\tbody: z.string().optional().describe('Request body for POST/PUT'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { url, method, headers, body } = params as {\n\t\t\t\t\turl: string\n\t\t\t\t\tmethod?: string\n\t\t\t\t\theaders?: Record<string, string>\n\t\t\t\t\tbody?: string\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\t\tmethod: method ?? 'GET',\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t})\n\n\t\t\t\t\tconst contentType = response.headers.get('content-type') ?? ''\n\t\t\t\t\tconst text = await response.text()\n\n\t\t\t\t\t// Truncate very large responses\n\t\t\t\t\tconst maxLen = 50_000\n\t\t\t\t\tconst content = text.length > maxLen\n\t\t\t\t\t\t? text.substring(0, maxLen) + `\\n\\n[Truncated — ${text.length} chars total]`\n\t\t\t\t\t\t: text\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: response.ok,\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\tcontentType,\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t]\n}\n\n/** Recursively list files relative to a directory */\nasync function listFilesRecursive(dir: string, prefix = ''): Promise<string[]> {\n\tconst entries = await fs.readdir(dir, { withFileTypes: true })\n\tconst files: string[] = []\n\tfor (const entry of entries) {\n\t\tconst rel = prefix ? `${prefix}/${entry.name}` : entry.name\n\t\tif (entry.isDirectory()) {\n\t\t\tfiles.push(...await listFilesRecursive(path.join(dir, entry.name), rel))\n\t\t} else {\n\t\t\tfiles.push(rel)\n\t\t}\n\t}\n\treturn files\n}\n\n/** Recursively list files with sizes relative to a directory */\nasync function listFilesWithSizes(\n\tdir: string,\n\tprefix = '',\n): Promise<Array<{ path: string; size: number; type: 'file' | 'directory' }>> {\n\tconst entries = await fs.readdir(dir, { withFileTypes: true })\n\tconst results: Array<{ path: string; size: number; type: 'file' | 'directory' }> = []\n\tfor (const entry of entries) {\n\t\tconst rel = prefix ? `${prefix}/${entry.name}` : entry.name\n\t\tconst fullPath = path.join(dir, entry.name)\n\t\tif (entry.isDirectory()) {\n\t\t\tresults.push({ path: rel, size: 0, type: 'directory' })\n\t\t\tresults.push(...(await listFilesWithSizes(fullPath, rel)))\n\t\t} else {\n\t\t\tconst stat = await fs.stat(fullPath)\n\t\t\tresults.push({ path: rel, size: stat.size, type: 'file' })\n\t\t}\n\t}\n\treturn results\n}\n","#!/usr/bin/env node\n\nimport 'dotenv/config'\nimport * as path from 'node:path'\nimport { createEngine } from './index.js'\nimport {\n\taddPawToLock,\n\tremovePawFromLock,\n\taddSkillToLock,\n\tremoveSkillFromLock,\n\taddPawToConfig,\n\tremovePawFromConfig,\n\taddSkillToConfig,\n\tremoveSkillFromConfig,\n} from './config/index.js'\nimport { readPawManifest, resolvePawPath } from './paw/manifest.js'\nimport { createLogger } from './core/logger.js'\n\nconst logger = createLogger('cli')\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2)\n\tconst command = args[0]\n\n\tconst projectRoot = process.cwd()\n\n\t// Allow init and help without a project root\n\tif (command !== 'init' && command !== 'help' && command !== '--help' && command !== '-h' && command !== '--version' && command !== '-v' && command !== undefined) {\n\t\tconst fsCheck = await import('node:fs/promises')\n\t\ttry {\n\t\t\tawait fsCheck.access(path.join(projectRoot, 'vole.config.json'))\n\t\t} catch {\n\t\t\tlogger.error('vole.config.json not found in current directory')\n\t\t\tlogger.info('Run \"vole init\" to create a new project, or cd to your project root')\n\t\t\tprocess.exit(1)\n\t\t}\n\t}\n\n\tswitch (command) {\n\t\tcase 'start':\n\t\t\tawait startInteractive(projectRoot)\n\t\t\tbreak\n\n\t\tcase 'run': {\n\t\t\tconst input = args.slice(1).join(' ')\n\t\t\tif (!input) {\n\t\t\t\tlogger.error('Usage: vole run \"<task>\"')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait runSingle(projectRoot, input)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'init':\n\t\t\tawait initProject(projectRoot)\n\t\t\tbreak\n\n\t\tcase 'paw':\n\t\t\tawait handlePawCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'skill':\n\t\t\tawait handleSkillCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'tool':\n\t\t\tawait handleToolCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'task':\n\t\t\tawait handleTaskCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'clawhub':\n\t\t\tawait handleClawHubCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\n\t\tcase undefined:\n\t\tcase 'help':\n\t\tcase '--help':\n\t\tcase '-h':\n\t\t\tprintHelp()\n\t\t\tbreak\n\n\t\tcase '--version':\n\t\tcase '-v':\n\t\t\tlogger.info('openvole v0.1.0')\n\t\t\tbreak\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown command: ${command}`)\n\t\t\tprintHelp()\n\t\t\tprocess.exit(1)\n\t}\n}\n\nfunction printHelp(): void {\n\tlogger.info(`\nOpenVole — Micro Agent Core\n\nUsage:\n vole init Initialize a new project\n vole start Start the agent loop (interactive)\n vole run \"<task>\" Run a single task\n\nPaw management:\n vole paw create <name> Scaffold a new Paw in paws/\n vole paw list List loaded Paws and their tools\n vole paw add <name> Install and register a Paw\n vole paw remove <name> Uninstall and deregister a Paw\n\nSkill management:\n vole skill create <name> Scaffold a new Skill in skills/\n vole skill list List Skills and activation status\n vole skill add <name> Install and register a Skill\n vole skill remove <name> Uninstall and deregister a Skill\n\nTool management:\n vole tool list List all registered tools\n vole tool call <name> [json-params] Call a tool directly (deterministic, no Brain)\n\nClawHub (OpenClaw skill registry):\n vole clawhub install <skill> Install a skill from ClawHub\n vole clawhub remove <skill> Remove a ClawHub-installed skill\n vole clawhub search <query> Search for skills on ClawHub\n\nTask management:\n vole task list Show task queue\n vole task cancel <id> Cancel a task\n\nOptions:\n -h, --help Show this help\n -v, --version Show version\n`)\n}\n\nasync function startInteractive(projectRoot: string): Promise<void> {\n\tconst engine = await createEngine(projectRoot)\n\tawait engine.start()\n\n\tlogger.info('\\nOpenVole is running. Type a task or \"exit\" to quit.\\n')\n\n\tconst readline = await import('node:readline')\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t})\n\n\tconst promptUser = (): void => {\n\t\trl.question('vole> ', (input) => {\n\t\t\tconst trimmed = input.trim()\n\t\t\tif (trimmed === 'exit' || trimmed === 'quit') {\n\t\t\t\trl.close()\n\t\t\t\tengine.shutdown().then(() => process.exit(0))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (trimmed) {\n\t\t\t\tengine.run(trimmed, 'user', 'cli:default')\n\t\t\t}\n\t\t\tpromptUser()\n\t\t})\n\t}\n\n\tpromptUser()\n\n\t// Graceful shutdown on SIGINT/SIGTERM\n\tconst gracefulShutdown = (): void => {\n\t\tlogger.info('\\nShutting down...')\n\t\trl.close()\n\t\tengine.shutdown().then(() => process.exit(0))\n\t}\n\n\tprocess.on('SIGINT', gracefulShutdown)\n\tprocess.on('SIGTERM', gracefulShutdown)\n}\n\nasync function runSingle(\n\tprojectRoot: string,\n\tinput: string,\n): Promise<void> {\n\tconst engine = await createEngine(projectRoot)\n\tawait engine.start()\n\tengine.run(input)\n\n\t// Wait for task completion\n\treturn new Promise<void>((resolve) => {\n\t\tengine.bus.on('task:completed', () => {\n\t\t\tengine.shutdown().then(resolve)\n\t\t})\n\t\tengine.bus.on('task:failed', () => {\n\t\t\tengine.shutdown().then(() => {\n\t\t\t\tprocess.exit(1)\n\t\t\t})\n\t\t})\n\t})\n}\n\nasync function initProject(projectRoot: string): Promise<void> {\n\tconst fs = await import('node:fs/promises')\n\n\tconst configPath = path.resolve(projectRoot, 'vole.config.json')\n\ttry {\n\t\tawait fs.access(configPath)\n\t\tlogger.error('vole.config.json already exists')\n\t\treturn\n\t} catch {\n\t\t// File doesn't exist, proceed\n\t}\n\n\tconst config = {\n\t\tpaws: [],\n\t\tskills: [],\n\t\tloop: {\n\t\t\tmaxIterations: 10,\n\t\t\tconfirmBeforeAct: true,\n\t\t\ttaskConcurrency: 1,\n\t\t},\n\t\theartbeat: {\n\t\t\tenabled: false,\n\t\t\tintervalMinutes: 30,\n\t\t},\n\t}\n\tawait fs.writeFile(configPath, JSON.stringify(config, null, 2) + '\\n', 'utf-8')\n\n\t// Create .openvole directory structure\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'skills'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'skills', 'clawhub'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'workspace'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'paws', 'paw-memory'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'paws', 'paw-session'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'paws', 'paw-mcp'), { recursive: true })\n\n\t// Create default MEMORY.md\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'paws', 'paw-memory', 'MEMORY.md'),\n\t\t'# Memory\\n\\nLong-term memory for the agent. Store important facts, user preferences, and decisions here.\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create HEARTBEAT.md inside .openvole\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'HEARTBEAT.md'),\n\t\t'# Heartbeat\\n\\n## Jobs\\n\\n<!-- Add recurring jobs here -->\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create BRAIN.md (custom system prompt — optional, overrides default)\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'BRAIN.md'),\n\t\t'# Brain\\n\\nCustom system prompt for the agent. Edit this to change how the Brain reasons and responds.\\nDelete this file to use the built-in default prompt.\\n\\n<!-- Write your custom prompt below -->\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create identity files\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'SOUL.md'),\n\t\t'# Soul\\n\\nThe agent\\'s personality, tone, and identity.\\n\\n## Identity\\n- Name: OpenVole Agent\\n- Personality: Helpful, concise, and proactive\\n- Tone: Professional but friendly\\n',\n\t\t'utf-8',\n\t)\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'USER.md'),\n\t\t'# User\\n\\nInformation about the user.\\n\\n## Profile\\n- Name:\\n- Timezone:\\n- Language: English\\n',\n\t\t'utf-8',\n\t)\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'AGENT.md'),\n\t\t'# Agent\\n\\nOperating rules and behavioral guidelines.\\n\\n## Rules\\n- Always be helpful and direct\\n- Ask for clarification when a request is ambiguous\\n- Save important findings to memory for future reference\\n- Store credentials in the vault, never in workspace or memory\\n- When reading API docs or instructions, save them to workspace immediately\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create .env template\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.env'),\n\t\t'# OpenVole Environment\\nVOLE_LOG_LEVEL=info\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create .gitignore\n\ttry {\n\t\tawait fs.access(path.join(projectRoot, '.gitignore'))\n\t} catch {\n\t\tawait fs.writeFile(\n\t\t\tpath.join(projectRoot, '.gitignore'),\n\t\t\t'node_modules/\\n.env\\n.openvole/\\n.DS_Store\\n',\n\t\t\t'utf-8',\n\t\t)\n\t}\n\n\tlogger.info('Created vole.config.json')\n\tlogger.info('Created .openvole/')\n\tlogger.info(' skills/ — local and ClawHub skills')\n\tlogger.info(' workspace/ — agent scratch space')\n\tlogger.info(' paws/paw-memory/ — agent memory (MEMORY.md + daily logs)')\n\tlogger.info(' paws/paw-session/ — session transcripts')\n\tlogger.info(' paws/paw-mcp/ — MCP server config')\n\tlogger.info('Created identity files (BRAIN.md, SOUL.md, USER.md, AGENT.md, HEARTBEAT.md)')\n\tlogger.info('Created .env')\n\tlogger.info('')\n\tlogger.info('Next: install paws and start')\n\tlogger.info(' npm install @openvole/paw-ollama @openvole/paw-memory')\n\tlogger.info(' npx vole start')\n}\n\nasync function handlePawCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'create': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole paw create <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait scaffoldPaw(projectRoot, name)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'list': {\n\t\t\t// Lightweight — read manifests without spawning paws\n\t\t\tconst config = await (await import('./config/index.js')).loadConfig(\n\t\t\t\tpath.resolve(projectRoot, 'vole.config.json'),\n\t\t\t)\n\t\t\tconst { normalizePawConfig } = await import('./config/index.js')\n\t\t\tconst { readPawManifest, resolvePawPath } = await import('./paw/manifest.js')\n\n\t\t\tconst paws: Array<{ name: string; tools: number; type: string }> = []\n\t\t\tfor (const pawEntry of config.paws) {\n\t\t\t\tconst pawConfig = normalizePawConfig(pawEntry)\n\t\t\t\tconst pawPath = resolvePawPath(pawConfig.name, projectRoot)\n\t\t\t\tconst manifest = await readPawManifest(pawPath)\n\t\t\t\tif (manifest) {\n\t\t\t\t\tpaws.push({\n\t\t\t\t\t\tname: manifest.name,\n\t\t\t\t\t\ttools: manifest.tools.length,\n\t\t\t\t\t\ttype: manifest.inProcess ? 'in-process' : 'subprocess',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (paws.length === 0) {\n\t\t\t\tlogger.info('No Paws configured')\n\t\t\t} else {\n\t\t\t\tlogger.info('PAW TOOLS TYPE')\n\t\t\t\tfor (const paw of paws) {\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`${paw.name.padEnd(29)}${String(paw.tools).padEnd(9)}${paw.type}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'add': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole paw add <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tlogger.info(`Installing ${name}...`)\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\tawait execaFn('npm', ['install', name], { cwd: projectRoot, stdio: 'inherit' })\n\n\t\t\t// Read manifest and auto-register in lock file\n\t\t\tconst pawPath = resolvePawPath(name, projectRoot)\n\t\t\tconst manifest = await readPawManifest(pawPath)\n\t\t\tif (manifest) {\n\t\t\t\tconst defaultAllow = manifest.permissions\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tnetwork: manifest.permissions.network,\n\t\t\t\t\t\t\tlisten: manifest.permissions.listen,\n\t\t\t\t\t\t\tfilesystem: manifest.permissions.filesystem,\n\t\t\t\t\t\t\tenv: manifest.permissions.env,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined\n\t\t\t\tawait addPawToLock(projectRoot, name, manifest.version, defaultAllow)\n\t\t\t\tawait addPawToConfig(projectRoot, name, defaultAllow)\n\t\t\t\tlogger.info(`Added ${name}@${manifest.version} to vole.config.json`)\n\t\t\t\tif (manifest.permissions?.listen?.length) {\n\t\t\t\t\tlogger.info(` listen ports: ${manifest.permissions.listen.join(', ')}`)\n\t\t\t\t}\n\t\t\t\tif (manifest.tools.length > 0) {\n\t\t\t\t\tlogger.info(` provides ${manifest.tools.length} tools: ${manifest.tools.map((t) => t.name).join(', ')}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogger.error(`Installed ${name} but could not read vole-paw.json — add it to vole.config.json manually`)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'remove': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole paw remove <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\tawait execaFn('npm', ['uninstall', name], { cwd: projectRoot, stdio: 'inherit' })\n\t\t\tawait removePawFromLock(projectRoot, name)\n\t\t\tawait removePawFromConfig(projectRoot, name)\n\t\t\tlogger.info(`Removed ${name} from vole.config.json`)\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown paw command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, add, remove')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nasync function handleSkillCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'create': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole skill create <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait scaffoldSkill(projectRoot, name)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'list': {\n\t\t\t// Lightweight — load SKILL.md files without spawning paws\n\t\t\tconst config = await (await import('./config/index.js')).loadConfig(\n\t\t\t\tpath.resolve(projectRoot, 'vole.config.json'),\n\t\t\t)\n\t\t\tconst { SkillRegistry } = await import('./skill/registry.js')\n\t\t\tconst { createMessageBus } = await import('./core/bus.js')\n\t\t\tconst { ToolRegistry } = await import('./tool/registry.js')\n\n\t\t\tconst bus = createMessageBus()\n\t\t\tconst toolRegistry = new ToolRegistry(bus)\n\t\t\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\n\t\t\tfor (const skillName of config.skills) {\n\t\t\t\tawait skillRegistry.load(skillName)\n\t\t\t}\n\n\t\t\tconst skills = skillRegistry.list()\n\t\t\tif (skills.length === 0) {\n\t\t\t\tlogger.info('No Skills configured')\n\t\t\t} else {\n\t\t\t\tlogger.info('SKILL STATUS MISSING')\n\t\t\t\tfor (const skill of skills) {\n\t\t\t\t\tconst status = skill.active ? 'active' : 'inactive'\n\t\t\t\t\tconst missing = skill.missingTools.length > 0\n\t\t\t\t\t\t? skill.missingTools.join(', ')\n\t\t\t\t\t\t: '—'\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`${skill.name.padEnd(31)}${status.padEnd(11)}${missing}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'add': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole skill add <path-to-skill>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst skillPath = path.resolve(projectRoot, name)\n\t\t\tconst { loadSkillFromDirectory } = await import('./skill/loader.js')\n\t\t\tconst definition = await loadSkillFromDirectory(skillPath)\n\n\t\t\tif (!definition) {\n\t\t\t\tlogger.error(`No valid SKILL.md found at ${skillPath}`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tawait addSkillToLock(projectRoot, name, definition.version ?? '0.0.0')\n\t\t\tawait addSkillToConfig(projectRoot, name)\n\t\t\tlogger.info(`Added \"${definition.name}\" to vole.config.json`)\n\t\t\tif (definition.requiredTools.length > 0) {\n\t\t\t\tlogger.info(` requires tools: ${definition.requiredTools.join(', ')}`)\n\t\t\t}\n\t\t\tif (definition.requires?.env.length) {\n\t\t\t\tlogger.info(` requires env: ${definition.requires.env.join(', ')}`)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'remove': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole skill remove <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait removeSkillFromLock(projectRoot, name)\n\t\t\tawait removeSkillFromConfig(projectRoot, name)\n\n\t\t\t// Delete from .openvole/skills/\n\t\t\tconst fsModule = await import('node:fs/promises')\n\t\t\tconst skillPath = name.startsWith('.') || name.startsWith('/')\n\t\t\t\t? path.resolve(projectRoot, name)\n\t\t\t\t: path.resolve(projectRoot, '.openvole', 'skills', name)\n\t\t\ttry {\n\t\t\t\tawait fsModule.rm(skillPath, { recursive: true })\n\t\t\t\tlogger.info(`Deleted ${skillPath}`)\n\t\t\t} catch {\n\t\t\t\t// Directory may not exist — that's fine\n\t\t\t}\n\n\t\t\tlogger.info(`Removed \"${name}\" from vole.config.json`)\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown skill command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, add, remove')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nasync function handleToolCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'list': {\n\t\t\t// Lightweight mode — no paw spawning, no heartbeat\n\t\t\t// Shows core tools + tools declared in paw manifests\n\t\t\tconst config = await (await import('./config/index.js')).loadConfig(\n\t\t\t\tpath.resolve(projectRoot, 'vole.config.json'),\n\t\t\t)\n\n\t\t\tconst tools: Array<{ name: string; pawName: string; type: string }> = []\n\n\t\t\t// Core tools\n\t\t\tconst { createMessageBus } = await import('./core/bus.js')\n\t\t\tconst { ToolRegistry } = await import('./tool/registry.js')\n\t\t\tconst { SchedulerStore } = await import('./core/scheduler.js')\n\t\t\tconst { TaskQueue } = await import('./core/task.js')\n\t\t\tconst { SkillRegistry } = await import('./skill/registry.js')\n\t\t\tconst { createCoreTools } = await import('./tool/core-tools.js')\n\t\t\tconst { Vault } = await import('./core/vault.js')\n\n\t\t\tconst bus = createMessageBus()\n\t\t\tconst toolRegistry = new ToolRegistry(bus)\n\t\t\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\t\t\tconst taskQueue = new TaskQueue(bus, 1)\n\t\t\tconst scheduler = new SchedulerStore()\n\t\t\tconst vault = new Vault(path.resolve(projectRoot, '.openvole', 'vault.json'), process.env.VOLE_VAULT_KEY)\n\t\t\tawait vault.init()\n\t\t\tconst coreTools = createCoreTools(scheduler, taskQueue, projectRoot, skillRegistry, vault)\n\t\t\ttoolRegistry.register('__core__', coreTools, true)\n\n\t\t\tfor (const entry of toolRegistry.list()) {\n\t\t\t\ttools.push({ name: entry.name, pawName: entry.pawName, type: 'in-process' })\n\t\t\t}\n\n\t\t\t// Read paw manifests (without spawning) to get declared tools\n\t\t\tconst { normalizePawConfig } = await import('./config/index.js')\n\t\t\tconst { readPawManifest, resolvePawPath } = await import('./paw/manifest.js')\n\t\t\tfor (const pawEntry of config.paws) {\n\t\t\t\tconst pawConfig = normalizePawConfig(pawEntry)\n\t\t\t\tconst pawPath = resolvePawPath(pawConfig.name, projectRoot)\n\t\t\t\tconst manifest = await readPawManifest(pawPath)\n\t\t\t\tif (manifest?.tools) {\n\t\t\t\t\tfor (const t of manifest.tools) {\n\t\t\t\t\t\ttools.push({\n\t\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\t\tpawName: pawConfig.name,\n\t\t\t\t\t\t\ttype: manifest.inProcess ? 'in-process' : 'subprocess',\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (tools.length === 0) {\n\t\t\t\tlogger.info('No tools registered')\n\t\t\t} else {\n\t\t\t\tlogger.info('TOOL PAW TYPE')\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`${tool.name.padEnd(21)}${tool.pawName.padEnd(23)}${tool.type}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'call': {\n\t\t\tconst toolName = args[1]\n\t\t\tconst paramsJson = args[2]\n\n\t\t\tif (!toolName) {\n\t\t\t\tlogger.error('Usage: vole tool call <tool-name> [json-params]')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tlet params: unknown = {}\n\t\t\tif (paramsJson) {\n\t\t\t\ttry {\n\t\t\t\t\tparams = JSON.parse(paramsJson)\n\t\t\t\t} catch {\n\t\t\t\t\tlogger.error('Invalid JSON params')\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Lightweight boot — only register core tools (no paw spawning)\n\t\t\tconst { createMessageBus } = await import('./core/bus.js')\n\t\t\tconst { ToolRegistry } = await import('./tool/registry.js')\n\t\t\tconst { SchedulerStore } = await import('./core/scheduler.js')\n\t\t\tconst { TaskQueue } = await import('./core/task.js')\n\t\t\tconst { SkillRegistry } = await import('./skill/registry.js')\n\t\t\tconst { Vault } = await import('./core/vault.js')\n\t\t\tconst { createCoreTools } = await import('./tool/core-tools.js')\n\n\t\t\tconst bus = createMessageBus()\n\t\t\tconst toolRegistry = new ToolRegistry(bus)\n\t\t\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\t\t\tconst taskQueue = new TaskQueue(bus, 1)\n\t\t\tconst scheduler = new SchedulerStore()\n\t\t\tscheduler.setPersistence(path.resolve(projectRoot, '.openvole', 'schedules.json'))\n\t\t\tawait scheduler.loadFromDisk()\n\t\t\tconst vault = new Vault(\n\t\t\t\tpath.resolve(projectRoot, '.openvole', 'vault.json'),\n\t\t\t\tprocess.env.VOLE_VAULT_KEY,\n\t\t\t)\n\t\t\tawait vault.init()\n\t\t\tconst coreTools = createCoreTools(scheduler, taskQueue, projectRoot, skillRegistry, vault)\n\t\t\ttoolRegistry.register('__core__', coreTools, true)\n\n\t\t\tconst tool = toolRegistry.get(toolName)\n\t\t\tif (!tool) {\n\t\t\t\tlogger.error(`Tool \"${toolName}\" not found in core tools`)\n\t\t\t\tlogger.info('Core tools only — paw tools require a running \"vole start\" instance')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (tool.parameters && typeof tool.parameters.parse === 'function') {\n\t\t\t\t\ttool.parameters.parse(params)\n\t\t\t\t}\n\t\t\t\tconst result = await tool.execute(params)\n\t\t\t\tconsole.log(JSON.stringify(result, null, 2))\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Tool execution failed: ${err instanceof Error ? err.message : err}`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown tool command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, call')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nasync function handleTaskCommand(\n\targs: string[],\n\t_projectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'list':\n\t\t\tlogger.info('Task list requires a running vole instance.')\n\t\t\tbreak\n\n\t\tcase 'cancel': {\n\t\t\tconst id = args[1]\n\t\t\tif (!id) {\n\t\t\t\tlogger.error('Usage: vole task cancel <id>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tlogger.info('Task cancellation requires a running vole instance.')\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown task command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, cancel')\n\t\t\tprocess.exit(1)\n\t}\n}\n\n/** Interactive prompt helper */\nasync function ask(question: string): Promise<string> {\n\tconst rl = (await import('node:readline')).createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t})\n\treturn new Promise((resolve) => {\n\t\trl.question(question, (answer) => {\n\t\t\trl.close()\n\t\t\tresolve(answer.trim())\n\t\t})\n\t})\n}\n\n/** Ask yes/no */\nasync function confirm(question: string): Promise<boolean> {\n\tconst answer = await ask(`${question} [y/N] `)\n\treturn answer.toLowerCase() === 'y'\n}\n\n/** Ask for a comma-separated list */\nasync function askList(question: string): Promise<string[]> {\n\tconst answer = await ask(question)\n\tif (!answer) return []\n\treturn answer.split(',').map((s) => s.trim()).filter(Boolean)\n}\n\ninterface ToolSpec {\n\tname: string\n\tdescription: string\n}\n\nasync function scaffoldPaw(projectRoot: string, name: string): Promise<void> {\n\tconst fs = await import('node:fs/promises')\n\n\tconst pawName = name.startsWith('paw-') ? name : `paw-${name}`\n\tconst pawDir = path.resolve(projectRoot, 'paws', pawName)\n\n\ttry {\n\t\tawait fs.access(pawDir)\n\t\tlogger.error(`Directory paws/${pawName} already exists`)\n\t\tprocess.exit(1)\n\t} catch {\n\t\t// Doesn't exist — good\n\t}\n\n\t// Interactive setup\n\tlogger.info(`\\nCreating Paw: ${pawName}\\n`)\n\n\tconst description = await ask('Description: ')\n\n\t// Collect tools\n\tconst tools: ToolSpec[] = []\n\tlogger.info('\\nTools are actions the agent can perform (e.g., send_email, search_docs).')\n\tif (await confirm('Add tools?')) {\n\t\tlet addMore = true\n\t\twhile (addMore) {\n\t\t\tconst toolName = await ask(' Tool name (e.g., send_message): ')\n\t\t\tif (!toolName) break\n\t\t\tconst toolDesc = await ask(' Tool description: ')\n\t\t\ttools.push({ name: toolName, description: toolDesc })\n\t\t\taddMore = await confirm(' Add another tool?')\n\t\t}\n\t}\n\n\t// Hooks\n\tlogger.info('\\nHooks let your Paw react to agent activity automatically.')\n\tconst wantObserve = await confirm('Log every tool execution? (observe hook)')\n\tconst wantPerceive = await confirm('Inject context before the agent thinks? (perceive hook)')\n\n\t// Permissions\n\tlogger.info('\\nPermissions control what this Paw can access.')\n\tconst networkDomains = await askList('Network domains (comma-separated, e.g., api.telegram.org): ')\n\tconst listenPorts = (await askList('Ports to listen on (comma-separated, e.g., 3000): ')).map(Number).filter((n) => !Number.isNaN(n))\n\tconst envVars = await askList('Env variables needed (comma-separated, e.g., TELEGRAM_TOKEN): ')\n\n\tlogger.info('')\n\n\t// Generate files\n\tawait fs.mkdir(path.join(pawDir, 'src'), { recursive: true })\n\n\t// vole-paw.json\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'vole-paw.json'),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tname: pawName,\n\t\t\t\tversion: '0.1.0',\n\t\t\t\tdescription,\n\t\t\t\tentry: './dist/index.js',\n\t\t\t\tbrain: false,\n\t\t\t\tinProcess: false,\n\t\t\t\ttransport: 'ipc',\n\t\t\t\ttools: tools.map((t) => ({ name: t.name, description: t.description })),\n\t\t\t\tpermissions: {\n\t\t\t\t\tnetwork: networkDomains,\n\t\t\t\t\tlisten: listenPorts,\n\t\t\t\t\tfilesystem: [],\n\t\t\t\t\tenv: envVars,\n\t\t\t\t},\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t) + '\\n',\n\t)\n\n\t// package.json\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'package.json'),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tname: pawName,\n\t\t\t\tversion: '0.1.0',\n\t\t\t\tdescription,\n\t\t\t\ttype: 'module',\n\t\t\t\tmain: './dist/index.js',\n\t\t\t\tscripts: {\n\t\t\t\t\tbuild: 'tsup',\n\t\t\t\t\ttypecheck: 'tsc --noEmit',\n\t\t\t\t},\n\t\t\t\tdependencies: {\n\t\t\t\t\t'@openvole/paw-sdk': 'workspace:*',\n\t\t\t\t},\n\t\t\t\tdevDependencies: {\n\t\t\t\t\t'@types/node': '^22.0.0',\n\t\t\t\t\ttsup: '^8.3.0',\n\t\t\t\t\ttypescript: '^5.6.0',\n\t\t\t\t},\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t) + '\\n',\n\t)\n\n\t// tsconfig.json\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'tsconfig.json'),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\textends: '../../tsconfig.base.json',\n\t\t\t\tcompilerOptions: { outDir: './dist', rootDir: './src' },\n\t\t\t\tinclude: ['src/**/*.ts'],\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t) + '\\n',\n\t)\n\n\t// tsup.config.ts\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'tsup.config.ts'),\n\t\t`import { defineConfig } from 'tsup'\n\nexport default defineConfig({\n\\tentry: ['src/index.ts'],\n\\tformat: ['esm'],\n\\tdts: true,\n\\tclean: true,\n\\tsourcemap: true,\n\\ttarget: 'node20',\n\\tsplitting: false,\n})\n`,\n\t)\n\n\t// src/index.ts\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'src', 'index.ts'),\n\t\t`import { definePaw } from '@openvole/paw-sdk'\nimport { paw } from './paw.js'\n\nexport default definePaw(paw)\n`,\n\t)\n\n\t// src/paw.ts — generate with real tools from the interactive session\n\tconst toolsCode = tools.length > 0\n\t\t? tools.map((t) => `\\t\\t{\n\\t\\t\\tname: '${t.name}',\n\\t\\t\\tdescription: '${t.description.replace(/'/g, \"\\\\'\")}',\n\\t\\t\\tparameters: z.object({\n\\t\\t\\t\\t// Define your parameters here\n\\t\\t\\t}),\n\\t\\t\\tasync execute(params) {\n\\t\\t\\t\\t// TODO: implement ${t.name}\n\\t\\t\\t\\tthrow new Error('Not implemented')\n\\t\\t\\t},\n\\t\\t},`).join('\\n')\n\t\t: ''\n\n\t// Generate hooks code\n\tlet hooksCode = ''\n\tif (wantObserve || wantPerceive) {\n\t\tconst hookParts: string[] = []\n\t\tif (wantObserve) {\n\t\t\thookParts.push(`\\t\\tonObserve: async (result) => {\n\\t\\t\\tconst status = result.success ? 'OK' : 'FAIL'\n\\t\\t\\tconsole.log(\\`[${pawName}] \\${result.toolName} → \\${status} (\\${result.durationMs}ms)\\`)\n\\t\\t},`)\n\t\t}\n\t\tif (wantPerceive) {\n\t\t\thookParts.push(`\\t\\tonPerceive: async (context) => {\n\\t\\t\\t// Add data to context.metadata before the agent thinks\n\\t\\t\\t// context.metadata.myData = { ... }\n\\t\\t\\treturn context\n\\t\\t},`)\n\t\t}\n\t\thooksCode = `\\n\\thooks: {\\n${hookParts.join('\\n')}\\n\\t},\\n`\n\t}\n\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'src', 'paw.ts'),\n\t\t`import { z, type PawDefinition } from '@openvole/paw-sdk'\n\nexport const paw: PawDefinition = {\n\\tname: '${pawName}',\n\\tversion: '0.1.0',\n\\tdescription: '${description.replace(/'/g, \"\\\\'\")}',\n\n\\ttools: [\n${toolsCode}\n\\t],\n${hooksCode}\n\\tasync onLoad() {\n\\t\\tconsole.log('[${pawName}] loaded')\n\\t},\n\n\\tasync onUnload() {\n\\t\\tconsole.log('[${pawName}] unloaded')\n\\t},\n}\n`,\n\t)\n\n\t// Auto-register in vole.lock.json\n\tconst allow: Record<string, unknown> = {}\n\tif (networkDomains.length > 0) allow.network = networkDomains\n\tif (listenPorts.length > 0) allow.listen = listenPorts\n\tif (envVars.length > 0) allow.env = envVars\n\tawait addPawToLock(\n\t\tprojectRoot,\n\t\t`./paws/${pawName}`,\n\t\t'0.1.0',\n\t\tObject.keys(allow).length > 0 ? allow as import('./paw/types.js').PawConfig['allow'] : undefined,\n\t)\n\n\tlogger.info(`Created paws/${pawName}/`)\n\tlogger.info(`Registered in vole.lock.json`)\n\tif (tools.length > 0) {\n\t\tlogger.info(`Generated ${tools.length} tool${tools.length > 1 ? 's' : ''}: ${tools.map((t) => t.name).join(', ')}`)\n\t}\n\tlogger.info('')\n\tlogger.info('Next: implement your tool logic in src/paw.ts, then build:')\n\tlogger.info(' pnpm install && pnpm build')\n}\n\nasync function scaffoldSkill(projectRoot: string, name: string): Promise<void> {\n\tconst fs = await import('node:fs/promises')\n\n\tconst skillName = name.startsWith('skill-') ? name : `skill-${name}`\n\tconst skillDir = path.resolve(projectRoot, '.openvole', 'skills', skillName)\n\n\ttry {\n\t\tawait fs.access(skillDir)\n\t\tlogger.error(`Skill \"${skillName}\" already exists`)\n\t\tprocess.exit(1)\n\t} catch {\n\t\t// Doesn't exist — good\n\t}\n\n\t// Interactive setup\n\tlogger.info(`\\nCreating Skill: ${skillName}\\n`)\n\n\tconst description = await ask('Description: ')\n\n\tlogger.info('\\nSkills describe behavior — what the agent should do, using tools provided by Paws.')\n\tconst requiredTools = await askList('Required tools (comma-separated, e.g., email_search, email_send): ')\n\tconst optionalTools = await askList('Optional tools (comma-separated, or empty): ')\n\tconst tags = await askList('Tags (comma-separated, e.g., email, productivity): ')\n\n\tlogger.info('')\n\tconst instructions = await ask('Instructions (what should the agent do?): ')\n\n\tlogger.info('')\n\n\t// Create skill directory with optional subdirectories\n\tawait fs.mkdir(skillDir, { recursive: true })\n\n\t// Build YAML frontmatter\n\tconst frontmatterLines = [\n\t\t`name: ${skillName}`,\n\t\t`description: \"${description.replace(/\"/g, '\\\\\"')}\"`,\n\t]\n\n\tif (requiredTools.length > 0) {\n\t\tfrontmatterLines.push('requiredTools:')\n\t\tfor (const t of requiredTools) {\n\t\t\tfrontmatterLines.push(` - ${t}`)\n\t\t}\n\t}\n\n\tif (optionalTools.length > 0) {\n\t\tfrontmatterLines.push('optionalTools:')\n\t\tfor (const t of optionalTools) {\n\t\t\tfrontmatterLines.push(` - ${t}`)\n\t\t}\n\t}\n\n\tif (tags.length > 0) {\n\t\tfrontmatterLines.push('tags:')\n\t\tfor (const t of tags) {\n\t\t\tfrontmatterLines.push(` - ${t}`)\n\t\t}\n\t}\n\n\t// SKILL.md\n\tconst skillMd = `---\n${frontmatterLines.join('\\n')}\n---\n\n# ${skillName}\n\n${instructions}\n`\n\n\tawait fs.writeFile(path.join(skillDir, 'SKILL.md'), skillMd)\n\n\t// Auto-register in config and lock file (use bare name — resolver finds it in .openvole/skills/)\n\tawait addSkillToLock(projectRoot, skillName, '0.1.0')\n\tawait addSkillToConfig(projectRoot, skillName)\n\n\tlogger.info(`Created .openvole/skills/${skillName}/`)\n\tlogger.info(` SKILL.md — edit to refine instructions`)\n\tlogger.info(`Added to vole.config.json`)\n\tif (requiredTools.length > 0) {\n\t\tlogger.info(`Requires tools: ${requiredTools.join(', ')}`)\n\t}\n}\n\nasync function handleClawHubCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'install': {\n\t\t\tconst skillName = args[1]\n\t\t\tif (!skillName) {\n\t\t\t\tlogger.error('Usage: vole clawhub install <skill-name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst fsModule = await import('node:fs/promises')\n\t\t\tconst clawHubDir = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub')\n\t\t\tawait fsModule.mkdir(clawHubDir, { recursive: true })\n\n\t\t\t// Install into .openvole/skills/clawhub/<name>\n\t\t\tlogger.info(`Installing \"${skillName}\" from ClawHub...`)\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\ttry {\n\t\t\t\tawait execaFn('npx', ['clawhub', 'install', skillName, '--dir', clawHubDir], {\n\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\tstdio: 'inherit',\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tlogger.error(`Failed to install \"${skillName}\" from ClawHub`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\t// Find the installed skill directory\n\t\t\tconst installed = await fsModule.readdir(clawHubDir).catch(() => [] as string[])\n\t\t\tconst skillDir = installed.find((d) => d === skillName || d.includes(skillName))\n\n\t\t\tif (!skillDir) {\n\t\t\t\tlogger.error(`Skill installed but directory not found in .openvole/skills/clawhub/`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst localPath = `clawhub/${skillDir}`\n\t\t\tconst { loadSkillFromDirectory } = await import('./skill/loader.js')\n\t\t\tconst definition = await loadSkillFromDirectory(path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', skillDir))\n\n\t\t\tif (definition) {\n\t\t\t\tawait addSkillToLock(projectRoot, localPath, definition.version ?? '0.0.0')\n\t\t\t\tawait addSkillToConfig(projectRoot, localPath)\n\t\t\t\tlogger.info(`Added \"${definition.name}\" to vole.config.json`)\n\t\t\t\tif (definition.requiredTools.length > 0) {\n\t\t\t\t\tlogger.info(` requires tools: ${definition.requiredTools.join(', ')}`)\n\t\t\t\t}\n\t\t\t\tif (definition.requires?.env.length) {\n\t\t\t\t\tlogger.info(` requires env: ${definition.requires.env.join(', ')}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogger.warn(`Installed \"${skillName}\" but could not parse SKILL.md — add to vole.config.json manually`)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'search': {\n\t\t\tconst query = args.slice(1).join(' ')\n\t\t\tif (!query) {\n\t\t\t\tlogger.error('Usage: vole clawhub search <query>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\ttry {\n\t\t\t\tawait execaFn('npx', ['clawhub', 'search', query], {\n\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\tstdio: 'inherit',\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tlogger.error('Search failed — make sure clawhub is available (npx clawhub)')\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'remove': {\n\t\t\tconst skillName = args[1]\n\t\t\tif (!skillName) {\n\t\t\t\tlogger.error('Usage: vole clawhub remove <skill-name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst fsModule = await import('node:fs/promises')\n\t\t\tconst skillPath = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', skillName)\n\n\t\t\ttry {\n\t\t\t\tawait fsModule.rm(skillPath, { recursive: true })\n\t\t\t\tlogger.info(`Deleted .openvole/skills/clawhub/${skillName}`)\n\t\t\t} catch {\n\t\t\t\tlogger.error(`Skill directory not found: .openvole/skills/clawhub/${skillName}`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\t// Remove from config\n\t\t\tawait removeSkillFromLock(projectRoot, `clawhub/${skillName}`)\n\t\t\tawait removeSkillFromConfig(projectRoot, `clawhub/${skillName}`)\n\n\t\t\tlogger.info(`Removed \"${skillName}\" from vole.config.json`)\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown clawhub command: ${subcommand}`)\n\t\t\tlogger.info('Available: install, remove, search')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nmain().catch((err) => {\n\tconsole.error('Fatal error:', err)\n\tprocess.exit(1)\n})\n","// === Public API Surface ===\n\n// Config\nexport {\n\tdefineConfig,\n\tloadConfig,\n\treadLockFile,\n\twriteLockFile,\n\taddPawToLock,\n\tremovePawFromLock,\n\taddSkillToLock,\n\tremoveSkillFromLock,\n} from './config/index.js'\nexport type { VoleConfig, LoopConfig, HeartbeatConfig, VoleLock, RateLimits } from './config/index.js'\n\n// Core\nexport { createMessageBus } from './core/bus.js'\nexport type { MessageBus, BusEvents } from './core/bus.js'\nexport { runAgentLoop } from './core/loop.js'\nexport type { LoopDependencies } from './core/loop.js'\nexport { TaskQueue } from './core/task.js'\nexport type { AgentTask, TaskStatus } from './core/task.js'\nexport { SchedulerStore } from './core/scheduler.js'\nexport { Vault } from './core/vault.js'\nexport type { VaultEntry } from './core/vault.js'\nexport { PHASE_ORDER } from './core/hooks.js'\nexport type { LoopPhase } from './core/hooks.js'\nexport { RateLimiter } from './core/rate-limiter.js'\n\n// Errors\nexport {\n\tcreateActionError,\n\tsuccessResult,\n\tfailureResult,\n} from './core/errors.js'\nexport type { ActionError, ActionResult, ActionErrorCode } from './core/errors.js'\n\n// Tool\nexport { ToolRegistry } from './tool/registry.js'\nexport type { ToolDefinition, ToolRegistryEntry } from './tool/types.js'\n\n// Context\nexport { createAgentContext } from './context/types.js'\nexport type {\n\tAgentContext,\n\tAgentMessage,\n\tToolSummary,\n\tActiveSkill,\n} from './context/types.js'\n\n// Paw\nexport { PawRegistry } from './paw/registry.js'\nexport { readPawManifest, resolvePawPath } from './paw/manifest.js'\nexport {\n\tcomputeEffectivePermissions,\n\tvalidatePermissions,\n} from './paw/sandbox.js'\nexport type {\n\tPawDefinition,\n\tPawManifest,\n\tPawConfig,\n\tPawInstance,\n\tAgentPlan,\n\tPlannedAction,\n\tBootstrapHook,\n\tPerceiveHook,\n\tObserveHook,\n\tCompactHook,\n\tScheduleHook,\n\tTransportType,\n\tEffectivePermissions,\n} from './paw/types.js'\n\n// Skill\nexport { SkillRegistry } from './skill/registry.js'\nexport { resolveSkills, buildActiveSkills } from './skill/resolver.js'\nexport type {\n\tSkillDefinition,\n\tSkillInstance,\n} from './skill/types.js'\n\n// IO\nexport { createTtyIO } from './io/tty.js'\nexport type { VoleIO } from './io/types.js'\n\n// === Engine — the main orchestrator ===\n\nimport * as path from 'node:path'\nimport { createMessageBus } from './core/bus.js'\nimport { ToolRegistry } from './tool/registry.js'\nimport { PawRegistry } from './paw/registry.js'\nimport { SkillRegistry } from './skill/registry.js'\nimport { TaskQueue } from './core/task.js'\nimport { runAgentLoop } from './core/loop.js'\nimport { createTtyIO } from './io/tty.js'\nimport { loadConfig, normalizePawConfig, type VoleConfig } from './config/index.js'\nimport type { VoleIO } from './io/types.js'\nimport * as fs from 'node:fs/promises'\nimport { SchedulerStore } from './core/scheduler.js'\nimport { createCoreTools } from './tool/core-tools.js'\nimport { RateLimiter } from './core/rate-limiter.js'\nimport { Vault } from './core/vault.js'\nimport { closeLogger } from './core/logger.js'\n\nexport interface VoleEngine {\n\tbus: ReturnType<typeof createMessageBus>\n\ttoolRegistry: ToolRegistry\n\tpawRegistry: PawRegistry\n\tskillRegistry: SkillRegistry\n\ttaskQueue: TaskQueue\n\tio: VoleIO\n\tconfig: VoleConfig\n\n\t/** Start the engine — load Paws and Skills */\n\tstart(): Promise<void>\n\t/** Submit a task for execution */\n\trun(input: string, source?: 'user' | 'schedule' | 'heartbeat' | 'paw', sessionId?: string): void\n\t/** Graceful shutdown */\n\tshutdown(): Promise<void>\n}\n\nconst engineLogger = {\n\tinfo: (msg: string, ...args: unknown[]) =>\n\t\tconsole.info(`[openvole] ${msg}`, ...args),\n\terror: (msg: string, ...args: unknown[]) =>\n\t\tconsole.error(`[openvole] ${msg}`, ...args),\n}\n\n/** Create and initialize the OpenVole engine */\nexport async function createEngine(\n\tprojectRoot: string,\n\toptions?: { io?: VoleIO; configPath?: string },\n): Promise<VoleEngine> {\n\tconst configPath =\n\t\toptions?.configPath ?? path.resolve(projectRoot, 'vole.config.ts')\n\tconst config = await loadConfig(configPath)\n\n\tconst bus = createMessageBus()\n\tconst toolRegistry = new ToolRegistry(bus)\n\tconst pawRegistry = new PawRegistry(bus, toolRegistry, projectRoot)\n\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\tconst io = options?.io ?? createTtyIO()\n\tconst rateLimiter = new RateLimiter()\n\tconst taskQueue = new TaskQueue(bus, config.loop.taskConcurrency, rateLimiter, config.loop.rateLimits)\n\tconst scheduler = new SchedulerStore()\n\tscheduler.setPersistence(path.resolve(projectRoot, '.openvole', 'schedules.json'))\n\tscheduler.setTickHandler((input) => {\n\t\ttaskQueue.enqueue(input, 'schedule')\n\t})\n\tconst vault = new Vault(\n\t\tpath.resolve(projectRoot, '.openvole', 'vault.json'),\n\t\tprocess.env.VOLE_VAULT_KEY,\n\t)\n\tawait vault.init()\n\n\t// Register built-in core tools\n\tconst coreTools = createCoreTools(scheduler, taskQueue, projectRoot, skillRegistry, vault)\n\ttoolRegistry.register('__core__', coreTools, true)\n\n\t// Wire up query sources so Paws can query skills and tasks\n\tpawRegistry.setQuerySources(skillRegistry, taskQueue, scheduler)\n\n\t// Wire up the task runner\n\ttaskQueue.setRunner(async (task) => {\n\t\tawait runAgentLoop(task, {\n\t\t\tbus,\n\t\t\ttoolRegistry,\n\t\t\tpawRegistry,\n\t\t\tskillRegistry,\n\t\t\tio,\n\t\t\tconfig: config.loop,\n\t\t\ttoolProfiles: config.toolProfiles,\n\t\t\trateLimiter,\n\t\t})\n\t})\n\n\tconst engine: VoleEngine = {\n\t\tbus,\n\t\ttoolRegistry,\n\t\tpawRegistry,\n\t\tskillRegistry,\n\t\ttaskQueue,\n\t\tio,\n\t\tconfig,\n\n\t\tasync start() {\n\t\t\tengineLogger.info('Starting OpenVole...')\n\n\t\t\t// Set Brain (setBrain resolves config path → manifest name after load)\n\t\t\tif (config.brain) {\n\t\t\t\t// setBrain is called after brain paw loads (below) so the mapping exists\n\t\t\t} else {\n\t\t\t\tengineLogger.info('No Brain Paw configured — Think step will be a no-op')\n\t\t\t}\n\n\t\t\t// Load Paws (Brain first, then others, in-process last)\n\t\t\tconst pawConfigs = config.paws.map(normalizePawConfig)\n\t\t\tconst brainConfig = pawConfigs.find((p) => p.name === config.brain)\n\t\t\tconst subprocessPaws = pawConfigs.filter(\n\t\t\t\t(p) => p.name !== config.brain,\n\t\t\t)\n\n\t\t\t// Load Brain Paw first\n\t\t\tif (brainConfig) {\n\t\t\t\tconst ok = await pawRegistry.load(brainConfig)\n\t\t\t\tif (ok) {\n\t\t\t\t\tpawRegistry.setBrain(config.brain!)\n\t\t\t\t\tengineLogger.info(`Brain Paw: ${pawRegistry.resolveManifestName(config.brain!)}`)\n\t\t\t\t} else {\n\t\t\t\t\tengineLogger.error(\n\t\t\t\t\t\t`Brain Paw \"${brainConfig.name}\" failed to load — running in no-op Think mode`,\n\t\t\t\t\t)\n\t\t\t\t\tpawRegistry.setBrain('')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Load other Paws\n\t\t\tfor (const pawConfig of subprocessPaws) {\n\t\t\t\tawait pawRegistry.load(pawConfig)\n\t\t\t}\n\n\t\t\t// Load Skills\n\t\t\tfor (const skillName of config.skills) {\n\t\t\t\tawait skillRegistry.load(skillName)\n\t\t\t}\n\n\t\t\t// Final resolver pass\n\t\t\tskillRegistry.resolve()\n\n\t\t\t// Restore persisted schedules from disk\n\t\t\tawait scheduler.restore()\n\n\t\t\t// Start heartbeat via scheduler (shows up in Schedules panel)\n\t\t\tif (config.heartbeat.enabled) {\n\t\t\t\tconst heartbeatMdPath = path.resolve(projectRoot, '.openvole', 'HEARTBEAT.md')\n\t\t\t\t// Convert intervalMinutes to cron expression (e.g. 30 → \"*/30 * * * *\")\n\t\t\t\tconst heartbeatCron = `*/${config.heartbeat.intervalMinutes} * * * *`\n\t\t\t\tscheduler.add(\n\t\t\t\t\t'__heartbeat__',\n\t\t\t\t\t'Heartbeat wake-up',\n\t\t\t\t\theartbeatCron,\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tlet heartbeatContent = ''\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\theartbeatContent = await fs.readFile(heartbeatMdPath, 'utf-8')\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// No HEARTBEAT.md — use default prompt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst input = heartbeatContent\n\t\t\t\t\t\t\t? `Heartbeat wake-up. Review your HEARTBEAT.md jobs and act on what is needed:\\n\\n${heartbeatContent}`\n\t\t\t\t\t\t\t: 'Heartbeat wake-up. Check active skills and decide if any actions are needed.'\n\n\t\t\t\t\t\ttaskQueue.enqueue(input, 'heartbeat')\n\t\t\t\t\t},\n\t\t\t\t\tundefined,\n\t\t\t\t\tconfig.heartbeat.runOnStart ?? false,\n\t\t\t\t)\n\t\t\t\tengineLogger.info(`Heartbeat enabled — cron: ${heartbeatCron}${config.heartbeat.runOnStart ? ', running now' : ''}`)\n\t\t\t}\n\n\t\t\tengineLogger.info(\n\t\t\t\t`Ready — ${toolRegistry.list().length} tools, ` +\n\t\t\t\t\t`${pawRegistry.list().length} paws, ` +\n\t\t\t\t\t`${skillRegistry.active().length}/${skillRegistry.list().length} skills active`,\n\t\t\t)\n\t\t},\n\n\t\trun(input, source = 'user', sessionId?) {\n\t\t\ttaskQueue.enqueue(input, source, sessionId ? { sessionId } : undefined)\n\t\t},\n\n\t\tasync shutdown() {\n\t\t\tengineLogger.info('Shutting down...')\n\t\t\tscheduler.clearAll()\n\t\t\tfor (const paw of pawRegistry.list()) {\n\t\t\t\tawait pawRegistry.unload(paw.name)\n\t\t\t}\n\t\t\ttoolRegistry.clear()\n\t\t\tengineLogger.info('Shutdown complete')\n\t\t\tcloseLogger()\n\t\t},\n\t}\n\n\treturn engine\n}\n","/** Summary of a tool available to the Brain */\nexport interface ToolSummary {\n\tname: string\n\tdescription: string\n\tpawName: string\n\t/** Parameter schema (Zod) — passed to Brain Paw for function calling */\n\tparameters?: unknown\n}\n\n/** A Skill whose required tools are all satisfied (compact — Brain reads full instructions on demand) */\nexport interface ActiveSkill {\n\tname: string\n\tdescription: string\n\tsatisfiedBy: string[]\n}\n\n/** A single message in the agent's reasoning history */\nexport interface AgentMessage {\n\trole: 'user' | 'brain' | 'tool_result' | 'error'\n\tcontent: string\n\ttoolCall?: { name: string; params: unknown }\n\ttimestamp: number\n}\n\n/** The shared data structure that flows through the agent loop */\nexport interface AgentContext {\n\ttaskId: string\n\tmessages: AgentMessage[]\n\tavailableTools: ToolSummary[]\n\tactiveSkills: ActiveSkill[]\n\tmetadata: Record<string, unknown>\n\titeration: number\n\tmaxIterations: number\n}\n\n/** Create an empty AgentContext for a new task */\nexport function createAgentContext(\n\ttaskId: string,\n\tmaxIterations: number,\n): AgentContext {\n\treturn {\n\t\ttaskId,\n\t\tmessages: [],\n\t\tavailableTools: [],\n\t\tactiveSkills: [],\n\t\tmetadata: {},\n\t\titeration: 0,\n\t\tmaxIterations,\n\t}\n}\n","/** Error codes for categorizing failures in the agent loop */\nexport type ActionErrorCode =\n\t| 'TOOL_TIMEOUT'\n\t| 'TOOL_EXCEPTION'\n\t| 'TOOL_NOT_FOUND'\n\t| 'PERMISSION_DENIED'\n\t| 'PAW_CRASHED'\n\t| 'BRAIN_ERROR'\n\t| 'INVALID_PLAN'\n\n/** Structured error attached to a failed action */\nexport interface ActionError {\n\tcode: ActionErrorCode\n\tmessage: string\n\ttoolName?: string\n\tpawName?: string\n\tdetails?: unknown\n}\n\n/** Result of a single tool execution during the Act phase */\nexport interface ActionResult {\n\ttoolName: string\n\tpawName: string\n\tsuccess: boolean\n\toutput?: unknown\n\terror?: ActionError\n\tdurationMs: number\n}\n\n/** Create a structured ActionError */\nexport function createActionError(\n\tcode: ActionErrorCode,\n\tmessage: string,\n\topts?: { toolName?: string; pawName?: string; details?: unknown },\n): ActionError {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\ttoolName: opts?.toolName,\n\t\tpawName: opts?.pawName,\n\t\tdetails: opts?.details,\n\t}\n}\n\n/** Create a successful ActionResult */\nexport function successResult(\n\ttoolName: string,\n\tpawName: string,\n\toutput: unknown,\n\tdurationMs: number,\n): ActionResult {\n\treturn { toolName, pawName, success: true, output, durationMs }\n}\n\n/** Create a failed ActionResult */\nexport function failureResult(\n\ttoolName: string,\n\tpawName: string,\n\terror: ActionError,\n\tdurationMs: number,\n): ActionResult {\n\treturn { toolName, pawName, success: false, error, durationMs }\n}\n","import type { AgentContext } from '../context/types.js'\nimport { createAgentContext } from '../context/types.js'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { PawRegistry } from '../paw/registry.js'\nimport type { SkillRegistry } from '../skill/registry.js'\nimport type { VoleIO } from '../io/types.js'\nimport type { LoopConfig } from '../config/index.js'\nimport type { RateLimiter } from './rate-limiter.js'\nimport type { AgentTask } from './task.js'\nimport type { MessageBus } from './bus.js'\nimport type { AgentPlan, PlannedAction } from '../paw/types.js'\nimport {\n\tcreateActionError,\n\tfailureResult,\n\tsuccessResult,\n\ttype ActionResult,\n} from './errors.js'\nimport { buildActiveSkills } from '../skill/resolver.js'\nimport { PHASE_ORDER } from './hooks.js'\n\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('loop')\n\n/** Maximum consecutive Brain failures before halting */\nconst MAX_BRAIN_FAILURES = 3\n\nexport interface LoopDependencies {\n\tbus: MessageBus\n\ttoolRegistry: ToolRegistry\n\tpawRegistry: PawRegistry\n\tskillRegistry: SkillRegistry\n\tio: VoleIO\n\tconfig: LoopConfig\n\ttoolProfiles?: Record<string, import('../config/index.js').ToolProfile>\n\trateLimiter?: RateLimiter\n}\n\n/**\n * Run the agent loop for a single task.\n * Perceive → Think → Act → Observe → loop\n */\nexport async function runAgentLoop(\n\ttask: AgentTask,\n\tdeps: LoopDependencies,\n): Promise<void> {\n\tconst { bus, toolRegistry, pawRegistry, skillRegistry, io, config, toolProfiles, rateLimiter } = deps\n\tconst rateLimits = config.rateLimits\n\tlet toolExecutionCount = 0\n\tlogger.info(`Agent loop started for task ${task.id}: \"${task.input}\"`)\n\n\tlet context = createAgentContext(task.id, config.maxIterations)\n\n\t// Set task source in metadata so Paws (e.g. paw-memory) can scope by source\n\tcontext.metadata.taskSource = task.source\n\tcontext.metadata.sessionId = task.sessionId\n\tif (task.metadata) {\n\t\tObject.assign(context.metadata, task.metadata)\n\t}\n\tif (task.source === 'heartbeat') {\n\t\tcontext.metadata.heartbeat = true\n\t}\n\n\t// Seed with user input\n\tcontext.messages.push({\n\t\trole: 'user',\n\t\tcontent: task.input,\n\t\ttimestamp: Date.now(),\n\t})\n\n\t// === BOOTSTRAP — runs once at task start ===\n\tlogger.debug('Phase: bootstrap')\n\tcontext = await pawRegistry.runBootstrapHooks(context)\n\n\tlet consecutiveBrainFailures = 0\n\n\tfor (\n\t\tcontext.iteration = 0;\n\t\tcontext.iteration < config.maxIterations;\n\t\tcontext.iteration++\n\t) {\n\t\t// Check cancellation\n\t\tif (task.status === 'cancelled') {\n\t\t\tlogger.info(`Task ${task.id} cancelled at iteration ${context.iteration}`)\n\t\t\treturn\n\t\t}\n\n\t\t// === COMPACT — compress context if it exceeds threshold ===\n\t\tif (\n\t\t\tconfig.compactThreshold > 0 &&\n\t\t\tcontext.messages.length > config.compactThreshold\n\t\t) {\n\t\t\tlogger.info(\n\t\t\t\t`Context has ${context.messages.length} messages (threshold: ${config.compactThreshold}), running compact`,\n\t\t\t)\n\t\t\tcontext = await pawRegistry.runCompactHooks(context)\n\t\t}\n\n\t\tlogger.info(\n\t\t\t`Loop running — iteration ${context.iteration + 1}/${config.maxIterations}`,\n\t\t)\n\n\t\t// === PERCEIVE (global only — lazy perceive runs in Act) ===\n\t\tlogger.debug(`Phase: ${PHASE_ORDER[0]}`)\n\t\tconst enrichedContext = await runPerceive(context, pawRegistry, toolRegistry, skillRegistry)\n\n\t\t// === RATE LIMIT CHECK (before Think) ===\n\t\tif (rateLimiter && rateLimits) {\n\t\t\tif (rateLimits.llmCallsPerMinute != null) {\n\t\t\t\tif (!rateLimiter.tryConsume('llm:per-minute', rateLimits.llmCallsPerMinute, 60_000)) {\n\t\t\t\t\tlogger.warn(`Rate limit hit: llmCallsPerMinute (${rateLimits.llmCallsPerMinute})`)\n\t\t\t\t\tbus.emit('rate:limited', { bucket: 'llm:per-minute', source: task.source })\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Rate limit exceeded: LLM calls per minute (limit: ${rateLimits.llmCallsPerMinute}). Retrying next iteration.`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rateLimits.llmCallsPerHour != null) {\n\t\t\t\tif (!rateLimiter.tryConsume('llm:per-hour', rateLimits.llmCallsPerHour, 3_600_000)) {\n\t\t\t\t\tlogger.warn(`Rate limit hit: llmCallsPerHour (${rateLimits.llmCallsPerHour})`)\n\t\t\t\t\tbus.emit('rate:limited', { bucket: 'llm:per-hour', source: task.source })\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Rate limit exceeded: LLM calls per hour (limit: ${rateLimits.llmCallsPerHour}). Retrying next iteration.`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// === THINK ===\n\t\tlogger.debug(`Phase: ${PHASE_ORDER[1]}`)\n\t\tconst plan = await runThink(enrichedContext, pawRegistry)\n\t\tif (plan && plan !== 'BRAIN_ERROR') {\n\t\t\tlogger.info(`Brain plan: done=${plan.done}, actions=${plan.actions.length}, response=${plan.response ? plan.response.substring(0, 100) + '...' : 'none'}`)\n\t\t}\n\n\t\tif (!plan) {\n\t\t\t// No Brain Paw configured — no-op Think\n\t\t\tlogger.debug('Think phase returned null (no Brain Paw)')\n\t\t\tbreak\n\t\t}\n\n\t\t// Handle Brain errors\n\t\tif (plan === 'BRAIN_ERROR') {\n\t\t\tconsecutiveBrainFailures++\n\t\t\tif (consecutiveBrainFailures >= MAX_BRAIN_FAILURES) {\n\t\t\t\tio.notify(\n\t\t\t\t\t`Brain Paw failed ${MAX_BRAIN_FAILURES} consecutive times. Halting task ${task.id}.`,\n\t\t\t\t)\n\t\t\t\ttask.error = `Brain failed ${MAX_BRAIN_FAILURES} consecutive times`\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tconsecutiveBrainFailures = 0\n\n\t\t// Check if the Brain says we're done\n\t\tif (plan.done) {\n\t\t\t// Detect if the Brain narrated tool calls instead of executing them\n\t\t\tif (plan.response && plan.actions.length === 0 && plan.response.startsWith('Calling tools:')) {\n\t\t\t\tlogger.warn('Brain narrated tool calls instead of executing them — forcing retry')\n\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\trole: 'error',\n\t\t\t\t\tcontent: 'You described tool calls as text instead of executing them. Use function calling to invoke tools — do not write tool calls as text. Try again.',\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t})\n\t\t\t\tplan.done = false\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (plan.response) {\n\t\t\t\ttask.result = plan.response\n\t\t\t\tio.notify(plan.response)\n\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\trole: 'brain',\n\t\t\t\t\tcontent: plan.response,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tlogger.info(`Task ${task.id} completed by Brain at iteration ${context.iteration + 1}`)\n\t\t\treturn\n\t\t}\n\n\t\t// If Brain has a response but also actions, show the response\n\t\tif (plan.response) {\n\t\t\tio.notify(plan.response)\n\t\t\tenrichedContext.messages.push({\n\t\t\t\trole: 'brain',\n\t\t\t\tcontent: plan.response,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t})\n\t\t}\n\n\t\t// === ACT ===\n\t\tlogger.debug(`Phase: ${PHASE_ORDER[2]}`)\n\t\tif (plan.actions.length > 0) {\n\t\t\t// Record the Brain's tool call intent in context so it sees its own reasoning on next iteration\n\t\t\tconst toolCallSummary = plan.actions.map((a) => `${a.tool}(${JSON.stringify(a.params)})`).join(', ')\n\t\t\tenrichedContext.messages.push({\n\t\t\t\trole: 'brain',\n\t\t\t\tcontent: plan.response || `Calling tools: ${toolCallSummary}`,\n\t\t\t\ttoolCall: plan.actions.length === 1\n\t\t\t\t\t? { name: plan.actions[0].tool, params: plan.actions[0].params }\n\t\t\t\t\t: { name: 'multiple', params: plan.actions.map((a) => ({ tool: a.tool, params: a.params })) },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t})\n\t\t\t// Check tool execution rate limit\n\t\t\tif (rateLimiter && rateLimits?.toolExecutionsPerTask != null) {\n\t\t\t\tconst incoming = plan.actions.length\n\t\t\t\tif (toolExecutionCount + incoming > rateLimits.toolExecutionsPerTask) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`Rate limit hit: toolExecutionsPerTask (${toolExecutionCount + incoming}/${rateLimits.toolExecutionsPerTask})`,\n\t\t\t\t\t)\n\t\t\t\t\tbus.emit('rate:limited', { bucket: 'tools:per-task', source: task.source })\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Rate limit exceeded: tool executions per task (limit: ${rateLimits.toolExecutionsPerTask}, used: ${toolExecutionCount}). Stopping task.`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Filter actions by tool profile for this task source\n\t\t\tconst profile = toolProfiles?.[task.source]\n\t\t\tif (profile) {\n\t\t\t\tconst blocked: string[] = []\n\t\t\t\tplan.actions = plan.actions.filter((a) => {\n\t\t\t\t\tif (profile.allow && !profile.allow.includes(a.tool)) {\n\t\t\t\t\t\tblocked.push(a.tool)\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\tif (profile.deny?.includes(a.tool)) {\n\t\t\t\t\t\tblocked.push(a.tool)\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\tif (blocked.length > 0) {\n\t\t\t\t\tlogger.warn(`Blocked tools for source \"${task.source}\": ${blocked.join(', ')}`)\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Tools blocked by security profile for \"${task.source}\" source: ${blocked.join(', ')}`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (plan.actions.length === 0) continue\n\t\t\t}\n\n\t\t\t// Log tool calls\n\t\t\tfor (const action of plan.actions) {\n\t\t\t\tlogger.info(`Tool call: ${action.tool}(${JSON.stringify(action.params)})`)\n\t\t\t}\n\n\t\t\t// Confirm before acting if configured\n\t\t\tif (config.confirmBeforeAct) {\n\t\t\t\tconst toolNames = plan.actions.map((a) => a.tool).join(', ')\n\t\t\t\tconst confirmed = await io.confirm(\n\t\t\t\t\t`Execute tools: ${toolNames}?`,\n\t\t\t\t)\n\t\t\t\tif (!confirmed) {\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: 'User declined to execute planned actions',\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst results = await runAct(\n\t\t\t\tplan.actions,\n\t\t\t\tplan.execution ?? 'sequential',\n\t\t\t\tenrichedContext,\n\t\t\t\ttoolRegistry,\n\t\t\t\tpawRegistry,\n\t\t\t)\n\n\t\t\t// Track tool executions for rate limiting\n\t\t\ttoolExecutionCount += results.length\n\n\t\t\t// === OBSERVE ===\n\t\t\tlogger.debug(`Phase: ${PHASE_ORDER[3]}`)\n\t\t\tfor (const result of results) {\n\t\t\t\t// Append to context\n\t\t\t\tif (result.success) {\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'tool_result',\n\t\t\t\t\t\tcontent: typeof result.output === 'string'\n\t\t\t\t\t\t\t? result.output\n\t\t\t\t\t\t\t: JSON.stringify(result.output),\n\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\tname: result.toolName,\n\t\t\t\t\t\t\tparams: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: result.error?.message ?? 'Unknown tool error',\n\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\tname: result.toolName,\n\t\t\t\t\t\t\tparams: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// Fire observe hooks\n\t\t\t\tpawRegistry.runObserveHooks(result)\n\t\t\t}\n\t\t}\n\n\t\t// Update context for next iteration\n\t\tObject.assign(context, enrichedContext)\n\t}\n\n\tif (context.iteration >= config.maxIterations) {\n\t\tlogger.warn(\n\t\t\t`Task ${task.id} reached max iterations (${config.maxIterations})`,\n\t\t)\n\t\tio.notify(\n\t\t\t`Task reached maximum iterations (${config.maxIterations}). Stopping.`,\n\t\t)\n\t}\n}\n\n/** Run the Perceive phase — only global hooks (Paws without tools) */\nasync function runPerceive(\n\tcontext: AgentContext,\n\tpawRegistry: PawRegistry,\n\ttoolRegistry: ToolRegistry,\n\tskillRegistry: SkillRegistry,\n): Promise<AgentContext> {\n\t// Set available tools and active skills\n\tconst enriched = { ...context }\n\tenriched.availableTools = toolRegistry.summaries()\n\tenriched.activeSkills = buildActiveSkills(\n\t\tskillRegistry.list(),\n\t\ttoolRegistry,\n\t)\n\n\t// Only run global perceive hooks (Paws without tools — context enrichers)\n\t// Paws with tools use lazy perceive, called just before their tool executes\n\treturn pawRegistry.runGlobalPerceiveHooks(enriched)\n}\n\n/** Run the Think phase — ask the Brain for a plan */\nasync function runThink(\n\tcontext: AgentContext,\n\tpawRegistry: PawRegistry,\n): Promise<AgentPlan | null | 'BRAIN_ERROR'> {\n\ttry {\n\t\treturn await pawRegistry.think(context)\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\tlogger.error(`Brain error: ${message}`)\n\n\t\t// Add error to context for next iteration\n\t\tcontext.messages.push({\n\t\t\trole: 'error',\n\t\t\tcontent: `Brain error: ${message}`,\n\t\t\ttimestamp: Date.now(),\n\t\t})\n\n\t\treturn 'BRAIN_ERROR'\n\t}\n}\n\n/** Run the Act phase — execute tool calls with lazy perceive */\nasync function runAct(\n\tactions: PlannedAction[],\n\texecution: 'parallel' | 'sequential',\n\tcontext: AgentContext,\n\ttoolRegistry: ToolRegistry,\n\tpawRegistry: PawRegistry,\n): Promise<ActionResult[]> {\n\t// Collect unique Paw names from planned actions and run their lazy perceive\n\tconst pawNames = new Set<string>()\n\tfor (const action of actions) {\n\t\tconst tool = toolRegistry.get(action.tool)\n\t\tif (tool) pawNames.add(tool.pawName)\n\t}\n\n\t// Run lazy perceive for each involved Paw (before any tools execute)\n\tfor (const pawName of pawNames) {\n\t\tawait pawRegistry.runLazyPerceive(pawName, context)\n\t}\n\n\tif (execution === 'parallel') {\n\t\treturn Promise.all(\n\t\t\tactions.map((action) =>\n\t\t\t\texecuteSingleAction(action, toolRegistry, pawRegistry),\n\t\t\t),\n\t\t)\n\t}\n\n\t// Sequential execution\n\tconst results: ActionResult[] = []\n\tfor (const action of actions) {\n\t\tconst result = await executeSingleAction(action, toolRegistry, pawRegistry)\n\t\tresults.push(result)\n\t}\n\treturn results\n}\n\n/** Execute a single tool call */\nasync function executeSingleAction(\n\taction: PlannedAction,\n\ttoolRegistry: ToolRegistry,\n\tpawRegistry: PawRegistry,\n): Promise<ActionResult> {\n\tconst startTime = Date.now()\n\tconst tool = toolRegistry.get(action.tool)\n\n\tif (!tool) {\n\t\treturn failureResult(\n\t\t\taction.tool,\n\t\t\t'unknown',\n\t\t\tcreateActionError('TOOL_NOT_FOUND', `Tool \"${action.tool}\" not found`, {\n\t\t\t\ttoolName: action.tool,\n\t\t\t}),\n\t\t\tDate.now() - startTime,\n\t\t)\n\t}\n\n\t// Check if the owning Paw is healthy\n\tif (!tool.inProcess && !pawRegistry.isHealthy(tool.pawName)) {\n\t\treturn failureResult(\n\t\t\taction.tool,\n\t\t\ttool.pawName,\n\t\t\tcreateActionError('PAW_CRASHED', `Paw \"${tool.pawName}\" is not healthy`, {\n\t\t\t\ttoolName: action.tool,\n\t\t\t\tpawName: tool.pawName,\n\t\t\t}),\n\t\t\tDate.now() - startTime,\n\t\t)\n\t}\n\n\ttry {\n\t\t// Validate parameters if schema is a proper Zod schema\n\t\tif (tool.parameters && typeof tool.parameters.parse === 'function') {\n\t\t\ttool.parameters.parse(action.params)\n\t\t}\n\n\t\tconst output = await tool.execute(action.params)\n\t\treturn successResult(action.tool, tool.pawName, output, Date.now() - startTime)\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err)\n\n\t\t// Determine error code\n\t\tconst isTimeout = message.toLowerCase().includes('timeout')\n\t\tconst isPermission = message.toLowerCase().includes('permission')\n\t\tconst code = isTimeout\n\t\t\t? 'TOOL_TIMEOUT'\n\t\t\t: isPermission\n\t\t\t\t? 'PERMISSION_DENIED'\n\t\t\t\t: 'TOOL_EXCEPTION'\n\n\t\treturn failureResult(\n\t\t\taction.tool,\n\t\t\ttool.pawName,\n\t\t\tcreateActionError(code, message, {\n\t\t\t\ttoolName: action.tool,\n\t\t\t\tpawName: tool.pawName,\n\t\t\t\tdetails: err instanceof Error ? err.stack : undefined,\n\t\t\t}),\n\t\t\tDate.now() - startTime,\n\t\t)\n\t}\n}\n","/**\n * Hook phase definitions.\n *\n * The actual hook execution logic lives in PawRegistry (perceive/observe hooks)\n * and the agent loop (think/act orchestration). This module defines the hook\n * lifecycle constants and types used across the system.\n */\n\n/** The four phases of the agent loop */\nexport type LoopPhase = 'perceive' | 'think' | 'act' | 'observe'\n\n/** Phase ordering for logging and tracing */\nexport const PHASE_ORDER: readonly LoopPhase[] = [\n\t'perceive',\n\t'think',\n\t'act',\n\t'observe',\n] as const\n","import { createLogger } from './logger.js'\n\nconst logger = createLogger('rate-limiter')\n\n/**\n * Sliding window counter rate limiter.\n * Tracks timestamps per bucket and checks against limits.\n */\nexport class RateLimiter {\n\tprivate buckets = new Map<string, number[]>()\n\n\t/**\n\t * Try to consume one token from the bucket.\n\t * Returns true if the request is under the limit, false if rate-limited.\n\t */\n\ttryConsume(bucket: string, limit: number, windowMs: number): boolean {\n\t\tconst now = Date.now()\n\t\tthis.cleanup(bucket, now, windowMs)\n\n\t\tconst timestamps = this.buckets.get(bucket) ?? []\n\t\tif (timestamps.length >= limit) {\n\t\t\tlogger.debug(`Bucket \"${bucket}\" rate-limited: ${timestamps.length}/${limit} in ${windowMs}ms window`)\n\t\t\treturn false\n\t\t}\n\n\t\ttimestamps.push(now)\n\t\tthis.buckets.set(bucket, timestamps)\n\t\treturn true\n\t}\n\n\t/**\n\t * Returns the number of remaining tokens in the bucket for the current window.\n\t */\n\tremaining(bucket: string, limit: number, windowMs: number): number {\n\t\tconst now = Date.now()\n\t\tthis.cleanup(bucket, now, windowMs)\n\n\t\tconst timestamps = this.buckets.get(bucket) ?? []\n\t\treturn Math.max(0, limit - timestamps.length)\n\t}\n\n\t/**\n\t * Remove expired timestamps from a bucket.\n\t */\n\tprivate cleanup(bucket: string, now: number, windowMs: number): void {\n\t\tconst timestamps = this.buckets.get(bucket)\n\t\tif (!timestamps) return\n\n\t\tconst cutoff = now - windowMs\n\t\tconst filtered = timestamps.filter((t) => t > cutoff)\n\n\t\tif (filtered.length === 0) {\n\t\t\tthis.buckets.delete(bucket)\n\t\t} else {\n\t\t\tthis.buckets.set(bucket, filtered)\n\t\t}\n\t}\n}\n","import type { MessageBus } from '../core/bus.js'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { PawConfig, PawInstance } from './types.js'\nimport { readPawManifest, resolvePawPath } from './manifest.js'\nimport { loadInProcessPaw, loadSubprocessPaw, shutdownPaw } from './loader.js'\nimport { validatePermissions } from './sandbox.js'\nimport type { IpcTransport } from '../core/ipc.js'\nimport type { AgentContext } from '../context/types.js'\nimport type { ActionResult } from '../core/errors.js'\nimport type { AgentPlan } from './types.js'\n\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-registry')\n\n/** Perceive hook config for ordering */\nexport interface PerceiveHookEntry {\n\tpawName: string\n\torder: number\n\tpipeline: boolean\n\t/** If true, this Paw has tools — its perceive runs lazily before tool execution, not every iteration */\n\thasTools: boolean\n}\n\n/** Interface for queryable registries (avoids circular imports) */\nexport interface QueryableSkillRegistry {\n\tlist(): Array<{ name: string; active: boolean; missingTools: string[]; definition: { description: string } }>\n}\n\nexport interface QueryableTaskQueue {\n\tlist(): Array<{ id: string; source: string; input: string; status: string; createdAt: number }>\n\tenqueue(input: string, source?: 'user' | 'schedule' | 'paw', options?: { sessionId?: string; metadata?: Record<string, unknown> }): { id: string }\n}\n\nexport interface QueryableScheduler {\n\tlist(): Array<{ id: string; input: string; cron: string; nextRun?: string; createdAt: number }>\n}\n\n/** Manages loaded Paws and their lifecycle */\nexport class PawRegistry {\n\tprivate paws = new Map<string, PawInstance>()\n\tprivate transports = new Map<string, IpcTransport>()\n\tprivate perceiveHooks: PerceiveHookEntry[] = []\n\tprivate observeHookPaws: string[] = []\n\tprivate bootstrapPaws: string[] = []\n\tprivate compactPaws: string[] = []\n\tprivate brainPawName: string | undefined\n\t/** Maps config path → manifest name (e.g. \"./paws/paw-ollama\" → \"@openvole/paw-ollama\") */\n\tprivate configToManifest = new Map<string, string>()\n\tprivate skillRegistry?: QueryableSkillRegistry\n\tprivate taskQueue?: QueryableTaskQueue\n\tprivate scheduler?: QueryableScheduler\n\n\tconstructor(\n\t\tprivate bus: MessageBus,\n\t\tprivate toolRegistry: ToolRegistry,\n\t\tprivate projectRoot: string,\n\t) {\n\t\t// Handle Paw crash events\n\t\tthis.bus.on('paw:crashed', ({ pawName }) => {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (instance) {\n\t\t\t\tinstance.healthy = false\n\t\t\t\tthis.toolRegistry.unregister(pawName)\n\t\t\t}\n\t\t})\n\t}\n\n\t/** Inject queryable registries (called after construction to avoid circular deps) */\n\tsetQuerySources(skills: QueryableSkillRegistry, tasks: QueryableTaskQueue, scheduler?: QueryableScheduler): void {\n\t\tthis.skillRegistry = skills\n\t\tthis.taskQueue = tasks\n\t\tthis.scheduler = scheduler\n\t}\n\n\t/** Load and register a Paw */\n\tasync load(config: PawConfig): Promise<boolean> {\n\t\tconst pawPath = resolvePawPath(config.name, this.projectRoot)\n\t\tconst manifest = await readPawManifest(pawPath)\n\n\t\tif (!manifest) {\n\t\t\tlogger.error(`Failed to read manifest for \"${config.name}\"`)\n\t\t\treturn false\n\t\t}\n\n\t\t// Use manifest name as identity, config name for resolution only\n\t\tconst pawName = manifest.name\n\n\t\tif (this.paws.has(pawName)) {\n\t\t\tlogger.warn(`Paw \"${pawName}\" is already loaded`)\n\t\t\treturn false\n\t\t}\n\n\t\t// Track config path → manifest name mapping\n\t\tthis.configToManifest.set(config.name, pawName)\n\n\t\t// Validate permissions\n\t\tvalidatePermissions(manifest, config)\n\n\t\ttry {\n\t\t\tlet instance: PawInstance\n\n\t\t\tif (manifest.inProcess) {\n\t\t\t\tinstance = await loadInProcessPaw(pawPath, manifest, config)\n\t\t\t\tthis.registerInProcessTools(instance)\n\t\t\t} else {\n\t\t\t\tconst result = await loadSubprocessPaw(pawPath, manifest, config)\n\t\t\t\tinstance = result.instance\n\t\t\t\tthis.transports.set(pawName, result.transport)\n\t\t\t\tthis.setupTransportHandlers(pawName, result.transport)\n\n\t\t\t\t// Wait for the Paw to register itself\n\t\t\t\tawait this.waitForRegistration(pawName, result.transport)\n\t\t\t}\n\n\t\t\tthis.paws.set(pawName, instance)\n\n\t\t\t// Track hooks\n\t\t\tif (instance.definition?.hooks?.onPerceive) {\n\t\t\t\tconst hookConfig = config.hooks?.perceive\n\t\t\t\tconst hasTools = (instance.definition?.tools?.length ?? 0) > 0 || manifest.tools.length > 0\n\t\t\t\tthis.perceiveHooks.push({\n\t\t\t\t\tpawName,\n\t\t\t\t\torder: hookConfig?.order ?? 100,\n\t\t\t\t\tpipeline: hookConfig?.pipeline ?? true,\n\t\t\t\t\thasTools,\n\t\t\t\t})\n\t\t\t\tthis.perceiveHooks.sort((a, b) => a.order - b.order)\n\t\t\t}\n\n\t\t\tif (instance.definition?.hooks?.onObserve) {\n\t\t\t\tthis.observeHookPaws.push(pawName)\n\t\t\t}\n\n\t\t\tif (instance.definition?.hooks?.onBootstrap) {\n\t\t\t\tthis.bootstrapPaws.push(pawName)\n\t\t\t}\n\n\t\t\tif (instance.definition?.hooks?.onCompact) {\n\t\t\t\tthis.compactPaws.push(pawName)\n\t\t\t}\n\n\t\t\tlogger.info(`Paw \"${pawName}\" loaded successfully`)\n\t\t\tthis.bus.emit('paw:registered', { pawName })\n\t\t\treturn true\n\t\t} catch (err) {\n\t\t\tlogger.error(`Failed to load Paw \"${pawName}\": ${err}`)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/** Unload a Paw (accepts config path or manifest name) */\n\tasync unload(name: string): Promise<boolean> {\n\t\t// Resolve config path to manifest name if needed\n\t\tconst pawName = this.configToManifest.get(name) ?? name\n\t\tconst instance = this.paws.get(pawName)\n\t\tif (!instance) {\n\t\t\tlogger.warn(`Paw \"${pawName}\" is not loaded`)\n\t\t\treturn false\n\t\t}\n\t\t// Use resolved name from here\n\t\tname = pawName\n\n\t\t// Shutdown the Paw\n\t\tawait shutdownPaw(instance)\n\n\t\t// Clean up transport\n\t\tconst transport = this.transports.get(name)\n\t\tif (transport) {\n\t\t\ttransport.dispose()\n\t\t\tthis.transports.delete(name)\n\t\t}\n\n\t\t// Remove tools from registry\n\t\tthis.toolRegistry.unregister(name)\n\n\t\t// Remove hooks\n\t\tthis.perceiveHooks = this.perceiveHooks.filter((h) => h.pawName !== name)\n\t\tthis.observeHookPaws = this.observeHookPaws.filter((n) => n !== name)\n\t\tthis.bootstrapPaws = this.bootstrapPaws.filter((n) => n !== name)\n\t\tthis.compactPaws = this.compactPaws.filter((n) => n !== name)\n\n\t\tthis.paws.delete(name)\n\t\t// Clean up config→manifest mapping\n\t\tfor (const [configName, manifestName] of this.configToManifest) {\n\t\t\tif (manifestName === name) {\n\t\t\t\tthis.configToManifest.delete(configName)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tlogger.info(`Paw \"${name}\" unloaded`)\n\t\tthis.bus.emit('paw:unregistered', { pawName: name })\n\t\treturn true\n\t}\n\n\t/** Resolve a config name to its manifest name */\n\tresolveManifestName(configName: string): string {\n\t\treturn this.configToManifest.get(configName) ?? configName\n\t}\n\n\t/** Set the Brain Paw name (accepts config path or manifest name) */\n\tsetBrain(name: string): void {\n\t\tthis.brainPawName = this.configToManifest.get(name) ?? name\n\t}\n\n\t/** Get the Brain Paw name */\n\tgetBrainName(): string | undefined {\n\t\treturn this.brainPawName\n\t}\n\n\t/** Get a Paw instance */\n\tget(name: string): PawInstance | undefined {\n\t\treturn this.paws.get(name)\n\t}\n\n\t/** List all loaded Paws */\n\tlist(): PawInstance[] {\n\t\treturn Array.from(this.paws.values())\n\t}\n\n\t/** Check if a Paw is healthy */\n\tisHealthy(name: string): boolean {\n\t\treturn this.paws.get(name)?.healthy ?? false\n\t}\n\n\t/**\n\t * Run GLOBAL perceive hooks — only Paws without tools.\n\t * Paws with tools use lazy perceive (called just before their tool executes).\n\t */\n\tasync runGlobalPerceiveHooks(context: AgentContext): Promise<AgentContext> {\n\t\tlet chainedContext = { ...context }\n\n\t\t// Only run hooks from Paws that have NO tools (context-only Paws)\n\t\tconst globalChained = this.perceiveHooks.filter((h) => h.pipeline && !h.hasTools)\n\t\tconst globalUnchained = this.perceiveHooks.filter((h) => !h.pipeline && !h.hasTools)\n\n\t\t// Run chained hooks sequentially\n\t\tfor (const hook of globalChained) {\n\t\t\tconst instance = this.paws.get(hook.pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\ttry {\n\t\t\t\tchainedContext = await this.callPerceive(hook.pawName, chainedContext)\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Perceive hook error from \"${hook.pawName}\": ${err}`)\n\t\t\t}\n\t\t}\n\n\t\t// Run unchained hooks in parallel on the original context\n\t\tif (globalUnchained.length > 0) {\n\t\t\tconst results = await Promise.allSettled(\n\t\t\t\tglobalUnchained.map(async (hook) => {\n\t\t\t\t\tconst instance = this.paws.get(hook.pawName)\n\t\t\t\t\tif (!instance?.healthy) return null\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await this.callPerceive(hook.pawName, context)\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tlogger.error(`Unchained perceive error from \"${hook.pawName}\": ${err}`)\n\t\t\t\t\t\treturn null\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t)\n\n\t\t\tfor (const result of results) {\n\t\t\t\tif (result.status === 'fulfilled' && result.value) {\n\t\t\t\t\tObject.assign(chainedContext.metadata, result.value.metadata)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn chainedContext\n\t}\n\n\t/**\n\t * Run LAZY perceive for a specific Paw — called just before its tool executes.\n\t * Only runs if the Paw has an onPerceive hook registered.\n\t */\n\tasync runLazyPerceive(pawName: string, context: AgentContext): Promise<AgentContext> {\n\t\tconst hook = this.perceiveHooks.find((h) => h.pawName === pawName && h.hasTools)\n\t\tif (!hook) return context\n\n\t\tconst instance = this.paws.get(pawName)\n\t\tif (!instance?.healthy) return context\n\n\t\ttry {\n\t\t\tlogger.debug(`Lazy perceive for \"${pawName}\" before tool execution`)\n\t\t\treturn await this.callPerceive(pawName, context)\n\t\t} catch (err) {\n\t\t\tlogger.error(`Lazy perceive error from \"${pawName}\": ${err}`)\n\t\t\treturn context\n\t\t}\n\t}\n\n\t/** Run all Observe hooks concurrently (fire-and-forget) */\n\trunObserveHooks(result: ActionResult): void {\n\t\tfor (const pawName of this.observeHookPaws) {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\tthis.callObserve(pawName, result).catch((err) => {\n\t\t\t\tlogger.error(`Observe hook error from \"${pawName}\": ${err}`)\n\t\t\t})\n\t\t}\n\t}\n\n\t/** Run bootstrap hooks — called once at the start of a task */\n\tasync runBootstrapHooks(context: AgentContext): Promise<AgentContext> {\n\t\tlet ctx = { ...context }\n\n\t\tfor (const pawName of this.bootstrapPaws) {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\ttry {\n\t\t\t\tif (instance.inProcess && instance.definition?.hooks?.onBootstrap) {\n\t\t\t\t\tctx = await instance.definition.hooks.onBootstrap(ctx)\n\t\t\t\t} else {\n\t\t\t\t\tconst transport = this.transports.get(pawName)\n\t\t\t\t\tif (transport) {\n\t\t\t\t\t\tctx = (await transport.request('bootstrap', ctx)) as AgentContext\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Bootstrap hook error from \"${pawName}\": ${err}`)\n\t\t\t}\n\t\t}\n\n\t\treturn ctx\n\t}\n\n\t/**\n\t * Run compact hooks — called when context exceeds size threshold.\n\t * Paws can compress/summarize messages to free up context window space.\n\t */\n\tasync runCompactHooks(context: AgentContext): Promise<AgentContext> {\n\t\tlet ctx = { ...context }\n\n\t\tfor (const pawName of this.compactPaws) {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\ttry {\n\t\t\t\tif (instance.inProcess && instance.definition?.hooks?.onCompact) {\n\t\t\t\t\tctx = await instance.definition.hooks.onCompact(ctx)\n\t\t\t\t} else {\n\t\t\t\t\tconst transport = this.transports.get(pawName)\n\t\t\t\t\tif (transport) {\n\t\t\t\t\t\tctx = (await transport.request('compact', ctx)) as AgentContext\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogger.info(`Compact hook from \"${pawName}\" reduced messages from ${context.messages.length} to ${ctx.messages.length}`)\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Compact hook error from \"${pawName}\": ${err}`)\n\t\t\t}\n\t\t}\n\n\t\treturn ctx\n\t}\n\n\t/** Call the Brain Paw's think function */\n\tasync think(context: AgentContext): Promise<AgentPlan | null> {\n\t\tif (!this.brainPawName) return null\n\n\t\tconst instance = this.paws.get(this.brainPawName)\n\t\tif (!instance?.healthy) {\n\t\t\tlogger.error(`Brain Paw \"${this.brainPawName}\" is not healthy`)\n\t\t\treturn null\n\t\t}\n\n\t\tif (instance.inProcess && instance.definition?.think) {\n\t\t\treturn instance.definition.think(context)\n\t\t}\n\n\t\tconst transport = this.transports.get(this.brainPawName)\n\t\tif (!transport) {\n\t\t\tlogger.error(`No transport for Brain Paw \"${this.brainPawName}\"`)\n\t\t\treturn null\n\t\t}\n\n\t\treturn (await transport.request('think', context)) as AgentPlan\n\t}\n\n\t/** Execute a tool on a subprocess Paw */\n\tasync executeRemoteTool(\n\t\tpawName: string,\n\t\ttoolName: string,\n\t\tparams: unknown,\n\t): Promise<unknown> {\n\t\tconst transport = this.transports.get(pawName)\n\t\tif (!transport) {\n\t\t\tthrow new Error(`No transport for Paw \"${pawName}\"`)\n\t\t}\n\n\t\treturn transport.request('execute_tool', { toolName, params })\n\t}\n\n\tprivate async callPerceive(\n\t\tpawName: string,\n\t\tcontext: AgentContext,\n\t): Promise<AgentContext> {\n\t\tconst instance = this.paws.get(pawName)!\n\n\t\tif (instance.inProcess && instance.definition?.hooks?.onPerceive) {\n\t\t\treturn instance.definition.hooks.onPerceive(context)\n\t\t}\n\n\t\tconst transport = this.transports.get(pawName)\n\t\tif (transport) {\n\t\t\treturn (await transport.request('perceive', context)) as AgentContext\n\t\t}\n\n\t\treturn context\n\t}\n\n\tprivate async callObserve(\n\t\tpawName: string,\n\t\tresult: ActionResult,\n\t): Promise<void> {\n\t\tconst instance = this.paws.get(pawName)!\n\n\t\tif (instance.inProcess && instance.definition?.hooks?.onObserve) {\n\t\t\tawait instance.definition.hooks.onObserve(result)\n\t\t\treturn\n\t\t}\n\n\t\tconst transport = this.transports.get(pawName)\n\t\tif (transport) {\n\t\t\tawait transport.request('observe', result)\n\t\t}\n\t}\n\n\tprivate registerInProcessTools(instance: PawInstance): void {\n\t\tif (instance.definition?.tools) {\n\t\t\tthis.toolRegistry.register(\n\t\t\t\tinstance.name,\n\t\t\t\tinstance.definition.tools,\n\t\t\t\ttrue,\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate setupTransportHandlers(\n\t\tpawName: string,\n\t\ttransport: IpcTransport,\n\t): void {\n\t\t// Handle Paw → Core: log\n\t\ttransport.onRequest('log', async (params) => {\n\t\t\tconst { level, message } = params as { level: string; message: string }\n\t\t\tconst prefix = `[${pawName}]`\n\t\t\tswitch (level) {\n\t\t\t\tcase 'error':\n\t\t\t\t\tconsole.error(prefix, message)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'warn':\n\t\t\t\t\tconsole.warn(prefix, message)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'info':\n\t\t\t\t\tconsole.info(prefix, message)\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tconsole.debug(prefix, message)\n\t\t\t}\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: emit\n\t\ttransport.onRequest('emit', async (params) => {\n\t\t\tconst { event } = params as { event: string; data: unknown }\n\t\t\tlogger.info(`Paw \"${pawName}\" emitted event: ${event}`)\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: subscribe to bus events\n\t\ttransport.onRequest('subscribe', async (params) => {\n\t\t\tconst { events } = params as { events: string[] }\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (instance) {\n\t\t\t\tinstance.subscriptions = events\n\t\t\t\tthis.setupBusForwarding(pawName, events, transport)\n\t\t\t\tlogger.info(`Paw \"${pawName}\" subscribed to events: ${events.join(', ')}`)\n\t\t\t}\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: query state\n\t\ttransport.onRequest('query', async (params) => {\n\t\t\tconst { type } = params as { type: 'tools' | 'paws' | 'skills' | 'tasks' }\n\t\t\treturn this.handleQuery(type)\n\t\t})\n\n\t\t// Handle Paw → Core: late tool registration (e.g. MCP tools discovered after initial registration)\n\t\ttransport.onRequest('register_tools', async (params) => {\n\t\t\tconst { tools } = params as { tools: Array<{ name: string; description: string }> }\n\t\t\tif (tools && tools.length > 0) {\n\t\t\t\tconst toolDefs = tools.map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tparameters: {} as import('zod').ZodSchema,\n\t\t\t\t\texecute: async (toolParams: unknown) =>\n\t\t\t\t\t\tthis.executeRemoteTool(pawName, t.name, toolParams),\n\t\t\t\t}))\n\t\t\t\tthis.toolRegistry.register(pawName, toolDefs, false)\n\t\t\t\tlogger.info(`Paw \"${pawName}\" late-registered ${tools.length} tool(s)`)\n\t\t\t}\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: create a task (for channel Paws that receive inbound messages)\n\t\ttransport.onRequest('create_task', async (params) => {\n\t\t\tconst { input, source, sessionId, metadata } = params as {\n\t\t\t\tinput: string\n\t\t\t\tsource?: 'paw' | 'schedule'\n\t\t\t\tsessionId?: string\n\t\t\t\tmetadata?: Record<string, unknown>\n\t\t\t}\n\t\t\tif (!this.taskQueue) {\n\t\t\t\treturn { error: 'Task queue not available' }\n\t\t\t}\n\t\t\tconst task = this.taskQueue.enqueue(input, source ?? 'paw', { sessionId, metadata })\n\t\t\tlogger.info(`Paw \"${pawName}\" created task ${task.id}: \"${input.substring(0, 50)}\"`)\n\t\t\treturn { taskId: task.id }\n\t\t})\n\t}\n\n\t/** Forward bus events to a Paw that subscribed */\n\tprivate setupBusForwarding(\n\t\tpawName: string,\n\t\tevents: string[],\n\t\ttransport: IpcTransport,\n\t): void {\n\t\tfor (const eventName of events) {\n\t\t\t// Use the bus wildcard or specific events\n\t\t\tthis.bus.on(eventName as keyof import('../core/bus.js').BusEvents, (data) => {\n\t\t\t\tconst instance = this.paws.get(pawName)\n\t\t\t\tif (!instance?.healthy) return\n\n\t\t\t\ttransport.notify('bus_event', { event: eventName, data })\n\t\t\t})\n\t\t}\n\t}\n\n\t/** Handle state queries from Paws */\n\tprivate handleQuery(type: string): unknown {\n\t\tswitch (type) {\n\t\t\tcase 'tools':\n\t\t\t\treturn this.toolRegistry.list().map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tpawName: t.pawName,\n\t\t\t\t\tinProcess: t.inProcess,\n\t\t\t\t}))\n\t\t\tcase 'paws':\n\t\t\t\treturn Array.from(this.paws.values()).map((p) => ({\n\t\t\t\t\tname: p.name,\n\t\t\t\t\thealthy: p.healthy,\n\t\t\t\t\tinProcess: p.inProcess,\n\t\t\t\t\ttransport: p.transport,\n\t\t\t\t\ttoolCount: this.toolRegistry.toolsForPaw(p.name).length,\n\t\t\t\t}))\n\t\t\tcase 'skills':\n\t\t\t\treturn this.skillRegistry?.list().map((s) => ({\n\t\t\t\t\tname: s.name,\n\t\t\t\t\tactive: s.active,\n\t\t\t\t\tmissingTools: s.missingTools,\n\t\t\t\t\tdescription: s.definition.description,\n\t\t\t\t})) ?? []\n\t\t\tcase 'tasks':\n\t\t\t\treturn this.taskQueue?.list().map((t) => ({\n\t\t\t\t\tid: t.id,\n\t\t\t\t\tsource: t.source,\n\t\t\t\t\tinput: t.input,\n\t\t\t\t\tstatus: t.status,\n\t\t\t\t\tcreatedAt: t.createdAt,\n\t\t\t\t\tstartedAt: (t as Record<string, unknown>).startedAt,\n\t\t\t\t\tcompletedAt: (t as Record<string, unknown>).completedAt,\n\t\t\t\t})) ?? []\n\t\t\tcase 'schedules':\n\t\t\t\treturn this.scheduler?.list() ?? []\n\t\t\tdefault:\n\t\t\t\treturn { error: `Unknown query type: ${type}` }\n\t\t}\n\t}\n\n\tprivate async waitForRegistration(\n\t\tpawName: string,\n\t\ttransport: IpcTransport,\n\t): Promise<void> {\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\treject(new Error(`Paw \"${pawName}\" did not register within 10 seconds`))\n\t\t\t}, 10_000)\n\n\t\t\ttransport.onRequest('register', async (params) => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tconst registration = params as {\n\t\t\t\t\ttools?: Array<{ name: string; description: string }>\n\t\t\t\t\thooks?: {\n\t\t\t\t\t\tbootstrap?: boolean\n\t\t\t\t\t\tperceive?: boolean\n\t\t\t\t\t\tobserve?: boolean\n\t\t\t\t\t\tcompact?: boolean\n\t\t\t\t\t\tschedule?: string[]\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Register tools from subprocess Paw using manifest tool descriptions\n\t\t\t\t// The actual execute calls are routed through IPC\n\t\t\t\tif (registration.tools) {\n\t\t\t\t\tconst toolDefs = registration.tools.map((t) => ({\n\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\tdescription: t.description,\n\t\t\t\t\t\tparameters: {} as import('zod').ZodSchema, // Schema validated on Paw side\n\t\t\t\t\t\texecute: async (toolParams: unknown) =>\n\t\t\t\t\t\t\tthis.executeRemoteTool(pawName, t.name, toolParams),\n\t\t\t\t\t}))\n\t\t\t\t\tthis.toolRegistry.register(pawName, toolDefs, false)\n\t\t\t\t}\n\n\t\t\t\t// Track hooks for subprocess Paws\n\t\t\t\tif (registration.hooks?.bootstrap) {\n\t\t\t\t\tthis.bootstrapPaws.push(pawName)\n\t\t\t\t}\n\t\t\t\tif (registration.hooks?.perceive) {\n\t\t\t\t\tconst config = this.paws.get(pawName)?.config\n\t\t\t\t\tconst hookConfig = config?.hooks?.perceive\n\t\t\t\t\tconst hasTools = (registration.tools?.length ?? 0) > 0\n\t\t\t\t\tthis.perceiveHooks.push({\n\t\t\t\t\t\tpawName,\n\t\t\t\t\t\torder: hookConfig?.order ?? 100,\n\t\t\t\t\t\tpipeline: hookConfig?.pipeline ?? true,\n\t\t\t\t\t\thasTools,\n\t\t\t\t\t})\n\t\t\t\t\tthis.perceiveHooks.sort((a, b) => a.order - b.order)\n\t\t\t\t}\n\t\t\t\tif (registration.hooks?.observe) {\n\t\t\t\t\tthis.observeHookPaws.push(pawName)\n\t\t\t\t}\n\t\t\t\tif (registration.hooks?.compact) {\n\t\t\t\t\tthis.compactPaws.push(pawName)\n\t\t\t\t}\n\n\t\t\t\tlogger.info(`Paw \"${pawName}\" registered with ${registration.tools?.length ?? 0} tools`)\n\t\t\t\tresolve()\n\t\t\t\treturn { ok: true }\n\t\t\t})\n\t\t})\n\t}\n}\n","import * as path from 'node:path'\nimport { execa, type ResultPromise } from 'execa'\nimport type { PawConfig, PawDefinition, PawInstance, PawManifest } from './types.js'\nimport { createTransport, type IpcTransport } from '../core/ipc.js'\nimport { buildSandboxEnv, computeEffectivePermissions } from './sandbox.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-loader')\n\n/** Load an in-process Paw by importing its module */\nexport async function loadInProcessPaw(\n\tpawPath: string,\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): Promise<PawInstance> {\n\tconst entryPath = path.resolve(pawPath, manifest.entry)\n\n\tlogger.info(`Loading in-process Paw \"${manifest.name}\" from ${entryPath}`)\n\n\tconst module = await import(entryPath)\n\tconst definition: PawDefinition = module.default ?? module\n\n\tif (definition.onLoad) {\n\t\tawait definition.onLoad(config)\n\t}\n\n\treturn {\n\t\tname: manifest.name,\n\t\tmanifest,\n\t\tconfig,\n\t\thealthy: true,\n\t\ttransport: 'ipc',\n\t\tinProcess: true,\n\t\tdefinition,\n\t}\n}\n\n/** Spawn a subprocess Paw and set up IPC transport */\nexport async function loadSubprocessPaw(\n\tpawPath: string,\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): Promise<{ instance: PawInstance; transport: IpcTransport }> {\n\tconst entryPath = path.resolve(pawPath, manifest.entry)\n\tconst transport = manifest.transport ?? 'ipc'\n\tconst permissions = computeEffectivePermissions(manifest, config)\n\tconst env = buildSandboxEnv(permissions)\n\n\tlogger.info(\n\t\t`Spawning subprocess Paw \"${manifest.name}\" (transport: ${transport}) from ${entryPath}`,\n\t)\n\n\tconst stdioConfig =\n\t\ttransport === 'ipc'\n\t\t\t? (['pipe', 'pipe', 'pipe', 'ipc'] as const)\n\t\t\t: (['pipe', 'pipe', 'pipe'] as const)\n\n\tconst child = execa('node', [entryPath], {\n\t\tenv,\n\t\tstdio: stdioConfig,\n\t\treject: false,\n\t\tcleanup: true,\n\t})\n\n\t// Forward stderr for logging\n\tchild.stderr?.on('data', (data: Buffer) => {\n\t\tlogger.warn(`[${manifest.name}] ${data.toString().trimEnd()}`)\n\t})\n\n\tconst ipcTransport = createTransport(transport, child as unknown as import('node:child_process').ChildProcess)\n\n\tconst instance: PawInstance = {\n\t\tname: manifest.name,\n\t\tmanifest,\n\t\tconfig,\n\t\thealthy: true,\n\t\ttransport,\n\t\tinProcess: false,\n\t\tprocess: {\n\t\t\tkill: () => child.kill(),\n\t\t\tpid: child.pid,\n\t\t},\n\t\tsendRequest: (method, params) => ipcTransport.request(method, params),\n\t}\n\n\t// Handle subprocess exit\n\t;(child as ResultPromise).then?.((result) => {\n\t\tif (instance.healthy) {\n\t\t\tinstance.healthy = false\n\t\t\tlogger.error(\n\t\t\t\t`Paw \"${manifest.name}\" exited unexpectedly (code: ${result.exitCode})`,\n\t\t\t)\n\t\t}\n\t}).catch?.(() => {\n\t\t// execa with reject: false should not throw, but handle just in case\n\t\tinstance.healthy = false\n\t})\n\n\treturn { instance, transport: ipcTransport }\n}\n\n/** Send a graceful shutdown signal to a subprocess Paw */\nexport async function shutdownPaw(instance: PawInstance): Promise<void> {\n\tif (instance.inProcess) {\n\t\tif (instance.definition?.onUnload) {\n\t\t\tawait instance.definition.onUnload()\n\t\t}\n\t\treturn\n\t}\n\n\tif (instance.sendRequest) {\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tinstance.sendRequest('shutdown'),\n\t\t\t\tnew Promise((resolve) => setTimeout(resolve, 5_000)),\n\t\t\t])\n\t\t} catch {\n\t\t\tlogger.warn(`Shutdown request to \"${instance.name}\" failed, killing process`)\n\t\t}\n\t}\n\n\tinstance.process?.kill()\n\tinstance.healthy = false\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { Readable, Writable } from 'node:stream'\nimport * as crypto from 'node:crypto'\nimport type { TransportType } from '../paw/types.js'\n\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('ipc')\n\n/** JSON-RPC 2.0 message */\nexport interface IpcMessage {\n\tjsonrpc: '2.0'\n\tid?: string\n\tmethod?: string\n\tparams?: unknown\n\tresult?: unknown\n\terror?: { code: number; message: string; data?: unknown }\n}\n\n/** Pending request waiting for a response */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void\n\treject: (error: Error) => void\n\ttimer: ReturnType<typeof setTimeout>\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000\n\n/** Transport abstraction that handles both Node IPC and stdio JSON-RPC */\nexport class IpcTransport {\n\tprivate pending = new Map<string, PendingRequest>()\n\tprivate handlers = new Map<string, (params: unknown) => Promise<unknown>>()\n\tprivate disposed = false\n\n\tconstructor(\n\t\tprivate type: TransportType,\n\t\tprivate childProcess: ChildProcess,\n\t\tprivate timeoutMs = DEFAULT_TIMEOUT_MS,\n\t) {\n\t\tif (type === 'ipc') {\n\t\t\tthis.setupIpcListeners()\n\t\t} else {\n\t\t\tthis.setupStdioListeners()\n\t\t}\n\t}\n\n\t/** Register a handler for incoming requests from the Paw */\n\tonRequest(method: string, handler: (params: unknown) => Promise<unknown>): void {\n\t\tthis.handlers.set(method, handler)\n\t}\n\n\t/** Send a request to the Paw and wait for a response */\n\tasync request(method: string, params?: unknown): Promise<unknown> {\n\t\tif (this.disposed) {\n\t\t\tthrow new Error('Transport has been disposed')\n\t\t}\n\n\t\tconst id = crypto.randomUUID()\n\t\tconst message: IpcMessage = { jsonrpc: '2.0', id, method, params }\n\t\tlogger.trace('Sending request: %s %s', method, JSON.stringify(params ?? '', null, 2))\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(id)\n\t\t\t\treject(new Error(`IPC request \"${method}\" timed out after ${this.timeoutMs}ms`))\n\t\t\t}, this.timeoutMs)\n\n\t\t\tthis.pending.set(id, { resolve, reject, timer })\n\t\t\tthis.send(message)\n\t\t})\n\t}\n\n\t/** Send a notification (no response expected) */\n\tnotify(method: string, params?: unknown): void {\n\t\tif (this.disposed) return\n\t\tconst message: IpcMessage = { jsonrpc: '2.0', method, params }\n\t\tthis.send(message)\n\t}\n\n\t/** Clean up resources */\n\tdispose(): void {\n\t\tthis.disposed = true\n\t\tfor (const [, pending] of this.pending) {\n\t\t\tclearTimeout(pending.timer)\n\t\t\tpending.reject(new Error('Transport disposed'))\n\t\t}\n\t\tthis.pending.clear()\n\t\tthis.handlers.clear()\n\t}\n\n\tprivate send(message: IpcMessage): void {\n\t\tif (this.type === 'ipc') {\n\t\t\tthis.childProcess.send?.(message)\n\t\t} else {\n\t\t\tconst json = JSON.stringify(message)\n\t\t\tconst header = `Content-Length: ${Buffer.byteLength(json)}\\r\\n\\r\\n`\n\t\t\tconst stdin = this.childProcess.stdin as Writable | null\n\t\t\tif (stdin?.writable) {\n\t\t\t\tstdin.write(header + json)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate handleMessage(msg: IpcMessage): void {\n\t\tlogger.trace('Received message: %s %s', msg.method ?? msg.id ?? 'unknown', JSON.stringify(msg.params ?? msg.result ?? '', null, 2))\n\n\t\t// Response to a pending request\n\t\tif (msg.id && this.pending.has(msg.id)) {\n\t\t\tconst pending = this.pending.get(msg.id)!\n\t\t\tthis.pending.delete(msg.id)\n\t\t\tclearTimeout(pending.timer)\n\n\t\t\tif (msg.error) {\n\t\t\t\tpending.reject(new Error(`${msg.error.message} (code: ${msg.error.code})`))\n\t\t\t} else {\n\t\t\t\tpending.resolve(msg.result)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Incoming request from Paw\n\t\tif (msg.method && this.handlers.has(msg.method)) {\n\t\t\tconst handler = this.handlers.get(msg.method)!\n\t\t\thandler(msg.params)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tif (msg.id) {\n\t\t\t\t\t\tthis.send({ jsonrpc: '2.0', id: msg.id, result })\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err: unknown) => {\n\t\t\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err)\n\t\t\t\t\tlogger.error('Handler error for \"%s\": %s', msg.method, errorMessage)\n\t\t\t\t\tif (msg.id) {\n\t\t\t\t\t\tthis.send({\n\t\t\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\t\terror: { code: -32603, message: errorMessage },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t}\n\t}\n\n\tprivate setupIpcListeners(): void {\n\t\tthis.childProcess.on('message', (msg: unknown) => {\n\t\t\tthis.handleMessage(msg as IpcMessage)\n\t\t})\n\t}\n\n\tprivate setupStdioListeners(): void {\n\t\tconst stdout = this.childProcess.stdout as Readable | null\n\t\tif (!stdout) {\n\t\t\tlogger.error('No stdout stream available for stdio transport')\n\t\t\treturn\n\t\t}\n\n\t\tlet buffer = ''\n\n\t\tstdout.setEncoding('utf-8')\n\t\tstdout.on('data', (chunk: string) => {\n\t\t\tbuffer += chunk\n\n\t\t\t// Parse Content-Length framed messages\n\t\t\twhile (buffer.length > 0) {\n\t\t\t\tconst headerEnd = buffer.indexOf('\\r\\n\\r\\n')\n\t\t\t\tif (headerEnd === -1) break\n\n\t\t\t\tconst header = buffer.substring(0, headerEnd)\n\t\t\t\tconst match = header.match(/Content-Length:\\s*(\\d+)/i)\n\t\t\t\tif (!match) {\n\t\t\t\t\tlogger.error('Invalid header in stdio transport: %s', header)\n\t\t\t\t\tbuffer = buffer.substring(headerEnd + 4)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst contentLength = Number.parseInt(match[1], 10)\n\t\t\t\tconst bodyStart = headerEnd + 4\n\t\t\t\tif (buffer.length < bodyStart + contentLength) break\n\n\t\t\t\tconst body = buffer.substring(bodyStart, bodyStart + contentLength)\n\t\t\t\tbuffer = buffer.substring(bodyStart + contentLength)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst msg = JSON.parse(body) as IpcMessage\n\t\t\t\t\tthis.handleMessage(msg)\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger.error('Failed to parse stdio JSON-RPC message: %s', err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n/** Create a transport for a Paw subprocess */\nexport function createTransport(\n\ttype: TransportType,\n\tchildProcess: ChildProcess,\n\ttimeoutMs?: number,\n): IpcTransport {\n\treturn new IpcTransport(type, childProcess, timeoutMs)\n}\n","import type { EffectivePermissions, PawConfig, PawManifest } from './types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-sandbox')\n\n/**\n * Compute effective permissions as the intersection of\n * what the manifest requests and what the config grants.\n */\nexport function computeEffectivePermissions(\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): EffectivePermissions {\n\tconst requested = manifest.permissions ?? { network: [], listen: [], filesystem: [], env: [] }\n\tconst granted = config.allow\n\n\t// If no allow block in config, treat as \"grant all requested\"\n\tif (!granted) {\n\t\treturn {\n\t\t\tnetwork: requested.network ?? [],\n\t\t\tlisten: requested.listen ?? [],\n\t\t\tfilesystem: requested.filesystem ?? [],\n\t\t\tenv: requested.env ?? [],\n\t\t}\n\t}\n\n\treturn {\n\t\tnetwork: intersectStrings(requested.network ?? [], granted.network ?? []),\n\t\tlisten: intersectNumbers(requested.listen ?? [], granted.listen ?? []),\n\t\tfilesystem: intersectStrings(requested.filesystem ?? [], granted.filesystem ?? []),\n\t\tenv: intersectStrings(requested.env ?? [], granted.env ?? []),\n\t}\n}\n\nfunction intersectStrings(a: string[], b: string[]): string[] {\n\tconst setB = new Set(b)\n\treturn a.filter((item) => setB.has(item))\n}\n\nfunction intersectNumbers(a: number[], b: number[]): number[] {\n\tconst setB = new Set(b)\n\treturn a.filter((item) => setB.has(item))\n}\n\n/**\n * Build the environment variables for a sandboxed Paw subprocess.\n * Only passes through env vars that are in the effective permissions.\n * Passes granted listen ports as VOLE_LISTEN_PORTS for the Paw to use.\n */\nexport function buildSandboxEnv(\n\tpermissions: EffectivePermissions,\n): Record<string, string | undefined> {\n\tconst env: Record<string, string | undefined> = {\n\t\t// Always pass NODE_ENV and PATH\n\t\tNODE_ENV: process.env.NODE_ENV,\n\t\tPATH: process.env.PATH,\n\t\t// Debug flag\n\t\tVOLE_LOG_LEVEL: process.env.VOLE_LOG_LEVEL,\n\t}\n\n\t// Pass granted listen ports so the Paw knows which ports it can bind\n\tif (permissions.listen.length > 0) {\n\t\tenv.VOLE_LISTEN_PORTS = permissions.listen.join(',')\n\t}\n\n\tfor (const key of permissions.env) {\n\t\tif (process.env[key] !== undefined) {\n\t\t\tenv[key] = process.env[key]\n\t\t} else {\n\t\t\tlogger.warn(`Env var \"${key}\" is permitted but not set in environment`)\n\t\t}\n\t}\n\n\treturn env\n}\n\n/**\n * Validate that a Paw's manifest permissions are reasonable.\n * Returns warnings (non-blocking) for review.\n */\nexport function validatePermissions(\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): string[] {\n\tconst warnings: string[] = []\n\tconst effective = computeEffectivePermissions(manifest, config)\n\tconst requested = manifest.permissions ?? {}\n\n\tfor (const domain of requested.network ?? []) {\n\t\tif (!effective.network.includes(domain)) {\n\t\t\twarnings.push(\n\t\t\t\t`Network access to \"${domain}\" requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const port of requested.listen ?? []) {\n\t\tif (!effective.listen.includes(port)) {\n\t\t\twarnings.push(\n\t\t\t\t`Listen on port ${port} requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const fspath of requested.filesystem ?? []) {\n\t\tif (!effective.filesystem.includes(fspath)) {\n\t\t\twarnings.push(\n\t\t\t\t`Filesystem access to \"${fspath}\" requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const envVar of requested.env ?? []) {\n\t\tif (!effective.env.includes(envVar)) {\n\t\t\twarnings.push(\n\t\t\t\t`Env var \"${envVar}\" requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tif (warnings.length > 0) {\n\t\tfor (const w of warnings) {\n\t\t\tlogger.info(w)\n\t\t}\n\t}\n\n\treturn warnings\n}\n","import * as readline from 'node:readline'\nimport type { VoleIO } from './types.js'\n\n/** Default TTY I/O implementation using stdin/stdout */\nexport function createTtyIO(): VoleIO {\n\treturn {\n\t\tasync confirm(message: string): Promise<boolean> {\n\t\t\tconst rl = readline.createInterface({\n\t\t\t\tinput: process.stdin,\n\t\t\t\toutput: process.stdout,\n\t\t\t})\n\t\t\ttry {\n\t\t\t\treturn await new Promise<boolean>((resolve) => {\n\t\t\t\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\t\t\t\tresolve(answer.trim().toLowerCase() === 'y')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} finally {\n\t\t\t\trl.close()\n\t\t\t}\n\t\t},\n\n\t\tasync prompt(message: string): Promise<string> {\n\t\t\tconst rl = readline.createInterface({\n\t\t\t\tinput: process.stdin,\n\t\t\t\toutput: process.stdout,\n\t\t\t})\n\t\t\ttry {\n\t\t\t\treturn await new Promise<string>((resolve) => {\n\t\t\t\t\trl.question(`${message} `, (answer) => {\n\t\t\t\t\t\tresolve(answer.trim())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} finally {\n\t\t\t\trl.close()\n\t\t\t}\n\t\t},\n\n\t\tnotify(message: string): void {\n\t\t\tprocess.stdout.write(`${message}\\n`)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;A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A,SAAO,MAAM,4BAA4B,UAAU,EAAE;AACrD,MAAAA,SAAO,KAAK,oCAAoC;AAChD,cAAQ,KAAK,CAAC;AAAA,EAChB;AACD;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACrB,UAAQ,MAAM,gBAAgB,GAAG;AACjC,UAAQ,KAAK,CAAC;AACf,CAAC;","names":["fs","path","logger","fs","path","logger","fs","path","crypto","logger","logger","fs","path","logger","fs","path","logger","registry_exports","fs","path","logger","init_registry","fs","path","z","stat","path","logger","logger","path","crypto","logger","resolve","logger","logger","resolve","logger","resolve","init_registry","resolve","path","init_registry","fs","logger","readline","resolve","fs","normalizePawConfig","readPawManifest","resolvePawPath","SkillRegistry","createMessageBus","ToolRegistry","loadSkillFromDirectory","SchedulerStore","TaskQueue","createCoreTools","Vault"]}
|
|
1
|
+
{"version":3,"sources":["../src/config/index.ts","../src/core/bus.ts","../src/core/logger.ts","../src/skill/resolver.ts","../src/core/task.ts","../src/core/scheduler.ts","../src/core/vault.ts","../src/tool/registry.ts","../src/paw/manifest.ts","../src/skill/loader.ts","../src/skill/registry.ts","../src/tool/core-tools.ts","../src/cli.ts","../src/index.ts","../src/context/types.ts","../src/core/errors.ts","../src/core/loop.ts","../src/core/hooks.ts","../src/core/rate-limiter.ts","../src/paw/registry.ts","../src/paw/loader.ts","../src/core/ipc.ts","../src/paw/sandbox.ts","../src/io/tty.ts"],"sourcesContent":["import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport type { PawConfig } from '../paw/types.js'\n\n/** Rate limit configuration */\nexport interface RateLimits {\n\t/** Max LLM (Brain) calls per minute */\n\tllmCallsPerMinute?: number\n\t/** Max LLM (Brain) calls per hour */\n\tllmCallsPerHour?: number\n\t/** Max tool executions per single task */\n\ttoolExecutionsPerTask?: number\n\t/** Max tasks per hour, keyed by source */\n\ttasksPerHour?: Record<string, number>\n}\n\n/** Loop configuration */\nexport interface LoopConfig {\n\tmaxIterations: number\n\tconfirmBeforeAct: boolean\n\ttaskConcurrency: number\n\t/** Max messages before triggering compact hooks (0 = disabled) */\n\tcompactThreshold: number\n\t/** Rate limits (undefined = no limits) */\n\trateLimits?: RateLimits\n}\n\n/** Tool profile — restricts which tools a task source can use */\nexport interface ToolProfile {\n\t/** Tools allowed (if set, only these tools can be used) */\n\tallow?: string[]\n\t/** Tools denied (if set, these tools are blocked) */\n\tdeny?: string[]\n}\n\n/** Heartbeat configuration */\nexport interface HeartbeatConfig {\n\tenabled: boolean\n\tintervalMinutes: number\n\t/** If true, run heartbeat immediately on startup (default: false) */\n\trunOnStart?: boolean\n}\n\n/** Security configuration */\nexport interface SecurityConfig {\n\t/** If true, paws can only access files inside .openvole/ directory. Default: true */\n\tsandboxFilesystem?: boolean\n\t/** Additional paths paws are allowed to access outside .openvole/ */\n\tallowedPaths?: string[]\n}\n\n/** The full OpenVole configuration */\nexport interface VoleConfig {\n\tbrain?: string\n\tpaws: Array<PawConfig | string>\n\tskills: string[]\n\tloop: LoopConfig\n\theartbeat: HeartbeatConfig\n\t/** Tool profiles per task source — restrict which tools can be used */\n\ttoolProfiles?: Record<string, ToolProfile>\n\t/** Security settings */\n\tsecurity?: SecurityConfig\n}\n\n/** CLI-managed lock file — tracks installed paws and skills */\nexport interface VoleLock {\n\tpaws: Array<{\n\t\tname: string\n\t\tversion: string\n\t\tallow?: PawConfig['allow']\n\t}>\n\tskills: Array<{\n\t\tname: string\n\t\tversion: string\n\t}>\n}\n\n/** Default configuration values */\nconst DEFAULT_LOOP_CONFIG: LoopConfig = {\n\tmaxIterations: 10,\n\tconfirmBeforeAct: true,\n\ttaskConcurrency: 1,\n\tcompactThreshold: 50,\n\trateLimits: undefined,\n}\n\nconst DEFAULT_HEARTBEAT_CONFIG: HeartbeatConfig = {\n\tenabled: false,\n\tintervalMinutes: 30,\n}\n\n/** Normalize a Paw entry (string shorthand → full config) */\nexport function normalizePawConfig(entry: PawConfig | string): PawConfig {\n\tif (typeof entry === 'string') {\n\t\treturn { name: entry }\n\t}\n\treturn entry\n}\n\n/** Create a VoleConfig with defaults applied */\nexport function defineConfig(config: Partial<VoleConfig>): VoleConfig {\n\treturn {\n\t\tbrain: config.brain,\n\t\tpaws: config.paws ?? [],\n\t\tskills: config.skills ?? [],\n\t\tloop: {\n\t\t\t...DEFAULT_LOOP_CONFIG,\n\t\t\t...config.loop,\n\t\t},\n\t\theartbeat: {\n\t\t\t...DEFAULT_HEARTBEAT_CONFIG,\n\t\t\t...config.heartbeat,\n\t\t},\n\t\ttoolProfiles: config.toolProfiles,\n\t\tsecurity: config.security,\n\t}\n}\n\n/** Load configuration — merges vole.config.{ts,mjs,js} with vole.lock.json */\nexport async function loadConfig(configPath: string): Promise<VoleConfig> {\n\tconst userConfig = await loadUserConfig(configPath)\n\tconst lockPath = path.join(path.dirname(configPath), '.openvole', 'vole.lock.json')\n\tconst lock = await loadLockFile(lockPath)\n\n\treturn mergeConfigWithLock(userConfig, lock)\n}\n\n/** Load the user-authored config file */\nasync function loadUserConfig(configPath: string): Promise<VoleConfig> {\n\t// Try JSON first (preferred), then fall back to JS/MJS\n\tconst dir = path.dirname(configPath)\n\tconst jsonPath = path.join(dir, 'vole.config.json')\n\n\t// Try JSON\n\ttry {\n\t\tconst raw = await fs.readFile(jsonPath, 'utf-8')\n\t\tconst config = JSON.parse(raw)\n\t\treturn {\n\t\t\tbrain: config.brain,\n\t\t\tpaws: config.paws ?? [],\n\t\t\tskills: config.skills ?? [],\n\t\t\tloop: {\n\t\t\t\t...DEFAULT_LOOP_CONFIG,\n\t\t\t\t...config.loop,\n\t\t\t},\n\t\t\theartbeat: {\n\t\t\t\t...DEFAULT_HEARTBEAT_CONFIG,\n\t\t\t\t...config.heartbeat,\n\t\t\t},\n\t\t\ttoolProfiles: config.toolProfiles,\n\t\t\tsecurity: config.security,\n\t\t}\n\t} catch {\n\t\t// JSON not found or invalid, try JS candidates\n\t}\n\n\t// Fall back to JS/MJS/TS imports\n\tconst candidates = [configPath]\n\tif (configPath.endsWith('.ts')) {\n\t\tcandidates.push(configPath.replace(/\\.ts$/, '.mjs'))\n\t\tcandidates.push(configPath.replace(/\\.ts$/, '.js'))\n\t}\n\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst module = await import(candidate)\n\t\t\tconst config = module.default ?? module\n\t\t\treturn {\n\t\t\t\tbrain: config.brain,\n\t\t\t\tpaws: config.paws ?? [],\n\t\t\t\tskills: config.skills ?? [],\n\t\t\t\tloop: {\n\t\t\t\t\t...DEFAULT_LOOP_CONFIG,\n\t\t\t\t\t...config.loop,\n\t\t\t\t},\n\t\t\t\theartbeat: {\n\t\t\t\t\t...DEFAULT_HEARTBEAT_CONFIG,\n\t\t\t\t\t...config.heartbeat,\n\t\t\t\t},\n\t\t\t\ttoolProfiles: config.toolProfiles,\n\t\tsecurity: config.security,\n\t\t\t}\n\t\t} catch {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tconsole.warn(`[config] No config found (tried: ${jsonPath}, ${candidates.join(', ')}), using defaults`)\n\treturn defineConfig({})\n}\n\n/** Load the CLI-managed lock file */\nasync function loadLockFile(lockPath: string): Promise<VoleLock> {\n\ttry {\n\t\tconst raw = await fs.readFile(lockPath, 'utf-8')\n\t\treturn JSON.parse(raw) as VoleLock\n\t} catch {\n\t\treturn { paws: [], skills: [] }\n\t}\n}\n\n/**\n * Merge user config with lock file.\n * Lock file entries are added if not already present in user config.\n * User config takes precedence (can override permissions, add hooks, etc.)\n */\nfunction mergeConfigWithLock(userConfig: VoleConfig, lock: VoleLock): VoleConfig {\n\tconst userPawNames = new Set(\n\t\tuserConfig.paws.map((p) => (typeof p === 'string' ? p : p.name)),\n\t)\n\tconst userSkillNames = new Set(userConfig.skills)\n\n\t// Add lock file paws not already in user config\n\tconst mergedPaws: Array<PawConfig | string> = [...userConfig.paws]\n\tfor (const lockPaw of lock.paws) {\n\t\tif (!userPawNames.has(lockPaw.name)) {\n\t\t\tmergedPaws.push(\n\t\t\t\tlockPaw.allow\n\t\t\t\t\t? { name: lockPaw.name, allow: lockPaw.allow }\n\t\t\t\t\t: lockPaw.name,\n\t\t\t)\n\t\t}\n\t}\n\n\t// Add lock file skills not already in user config\n\tconst mergedSkills = [...userConfig.skills]\n\tfor (const lockSkill of lock.skills) {\n\t\tif (!userSkillNames.has(lockSkill.name)) {\n\t\t\tmergedSkills.push(lockSkill.name)\n\t\t}\n\t}\n\n\treturn {\n\t\t...userConfig,\n\t\tpaws: mergedPaws,\n\t\tskills: mergedSkills,\n\t}\n}\n\n// === Lock file management (used by CLI) ===\n\n/** Read the lock file */\nexport async function readLockFile(projectRoot: string): Promise<VoleLock> {\n\tconst lockPath = path.join(projectRoot, '.openvole', 'vole.lock.json')\n\ttry {\n\t\tconst raw = await fs.readFile(lockPath, 'utf-8')\n\t\treturn JSON.parse(raw) as VoleLock\n\t} catch {\n\t\treturn { paws: [], skills: [] }\n\t}\n}\n\n/** Write the lock file */\nexport async function writeLockFile(\n\tprojectRoot: string,\n\tlock: VoleLock,\n): Promise<void> {\n\tconst openvoleDir = path.join(projectRoot, '.openvole')\n\tawait fs.mkdir(openvoleDir, { recursive: true })\n\tconst lockPath = path.join(openvoleDir, 'vole.lock.json')\n\tawait fs.writeFile(lockPath, JSON.stringify(lock, null, 2) + '\\n', 'utf-8')\n}\n\n/** Add a Paw to the lock file */\nexport async function addPawToLock(\n\tprojectRoot: string,\n\tname: string,\n\tversion: string,\n\tallow?: PawConfig['allow'],\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tconst existing = lock.paws.findIndex((p) => p.name === name)\n\tconst entry = { name, version, allow }\n\n\tif (existing >= 0) {\n\t\tlock.paws[existing] = entry\n\t} else {\n\t\tlock.paws.push(entry)\n\t}\n\n\tawait writeLockFile(projectRoot, lock)\n}\n\n/** Remove a Paw from the lock file */\nexport async function removePawFromLock(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tlock.paws = lock.paws.filter((p) => p.name !== name)\n\tawait writeLockFile(projectRoot, lock)\n}\n\n/** Add a Skill to the lock file */\nexport async function addSkillToLock(\n\tprojectRoot: string,\n\tname: string,\n\tversion: string,\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tconst existing = lock.skills.findIndex((s) => s.name === name)\n\tconst entry = { name, version }\n\n\tif (existing >= 0) {\n\t\tlock.skills[existing] = entry\n\t} else {\n\t\tlock.skills.push(entry)\n\t}\n\n\tawait writeLockFile(projectRoot, lock)\n}\n\n/** Remove a Skill from the lock file */\nexport async function removeSkillFromLock(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst lock = await readLockFile(projectRoot)\n\tlock.skills = lock.skills.filter((s) => s.name !== name)\n\tawait writeLockFile(projectRoot, lock)\n}\n\n// === vole.config.json management ===\n\n/** Read the raw vole.config.json */\nexport async function readConfigFile(\n\tprojectRoot: string,\n): Promise<Record<string, unknown>> {\n\tconst configPath = path.join(projectRoot, 'vole.config.json')\n\ttry {\n\t\tconst raw = await fs.readFile(configPath, 'utf-8')\n\t\treturn JSON.parse(raw)\n\t} catch {\n\t\treturn {}\n\t}\n}\n\n/** Write the vole.config.json */\nexport async function writeConfigFile(\n\tprojectRoot: string,\n\tconfig: Record<string, unknown>,\n): Promise<void> {\n\tconst configPath = path.join(projectRoot, 'vole.config.json')\n\tawait fs.writeFile(configPath, JSON.stringify(config, null, 2) + '\\n', 'utf-8')\n}\n\n/** Add a Paw to vole.config.json if not already present */\nexport async function addPawToConfig(\n\tprojectRoot: string,\n\tname: string,\n\tallow?: PawConfig['allow'],\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst paws = (config.paws ?? []) as Array<PawConfig | string>\n\tconst existing = paws.find((p) =>\n\t\ttypeof p === 'string' ? p === name : p.name === name,\n\t)\n\tif (existing) return\n\n\tpaws.push(allow ? { name, allow } : name)\n\tconfig.paws = paws\n\tawait writeConfigFile(projectRoot, config)\n}\n\n/** Remove a Paw from vole.config.json */\nexport async function removePawFromConfig(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst paws = (config.paws ?? []) as Array<PawConfig | string>\n\tconfig.paws = paws.filter((p) =>\n\t\ttypeof p === 'string' ? p !== name : p.name !== name,\n\t)\n\tawait writeConfigFile(projectRoot, config)\n}\n\n/** Add a Skill to vole.config.json if not already present */\nexport async function addSkillToConfig(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst skills = (config.skills ?? []) as string[]\n\tif (skills.includes(name)) return\n\n\tskills.push(name)\n\tconfig.skills = skills\n\tawait writeConfigFile(projectRoot, config)\n}\n\n/** Remove a Skill from vole.config.json */\nexport async function removeSkillFromConfig(\n\tprojectRoot: string,\n\tname: string,\n): Promise<void> {\n\tconst config = await readConfigFile(projectRoot)\n\tconst skills = (config.skills ?? []) as string[]\n\tconfig.skills = skills.filter((s) => s !== name)\n\tawait writeConfigFile(projectRoot, config)\n}\n","import mitt, { type Emitter } from 'mitt'\n\n/** Events emitted on the message bus */\nexport type BusEvents = {\n\t'tool:registered': { toolName: string; pawName: string }\n\t'tool:unregistered': { toolName: string; pawName: string }\n\t'paw:registered': { pawName: string }\n\t'paw:unregistered': { pawName: string }\n\t'paw:crashed': { pawName: string; error?: unknown }\n\t'task:queued': { taskId: string }\n\t'task:started': { taskId: string }\n\t'task:completed': { taskId: string; result?: string }\n\t'task:failed': { taskId: string; error?: unknown }\n\t'task:cancelled': { taskId: string }\n\t'rate:limited': { bucket: string; source?: string }\n}\n\nexport type MessageBus = Emitter<BusEvents>\n\n/** Create a new message bus instance */\nexport function createMessageBus(): MessageBus {\n\treturn mitt<BusEvents>()\n}\n","import * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nconst LEVELS = { error: 0, warn: 1, info: 2, debug: 3, trace: 4 } as const\ntype Level = keyof typeof LEVELS\n\nlet logStream: fs.WriteStream | undefined\n\n/** Initialize file logging from VOLE_LOG_FILE env var */\nfunction getLogStream(): fs.WriteStream | undefined {\n\tif (logStream) return logStream\n\tconst logFile = process.env.VOLE_LOG_FILE\n\tif (!logFile) return undefined\n\tconst dir = path.dirname(logFile)\n\tfs.mkdirSync(dir, { recursive: true })\n\tlogStream = fs.createWriteStream(logFile, { flags: 'a' })\n\treturn logStream\n}\n\n/** Close the log file stream (called on shutdown) */\nexport function closeLogger(): void {\n\tlogStream?.end()\n\tlogStream = undefined\n}\n\nfunction currentLevel(): number {\n\tconst level = (process.env.VOLE_LOG_LEVEL ?? 'info').toLowerCase() as Level\n\treturn LEVELS[level] ?? LEVELS.info\n}\n\nfunction writeToFile(level: string, prefix: string, msg: string, args: unknown[]): void {\n\tconst stream = getLogStream()\n\tif (!stream) return\n\tconst timestamp = new Date().toISOString()\n\tconst argsStr = args.length > 0 ? ' ' + args.map(a => typeof a === 'string' ? a : JSON.stringify(a)).join(' ') : ''\n\tstream.write(`${timestamp} [${level.toUpperCase()}] ${prefix} ${msg}${argsStr}\\n`)\n}\n\nexport function createLogger(tag: string) {\n\tconst prefix = `[${tag}]`\n\treturn {\n\t\terror: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.error) console.error(prefix, msg, ...args)\n\t\t\twriteToFile('error', prefix, msg, args)\n\t\t},\n\t\twarn: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.warn) console.warn(prefix, msg, ...args)\n\t\t\twriteToFile('warn', prefix, msg, args)\n\t\t},\n\t\tinfo: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.info) console.info(prefix, msg, ...args)\n\t\t\twriteToFile('info', prefix, msg, args)\n\t\t},\n\t\tdebug: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.debug) console.debug(prefix, msg, ...args)\n\t\t\twriteToFile('debug', prefix, msg, args)\n\t\t},\n\t\ttrace: (msg: string, ...args: unknown[]) => {\n\t\t\tif (currentLevel() >= LEVELS.trace) console.debug(prefix, msg, ...args)\n\t\t\twriteToFile('trace', prefix, msg, args)\n\t\t},\n\t}\n}\n","import { execFileSync } from 'node:child_process'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { SkillInstance } from './types.js'\nimport type { ActiveSkill } from '../context/types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('skill-resolver')\n\n/**\n * Resolve Skill activation based on the current tool registry\n * and runtime requirements (env vars, binaries).\n *\n * A Skill is active if:\n * - All requiredTools are registered in the tool registry\n * - All requires.env vars are set in the environment\n * - All requires.bins are available on PATH\n * - At least one of requires.anyBins is available (if specified)\n */\nexport function resolveSkills(\n\tskills: SkillInstance[],\n\ttoolRegistry: ToolRegistry,\n): void {\n\tfor (const skill of skills) {\n\t\tconst missing: string[] = []\n\n\t\t// Check required tools\n\t\tfor (const toolName of skill.definition.requiredTools) {\n\t\t\tif (!toolRegistry.has(toolName)) {\n\t\t\t\tmissing.push(`tool:${toolName}`)\n\t\t\t}\n\t\t}\n\n\t\t// Check OpenClaw-compatible requirements\n\t\tconst requires = skill.definition.requires\n\t\tif (requires) {\n\t\t\t// Check env vars\n\t\t\tfor (const envVar of requires.env) {\n\t\t\t\tif (!process.env[envVar]) {\n\t\t\t\t\tmissing.push(`env:${envVar}`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check required binaries\n\t\t\tfor (const bin of requires.bins) {\n\t\t\t\tif (!isBinaryAvailable(bin)) {\n\t\t\t\t\tmissing.push(`bin:${bin}`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check anyBins — at least one must exist\n\t\t\tif (requires.anyBins.length > 0) {\n\t\t\t\tconst hasAny = requires.anyBins.some(isBinaryAvailable)\n\t\t\t\tif (!hasAny) {\n\t\t\t\t\tmissing.push(`anyBin:${requires.anyBins.join('|')}`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst wasActive = skill.active\n\t\tskill.active = missing.length === 0\n\t\tskill.missingTools = missing\n\n\t\tif (skill.active && !wasActive) {\n\t\t\tconst providers = skill.definition.requiredTools\n\t\t\t\t.map((t) => toolRegistry.get(t)?.pawName)\n\t\t\t\t.filter(Boolean)\n\t\t\tconst providerInfo = providers.length > 0\n\t\t\t\t? ` (tools provided by: ${[...new Set(providers)].join(', ')})`\n\t\t\t\t: ''\n\t\t\tlogger.info(`Skill \"${skill.name}\" activated${providerInfo}`)\n\t\t} else if (!skill.active && wasActive) {\n\t\t\tlogger.warn(\n\t\t\t\t`Skill \"${skill.name}\" deactivated (missing: ${missing.join(', ')})`,\n\t\t\t)\n\t\t} else if (!skill.active) {\n\t\t\tlogger.debug(\n\t\t\t\t`Skill \"${skill.name}\" inactive (missing: ${missing.join(', ')})`,\n\t\t\t)\n\t\t}\n\t}\n}\n\n/** Build ActiveSkill entries for the AgentContext */\nexport function buildActiveSkills(\n\tskills: SkillInstance[],\n\ttoolRegistry: ToolRegistry,\n): ActiveSkill[] {\n\treturn skills\n\t\t.filter((s) => s.active)\n\t\t.map((s) => {\n\t\t\tconst satisfiedBy = s.definition.requiredTools\n\t\t\t\t.map((t) => toolRegistry.get(t)?.pawName)\n\t\t\t\t.filter((name): name is string => name != null)\n\n\t\t\treturn {\n\t\t\t\tname: s.name,\n\t\t\t\tdescription: s.definition.description,\n\t\t\t\tsatisfiedBy: [...new Set(satisfiedBy)],\n\t\t\t}\n\t\t})\n}\n\n/** Check if a binary is available on PATH */\nfunction isBinaryAvailable(name: string): boolean {\n\ttry {\n\t\tconst cmd = process.platform === 'win32' ? 'where' : 'which'\n\t\texecFileSync(cmd, [name], { stdio: 'ignore' })\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n","import * as crypto from 'node:crypto'\nimport type { MessageBus } from './bus.js'\nimport type { RateLimiter } from './rate-limiter.js'\nimport type { RateLimits } from '../config/index.js'\nimport { createLogger } from './logger.js'\n\n/** Task states */\nexport type TaskStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled'\n\n/** A discrete unit of work for the agent loop */\nexport interface AgentTask {\n\tid: string\n\tsource: 'user' | 'schedule' | 'heartbeat' | 'paw'\n\tinput: string\n\tstatus: TaskStatus\n\tcreatedAt: number\n\tstartedAt?: number\n\tcompletedAt?: number\n\tresult?: string\n\terror?: string\n\tsessionId?: string\n\tmetadata?: Record<string, unknown>\n}\n\nexport type TaskRunner = (task: AgentTask) => Promise<void>\n\nconst logger = createLogger('task-queue')\n\n/** FIFO task queue with configurable concurrency */\nexport class TaskQueue {\n\tprivate queue: AgentTask[] = []\n\tprivate running = new Map<string, AgentTask>()\n\tprivate completed: AgentTask[] = []\n\tprivate runner: TaskRunner | undefined\n\tprivate draining = false\n\n\tconstructor(\n\t\tprivate bus: MessageBus,\n\t\tprivate concurrency = 1,\n\t\tprivate rateLimiter?: RateLimiter,\n\t\tprivate rateLimits?: RateLimits,\n\t) {}\n\n\t/** Set the task runner function (called by the agent loop) */\n\tsetRunner(runner: TaskRunner): void {\n\t\tthis.runner = runner\n\t}\n\n\t/** Enqueue a new task */\n\tenqueue(\n\t\tinput: string,\n\t\tsource: 'user' | 'schedule' | 'heartbeat' | 'paw' = 'user',\n\t\toptions?: { sessionId?: string; metadata?: Record<string, unknown> },\n\t): AgentTask {\n\t\tconst task: AgentTask = {\n\t\t\tid: crypto.randomUUID(),\n\t\t\tsource,\n\t\t\tinput,\n\t\t\tstatus: 'queued',\n\t\t\tcreatedAt: Date.now(),\n\t\t\tsessionId: options?.sessionId,\n\t\t\tmetadata: options?.metadata,\n\t\t}\n\n\t\t// Check tasksPerHour rate limit (warn but still enqueue)\n\t\tif (this.rateLimiter && this.rateLimits?.tasksPerHour) {\n\t\t\tconst limit = this.rateLimits.tasksPerHour[source]\n\t\t\tif (limit != null) {\n\t\t\t\tconst bucket = `tasks:per-hour:${source}`\n\t\t\t\tif (!this.rateLimiter.tryConsume(bucket, limit, 3_600_000)) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`Rate limit warning: tasksPerHour for source \"${source}\" exceeded (limit: ${limit}). Task will still be enqueued.`,\n\t\t\t\t\t)\n\t\t\t\t\tthis.bus.emit('rate:limited', { bucket, source })\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthis.queue.push(task)\n\t\tlogger.info(`Task ${task.id} queued (source: ${source})`)\n\t\tthis.bus.emit('task:queued', { taskId: task.id })\n\t\tthis.drain()\n\t\treturn task\n\t}\n\n\t/** Cancel a task by ID */\n\tcancel(taskId: string): boolean {\n\t\t// Cancel from queue\n\t\tconst queueIdx = this.queue.findIndex((t) => t.id === taskId)\n\t\tif (queueIdx !== -1) {\n\t\t\tconst task = this.queue.splice(queueIdx, 1)[0]\n\t\t\ttask.status = 'cancelled'\n\t\t\ttask.completedAt = Date.now()\n\t\t\tthis.completed.push(task)\n\t\t\tlogger.info(`Task ${taskId} cancelled (was queued)`)\n\t\t\tthis.bus.emit('task:cancelled', { taskId })\n\t\t\treturn true\n\t\t}\n\n\t\t// Cancel running task (mark it — the loop must check this)\n\t\tconst running = this.running.get(taskId)\n\t\tif (running) {\n\t\t\trunning.status = 'cancelled'\n\t\t\tlogger.info(`Task ${taskId} marked for cancellation (running)`)\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/** Cancel all queued tasks (for shutdown) */\n\tcancelAll(): void {\n\t\twhile (this.queue.length > 0) {\n\t\t\tconst task = this.queue.shift()!\n\t\t\ttask.status = 'cancelled'\n\t\t\ttask.completedAt = Date.now()\n\t\t\tthis.completed.push(task)\n\t\t\tthis.bus.emit('task:cancelled', { taskId: task.id })\n\t\t}\n\t\t// Mark running tasks as cancelled\n\t\tfor (const task of this.running.values()) {\n\t\t\ttask.status = 'cancelled'\n\t\t}\n\t}\n\n\t/** Get all tasks (queued + running + completed) */\n\tlist(): AgentTask[] {\n\t\treturn [\n\t\t\t...this.queue,\n\t\t\t...Array.from(this.running.values()),\n\t\t\t...this.completed.slice(-50), // keep last 50 completed\n\t\t]\n\t}\n\n\t/** Get a task by ID */\n\tget(taskId: string): AgentTask | undefined {\n\t\treturn (\n\t\t\tthis.queue.find((t) => t.id === taskId) ??\n\t\t\tthis.running.get(taskId) ??\n\t\t\tthis.completed.find((t) => t.id === taskId)\n\t\t)\n\t}\n\n\t/** Check if a task has been cancelled */\n\tisCancelled(taskId: string): boolean {\n\t\tconst task = this.running.get(taskId)\n\t\treturn task?.status === 'cancelled'\n\t}\n\n\tprivate async drain(): Promise<void> {\n\t\tif (this.draining) return\n\t\tthis.draining = true\n\n\t\ttry {\n\t\t\twhile (this.queue.length > 0 && this.running.size < this.concurrency) {\n\t\t\t\tif (!this.runner) {\n\t\t\t\t\tlogger.error('No task runner configured')\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tconst task = this.queue.shift()!\n\t\t\t\ttask.status = 'running'\n\t\t\t\ttask.startedAt = Date.now()\n\t\t\t\tthis.running.set(task.id, task)\n\n\t\t\t\tlogger.info(`Task ${task.id} started`)\n\t\t\t\tthis.bus.emit('task:started', { taskId: task.id })\n\n\t\t\t\t// Run task without blocking the drain loop for concurrency > 1\n\t\t\t\tthis.runTask(task)\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.draining = false\n\t\t}\n\t}\n\n\tprivate async runTask(task: AgentTask): Promise<void> {\n\t\ttry {\n\t\t\tawait this.runner!(task)\n\t\t\tif (task.status !== 'cancelled') {\n\t\t\t\ttask.status = 'completed'\n\t\t\t}\n\t\t\ttask.completedAt = Date.now()\n\t\t\tlogger.info(`Task ${task.id} ${task.status}`)\n\t\t\tthis.bus.emit('task:completed', { taskId: task.id, result: task.result })\n\t\t} catch (err) {\n\t\t\ttask.status = 'failed'\n\t\t\ttask.completedAt = Date.now()\n\t\t\ttask.error = err instanceof Error ? err.message : String(err)\n\t\t\tlogger.error(`Task ${task.id} failed: ${task.error}`)\n\t\t\tthis.bus.emit('task:failed', { taskId: task.id, error: err })\n\t\t} finally {\n\t\t\tthis.running.delete(task.id)\n\t\t\tthis.completed.push(task)\n\t\t\t// Drain next tasks\n\t\t\tthis.drain()\n\t\t}\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport { Cron } from 'croner'\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('scheduler')\n\ninterface ScheduleEntry {\n\tid: string\n\tinput: string\n\t/** Cron expression (e.g. \"0 13 * * *\" for daily at 1 PM UTC) */\n\tcron: string\n\tjob: Cron\n\tcreatedAt: number\n}\n\n/** Persisted schedule data (no job handle) */\ninterface PersistedSchedule {\n\tid: string\n\tinput: string\n\tcron: string\n\tcreatedAt: number\n}\n\n/** Persistent store for recurring schedules using cron expressions */\nexport class SchedulerStore {\n\tprivate schedules = new Map<string, ScheduleEntry>()\n\tprivate savePath: string | undefined\n\tprivate tickHandler: ((input: string) => void) | undefined\n\n\t/** Set the file path for persistence */\n\tsetPersistence(filePath: string): void {\n\t\tthis.savePath = filePath\n\t}\n\n\t/** Set the handler called when a schedule ticks */\n\tsetTickHandler(handler: (input: string) => void): void {\n\t\tthis.tickHandler = handler\n\t}\n\n\t/** Load schedule data from disk without starting cron jobs (for read-only access). Never persists. */\n\tasync loadFromDisk(): Promise<void> {\n\t\tif (!this.savePath) return\n\t\tconst savedPath = this.savePath\n\t\t// Temporarily disable persistence so read-only access can't overwrite the file\n\t\tthis.savePath = undefined\n\t\ttry {\n\t\t\tconst raw = await fs.readFile(savedPath, 'utf-8')\n\t\t\tconst persisted = JSON.parse(raw) as PersistedSchedule[]\n\t\t\tfor (const s of persisted) {\n\t\t\t\tconst job = new Cron(s.cron, { timezone: 'UTC', paused: true }, () => {})\n\t\t\t\tthis.schedules.set(s.id, {\n\t\t\t\t\tid: s.id,\n\t\t\t\t\tinput: s.input,\n\t\t\t\t\tcron: s.cron,\n\t\t\t\t\tjob,\n\t\t\t\t\tcreatedAt: s.createdAt,\n\t\t\t\t})\n\t\t\t}\n\t\t} catch {\n\t\t\t// No file or invalid\n\t\t}\n\t\tthis.savePath = savedPath\n\t}\n\n\t/** Load persisted schedules from disk and restart their jobs */\n\tasync restore(): Promise<void> {\n\t\tif (!this.savePath || !this.tickHandler) return\n\n\t\ttry {\n\t\t\tconst raw = await fs.readFile(this.savePath, 'utf-8')\n\t\t\tconst persisted = JSON.parse(raw) as PersistedSchedule[]\n\n\t\t\tfor (const s of persisted) {\n\t\t\t\tthis.add(s.id, s.input, s.cron, () => {\n\t\t\t\t\tthis.tickHandler!(s.input)\n\t\t\t\t}, s.createdAt)\n\t\t\t}\n\n\t\t\tif (persisted.length > 0) {\n\t\t\t\tlogger.info(`Restored ${persisted.length} schedule(s) from disk`)\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tlogger.warn(`Could not restore schedules: ${err}`)\n\t\t}\n\t}\n\n\t/** Create or replace a recurring schedule */\n\tadd(\n\t\tid: string,\n\t\tinput: string,\n\t\tcron: string,\n\t\tonTick: () => void,\n\t\tcreatedAt?: number,\n\t\timmediate = false,\n\t): void {\n\t\t// Cancel existing schedule with same ID (idempotent upsert)\n\t\tif (this.schedules.has(id)) {\n\t\t\tthis.cancel(id, true)\n\t\t}\n\n\t\tif (immediate) {\n\t\t\tsetTimeout(onTick, 0)\n\t\t}\n\n\t\tconst job = new Cron(cron, { timezone: 'UTC' }, onTick)\n\n\t\tthis.schedules.set(id, {\n\t\t\tid,\n\t\t\tinput,\n\t\t\tcron,\n\t\t\tjob,\n\t\t\tcreatedAt: createdAt ?? Date.now(),\n\t\t})\n\n\t\tconst next = job.nextRun()\n\t\tlogger.info(`Schedule \"${id}\" created — cron: ${cron} (next: ${next?.toISOString() ?? 'unknown'}): \"${input.substring(0, 80)}\"`)\n\t\tthis.persist()\n\t}\n\n\t/** Cancel a schedule by ID */\n\tcancel(id: string, skipPersist = false): boolean {\n\t\tconst entry = this.schedules.get(id)\n\t\tif (!entry) return false\n\n\t\tentry.job.stop()\n\t\tthis.schedules.delete(id)\n\t\tlogger.info(`Schedule \"${id}\" cancelled`)\n\t\tif (!skipPersist) this.persist()\n\t\treturn true\n\t}\n\n\t/** List all active schedules */\n\tlist(): Array<{ id: string; input: string; cron: string; nextRun?: string; createdAt: number }> {\n\t\treturn Array.from(this.schedules.values()).map(({ id, input, cron, job, createdAt }) => ({\n\t\t\tid,\n\t\t\tinput,\n\t\t\tcron,\n\t\t\tnextRun: job.nextRun()?.toISOString(),\n\t\t\tcreatedAt,\n\t\t}))\n\t}\n\n\t/** Clear all schedules (for shutdown). Disables persistence so the file is never overwritten. */\n\tclearAll(): void {\n\t\tthis.savePath = undefined\n\t\tfor (const entry of this.schedules.values()) {\n\t\t\tentry.job.stop()\n\t\t}\n\t\tthis.schedules.clear()\n\t\tlogger.info('All schedules cleared')\n\t}\n\n\t/** Save schedules to disk */\n\tprivate async persist(): Promise<void> {\n\t\t// Snapshot path and data synchronously so concurrent clearAll() can't interfere\n\t\tconst targetPath = this.savePath\n\t\tif (!targetPath) return\n\n\t\t// Don't persist the heartbeat — it's recreated from config on startup\n\t\tconst toSave: PersistedSchedule[] = Array.from(this.schedules.values())\n\t\t\t.filter((s) => s.id !== '__heartbeat__')\n\t\t\t.map(({ id, input, cron, createdAt }) => ({\n\t\t\t\tid,\n\t\t\t\tinput,\n\t\t\t\tcron,\n\t\t\t\tcreatedAt,\n\t\t\t}))\n\n\t\t// Safety: never overwrite a non-empty file with an empty array.\n\t\t// If we have nothing to save but the file has schedules, skip the write.\n\t\tif (toSave.length === 0) {\n\t\t\ttry {\n\t\t\t\tconst existing = await fs.readFile(targetPath, 'utf-8')\n\t\t\t\tconst parsed = JSON.parse(existing) as unknown[]\n\t\t\t\tif (parsed.length > 0) {\n\t\t\t\t\tlogger.warn(`Refusing to overwrite ${parsed.length} persisted schedule(s) with empty list`)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// File doesn't exist or is invalid — safe to write []\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tawait fs.mkdir(path.dirname(targetPath), { recursive: true })\n\t\t\tawait fs.writeFile(targetPath, JSON.stringify(toSave, null, 2) + '\\n', 'utf-8')\n\t\t\tlogger.debug(`Persisted ${toSave.length} schedule(s) to disk`)\n\t\t} catch (err) {\n\t\t\tlogger.error(`Failed to persist schedules: ${err}`)\n\t\t}\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport * as crypto from 'node:crypto'\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('vault')\n\nexport interface VaultEntry {\n\tvalue: string // encrypted if VOLE_VAULT_KEY is set, plain text otherwise\n\tsource: 'user' | 'tool' | 'brain'\n\tcreatedAt: number\n\t/** Optional metadata — context about the stored value (service, handle, url, etc.) */\n\tmeta?: Record<string, string>\n}\n\nexport class Vault {\n\tprivate entries: Map<string, VaultEntry> = new Map()\n\tprivate vaultPath: string\n\tprivate encryptionKey?: Buffer\n\n\tconstructor(vaultPath: string, encryptionKey?: string) {\n\t\tthis.vaultPath = vaultPath\n\t\tif (encryptionKey) {\n\t\t\t// Derive a 32-byte key from the provided string using SHA-256\n\t\t\tthis.encryptionKey = crypto.createHash('sha256').update(encryptionKey).digest()\n\t\t}\n\t}\n\n\tasync init(): Promise<void> {\n\t\tif (!this.encryptionKey) {\n\t\t\tlogger.debug('VOLE_VAULT_KEY not set — vault values will be stored in plain text')\n\t\t}\n\n\t\ttry {\n\t\t\tconst raw = await fs.readFile(this.vaultPath, 'utf-8')\n\t\t\tconst data = JSON.parse(raw) as Record<string, VaultEntry>\n\t\t\tthis.entries = new Map(Object.entries(data))\n\t\t} catch {\n\t\t\t// File doesn't exist or is invalid — start fresh\n\t\t\tthis.entries = new Map()\n\t\t}\n\t}\n\n\tasync store(key: string, value: string, source: string = 'brain', meta?: Record<string, string>): Promise<boolean> {\n\t\tif (this.entries.has(key)) {\n\t\t\treturn false // write-once\n\t\t}\n\n\t\tconst entry: VaultEntry = {\n\t\t\tvalue: this.encrypt(value),\n\t\t\tsource: source as VaultEntry['source'],\n\t\t\tcreatedAt: Date.now(),\n\t\t\t...(meta && Object.keys(meta).length > 0 ? { meta } : {}),\n\t\t}\n\t\tthis.entries.set(key, entry)\n\t\tawait this.save()\n\t\treturn true\n\t}\n\n\tasync get(key: string): Promise<string | null> {\n\t\tconst entry = this.entries.get(key)\n\t\tif (!entry) return null\n\t\treturn this.decrypt(entry.value)\n\t}\n\n\tasync list(): Promise<Array<{ key: string; source: string; createdAt: number; meta?: Record<string, string> }>> {\n\t\tconst result: Array<{ key: string; source: string; createdAt: number; meta?: Record<string, string> }> = []\n\t\tfor (const [key, entry] of this.entries) {\n\t\t\tresult.push({ key, source: entry.source, createdAt: entry.createdAt, meta: entry.meta })\n\t\t}\n\t\treturn result\n\t}\n\n\tasync delete(key: string): Promise<boolean> {\n\t\tif (!this.entries.has(key)) return false\n\t\tthis.entries.delete(key)\n\t\tawait this.save()\n\t\treturn true\n\t}\n\n\tprivate async save(): Promise<void> {\n\t\tconst dir = path.dirname(this.vaultPath)\n\t\tawait fs.mkdir(dir, { recursive: true })\n\t\tconst obj: Record<string, VaultEntry> = Object.fromEntries(this.entries)\n\t\tawait fs.writeFile(this.vaultPath, JSON.stringify(obj, null, 2) + '\\n', 'utf-8')\n\t}\n\n\tprivate encrypt(value: string): string {\n\t\tif (!this.encryptionKey) return value\n\n\t\tconst iv = crypto.randomBytes(12)\n\t\tconst cipher = crypto.createCipheriv('aes-256-gcm', this.encryptionKey, iv)\n\t\tconst encrypted = Buffer.concat([cipher.update(value, 'utf-8'), cipher.final()])\n\t\tconst authTag = cipher.getAuthTag()\n\n\t\treturn `${iv.toString('base64')}:${authTag.toString('base64')}:${encrypted.toString('base64')}`\n\t}\n\n\tprivate decrypt(value: string): string {\n\t\tif (!this.encryptionKey) return value\n\n\t\t// Check if value looks like encrypted format (iv:authTag:encrypted)\n\t\tconst parts = value.split(':')\n\t\tif (parts.length !== 3) return value // not encrypted, return as-is\n\n\t\tconst [ivB64, authTagB64, encryptedB64] = parts\n\t\tconst iv = Buffer.from(ivB64, 'base64')\n\t\tconst authTag = Buffer.from(authTagB64, 'base64')\n\t\tconst encrypted = Buffer.from(encryptedB64, 'base64')\n\n\t\tconst decipher = crypto.createDecipheriv('aes-256-gcm', this.encryptionKey, iv)\n\t\tdecipher.setAuthTag(authTag)\n\t\treturn Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf-8')\n\t}\n}\n","import type { ToolDefinition, ToolRegistryEntry } from './types.js'\nimport type { ToolSummary } from '../context/types.js'\nimport type { MessageBus } from '../core/bus.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('tool-registry')\n\n/** Convert a Zod schema to a serializable JSON Schema object */\nfunction zodToJsonSchema(schema: unknown): Record<string, unknown> | undefined {\n\tif (!schema || typeof schema !== 'object') return undefined\n\n\ttry {\n\t\tconst zodSchema = schema as { _def?: { shape?: () => Record<string, unknown> }; shape?: Record<string, unknown> }\n\t\tconst shape = typeof zodSchema._def?.shape === 'function' ? zodSchema._def.shape() : zodSchema.shape\n\t\tif (!shape || typeof shape !== 'object') return undefined\n\n\t\tconst properties: Record<string, unknown> = {}\n\t\tconst required: string[] = []\n\n\t\tfor (const [key, val] of Object.entries(shape)) {\n\t\t\tconst field = val as { _def?: { typeName?: string; description?: string; innerType?: { _def?: { typeName?: string; values?: string[] } }; values?: string[] } }\n\t\t\tconst isOptional = field?._def?.typeName === 'ZodOptional' || field?._def?.typeName === 'ZodDefault'\n\t\t\tconst inner = isOptional ? field?._def?.innerType?._def : field?._def\n\t\t\tconst typeName = inner?.typeName\n\n\t\t\tlet type = 'string'\n\t\t\tif (typeName === 'ZodNumber') type = 'number'\n\t\t\telse if (typeName === 'ZodBoolean') type = 'boolean'\n\t\t\telse if (typeName === 'ZodRecord') type = 'object'\n\n\t\t\tconst prop: Record<string, unknown> = { type }\n\t\t\tconst description = field?._def?.description\n\t\t\tif (description) prop.description = description\n\t\t\tif (typeName === 'ZodEnum') {\n\t\t\t\tprop.enum = inner?.values\n\t\t\t}\n\n\t\t\tproperties[key] = prop\n\t\t\tif (!isOptional) required.push(key)\n\t\t}\n\n\t\treturn {\n\t\t\ttype: 'object',\n\t\t\tproperties,\n\t\t\t...(required.length > 0 ? { required } : {}),\n\t\t}\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nexport class ToolRegistry {\n\tprivate tools = new Map<string, ToolRegistryEntry>()\n\n\tconstructor(private bus: MessageBus) {}\n\n\t/** Register tools from a Paw. Skips tools with conflicting names. */\n\tregister(pawName: string, tools: ToolDefinition[], inProcess: boolean): void {\n\t\tfor (const tool of tools) {\n\t\t\tif (this.tools.has(tool.name)) {\n\t\t\t\tconst existing = this.tools.get(tool.name)!\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`Tool name conflict: \"${tool.name}\" already registered by \"${existing.pawName}\", ` +\n\t\t\t\t\t\t`ignoring registration from \"${pawName}\"`,\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tthis.tools.set(tool.name, {\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tparameters: tool.parameters,\n\t\t\t\tpawName,\n\t\t\t\tinProcess,\n\t\t\t\texecute: tool.execute,\n\t\t\t})\n\n\t\t\tlogger.debug(`Registered tool \"${tool.name}\" from \"${pawName}\"`)\n\t\t\tthis.bus.emit('tool:registered', { toolName: tool.name, pawName })\n\t\t}\n\t}\n\n\t/** Remove all tools owned by a specific Paw */\n\tunregister(pawName: string): void {\n\t\tconst toRemove: string[] = []\n\t\tfor (const [name, entry] of this.tools) {\n\t\t\tif (entry.pawName === pawName) {\n\t\t\t\ttoRemove.push(name)\n\t\t\t}\n\t\t}\n\n\t\tfor (const name of toRemove) {\n\t\t\tthis.tools.delete(name)\n\t\t\tlogger.info(`Unregistered tool \"${name}\" from \"${pawName}\"`)\n\t\t\tthis.bus.emit('tool:unregistered', { toolName: name, pawName })\n\t\t}\n\t}\n\n\t/** Get a tool entry by name */\n\tget(toolName: string): ToolRegistryEntry | undefined {\n\t\treturn this.tools.get(toolName)\n\t}\n\n\t/** List all registered tools */\n\tlist(): ToolRegistryEntry[] {\n\t\treturn Array.from(this.tools.values())\n\t}\n\n\t/** Check if a tool exists */\n\thas(toolName: string): boolean {\n\t\treturn this.tools.has(toolName)\n\t}\n\n\t/** Get tool summaries for AgentContext */\n\tsummaries(): ToolSummary[] {\n\t\treturn this.list().map((t) => ({\n\t\t\tname: t.name,\n\t\t\tdescription: t.description,\n\t\t\tpawName: t.pawName,\n\t\t\tparameters: zodToJsonSchema(t.parameters),\n\t\t}))\n\t}\n\n\t/** Get all tool names owned by a specific Paw */\n\ttoolsForPaw(pawName: string): string[] {\n\t\treturn this.list()\n\t\t\t.filter((t) => t.pawName === pawName)\n\t\t\t.map((t) => t.name)\n\t}\n\n\t/** Clear all tools (for shutdown) */\n\tclear(): void {\n\t\tthis.tools.clear()\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport { accessSync } from 'node:fs'\nimport * as path from 'node:path'\nimport { z } from 'zod'\nimport type { PawManifest } from './types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-manifest')\n\n/** Schema for vole-paw.json */\nconst pawManifestSchema = z.object({\n\tname: z.string().min(1),\n\tversion: z.string().min(1),\n\tdescription: z.string(),\n\tentry: z.string().min(1),\n\tbrain: z.boolean().default(false),\n\tinProcess: z.boolean().optional().default(false),\n\ttransport: z.enum(['ipc', 'stdio']).optional().default('ipc'),\n\ttools: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string().min(1),\n\t\t\t\tdescription: z.string(),\n\t\t\t}),\n\t\t)\n\t\t.default([]),\n\tpermissions: z\n\t\t.object({\n\t\t\tnetwork: z.array(z.string()).optional().default([]),\n\t\t\tlisten: z.array(z.number().int().positive()).optional().default([]),\n\t\t\tfilesystem: z.array(z.string()).optional().default([]),\n\t\t\tenv: z.array(z.string()).optional().default([]),\n\t\t})\n\t\t.optional()\n\t\t.default({}),\n})\n\n/** Resolve a Paw package path from its name */\nexport function resolvePawPath(name: string, projectRoot: string): string {\n\tif (name.startsWith('.') || name.startsWith('/')) {\n\t\treturn path.resolve(projectRoot, name)\n\t}\n\t// Try .openvole/paws/<name> first, then node_modules\n\tconst openvoleDir = path.resolve(projectRoot, '.openvole', 'paws', name)\n\ttry {\n\t\taccessSync(path.join(openvoleDir, 'vole-paw.json'))\n\t\treturn openvoleDir\n\t} catch {\n\t\t// Not found — fall through to node_modules\n\t}\n\treturn path.resolve(projectRoot, 'node_modules', name)\n}\n\n/** Read and validate a vole-paw.json manifest */\nexport async function readPawManifest(\n\tpawPath: string,\n): Promise<PawManifest | null> {\n\tconst manifestPath = path.join(pawPath, 'vole-paw.json')\n\n\ttry {\n\t\tconst raw = await fs.readFile(manifestPath, 'utf-8')\n\t\tconst parsed = JSON.parse(raw)\n\t\tconst result = pawManifestSchema.safeParse(parsed)\n\n\t\tif (!result.success) {\n\t\t\tlogger.error(\n\t\t\t\t'Invalid manifest at %s: %s',\n\t\t\t\tmanifestPath,\n\t\t\t\tresult.error.message,\n\t\t\t)\n\t\t\treturn null\n\t\t}\n\n\t\treturn result.data as PawManifest\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\tlogger.error('Manifest not found: %s', manifestPath)\n\t\t} else {\n\t\t\tlogger.error('Failed to read manifest %s: %s', manifestPath, err)\n\t\t}\n\t\treturn null\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport { parse as parseYaml } from 'yaml'\nimport type { SkillDefinition } from './types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('skill-loader')\n\n/** Parse a SKILL.md file into a SkillDefinition */\nexport async function loadSkillFromDirectory(\n\tskillDir: string,\n): Promise<SkillDefinition | null> {\n\tconst skillMdPath = path.join(skillDir, 'SKILL.md')\n\n\ttry {\n\t\tconst raw = await fs.readFile(skillMdPath, 'utf-8')\n\t\treturn parseSkillMd(raw, skillMdPath)\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n\t\t\tlogger.error('SKILL.md not found: %s', skillMdPath)\n\t\t} else {\n\t\t\tlogger.error('Failed to read SKILL.md at %s: %s', skillMdPath, err)\n\t\t}\n\t\treturn null\n\t}\n}\n\n/** Parse SKILL.md content (YAML frontmatter + markdown body) */\nfunction parseSkillMd(\n\tcontent: string,\n\tfilePath: string,\n): SkillDefinition | null {\n\tconst { frontmatter, body } = extractFrontmatter(content)\n\n\tif (!frontmatter) {\n\t\tlogger.error('No YAML frontmatter found in %s', filePath)\n\t\treturn null\n\t}\n\n\tlet meta: Record<string, unknown>\n\ttry {\n\t\tmeta = parseYaml(frontmatter) as Record<string, unknown>\n\t} catch (err) {\n\t\tlogger.error('Invalid YAML frontmatter in %s: %s', filePath, err)\n\t\treturn null\n\t}\n\n\tif (!meta.name || typeof meta.name !== 'string') {\n\t\tlogger.error('SKILL.md missing \"name\" in frontmatter: %s', filePath)\n\t\treturn null\n\t}\n\n\tif (!meta.description || typeof meta.description !== 'string') {\n\t\tlogger.error('SKILL.md missing \"description\" in frontmatter: %s', filePath)\n\t\treturn null\n\t}\n\n\tconst instructions = body.trim()\n\tif (!instructions) {\n\t\tlogger.error('SKILL.md has no instructions (empty body): %s', filePath)\n\t\treturn null\n\t}\n\n\t// Extract OpenClaw metadata if present\n\tconst openclaw = extractOpenClawMetadata(meta)\n\n\treturn {\n\t\tname: meta.name as string,\n\t\tdescription: meta.description as string,\n\t\tversion: typeof meta.version === 'string'\n\t\t\t? meta.version\n\t\t\t: typeof meta.version === 'number'\n\t\t\t\t? String(meta.version)\n\t\t\t\t: undefined,\n\t\trequiredTools: toStringArray(meta.requiredTools),\n\t\toptionalTools: toStringArray(meta.optionalTools),\n\t\tinstructions,\n\t\ttags: toStringArray(meta.tags),\n\t\t// OpenClaw compatibility fields\n\t\trequires: openclaw.requires,\n\t}\n}\n\n/**\n * Extract OpenClaw-specific metadata from frontmatter.\n *\n * OpenClaw skills use this structure:\n * metadata:\n * openclaw:\n * requires:\n * env: [TODOIST_API_KEY]\n * bins: [curl]\n * anyBins: [python3, python]\n * config: [browser.enabled]\n * primaryEnv: TODOIST_API_KEY\n * emoji: \"✅\"\n *\n * Or as inline JSON:\n * metadata: { \"openclaw\": { \"requires\": { \"bins\": [\"uv\"] } } }\n */\nfunction extractOpenClawMetadata(meta: Record<string, unknown>): {\n\trequires: SkillDefinition['requires']\n} {\n\tconst metadata = meta.metadata as Record<string, unknown> | undefined\n\tif (!metadata) return { requires: undefined }\n\n\t// Support both \"openclaw\" and \"clawdbot\" (legacy name)\n\tconst oc = (metadata.openclaw ?? metadata.clawdbot) as Record<string, unknown> | undefined\n\tif (!oc) return { requires: undefined }\n\n\tconst req = oc.requires as Record<string, unknown> | undefined\n\tif (!req) return { requires: undefined }\n\n\treturn {\n\t\trequires: {\n\t\t\tenv: toStringArray(req.env),\n\t\t\tbins: toStringArray(req.bins),\n\t\t\tanyBins: toStringArray(req.anyBins),\n\t\t},\n\t}\n}\n\n/** Extract YAML frontmatter and markdown body from a file */\nfunction extractFrontmatter(content: string): {\n\tfrontmatter: string | null\n\tbody: string\n} {\n\tconst match = content.match(/^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/)\n\tif (!match) {\n\t\treturn { frontmatter: null, body: content }\n\t}\n\treturn { frontmatter: match[1], body: match[2] }\n}\n\n/** Safely convert a value to string[] */\nfunction toStringArray(value: unknown): string[] {\n\tif (!value) return []\n\tif (Array.isArray(value)) return value.filter((v) => typeof v === 'string')\n\treturn []\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport type { MessageBus } from '../core/bus.js'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { SkillInstance } from './types.js'\nimport { loadSkillFromDirectory } from './loader.js'\nimport { resolveSkills } from './resolver.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('skill-registry')\n\n/**\n * Resolve a Skill directory path from its name.\n * Resolution order:\n * 1. Explicit path (./ or /) — use as-is\n * 2. skills/<name> — local skills\n * 3. skills/clawhub/<name> — ClawHub-installed skills\n * 4. node_modules/<name> — npm-installed skills\n */\nasync function resolveSkillPath(name: string, projectRoot: string): Promise<string> {\n\t// Explicit path (./ or /)\n\tif (name.startsWith('.') || name.startsWith('/')) {\n\t\treturn path.resolve(projectRoot, name)\n\t}\n\n\t// clawhub/<name> format → .openvole/skills/clawhub/<name>\n\tif (name.startsWith('clawhub/')) {\n\t\treturn path.resolve(projectRoot, '.openvole', 'skills', name)\n\t}\n\n\t// Try .openvole/skills/<name> (local skills)\n\tconst localPath = path.resolve(projectRoot, '.openvole', 'skills', name)\n\tif (await exists(path.join(localPath, 'SKILL.md'))) return localPath\n\n\t// Try .openvole/skills/clawhub/<name> (ClawHub-installed)\n\tconst clawHubPath = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', name)\n\tif (await exists(path.join(clawHubPath, 'SKILL.md'))) return clawHubPath\n\n\t// Fall back to node_modules\n\treturn path.resolve(projectRoot, 'node_modules', name)\n}\n\nasync function exists(filePath: string): Promise<boolean> {\n\ttry {\n\t\tawait fs.access(filePath)\n\t\treturn true\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/** Manages loaded Skills and their activation state */\nexport class SkillRegistry {\n\tprivate skills = new Map<string, SkillInstance>()\n\n\tconstructor(\n\t\tprivate bus: MessageBus,\n\t\tprivate toolRegistry: ToolRegistry,\n\t\tprivate projectRoot: string,\n\t) {\n\t\t// Re-run resolver when tools change\n\t\tthis.bus.on('tool:registered', () => this.resolve())\n\t\tthis.bus.on('tool:unregistered', () => this.resolve())\n\t}\n\n\t/** Load a Skill from a directory containing SKILL.md */\n\tasync load(nameOrPath: string): Promise<boolean> {\n\t\tconst skillDir = await resolveSkillPath(nameOrPath, this.projectRoot)\n\t\tconst definition = await loadSkillFromDirectory(skillDir)\n\n\t\tif (!definition) {\n\t\t\treturn false\n\t\t}\n\n\t\t// Use the config key as the registry key to avoid collisions\n\t\t// clawhub/summarize → \"clawhub/summarize\", email-triage → \"email-triage\"\n\t\tconst registryKey = nameOrPath.startsWith('.') || nameOrPath.startsWith('/')\n\t\t\t? definition.name\n\t\t\t: nameOrPath\n\n\t\tif (this.skills.has(registryKey)) {\n\t\t\tlogger.warn(`Skill \"${registryKey}\" is already loaded`)\n\t\t\treturn false\n\t\t}\n\n\t\tconst instance: SkillInstance = {\n\t\t\tname: registryKey,\n\t\t\tdefinition,\n\t\t\tpath: skillDir,\n\t\t\tactive: false,\n\t\t\tmissingTools: [...definition.requiredTools],\n\t\t}\n\n\t\tthis.skills.set(registryKey, instance)\n\t\tlogger.info(`Skill \"${registryKey}\" loaded from ${skillDir}`)\n\n\t\t// Run resolver to check activation\n\t\tthis.resolve()\n\t\treturn true\n\t}\n\n\t/** Unload a Skill */\n\tunload(name: string): boolean {\n\t\tif (!this.skills.has(name)) {\n\t\t\treturn false\n\t\t}\n\t\tthis.skills.delete(name)\n\t\tlogger.info(`Skill \"${name}\" unloaded`)\n\t\treturn true\n\t}\n\n\t/** Re-run the resolver against the current tool registry */\n\tresolve(): void {\n\t\tresolveSkills(Array.from(this.skills.values()), this.toolRegistry)\n\t}\n\n\t/** Get all Skill instances */\n\tlist(): SkillInstance[] {\n\t\treturn Array.from(this.skills.values())\n\t}\n\n\t/** Get active Skills only */\n\tactive(): SkillInstance[] {\n\t\treturn this.list().filter((s) => s.active)\n\t}\n\n\t/** Get a Skill by name */\n\tget(name: string): SkillInstance | undefined {\n\t\treturn this.skills.get(name)\n\t}\n}\n","import * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\nimport { z } from 'zod'\nimport type { ToolDefinition } from './types.js'\nimport type { SchedulerStore } from '../core/scheduler.js'\nimport type { TaskQueue } from '../core/task.js'\nimport type { SkillRegistry } from '../skill/registry.js'\nimport type { Vault } from '../core/vault.js'\n\n/** Create the built-in core tools that are always available to the Brain */\nexport function createCoreTools(\n\tscheduler: SchedulerStore,\n\ttaskQueue: TaskQueue,\n\tprojectRoot: string,\n\tskillRegistry: SkillRegistry,\n\tvault: Vault,\n): ToolDefinition[] {\n\tconst heartbeatPath = path.resolve(projectRoot, '.openvole', 'HEARTBEAT.md')\n\tconst workspaceDir = path.resolve(projectRoot, '.openvole', 'workspace')\n\n\t/** Validate that a resolved path stays inside the workspace directory */\n\tfunction resolveWorkspacePath(relativePath: string): string | null {\n\t\tconst resolved = path.resolve(workspaceDir, relativePath)\n\t\tif (!resolved.startsWith(workspaceDir + path.sep) && resolved !== workspaceDir) {\n\t\t\treturn null\n\t\t}\n\t\treturn resolved\n\t}\n\n\treturn [\n\t\t// === Scheduling tools ===\n\t\t{\n\t\t\tname: 'schedule_task',\n\t\t\tdescription: 'Create a recurring scheduled task using a cron expression. Examples: \"0 13 * * *\" = daily at 1 PM UTC, \"*/30 * * * *\" = every 30 minutes, \"0 9 * * 1\" = every Monday at 9 AM UTC.',\n\t\t\tparameters: z.object({\n\t\t\t\tid: z.string().describe('Unique schedule ID (for cancellation)'),\n\t\t\t\tinput: z.string().describe('The task input to enqueue each time'),\n\t\t\t\tcron: z.string().describe('Cron expression in UTC (minute hour day month weekday). Examples: \"0 13 * * *\" for daily 1 PM, \"*/30 * * * *\" for every 30 min'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { id, input, cron } = params as {\n\t\t\t\t\tid: string\n\t\t\t\t\tinput: string\n\t\t\t\t\tcron: string\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tscheduler.add(id, input, cron, () => {\n\t\t\t\t\t\ttaskQueue.enqueue(input, 'schedule')\n\t\t\t\t\t})\n\t\t\t\t\tconst schedules = scheduler.list()\n\t\t\t\t\tconst entry = schedules.find((s) => s.id === id)\n\t\t\t\t\treturn { ok: true, id, cron, nextRun: entry?.nextRun }\n\t\t\t\t} catch (err) {\n\t\t\t\t\treturn { ok: false, error: `Invalid cron expression: ${err instanceof Error ? err.message : err}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'cancel_schedule',\n\t\t\tdescription: 'Cancel a previously created scheduled task',\n\t\t\tparameters: z.object({\n\t\t\t\tid: z.string().describe('Schedule ID to cancel'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { id } = params as { id: string }\n\t\t\t\tconst cancelled = scheduler.cancel(id)\n\t\t\t\treturn { ok: cancelled, id }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'list_schedules',\n\t\t\tdescription: 'List all active scheduled tasks with cron expression and next run time',\n\t\t\tparameters: z.object({}),\n\t\t\tasync execute() {\n\t\t\t\treturn scheduler.list()\n\t\t\t},\n\t\t},\n\n\t\t// === Heartbeat tools ===\n\t\t{\n\t\t\tname: 'heartbeat_read',\n\t\t\tdescription: 'Read the HEARTBEAT.md file containing recurring job definitions',\n\t\t\tparameters: z.object({}),\n\t\t\tasync execute() {\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(heartbeatPath, 'utf-8')\n\t\t\t\t\treturn { ok: true, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: true, content: '' }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'heartbeat_write',\n\t\t\tdescription: 'Update the HEARTBEAT.md file with new recurring job definitions',\n\t\t\tparameters: z.object({\n\t\t\t\tcontent: z.string().describe('The full content to write to HEARTBEAT.md'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { content } = params as { content: string }\n\t\t\t\tawait fs.writeFile(heartbeatPath, content, 'utf-8')\n\t\t\t\treturn { ok: true }\n\t\t\t},\n\t\t},\n\n\t\t// === Skill tools (on-demand loading) ===\n\t\t{\n\t\t\tname: 'skill_read',\n\t\t\tdescription: 'Read the full SKILL.md instructions for a skill by name. Use this when a skill is relevant to the current task.',\n\t\t\tparameters: z.object({\n\t\t\t\tname: z.string().describe('Skill name to read'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { name } = params as { name: string }\n\t\t\t\tconst skill = skillRegistry.get(name)\n\t\t\t\tif (!skill) {\n\t\t\t\t\treturn { ok: false, error: `Skill \"${name}\" not found` }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(\n\t\t\t\t\t\tpath.join(skill.path, 'SKILL.md'),\n\t\t\t\t\t\t'utf-8',\n\t\t\t\t\t)\n\t\t\t\t\treturn { ok: true, name, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `Failed to read SKILL.md for \"${name}\"` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'skill_read_reference',\n\t\t\tdescription: 'Read a reference file from a skill\\'s references/ directory. Use this for API docs, schemas, or detailed guides.',\n\t\t\tparameters: z.object({\n\t\t\t\tname: z.string().describe('Skill name'),\n\t\t\t\tfile: z.string().describe('File path relative to the skill\\'s references/ directory'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { name, file } = params as { name: string; file: string }\n\t\t\t\tconst skill = skillRegistry.get(name)\n\t\t\t\tif (!skill) {\n\t\t\t\t\treturn { ok: false, error: `Skill \"${name}\" not found` }\n\t\t\t\t}\n\t\t\t\t// Prevent path traversal\n\t\t\t\tconst resolved = path.resolve(skill.path, 'references', file)\n\t\t\t\tif (!resolved.startsWith(path.resolve(skill.path, 'references'))) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid file path' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(resolved, 'utf-8')\n\t\t\t\t\treturn { ok: true, name, file, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `File not found: references/${file}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'skill_list_files',\n\t\t\tdescription: 'List all files in a skill\\'s directory including scripts, references, and assets.',\n\t\t\tparameters: z.object({\n\t\t\t\tname: z.string().describe('Skill name'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { name } = params as { name: string }\n\t\t\t\tconst skill = skillRegistry.get(name)\n\t\t\t\tif (!skill) {\n\t\t\t\t\treturn { ok: false, error: `Skill \"${name}\" not found` }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst files = await listFilesRecursive(skill.path)\n\t\t\t\t\treturn { ok: true, name, files }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `Failed to list files for \"${name}\"` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\n\t\t// === Workspace tools ===\n\t\t{\n\t\t\tname: 'workspace_write',\n\t\t\tdescription: 'Write a file to the workspace scratch space (.openvole/workspace/). Creates parent directories automatically.',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('File path relative to the workspace directory'),\n\t\t\t\tfile: z.string().optional().describe('Alias for path'),\n\t\t\t\tcontent: z.string().describe('Content to write to the file'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst p = params as { path?: string; file?: string; content: string }\n\t\t\t\tconst relPath = p.path ?? p.file\n\t\t\t\tconst content = p.content\n\t\t\t\tif (!relPath) return { ok: false, error: 'Missing path or file parameter' }\n\t\t\t\tconst resolved = resolveWorkspacePath(relPath)\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\tawait fs.mkdir(path.dirname(resolved), { recursive: true })\n\t\t\t\tawait fs.writeFile(resolved, content, 'utf-8')\n\t\t\t\treturn { ok: true, path: relPath }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'workspace_read',\n\t\t\tdescription: 'Read a file from the workspace scratch space (.openvole/workspace/).',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('File path relative to the workspace directory'),\n\t\t\t\tfile: z.string().optional().describe('Alias for path'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst p = params as { path?: string; file?: string }\n\t\t\t\tconst relPath = p.path ?? p.file\n\t\t\t\tif (!relPath) return { ok: false, error: 'Missing path or file parameter' }\n\t\t\t\tconst resolved = resolveWorkspacePath(relPath)\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst content = await fs.readFile(resolved, 'utf-8')\n\t\t\t\t\treturn { ok: true, content }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `File not found: ${relPath}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'workspace_list',\n\t\t\tdescription: 'List files and directories in the workspace scratch space (.openvole/workspace/). Returns recursive listing with file sizes.',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('Subdirectory to list (relative to workspace root). Defaults to root.'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { path: relPath } = params as { path?: string }\n\t\t\t\tconst resolved = relPath ? resolveWorkspacePath(relPath) : workspaceDir\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst files = await listFilesWithSizes(resolved)\n\t\t\t\t\treturn { ok: true, files }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: true, files: [] }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'workspace_delete',\n\t\t\tdescription: 'Delete a file or directory from the workspace scratch space (.openvole/workspace/).',\n\t\t\tparameters: z.object({\n\t\t\t\tpath: z.string().optional().describe('File or directory path relative to the workspace directory'),\n\t\t\t\tfile: z.string().optional().describe('Alias for path'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst p = params as { path?: string; file?: string }\n\t\t\t\tconst relPath = p.path ?? p.file\n\t\t\t\tif (!relPath) return { ok: false, error: 'Missing path or file parameter' }\n\t\t\t\tconst resolved = resolveWorkspacePath(relPath)\n\t\t\t\tif (!resolved) {\n\t\t\t\t\treturn { ok: false, error: 'Invalid path — must stay inside workspace directory' }\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tawait fs.rm(resolved, { recursive: true })\n\t\t\t\t\treturn { ok: true }\n\t\t\t\t} catch {\n\t\t\t\t\treturn { ok: false, error: `Not found: ${relPath}` }\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\n\t\t// === Vault tools ===\n\t\t{\n\t\t\tname: 'vault_store',\n\t\t\tdescription: 'Store a key-value pair in the secure vault with context metadata. Write-once: fails if key already exists (delete first to update).',\n\t\t\tparameters: z.object({\n\t\t\t\tkey: z.string().describe('Key name for the stored value'),\n\t\t\t\tvalue: z.string().describe('Value to store (will be encrypted if VOLE_VAULT_KEY is set)'),\n\t\t\t\tsource: z.enum(['user', 'tool', 'brain']).optional().describe('Who stored this value. Defaults to brain.'),\n\t\t\t\tmeta: z.record(z.string()).optional().describe('Context metadata — e.g. { \"service\": \"vibegigs\", \"handle\": \"bumblebee\", \"url\": \"https://vibegigs.com\" }'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { key, value, source, meta } = params as { key: string; value: string; source?: string; meta?: Record<string, string> }\n\t\t\t\tconst ok = await vault.store(key, value, source ?? 'brain', meta)\n\t\t\t\tif (!ok) {\n\t\t\t\t\treturn { ok: false, error: 'Key already exists' }\n\t\t\t\t}\n\t\t\t\treturn { ok: true, key }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'vault_get',\n\t\t\tdescription: 'Retrieve a value from the secure vault by key.',\n\t\t\tparameters: z.object({\n\t\t\t\tkey: z.string().describe('Key name to retrieve'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { key } = params as { key: string }\n\t\t\t\tconst value = await vault.get(key)\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn { ok: false, error: `Key not found: ${key}` }\n\t\t\t\t}\n\t\t\t\treturn { ok: true, value }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'vault_list',\n\t\t\tdescription: 'List all keys in the vault with their sources and creation dates. Never returns values.',\n\t\t\tparameters: z.object({}),\n\t\t\tasync execute() {\n\t\t\t\tconst entries = await vault.list()\n\t\t\t\treturn { ok: true, entries }\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: 'vault_delete',\n\t\t\tdescription: 'Delete a key from the secure vault.',\n\t\t\tparameters: z.object({\n\t\t\t\tkey: z.string().describe('Key name to delete'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { key } = params as { key: string }\n\t\t\t\tconst ok = await vault.delete(key)\n\t\t\t\tif (!ok) {\n\t\t\t\t\treturn { ok: false, error: `Key not found: ${key}` }\n\t\t\t\t}\n\t\t\t\treturn { ok: true }\n\t\t\t},\n\t\t},\n\n\t\t// === Web tools ===\n\t\t{\n\t\t\tname: 'web_fetch',\n\t\t\tdescription: 'Fetch a URL and return its content as text. Use for APIs, web pages, JSON endpoints, or downloading text content. Much lighter than browser_navigate — use this when you just need the content, not browser interaction.',\n\t\t\tparameters: z.object({\n\t\t\t\turl: z.string().describe('The URL to fetch'),\n\t\t\t\tmethod: z.enum(['GET', 'POST', 'PUT', 'DELETE']).optional().describe('HTTP method. Defaults to GET.'),\n\t\t\t\theaders: z.record(z.string()).optional().describe('Request headers (e.g. { \"Authorization\": \"Bearer ...\" })'),\n\t\t\t\tbody: z.string().optional().describe('Request body for POST/PUT'),\n\t\t\t}),\n\t\t\tasync execute(params) {\n\t\t\t\tconst { url, method, headers, body } = params as {\n\t\t\t\t\turl: string\n\t\t\t\t\tmethod?: string\n\t\t\t\t\theaders?: Record<string, string>\n\t\t\t\t\tbody?: string\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await fetch(url, {\n\t\t\t\t\t\tmethod: method ?? 'GET',\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tbody,\n\t\t\t\t\t})\n\n\t\t\t\t\tconst contentType = response.headers.get('content-type') ?? ''\n\t\t\t\t\tconst text = await response.text()\n\n\t\t\t\t\t// Truncate very large responses\n\t\t\t\t\tconst maxLen = 50_000\n\t\t\t\t\tconst content = text.length > maxLen\n\t\t\t\t\t\t? text.substring(0, maxLen) + `\\n\\n[Truncated — ${text.length} chars total]`\n\t\t\t\t\t\t: text\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: response.ok,\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\tcontentType,\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t]\n}\n\n/** Recursively list files relative to a directory */\nasync function listFilesRecursive(dir: string, prefix = ''): Promise<string[]> {\n\tconst entries = await fs.readdir(dir, { withFileTypes: true })\n\tconst files: string[] = []\n\tfor (const entry of entries) {\n\t\tconst rel = prefix ? `${prefix}/${entry.name}` : entry.name\n\t\tif (entry.isDirectory()) {\n\t\t\tfiles.push(...await listFilesRecursive(path.join(dir, entry.name), rel))\n\t\t} else {\n\t\t\tfiles.push(rel)\n\t\t}\n\t}\n\treturn files\n}\n\n/** Recursively list files with sizes relative to a directory */\nasync function listFilesWithSizes(\n\tdir: string,\n\tprefix = '',\n): Promise<Array<{ path: string; size: number; type: 'file' | 'directory' }>> {\n\tconst entries = await fs.readdir(dir, { withFileTypes: true })\n\tconst results: Array<{ path: string; size: number; type: 'file' | 'directory' }> = []\n\tfor (const entry of entries) {\n\t\tconst rel = prefix ? `${prefix}/${entry.name}` : entry.name\n\t\tconst fullPath = path.join(dir, entry.name)\n\t\tif (entry.isDirectory()) {\n\t\t\tresults.push({ path: rel, size: 0, type: 'directory' })\n\t\t\tresults.push(...(await listFilesWithSizes(fullPath, rel)))\n\t\t} else {\n\t\t\tconst stat = await fs.stat(fullPath)\n\t\t\tresults.push({ path: rel, size: stat.size, type: 'file' })\n\t\t}\n\t}\n\treturn results\n}\n","#!/usr/bin/env node\n\nimport 'dotenv/config'\nimport * as path from 'node:path'\nimport { createEngine } from './index.js'\nimport {\n\taddPawToLock,\n\tremovePawFromLock,\n\taddSkillToLock,\n\tremoveSkillFromLock,\n\taddPawToConfig,\n\tremovePawFromConfig,\n\taddSkillToConfig,\n\tremoveSkillFromConfig,\n} from './config/index.js'\nimport { readPawManifest, resolvePawPath } from './paw/manifest.js'\nimport { createLogger } from './core/logger.js'\n\nconst logger = createLogger('cli')\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2)\n\tconst command = args[0]\n\n\tconst projectRoot = process.cwd()\n\n\t// Allow init and help without a project root\n\tif (command !== 'init' && command !== 'help' && command !== '--help' && command !== '-h' && command !== '--version' && command !== '-v' && command !== undefined) {\n\t\tconst fsCheck = await import('node:fs/promises')\n\t\ttry {\n\t\t\tawait fsCheck.access(path.join(projectRoot, 'vole.config.json'))\n\t\t} catch {\n\t\t\tlogger.error('vole.config.json not found in current directory')\n\t\t\tlogger.info('Run \"vole init\" to create a new project, or cd to your project root')\n\t\t\tprocess.exit(1)\n\t\t}\n\t}\n\n\tswitch (command) {\n\t\tcase 'start':\n\t\t\tawait startInteractive(projectRoot)\n\t\t\tbreak\n\n\t\tcase 'run': {\n\t\t\tconst input = args.slice(1).join(' ')\n\t\t\tif (!input) {\n\t\t\t\tlogger.error('Usage: vole run \"<task>\"')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait runSingle(projectRoot, input)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'init':\n\t\t\tawait initProject(projectRoot)\n\t\t\tbreak\n\n\t\tcase 'paw':\n\t\t\tawait handlePawCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'skill':\n\t\t\tawait handleSkillCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'tool':\n\t\t\tawait handleToolCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'task':\n\t\t\tawait handleTaskCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\t\tcase 'clawhub':\n\t\t\tawait handleClawHubCommand(args.slice(1), projectRoot)\n\t\t\tbreak\n\n\n\t\tcase undefined:\n\t\tcase 'help':\n\t\tcase '--help':\n\t\tcase '-h':\n\t\t\tprintHelp()\n\t\t\tbreak\n\n\t\tcase '--version':\n\t\tcase '-v':\n\t\t\tlogger.info('openvole v0.1.0')\n\t\t\tbreak\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown command: ${command}`)\n\t\t\tprintHelp()\n\t\t\tprocess.exit(1)\n\t}\n}\n\nfunction printHelp(): void {\n\tlogger.info(`\nOpenVole — Micro Agent Core\n\nUsage:\n vole init Initialize a new project\n vole start Start the agent loop (interactive)\n vole run \"<task>\" Run a single task\n\nPaw management:\n vole paw create <name> Scaffold a new Paw in paws/\n vole paw list List loaded Paws and their tools\n vole paw add <name> Install and register a Paw\n vole paw remove <name> Uninstall and deregister a Paw\n\nSkill management:\n vole skill create <name> Scaffold a new Skill in skills/\n vole skill list List Skills and activation status\n vole skill add <name> Install and register a Skill\n vole skill remove <name> Uninstall and deregister a Skill\n\nTool management:\n vole tool list List all registered tools\n vole tool call <name> [json-params] Call a tool directly (deterministic, no Brain)\n\nClawHub (OpenClaw skill registry):\n vole clawhub install <skill> Install a skill from ClawHub\n vole clawhub remove <skill> Remove a ClawHub-installed skill\n vole clawhub search <query> Search for skills on ClawHub\n\nTask management:\n vole task list Show task queue\n vole task cancel <id> Cancel a task\n\nOptions:\n -h, --help Show this help\n -v, --version Show version\n`)\n}\n\nasync function startInteractive(projectRoot: string): Promise<void> {\n\tconst engine = await createEngine(projectRoot)\n\tawait engine.start()\n\n\tlogger.info('\\nOpenVole is running. Type a task or \"exit\" to quit.\\n')\n\n\tconst readline = await import('node:readline')\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t})\n\n\tconst promptUser = (): void => {\n\t\trl.question('vole> ', (input) => {\n\t\t\tconst trimmed = input.trim()\n\t\t\tif (trimmed === 'exit' || trimmed === 'quit') {\n\t\t\t\trl.close()\n\t\t\t\tengine.shutdown().then(() => process.exit(0))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (trimmed) {\n\t\t\t\tengine.run(trimmed, 'user', 'cli:default')\n\t\t\t}\n\t\t\tpromptUser()\n\t\t})\n\t}\n\n\tpromptUser()\n\n\t// Graceful shutdown on SIGINT/SIGTERM\n\tconst gracefulShutdown = (): void => {\n\t\tlogger.info('\\nShutting down...')\n\t\trl.close()\n\t\tengine.shutdown().then(() => process.exit(0))\n\t}\n\n\tprocess.on('SIGINT', gracefulShutdown)\n\tprocess.on('SIGTERM', gracefulShutdown)\n}\n\nasync function runSingle(\n\tprojectRoot: string,\n\tinput: string,\n): Promise<void> {\n\tconst engine = await createEngine(projectRoot, { headless: true })\n\tawait engine.start()\n\tengine.run(input)\n\n\t// Wait for task completion\n\treturn new Promise<void>((resolve) => {\n\t\tengine.bus.on('task:completed', () => {\n\t\t\tengine.shutdown().then(resolve)\n\t\t})\n\t\tengine.bus.on('task:failed', () => {\n\t\t\tengine.shutdown().then(() => {\n\t\t\t\tprocess.exit(1)\n\t\t\t})\n\t\t})\n\t})\n}\n\nasync function initProject(projectRoot: string): Promise<void> {\n\tconst fs = await import('node:fs/promises')\n\n\tconst configPath = path.resolve(projectRoot, 'vole.config.json')\n\ttry {\n\t\tawait fs.access(configPath)\n\t\tlogger.error('vole.config.json already exists')\n\t\treturn\n\t} catch {\n\t\t// File doesn't exist, proceed\n\t}\n\n\tconst config = {\n\t\tpaws: [],\n\t\tskills: [],\n\t\tloop: {\n\t\t\tmaxIterations: 10,\n\t\t\tconfirmBeforeAct: true,\n\t\t\ttaskConcurrency: 1,\n\t\t},\n\t\theartbeat: {\n\t\t\tenabled: false,\n\t\t\tintervalMinutes: 30,\n\t\t},\n\t}\n\tawait fs.writeFile(configPath, JSON.stringify(config, null, 2) + '\\n', 'utf-8')\n\n\t// Create .openvole directory structure\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'skills'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'skills', 'clawhub'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'workspace'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'paws', 'paw-memory'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'paws', 'paw-session'), { recursive: true })\n\tawait fs.mkdir(path.join(projectRoot, '.openvole', 'paws', 'paw-mcp'), { recursive: true })\n\n\t// Create default MEMORY.md\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'paws', 'paw-memory', 'MEMORY.md'),\n\t\t'# Memory\\n\\nLong-term memory for the agent. Store important facts, user preferences, and decisions here.\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create HEARTBEAT.md inside .openvole\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'HEARTBEAT.md'),\n\t\t'# Heartbeat\\n\\n## Jobs\\n\\n<!-- Add recurring jobs here -->\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create BRAIN.md (custom system prompt — optional, overrides default)\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'BRAIN.md'),\n\t\t'# Brain\\n\\nCustom system prompt for the agent. Edit this to change how the Brain reasons and responds.\\nDelete this file to use the built-in default prompt.\\n\\n<!-- Write your custom prompt below -->\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create identity files\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'SOUL.md'),\n\t\t'# Soul\\n\\nThe agent\\'s personality, tone, and identity.\\n\\n## Identity\\n- Name: OpenVole Agent\\n- Personality: Helpful, concise, and proactive\\n- Tone: Professional but friendly\\n',\n\t\t'utf-8',\n\t)\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'USER.md'),\n\t\t'# User\\n\\nInformation about the user.\\n\\n## Profile\\n- Name:\\n- Timezone:\\n- Language: English\\n',\n\t\t'utf-8',\n\t)\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.openvole', 'AGENT.md'),\n\t\t'# Agent\\n\\nOperating rules and behavioral guidelines.\\n\\n## Rules\\n- Always be helpful and direct\\n- Ask for clarification when a request is ambiguous\\n- Save important findings to memory for future reference\\n- Store credentials in the vault, never in workspace or memory\\n- When reading API docs or instructions, save them to workspace immediately\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create .env template\n\tawait fs.writeFile(\n\t\tpath.join(projectRoot, '.env'),\n\t\t'# OpenVole Environment\\nVOLE_LOG_LEVEL=info\\n',\n\t\t'utf-8',\n\t)\n\n\t// Create .gitignore\n\ttry {\n\t\tawait fs.access(path.join(projectRoot, '.gitignore'))\n\t} catch {\n\t\tawait fs.writeFile(\n\t\t\tpath.join(projectRoot, '.gitignore'),\n\t\t\t'node_modules/\\n.env\\n.openvole/\\n.DS_Store\\n',\n\t\t\t'utf-8',\n\t\t)\n\t}\n\n\tlogger.info('Created vole.config.json')\n\tlogger.info('Created .openvole/')\n\tlogger.info(' skills/ — local and ClawHub skills')\n\tlogger.info(' workspace/ — agent scratch space')\n\tlogger.info(' paws/paw-memory/ — agent memory (MEMORY.md + daily logs)')\n\tlogger.info(' paws/paw-session/ — session transcripts')\n\tlogger.info(' paws/paw-mcp/ — MCP server config')\n\tlogger.info('Created identity files (BRAIN.md, SOUL.md, USER.md, AGENT.md, HEARTBEAT.md)')\n\tlogger.info('Created .env')\n\tlogger.info('')\n\tlogger.info('Next: install paws and start')\n\tlogger.info(' npm install @openvole/paw-ollama @openvole/paw-memory')\n\tlogger.info(' npx vole start')\n}\n\nasync function handlePawCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'create': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole paw create <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait scaffoldPaw(projectRoot, name)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'list': {\n\t\t\t// Lightweight — read manifests without spawning paws\n\t\t\tconst config = await (await import('./config/index.js')).loadConfig(\n\t\t\t\tpath.resolve(projectRoot, 'vole.config.json'),\n\t\t\t)\n\t\t\tconst { normalizePawConfig } = await import('./config/index.js')\n\t\t\tconst { readPawManifest, resolvePawPath } = await import('./paw/manifest.js')\n\n\t\t\tconst paws: Array<{ name: string; tools: number; type: string }> = []\n\t\t\tfor (const pawEntry of config.paws) {\n\t\t\t\tconst pawConfig = normalizePawConfig(pawEntry)\n\t\t\t\tconst pawPath = resolvePawPath(pawConfig.name, projectRoot)\n\t\t\t\tconst manifest = await readPawManifest(pawPath)\n\t\t\t\tif (manifest) {\n\t\t\t\t\tpaws.push({\n\t\t\t\t\t\tname: manifest.name,\n\t\t\t\t\t\ttools: manifest.tools.length,\n\t\t\t\t\t\ttype: manifest.inProcess ? 'in-process' : 'subprocess',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (paws.length === 0) {\n\t\t\t\tlogger.info('No Paws configured')\n\t\t\t} else {\n\t\t\t\tlogger.info('PAW TOOLS TYPE')\n\t\t\t\tfor (const paw of paws) {\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`${paw.name.padEnd(29)}${String(paw.tools).padEnd(9)}${paw.type}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'add': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole paw add <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tlogger.info(`Installing ${name}...`)\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\tawait execaFn('npm', ['install', name], { cwd: projectRoot, stdio: 'inherit' })\n\n\t\t\t// Read manifest and auto-register in lock file\n\t\t\tconst pawPath = resolvePawPath(name, projectRoot)\n\t\t\tconst manifest = await readPawManifest(pawPath)\n\t\t\tif (manifest) {\n\t\t\t\tconst defaultAllow = manifest.permissions\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tnetwork: manifest.permissions.network,\n\t\t\t\t\t\t\tlisten: manifest.permissions.listen,\n\t\t\t\t\t\t\tfilesystem: manifest.permissions.filesystem,\n\t\t\t\t\t\t\tenv: manifest.permissions.env,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined\n\t\t\t\tawait addPawToLock(projectRoot, name, manifest.version, defaultAllow)\n\t\t\t\tawait addPawToConfig(projectRoot, name, defaultAllow)\n\t\t\t\tlogger.info(`Added ${name}@${manifest.version} to vole.config.json`)\n\t\t\t\tif (manifest.permissions?.listen?.length) {\n\t\t\t\t\tlogger.info(` listen ports: ${manifest.permissions.listen.join(', ')}`)\n\t\t\t\t}\n\t\t\t\tif (manifest.tools.length > 0) {\n\t\t\t\t\tlogger.info(` provides ${manifest.tools.length} tools: ${manifest.tools.map((t) => t.name).join(', ')}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogger.error(`Installed ${name} but could not read vole-paw.json — add it to vole.config.json manually`)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'remove': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole paw remove <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\tawait execaFn('npm', ['uninstall', name], { cwd: projectRoot, stdio: 'inherit' })\n\t\t\tawait removePawFromLock(projectRoot, name)\n\t\t\tawait removePawFromConfig(projectRoot, name)\n\t\t\tlogger.info(`Removed ${name} from vole.config.json`)\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown paw command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, add, remove')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nasync function handleSkillCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'create': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole skill create <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait scaffoldSkill(projectRoot, name)\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'list': {\n\t\t\t// Lightweight — load SKILL.md files without spawning paws\n\t\t\tconst config = await (await import('./config/index.js')).loadConfig(\n\t\t\t\tpath.resolve(projectRoot, 'vole.config.json'),\n\t\t\t)\n\t\t\tconst { SkillRegistry } = await import('./skill/registry.js')\n\t\t\tconst { createMessageBus } = await import('./core/bus.js')\n\t\t\tconst { ToolRegistry } = await import('./tool/registry.js')\n\n\t\t\tconst bus = createMessageBus()\n\t\t\tconst toolRegistry = new ToolRegistry(bus)\n\t\t\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\n\t\t\tfor (const skillName of config.skills) {\n\t\t\t\tawait skillRegistry.load(skillName)\n\t\t\t}\n\n\t\t\tconst skills = skillRegistry.list()\n\t\t\tif (skills.length === 0) {\n\t\t\t\tlogger.info('No Skills configured')\n\t\t\t} else {\n\t\t\t\tlogger.info('SKILL STATUS MISSING')\n\t\t\t\tfor (const skill of skills) {\n\t\t\t\t\tconst status = skill.active ? 'active' : 'inactive'\n\t\t\t\t\tconst missing = skill.missingTools.length > 0\n\t\t\t\t\t\t? skill.missingTools.join(', ')\n\t\t\t\t\t\t: '—'\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`${skill.name.padEnd(31)}${status.padEnd(11)}${missing}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'add': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole skill add <path-to-skill>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst skillPath = path.resolve(projectRoot, name)\n\t\t\tconst { loadSkillFromDirectory } = await import('./skill/loader.js')\n\t\t\tconst definition = await loadSkillFromDirectory(skillPath)\n\n\t\t\tif (!definition) {\n\t\t\t\tlogger.error(`No valid SKILL.md found at ${skillPath}`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tawait addSkillToLock(projectRoot, name, definition.version ?? '0.0.0')\n\t\t\tawait addSkillToConfig(projectRoot, name)\n\t\t\tlogger.info(`Added \"${definition.name}\" to vole.config.json`)\n\t\t\tif (definition.requiredTools.length > 0) {\n\t\t\t\tlogger.info(` requires tools: ${definition.requiredTools.join(', ')}`)\n\t\t\t}\n\t\t\tif (definition.requires?.env.length) {\n\t\t\t\tlogger.info(` requires env: ${definition.requires.env.join(', ')}`)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'remove': {\n\t\t\tconst name = args[1]\n\t\t\tif (!name) {\n\t\t\t\tlogger.error('Usage: vole skill remove <name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tawait removeSkillFromLock(projectRoot, name)\n\t\t\tawait removeSkillFromConfig(projectRoot, name)\n\n\t\t\t// Delete from .openvole/skills/\n\t\t\tconst fsModule = await import('node:fs/promises')\n\t\t\tconst skillPath = name.startsWith('.') || name.startsWith('/')\n\t\t\t\t? path.resolve(projectRoot, name)\n\t\t\t\t: path.resolve(projectRoot, '.openvole', 'skills', name)\n\t\t\ttry {\n\t\t\t\tawait fsModule.rm(skillPath, { recursive: true })\n\t\t\t\tlogger.info(`Deleted ${skillPath}`)\n\t\t\t} catch {\n\t\t\t\t// Directory may not exist — that's fine\n\t\t\t}\n\n\t\t\tlogger.info(`Removed \"${name}\" from vole.config.json`)\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown skill command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, add, remove')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nasync function handleToolCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'list': {\n\t\t\t// Lightweight mode — no paw spawning, no heartbeat\n\t\t\t// Shows core tools + tools declared in paw manifests\n\t\t\tconst config = await (await import('./config/index.js')).loadConfig(\n\t\t\t\tpath.resolve(projectRoot, 'vole.config.json'),\n\t\t\t)\n\n\t\t\tconst tools: Array<{ name: string; pawName: string; type: string }> = []\n\n\t\t\t// Core tools\n\t\t\tconst { createMessageBus } = await import('./core/bus.js')\n\t\t\tconst { ToolRegistry } = await import('./tool/registry.js')\n\t\t\tconst { SchedulerStore } = await import('./core/scheduler.js')\n\t\t\tconst { TaskQueue } = await import('./core/task.js')\n\t\t\tconst { SkillRegistry } = await import('./skill/registry.js')\n\t\t\tconst { createCoreTools } = await import('./tool/core-tools.js')\n\t\t\tconst { Vault } = await import('./core/vault.js')\n\n\t\t\tconst bus = createMessageBus()\n\t\t\tconst toolRegistry = new ToolRegistry(bus)\n\t\t\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\t\t\tconst taskQueue = new TaskQueue(bus, 1)\n\t\t\tconst scheduler = new SchedulerStore()\n\t\t\tconst vault = new Vault(path.resolve(projectRoot, '.openvole', 'vault.json'), process.env.VOLE_VAULT_KEY)\n\t\t\tawait vault.init()\n\t\t\tconst coreTools = createCoreTools(scheduler, taskQueue, projectRoot, skillRegistry, vault)\n\t\t\ttoolRegistry.register('__core__', coreTools, true)\n\n\t\t\tfor (const entry of toolRegistry.list()) {\n\t\t\t\ttools.push({ name: entry.name, pawName: entry.pawName, type: 'in-process' })\n\t\t\t}\n\n\t\t\t// Read paw manifests (without spawning) to get declared tools\n\t\t\tconst { normalizePawConfig } = await import('./config/index.js')\n\t\t\tconst { readPawManifest, resolvePawPath } = await import('./paw/manifest.js')\n\t\t\tfor (const pawEntry of config.paws) {\n\t\t\t\tconst pawConfig = normalizePawConfig(pawEntry)\n\t\t\t\tconst pawPath = resolvePawPath(pawConfig.name, projectRoot)\n\t\t\t\tconst manifest = await readPawManifest(pawPath)\n\t\t\t\tif (manifest?.tools) {\n\t\t\t\t\tfor (const t of manifest.tools) {\n\t\t\t\t\t\ttools.push({\n\t\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\t\tpawName: pawConfig.name,\n\t\t\t\t\t\t\ttype: manifest.inProcess ? 'in-process' : 'subprocess',\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (tools.length === 0) {\n\t\t\t\tlogger.info('No tools registered')\n\t\t\t} else {\n\t\t\t\tlogger.info('TOOL PAW TYPE')\n\t\t\t\tfor (const tool of tools) {\n\t\t\t\t\tlogger.info(\n\t\t\t\t\t\t`${tool.name.padEnd(21)}${tool.pawName.padEnd(23)}${tool.type}`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'call': {\n\t\t\tconst toolName = args[1]\n\t\t\tconst paramsJson = args[2]\n\n\t\t\tif (!toolName) {\n\t\t\t\tlogger.error('Usage: vole tool call <tool-name> [json-params]')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tlet params: unknown = {}\n\t\t\tif (paramsJson) {\n\t\t\t\ttry {\n\t\t\t\t\tparams = JSON.parse(paramsJson)\n\t\t\t\t} catch {\n\t\t\t\t\tlogger.error('Invalid JSON params')\n\t\t\t\t\tprocess.exit(1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Lightweight boot — only register core tools (no paw spawning)\n\t\t\tconst { createMessageBus } = await import('./core/bus.js')\n\t\t\tconst { ToolRegistry } = await import('./tool/registry.js')\n\t\t\tconst { SchedulerStore } = await import('./core/scheduler.js')\n\t\t\tconst { TaskQueue } = await import('./core/task.js')\n\t\t\tconst { SkillRegistry } = await import('./skill/registry.js')\n\t\t\tconst { Vault } = await import('./core/vault.js')\n\t\t\tconst { createCoreTools } = await import('./tool/core-tools.js')\n\n\t\t\tconst bus = createMessageBus()\n\t\t\tconst toolRegistry = new ToolRegistry(bus)\n\t\t\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\t\t\tconst taskQueue = new TaskQueue(bus, 1)\n\t\t\tconst scheduler = new SchedulerStore()\n\t\t\tscheduler.setPersistence(path.resolve(projectRoot, '.openvole', 'schedules.json'))\n\t\t\tawait scheduler.loadFromDisk()\n\t\t\tconst vault = new Vault(\n\t\t\t\tpath.resolve(projectRoot, '.openvole', 'vault.json'),\n\t\t\t\tprocess.env.VOLE_VAULT_KEY,\n\t\t\t)\n\t\t\tawait vault.init()\n\t\t\tconst coreTools = createCoreTools(scheduler, taskQueue, projectRoot, skillRegistry, vault)\n\t\t\ttoolRegistry.register('__core__', coreTools, true)\n\n\t\t\tconst tool = toolRegistry.get(toolName)\n\t\t\tif (!tool) {\n\t\t\t\tlogger.error(`Tool \"${toolName}\" not found in core tools`)\n\t\t\t\tlogger.info('Core tools only — paw tools require a running \"vole start\" instance')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tif (tool.parameters && typeof tool.parameters.parse === 'function') {\n\t\t\t\t\ttool.parameters.parse(params)\n\t\t\t\t}\n\t\t\t\tconst result = await tool.execute(params)\n\t\t\t\tconsole.log(JSON.stringify(result, null, 2))\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Tool execution failed: ${err instanceof Error ? err.message : err}`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown tool command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, call')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nasync function handleTaskCommand(\n\targs: string[],\n\t_projectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'list':\n\t\t\tlogger.info('Task list requires a running vole instance.')\n\t\t\tbreak\n\n\t\tcase 'cancel': {\n\t\t\tconst id = args[1]\n\t\t\tif (!id) {\n\t\t\t\tlogger.error('Usage: vole task cancel <id>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\t\t\tlogger.info('Task cancellation requires a running vole instance.')\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown task command: ${subcommand}`)\n\t\t\tlogger.info('Available: list, cancel')\n\t\t\tprocess.exit(1)\n\t}\n}\n\n/** Interactive prompt helper */\nasync function ask(question: string): Promise<string> {\n\tconst rl = (await import('node:readline')).createInterface({\n\t\tinput: process.stdin,\n\t\toutput: process.stdout,\n\t})\n\treturn new Promise((resolve) => {\n\t\trl.question(question, (answer) => {\n\t\t\trl.close()\n\t\t\tresolve(answer.trim())\n\t\t})\n\t})\n}\n\n/** Ask yes/no */\nasync function confirm(question: string): Promise<boolean> {\n\tconst answer = await ask(`${question} [y/N] `)\n\treturn answer.toLowerCase() === 'y'\n}\n\n/** Ask for a comma-separated list */\nasync function askList(question: string): Promise<string[]> {\n\tconst answer = await ask(question)\n\tif (!answer) return []\n\treturn answer.split(',').map((s) => s.trim()).filter(Boolean)\n}\n\ninterface ToolSpec {\n\tname: string\n\tdescription: string\n}\n\nasync function scaffoldPaw(projectRoot: string, name: string): Promise<void> {\n\tconst fs = await import('node:fs/promises')\n\n\tconst pawName = name.startsWith('paw-') ? name : `paw-${name}`\n\tconst pawDir = path.resolve(projectRoot, 'paws', pawName)\n\n\ttry {\n\t\tawait fs.access(pawDir)\n\t\tlogger.error(`Directory paws/${pawName} already exists`)\n\t\tprocess.exit(1)\n\t} catch {\n\t\t// Doesn't exist — good\n\t}\n\n\t// Interactive setup\n\tlogger.info(`\\nCreating Paw: ${pawName}\\n`)\n\n\tconst description = await ask('Description: ')\n\n\t// Collect tools\n\tconst tools: ToolSpec[] = []\n\tlogger.info('\\nTools are actions the agent can perform (e.g., send_email, search_docs).')\n\tif (await confirm('Add tools?')) {\n\t\tlet addMore = true\n\t\twhile (addMore) {\n\t\t\tconst toolName = await ask(' Tool name (e.g., send_message): ')\n\t\t\tif (!toolName) break\n\t\t\tconst toolDesc = await ask(' Tool description: ')\n\t\t\ttools.push({ name: toolName, description: toolDesc })\n\t\t\taddMore = await confirm(' Add another tool?')\n\t\t}\n\t}\n\n\t// Hooks\n\tlogger.info('\\nHooks let your Paw react to agent activity automatically.')\n\tconst wantObserve = await confirm('Log every tool execution? (observe hook)')\n\tconst wantPerceive = await confirm('Inject context before the agent thinks? (perceive hook)')\n\n\t// Permissions\n\tlogger.info('\\nPermissions control what this Paw can access.')\n\tconst networkDomains = await askList('Network domains (comma-separated, e.g., api.telegram.org): ')\n\tconst listenPorts = (await askList('Ports to listen on (comma-separated, e.g., 3000): ')).map(Number).filter((n) => !Number.isNaN(n))\n\tconst envVars = await askList('Env variables needed (comma-separated, e.g., TELEGRAM_TOKEN): ')\n\n\tlogger.info('')\n\n\t// Generate files\n\tawait fs.mkdir(path.join(pawDir, 'src'), { recursive: true })\n\n\t// vole-paw.json\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'vole-paw.json'),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tname: pawName,\n\t\t\t\tversion: '0.1.0',\n\t\t\t\tdescription,\n\t\t\t\tentry: './dist/index.js',\n\t\t\t\tbrain: false,\n\t\t\t\tinProcess: false,\n\t\t\t\ttransport: 'ipc',\n\t\t\t\ttools: tools.map((t) => ({ name: t.name, description: t.description })),\n\t\t\t\tpermissions: {\n\t\t\t\t\tnetwork: networkDomains,\n\t\t\t\t\tlisten: listenPorts,\n\t\t\t\t\tfilesystem: [],\n\t\t\t\t\tenv: envVars,\n\t\t\t\t},\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t) + '\\n',\n\t)\n\n\t// package.json\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'package.json'),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tname: pawName,\n\t\t\t\tversion: '0.1.0',\n\t\t\t\tdescription,\n\t\t\t\ttype: 'module',\n\t\t\t\tmain: './dist/index.js',\n\t\t\t\tscripts: {\n\t\t\t\t\tbuild: 'tsup',\n\t\t\t\t\ttypecheck: 'tsc --noEmit',\n\t\t\t\t},\n\t\t\t\tdependencies: {\n\t\t\t\t\t'@openvole/paw-sdk': 'workspace:*',\n\t\t\t\t},\n\t\t\t\tdevDependencies: {\n\t\t\t\t\t'@types/node': '^22.0.0',\n\t\t\t\t\ttsup: '^8.3.0',\n\t\t\t\t\ttypescript: '^5.6.0',\n\t\t\t\t},\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t) + '\\n',\n\t)\n\n\t// tsconfig.json\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'tsconfig.json'),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\textends: '../../tsconfig.base.json',\n\t\t\t\tcompilerOptions: { outDir: './dist', rootDir: './src' },\n\t\t\t\tinclude: ['src/**/*.ts'],\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t) + '\\n',\n\t)\n\n\t// tsup.config.ts\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'tsup.config.ts'),\n\t\t`import { defineConfig } from 'tsup'\n\nexport default defineConfig({\n\\tentry: ['src/index.ts'],\n\\tformat: ['esm'],\n\\tdts: true,\n\\tclean: true,\n\\tsourcemap: true,\n\\ttarget: 'node20',\n\\tsplitting: false,\n})\n`,\n\t)\n\n\t// src/index.ts\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'src', 'index.ts'),\n\t\t`import { definePaw } from '@openvole/paw-sdk'\nimport { paw } from './paw.js'\n\nexport default definePaw(paw)\n`,\n\t)\n\n\t// src/paw.ts — generate with real tools from the interactive session\n\tconst toolsCode = tools.length > 0\n\t\t? tools.map((t) => `\\t\\t{\n\\t\\t\\tname: '${t.name}',\n\\t\\t\\tdescription: '${t.description.replace(/'/g, \"\\\\'\")}',\n\\t\\t\\tparameters: z.object({\n\\t\\t\\t\\t// Define your parameters here\n\\t\\t\\t}),\n\\t\\t\\tasync execute(params) {\n\\t\\t\\t\\t// TODO: implement ${t.name}\n\\t\\t\\t\\tthrow new Error('Not implemented')\n\\t\\t\\t},\n\\t\\t},`).join('\\n')\n\t\t: ''\n\n\t// Generate hooks code\n\tlet hooksCode = ''\n\tif (wantObserve || wantPerceive) {\n\t\tconst hookParts: string[] = []\n\t\tif (wantObserve) {\n\t\t\thookParts.push(`\\t\\tonObserve: async (result) => {\n\\t\\t\\tconst status = result.success ? 'OK' : 'FAIL'\n\\t\\t\\tconsole.log(\\`[${pawName}] \\${result.toolName} → \\${status} (\\${result.durationMs}ms)\\`)\n\\t\\t},`)\n\t\t}\n\t\tif (wantPerceive) {\n\t\t\thookParts.push(`\\t\\tonPerceive: async (context) => {\n\\t\\t\\t// Add data to context.metadata before the agent thinks\n\\t\\t\\t// context.metadata.myData = { ... }\n\\t\\t\\treturn context\n\\t\\t},`)\n\t\t}\n\t\thooksCode = `\\n\\thooks: {\\n${hookParts.join('\\n')}\\n\\t},\\n`\n\t}\n\n\tawait fs.writeFile(\n\t\tpath.join(pawDir, 'src', 'paw.ts'),\n\t\t`import { z, type PawDefinition } from '@openvole/paw-sdk'\n\nexport const paw: PawDefinition = {\n\\tname: '${pawName}',\n\\tversion: '0.1.0',\n\\tdescription: '${description.replace(/'/g, \"\\\\'\")}',\n\n\\ttools: [\n${toolsCode}\n\\t],\n${hooksCode}\n\\tasync onLoad() {\n\\t\\tconsole.log('[${pawName}] loaded')\n\\t},\n\n\\tasync onUnload() {\n\\t\\tconsole.log('[${pawName}] unloaded')\n\\t},\n}\n`,\n\t)\n\n\t// Auto-register in vole.lock.json\n\tconst allow: Record<string, unknown> = {}\n\tif (networkDomains.length > 0) allow.network = networkDomains\n\tif (listenPorts.length > 0) allow.listen = listenPorts\n\tif (envVars.length > 0) allow.env = envVars\n\tawait addPawToLock(\n\t\tprojectRoot,\n\t\t`./paws/${pawName}`,\n\t\t'0.1.0',\n\t\tObject.keys(allow).length > 0 ? allow as import('./paw/types.js').PawConfig['allow'] : undefined,\n\t)\n\n\tlogger.info(`Created paws/${pawName}/`)\n\tlogger.info(`Registered in vole.lock.json`)\n\tif (tools.length > 0) {\n\t\tlogger.info(`Generated ${tools.length} tool${tools.length > 1 ? 's' : ''}: ${tools.map((t) => t.name).join(', ')}`)\n\t}\n\tlogger.info('')\n\tlogger.info('Next: implement your tool logic in src/paw.ts, then build:')\n\tlogger.info(' pnpm install && pnpm build')\n}\n\nasync function scaffoldSkill(projectRoot: string, name: string): Promise<void> {\n\tconst fs = await import('node:fs/promises')\n\n\tconst skillName = name.startsWith('skill-') ? name : `skill-${name}`\n\tconst skillDir = path.resolve(projectRoot, '.openvole', 'skills', skillName)\n\n\ttry {\n\t\tawait fs.access(skillDir)\n\t\tlogger.error(`Skill \"${skillName}\" already exists`)\n\t\tprocess.exit(1)\n\t} catch {\n\t\t// Doesn't exist — good\n\t}\n\n\t// Interactive setup\n\tlogger.info(`\\nCreating Skill: ${skillName}\\n`)\n\n\tconst description = await ask('Description: ')\n\n\tlogger.info('\\nSkills describe behavior — what the agent should do, using tools provided by Paws.')\n\tconst requiredTools = await askList('Required tools (comma-separated, e.g., email_search, email_send): ')\n\tconst optionalTools = await askList('Optional tools (comma-separated, or empty): ')\n\tconst tags = await askList('Tags (comma-separated, e.g., email, productivity): ')\n\n\tlogger.info('')\n\tconst instructions = await ask('Instructions (what should the agent do?): ')\n\n\tlogger.info('')\n\n\t// Create skill directory with optional subdirectories\n\tawait fs.mkdir(skillDir, { recursive: true })\n\n\t// Build YAML frontmatter\n\tconst frontmatterLines = [\n\t\t`name: ${skillName}`,\n\t\t`description: \"${description.replace(/\"/g, '\\\\\"')}\"`,\n\t]\n\n\tif (requiredTools.length > 0) {\n\t\tfrontmatterLines.push('requiredTools:')\n\t\tfor (const t of requiredTools) {\n\t\t\tfrontmatterLines.push(` - ${t}`)\n\t\t}\n\t}\n\n\tif (optionalTools.length > 0) {\n\t\tfrontmatterLines.push('optionalTools:')\n\t\tfor (const t of optionalTools) {\n\t\t\tfrontmatterLines.push(` - ${t}`)\n\t\t}\n\t}\n\n\tif (tags.length > 0) {\n\t\tfrontmatterLines.push('tags:')\n\t\tfor (const t of tags) {\n\t\t\tfrontmatterLines.push(` - ${t}`)\n\t\t}\n\t}\n\n\t// SKILL.md\n\tconst skillMd = `---\n${frontmatterLines.join('\\n')}\n---\n\n# ${skillName}\n\n${instructions}\n`\n\n\tawait fs.writeFile(path.join(skillDir, 'SKILL.md'), skillMd)\n\n\t// Auto-register in config and lock file (use bare name — resolver finds it in .openvole/skills/)\n\tawait addSkillToLock(projectRoot, skillName, '0.1.0')\n\tawait addSkillToConfig(projectRoot, skillName)\n\n\tlogger.info(`Created .openvole/skills/${skillName}/`)\n\tlogger.info(` SKILL.md — edit to refine instructions`)\n\tlogger.info(`Added to vole.config.json`)\n\tif (requiredTools.length > 0) {\n\t\tlogger.info(`Requires tools: ${requiredTools.join(', ')}`)\n\t}\n}\n\nasync function handleClawHubCommand(\n\targs: string[],\n\tprojectRoot: string,\n): Promise<void> {\n\tconst subcommand = args[0]\n\n\tswitch (subcommand) {\n\t\tcase 'install': {\n\t\t\tconst skillName = args[1]\n\t\t\tif (!skillName) {\n\t\t\t\tlogger.error('Usage: vole clawhub install <skill-name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst fsModule = await import('node:fs/promises')\n\t\t\tconst clawHubDir = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub')\n\t\t\tawait fsModule.mkdir(clawHubDir, { recursive: true })\n\n\t\t\t// Install into .openvole/skills/clawhub/<name>\n\t\t\tlogger.info(`Installing \"${skillName}\" from ClawHub...`)\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\ttry {\n\t\t\t\tawait execaFn('npx', ['clawhub', 'install', skillName, '--dir', clawHubDir], {\n\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\tstdio: 'inherit',\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tlogger.error(`Failed to install \"${skillName}\" from ClawHub`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\t// Find the installed skill directory\n\t\t\tconst installed = await fsModule.readdir(clawHubDir).catch(() => [] as string[])\n\t\t\tconst skillDir = installed.find((d) => d === skillName || d.includes(skillName))\n\n\t\t\tif (!skillDir) {\n\t\t\t\tlogger.error(`Skill installed but directory not found in .openvole/skills/clawhub/`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst localPath = `clawhub/${skillDir}`\n\t\t\tconst { loadSkillFromDirectory } = await import('./skill/loader.js')\n\t\t\tconst definition = await loadSkillFromDirectory(path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', skillDir))\n\n\t\t\tif (definition) {\n\t\t\t\tawait addSkillToLock(projectRoot, localPath, definition.version ?? '0.0.0')\n\t\t\t\tawait addSkillToConfig(projectRoot, localPath)\n\t\t\t\tlogger.info(`Added \"${definition.name}\" to vole.config.json`)\n\t\t\t\tif (definition.requiredTools.length > 0) {\n\t\t\t\t\tlogger.info(` requires tools: ${definition.requiredTools.join(', ')}`)\n\t\t\t\t}\n\t\t\t\tif (definition.requires?.env.length) {\n\t\t\t\t\tlogger.info(` requires env: ${definition.requires.env.join(', ')}`)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Check if it's an OpenClaw plugin instead of a skill\n\t\t\t\tconst fsCheck = await import('node:fs/promises')\n\t\t\t\tconst pluginJsonPath = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', skillDir ?? skillName, 'openclaw.plugin.json')\n\t\t\t\ttry {\n\t\t\t\t\tawait fsCheck.access(pluginJsonPath)\n\t\t\t\t\tlogger.error(`\"${skillName}\" is an OpenClaw plugin, not a skill. OpenVole does not support OpenClaw plugins — use Paws instead.`)\n\t\t\t\t} catch {\n\t\t\t\t\tlogger.warn(`Installed \"${skillName}\" but could not parse SKILL.md — add to vole.config.json manually`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'search': {\n\t\t\tconst query = args.slice(1).join(' ')\n\t\t\tif (!query) {\n\t\t\t\tlogger.error('Usage: vole clawhub search <query>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst { execa: execaFn } = await import('execa')\n\t\t\ttry {\n\t\t\t\tawait execaFn('npx', ['clawhub', 'search', query], {\n\t\t\t\t\tcwd: projectRoot,\n\t\t\t\t\tstdio: 'inherit',\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\tlogger.error('Search failed — make sure clawhub is available (npx clawhub)')\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tcase 'remove': {\n\t\t\tconst skillName = args[1]\n\t\t\tif (!skillName) {\n\t\t\t\tlogger.error('Usage: vole clawhub remove <skill-name>')\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\tconst fsModule = await import('node:fs/promises')\n\t\t\tconst skillPath = path.resolve(projectRoot, '.openvole', 'skills', 'clawhub', skillName)\n\n\t\t\ttry {\n\t\t\t\tawait fsModule.rm(skillPath, { recursive: true })\n\t\t\t\tlogger.info(`Deleted .openvole/skills/clawhub/${skillName}`)\n\t\t\t} catch {\n\t\t\t\tlogger.error(`Skill directory not found: .openvole/skills/clawhub/${skillName}`)\n\t\t\t\tprocess.exit(1)\n\t\t\t}\n\n\t\t\t// Remove from config\n\t\t\tawait removeSkillFromLock(projectRoot, `clawhub/${skillName}`)\n\t\t\tawait removeSkillFromConfig(projectRoot, `clawhub/${skillName}`)\n\n\t\t\tlogger.info(`Removed \"${skillName}\" from vole.config.json`)\n\t\t\tbreak\n\t\t}\n\n\t\tdefault:\n\t\t\tlogger.error(`Unknown clawhub command: ${subcommand}`)\n\t\t\tlogger.info('Available: install, remove, search')\n\t\t\tprocess.exit(1)\n\t}\n}\n\nmain().catch((err) => {\n\tconsole.error('Fatal error:', err)\n\tprocess.exit(1)\n})\n","// === Public API Surface ===\n\n// Config\nexport {\n\tdefineConfig,\n\tloadConfig,\n\treadLockFile,\n\twriteLockFile,\n\taddPawToLock,\n\tremovePawFromLock,\n\taddSkillToLock,\n\tremoveSkillFromLock,\n} from './config/index.js'\nexport type { VoleConfig, LoopConfig, HeartbeatConfig, VoleLock, RateLimits } from './config/index.js'\n\n// Core\nexport { createMessageBus } from './core/bus.js'\nexport type { MessageBus, BusEvents } from './core/bus.js'\nexport { runAgentLoop } from './core/loop.js'\nexport type { LoopDependencies } from './core/loop.js'\nexport { TaskQueue } from './core/task.js'\nexport type { AgentTask, TaskStatus } from './core/task.js'\nexport { SchedulerStore } from './core/scheduler.js'\nexport { Vault } from './core/vault.js'\nexport type { VaultEntry } from './core/vault.js'\nexport { PHASE_ORDER } from './core/hooks.js'\nexport type { LoopPhase } from './core/hooks.js'\nexport { RateLimiter } from './core/rate-limiter.js'\n\n// Errors\nexport {\n\tcreateActionError,\n\tsuccessResult,\n\tfailureResult,\n} from './core/errors.js'\nexport type { ActionError, ActionResult, ActionErrorCode } from './core/errors.js'\n\n// Tool\nexport { ToolRegistry } from './tool/registry.js'\nexport type { ToolDefinition, ToolRegistryEntry } from './tool/types.js'\n\n// Context\nexport { createAgentContext } from './context/types.js'\nexport type {\n\tAgentContext,\n\tAgentMessage,\n\tToolSummary,\n\tActiveSkill,\n} from './context/types.js'\n\n// Paw\nexport { PawRegistry } from './paw/registry.js'\nexport { readPawManifest, resolvePawPath } from './paw/manifest.js'\nexport {\n\tcomputeEffectivePermissions,\n\tvalidatePermissions,\n} from './paw/sandbox.js'\nexport type {\n\tPawDefinition,\n\tPawManifest,\n\tPawConfig,\n\tPawInstance,\n\tAgentPlan,\n\tPlannedAction,\n\tBootstrapHook,\n\tPerceiveHook,\n\tObserveHook,\n\tCompactHook,\n\tScheduleHook,\n\tTransportType,\n\tEffectivePermissions,\n} from './paw/types.js'\n\n// Skill\nexport { SkillRegistry } from './skill/registry.js'\nexport { resolveSkills, buildActiveSkills } from './skill/resolver.js'\nexport type {\n\tSkillDefinition,\n\tSkillInstance,\n} from './skill/types.js'\n\n// IO\nexport { createTtyIO } from './io/tty.js'\nexport type { VoleIO } from './io/types.js'\n\n// === Engine — the main orchestrator ===\n\nimport * as path from 'node:path'\nimport { createMessageBus } from './core/bus.js'\nimport { ToolRegistry } from './tool/registry.js'\nimport { PawRegistry } from './paw/registry.js'\nimport { SkillRegistry } from './skill/registry.js'\nimport { TaskQueue } from './core/task.js'\nimport { runAgentLoop } from './core/loop.js'\nimport { createTtyIO } from './io/tty.js'\nimport { loadConfig, normalizePawConfig, type VoleConfig } from './config/index.js'\nimport type { VoleIO } from './io/types.js'\nimport * as fs from 'node:fs/promises'\nimport { SchedulerStore } from './core/scheduler.js'\nimport { createCoreTools } from './tool/core-tools.js'\nimport { RateLimiter } from './core/rate-limiter.js'\nimport { Vault } from './core/vault.js'\nimport { closeLogger } from './core/logger.js'\n\nexport interface VoleEngine {\n\tbus: ReturnType<typeof createMessageBus>\n\ttoolRegistry: ToolRegistry\n\tpawRegistry: PawRegistry\n\tskillRegistry: SkillRegistry\n\ttaskQueue: TaskQueue\n\tio: VoleIO\n\tconfig: VoleConfig\n\n\t/** Start the engine — load Paws and Skills */\n\tstart(): Promise<void>\n\t/** Submit a task for execution */\n\trun(input: string, source?: 'user' | 'schedule' | 'heartbeat' | 'paw', sessionId?: string): void\n\t/** Graceful shutdown */\n\tshutdown(): Promise<void>\n}\n\nconst engineLogger = {\n\tinfo: (msg: string, ...args: unknown[]) =>\n\t\tconsole.info(`[openvole] ${msg}`, ...args),\n\terror: (msg: string, ...args: unknown[]) =>\n\t\tconsole.error(`[openvole] ${msg}`, ...args),\n}\n\n/** Create and initialize the OpenVole engine */\nexport async function createEngine(\n\tprojectRoot: string,\n\toptions?: { io?: VoleIO; configPath?: string; headless?: boolean },\n): Promise<VoleEngine> {\n\tconst configPath =\n\t\toptions?.configPath ?? path.resolve(projectRoot, 'vole.config.ts')\n\tconst config = await loadConfig(configPath)\n\n\tconst bus = createMessageBus()\n\tconst toolRegistry = new ToolRegistry(bus)\n\tconst pawRegistry = new PawRegistry(bus, toolRegistry, projectRoot)\n\tconst skillRegistry = new SkillRegistry(bus, toolRegistry, projectRoot)\n\tconst io = options?.io ?? createTtyIO()\n\tconst rateLimiter = new RateLimiter()\n\tconst taskQueue = new TaskQueue(bus, config.loop.taskConcurrency, rateLimiter, config.loop.rateLimits)\n\tconst scheduler = new SchedulerStore()\n\tscheduler.setPersistence(path.resolve(projectRoot, '.openvole', 'schedules.json'))\n\tscheduler.setTickHandler((input) => {\n\t\ttaskQueue.enqueue(input, 'schedule')\n\t})\n\tconst vault = new Vault(\n\t\tpath.resolve(projectRoot, '.openvole', 'vault.json'),\n\t\tprocess.env.VOLE_VAULT_KEY,\n\t)\n\tawait vault.init()\n\n\t// Register built-in core tools\n\tconst coreTools = createCoreTools(scheduler, taskQueue, projectRoot, skillRegistry, vault)\n\ttoolRegistry.register('__core__', coreTools, true)\n\n\t// Wire up query sources so Paws can query skills and tasks\n\tpawRegistry.setQuerySources(skillRegistry, taskQueue, scheduler)\n\n\t// Wire up the task runner\n\ttaskQueue.setRunner(async (task) => {\n\t\tawait runAgentLoop(task, {\n\t\t\tbus,\n\t\t\ttoolRegistry,\n\t\t\tpawRegistry,\n\t\t\tskillRegistry,\n\t\t\tio,\n\t\t\tconfig: config.loop,\n\t\t\ttoolProfiles: config.toolProfiles,\n\t\t\trateLimiter,\n\t\t})\n\t})\n\n\tlet shuttingDown = false\n\n\tconst engine: VoleEngine = {\n\t\tbus,\n\t\ttoolRegistry,\n\t\tpawRegistry,\n\t\tskillRegistry,\n\t\ttaskQueue,\n\t\tio,\n\t\tconfig,\n\n\t\tasync start() {\n\t\t\tengineLogger.info('Starting OpenVole...')\n\t\t\tconst headless = options?.headless ?? false\n\n\t\t\t// Set Brain (setBrain resolves config path → manifest name after load)\n\t\t\tif (config.brain) {\n\t\t\t\t// setBrain is called after brain paw loads (below) so the mapping exists\n\t\t\t} else {\n\t\t\t\tengineLogger.info('No Brain Paw configured — Think step will be a no-op')\n\t\t\t}\n\n\t\t\t// In headless mode, skip dashboard and channel paws (telegram, slack, discord, whatsapp)\n\t\t\tconst headlessSkipPatterns = ['paw-dashboard', 'paw-telegram', 'paw-slack', 'paw-discord', 'paw-whatsapp']\n\n\t\t\t// Load Paws (Brain first, then others, in-process last)\n\t\t\tconst pawConfigs = config.paws.map(normalizePawConfig)\n\t\t\tconst brainConfig = pawConfigs.find((p) => p.name === config.brain)\n\t\t\tconst subprocessPaws = pawConfigs.filter(\n\t\t\t\t(p) => p.name !== config.brain,\n\t\t\t)\n\n\t\t\t// Load Brain Paw first\n\t\t\tif (brainConfig) {\n\t\t\t\tconst ok = await pawRegistry.load(brainConfig)\n\t\t\t\tif (ok) {\n\t\t\t\t\tpawRegistry.setBrain(config.brain!)\n\t\t\t\t\tengineLogger.info(`Brain Paw: ${pawRegistry.resolveManifestName(config.brain!)}`)\n\t\t\t\t} else {\n\t\t\t\t\tengineLogger.error(\n\t\t\t\t\t\t`Brain Paw \"${brainConfig.name}\" failed to load — running in no-op Think mode`,\n\t\t\t\t\t)\n\t\t\t\t\tpawRegistry.setBrain('')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Load other Paws in parallel\n\t\t\tconst pawsToLoad = headless\n\t\t\t\t? subprocessPaws.filter((p) => !headlessSkipPatterns.some((pat) => p.name.includes(pat)))\n\t\t\t\t: subprocessPaws\n\t\t\tawait Promise.all(pawsToLoad.map((pawConfig) => pawRegistry.load(pawConfig)))\n\n\t\t\t// Load Skills\n\t\t\tfor (const skillName of config.skills) {\n\t\t\t\tawait skillRegistry.load(skillName)\n\t\t\t}\n\n\t\t\t// Final resolver pass\n\t\t\tskillRegistry.resolve()\n\n\t\t\t// Restore persisted schedules from disk (skip in headless — vole run shouldn't touch schedules)\n\t\t\tif (!headless) {\n\t\t\t\tawait scheduler.restore()\n\t\t\t} else {\n\t\t\t\t// In headless mode, use loadFromDisk for read-only access (no persistence)\n\t\t\t\tawait scheduler.loadFromDisk()\n\t\t\t}\n\n\t\t\t// Start heartbeat via scheduler (skip in headless mode)\n\t\t\tif (config.heartbeat.enabled && !headless) {\n\t\t\t\tconst heartbeatMdPath = path.resolve(projectRoot, '.openvole', 'HEARTBEAT.md')\n\t\t\t\t// Convert intervalMinutes to cron expression (e.g. 30 → \"*/30 * * * *\")\n\t\t\t\tconst heartbeatCron = `*/${config.heartbeat.intervalMinutes} * * * *`\n\t\t\t\tscheduler.add(\n\t\t\t\t\t'__heartbeat__',\n\t\t\t\t\t'Heartbeat wake-up',\n\t\t\t\t\theartbeatCron,\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tlet heartbeatContent = ''\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\theartbeatContent = await fs.readFile(heartbeatMdPath, 'utf-8')\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// No HEARTBEAT.md — use default prompt\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst input = heartbeatContent\n\t\t\t\t\t\t\t? `Heartbeat wake-up. Review your HEARTBEAT.md jobs and act on what is needed:\\n\\n${heartbeatContent}`\n\t\t\t\t\t\t\t: 'Heartbeat wake-up. Check active skills and decide if any actions are needed.'\n\n\t\t\t\t\t\ttaskQueue.enqueue(input, 'heartbeat')\n\t\t\t\t\t},\n\t\t\t\t\tundefined,\n\t\t\t\t\tconfig.heartbeat.runOnStart ?? false,\n\t\t\t\t)\n\t\t\t\tengineLogger.info(`Heartbeat enabled — cron: ${heartbeatCron}${config.heartbeat.runOnStart ? ', running now' : ''}`)\n\t\t\t}\n\n\t\t\tengineLogger.info(\n\t\t\t\t`Ready — ${toolRegistry.list().length} tools, ` +\n\t\t\t\t\t`${pawRegistry.list().length} paws, ` +\n\t\t\t\t\t`${skillRegistry.active().length}/${skillRegistry.list().length} skills active`,\n\t\t\t)\n\t\t},\n\n\t\trun(input, source = 'user', sessionId?) {\n\t\t\ttaskQueue.enqueue(input, source, sessionId ? { sessionId } : undefined)\n\t\t},\n\n\t\tasync shutdown() {\n\t\t\tif (shuttingDown) return\n\t\t\tshuttingDown = true\n\t\t\tengineLogger.info('Shutting down...')\n\t\t\tscheduler.clearAll()\n\t\t\ttaskQueue.cancelAll()\n\t\t\tfor (const paw of pawRegistry.list()) {\n\t\t\t\tawait pawRegistry.unload(paw.name)\n\t\t\t}\n\t\t\ttoolRegistry.clear()\n\t\t\tengineLogger.info('Shutdown complete')\n\t\t\tcloseLogger()\n\t\t},\n\t}\n\n\treturn engine\n}\n","/** Summary of a tool available to the Brain */\nexport interface ToolSummary {\n\tname: string\n\tdescription: string\n\tpawName: string\n\t/** Parameter schema (Zod) — passed to Brain Paw for function calling */\n\tparameters?: unknown\n}\n\n/** A Skill whose required tools are all satisfied (compact — Brain reads full instructions on demand) */\nexport interface ActiveSkill {\n\tname: string\n\tdescription: string\n\tsatisfiedBy: string[]\n}\n\n/** A single message in the agent's reasoning history */\nexport interface AgentMessage {\n\trole: 'user' | 'brain' | 'tool_result' | 'error'\n\tcontent: string\n\ttoolCall?: { name: string; params: unknown }\n\ttimestamp: number\n}\n\n/** The shared data structure that flows through the agent loop */\nexport interface AgentContext {\n\ttaskId: string\n\tmessages: AgentMessage[]\n\tavailableTools: ToolSummary[]\n\tactiveSkills: ActiveSkill[]\n\tmetadata: Record<string, unknown>\n\titeration: number\n\tmaxIterations: number\n}\n\n/** Create an empty AgentContext for a new task */\nexport function createAgentContext(\n\ttaskId: string,\n\tmaxIterations: number,\n): AgentContext {\n\treturn {\n\t\ttaskId,\n\t\tmessages: [],\n\t\tavailableTools: [],\n\t\tactiveSkills: [],\n\t\tmetadata: {},\n\t\titeration: 0,\n\t\tmaxIterations,\n\t}\n}\n","/** Error codes for categorizing failures in the agent loop */\nexport type ActionErrorCode =\n\t| 'TOOL_TIMEOUT'\n\t| 'TOOL_EXCEPTION'\n\t| 'TOOL_NOT_FOUND'\n\t| 'PERMISSION_DENIED'\n\t| 'PAW_CRASHED'\n\t| 'BRAIN_ERROR'\n\t| 'INVALID_PLAN'\n\n/** Structured error attached to a failed action */\nexport interface ActionError {\n\tcode: ActionErrorCode\n\tmessage: string\n\ttoolName?: string\n\tpawName?: string\n\tdetails?: unknown\n}\n\n/** Result of a single tool execution during the Act phase */\nexport interface ActionResult {\n\ttoolName: string\n\tpawName: string\n\tsuccess: boolean\n\toutput?: unknown\n\terror?: ActionError\n\tdurationMs: number\n}\n\n/** Create a structured ActionError */\nexport function createActionError(\n\tcode: ActionErrorCode,\n\tmessage: string,\n\topts?: { toolName?: string; pawName?: string; details?: unknown },\n): ActionError {\n\treturn {\n\t\tcode,\n\t\tmessage,\n\t\ttoolName: opts?.toolName,\n\t\tpawName: opts?.pawName,\n\t\tdetails: opts?.details,\n\t}\n}\n\n/** Create a successful ActionResult */\nexport function successResult(\n\ttoolName: string,\n\tpawName: string,\n\toutput: unknown,\n\tdurationMs: number,\n): ActionResult {\n\treturn { toolName, pawName, success: true, output, durationMs }\n}\n\n/** Create a failed ActionResult */\nexport function failureResult(\n\ttoolName: string,\n\tpawName: string,\n\terror: ActionError,\n\tdurationMs: number,\n): ActionResult {\n\treturn { toolName, pawName, success: false, error, durationMs }\n}\n","import type { AgentContext } from '../context/types.js'\nimport { createAgentContext } from '../context/types.js'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { PawRegistry } from '../paw/registry.js'\nimport type { SkillRegistry } from '../skill/registry.js'\nimport type { VoleIO } from '../io/types.js'\nimport type { LoopConfig } from '../config/index.js'\nimport type { RateLimiter } from './rate-limiter.js'\nimport type { AgentTask } from './task.js'\nimport type { MessageBus } from './bus.js'\nimport type { AgentPlan, PlannedAction } from '../paw/types.js'\nimport {\n\tcreateActionError,\n\tfailureResult,\n\tsuccessResult,\n\ttype ActionResult,\n} from './errors.js'\nimport { buildActiveSkills } from '../skill/resolver.js'\nimport { PHASE_ORDER } from './hooks.js'\n\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('loop')\n\n/** Maximum consecutive Brain failures before halting */\nconst MAX_BRAIN_FAILURES = 3\n\nexport interface LoopDependencies {\n\tbus: MessageBus\n\ttoolRegistry: ToolRegistry\n\tpawRegistry: PawRegistry\n\tskillRegistry: SkillRegistry\n\tio: VoleIO\n\tconfig: LoopConfig\n\ttoolProfiles?: Record<string, import('../config/index.js').ToolProfile>\n\trateLimiter?: RateLimiter\n}\n\n/**\n * Run the agent loop for a single task.\n * Perceive → Think → Act → Observe → loop\n */\nexport async function runAgentLoop(\n\ttask: AgentTask,\n\tdeps: LoopDependencies,\n): Promise<void> {\n\tconst { bus, toolRegistry, pawRegistry, skillRegistry, io, config, toolProfiles, rateLimiter } = deps\n\tconst rateLimits = config.rateLimits\n\tlet toolExecutionCount = 0\n\tlogger.info(`Agent loop started for task ${task.id}: \"${task.input}\"`)\n\n\tlet context = createAgentContext(task.id, config.maxIterations)\n\n\t// Set task source in metadata so Paws (e.g. paw-memory) can scope by source\n\tcontext.metadata.taskSource = task.source\n\tcontext.metadata.sessionId = task.sessionId\n\tif (task.metadata) {\n\t\tObject.assign(context.metadata, task.metadata)\n\t}\n\tif (task.source === 'heartbeat') {\n\t\tcontext.metadata.heartbeat = true\n\t}\n\n\t// Seed with user input\n\tcontext.messages.push({\n\t\trole: 'user',\n\t\tcontent: task.input,\n\t\ttimestamp: Date.now(),\n\t})\n\n\t// === BOOTSTRAP — runs once at task start ===\n\tlogger.debug('Phase: bootstrap')\n\tcontext = await pawRegistry.runBootstrapHooks(context)\n\n\tlet consecutiveBrainFailures = 0\n\n\tfor (\n\t\tcontext.iteration = 0;\n\t\tcontext.iteration < config.maxIterations;\n\t\tcontext.iteration++\n\t) {\n\t\t// Check cancellation\n\t\tif (task.status === 'cancelled') {\n\t\t\tlogger.info(`Task ${task.id} cancelled at iteration ${context.iteration}`)\n\t\t\treturn\n\t\t}\n\n\t\t// === COMPACT — compress context if it exceeds threshold ===\n\t\tif (\n\t\t\tconfig.compactThreshold > 0 &&\n\t\t\tcontext.messages.length > config.compactThreshold\n\t\t) {\n\t\t\tlogger.info(\n\t\t\t\t`Context has ${context.messages.length} messages (threshold: ${config.compactThreshold}), running compact`,\n\t\t\t)\n\t\t\tcontext = await pawRegistry.runCompactHooks(context)\n\t\t}\n\n\t\tlogger.info(\n\t\t\t`Loop running — iteration ${context.iteration + 1}/${config.maxIterations}`,\n\t\t)\n\n\t\t// === PERCEIVE (global only — lazy perceive runs in Act) ===\n\t\tlogger.debug(`Phase: ${PHASE_ORDER[0]}`)\n\t\tconst enrichedContext = await runPerceive(context, pawRegistry, toolRegistry, skillRegistry)\n\n\t\t// === RATE LIMIT CHECK (before Think) ===\n\t\tif (rateLimiter && rateLimits) {\n\t\t\tif (rateLimits.llmCallsPerMinute != null) {\n\t\t\t\tif (!rateLimiter.tryConsume('llm:per-minute', rateLimits.llmCallsPerMinute, 60_000)) {\n\t\t\t\t\tlogger.warn(`Rate limit hit: llmCallsPerMinute (${rateLimits.llmCallsPerMinute})`)\n\t\t\t\t\tbus.emit('rate:limited', { bucket: 'llm:per-minute', source: task.source })\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Rate limit exceeded: LLM calls per minute (limit: ${rateLimits.llmCallsPerMinute}). Retrying next iteration.`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rateLimits.llmCallsPerHour != null) {\n\t\t\t\tif (!rateLimiter.tryConsume('llm:per-hour', rateLimits.llmCallsPerHour, 3_600_000)) {\n\t\t\t\t\tlogger.warn(`Rate limit hit: llmCallsPerHour (${rateLimits.llmCallsPerHour})`)\n\t\t\t\t\tbus.emit('rate:limited', { bucket: 'llm:per-hour', source: task.source })\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Rate limit exceeded: LLM calls per hour (limit: ${rateLimits.llmCallsPerHour}). Retrying next iteration.`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// === THINK ===\n\t\tlogger.debug(`Phase: ${PHASE_ORDER[1]}`)\n\t\tconst plan = await runThink(enrichedContext, pawRegistry)\n\t\tif (plan && plan !== 'BRAIN_ERROR') {\n\t\t\tlogger.info(`Brain plan: done=${plan.done}, actions=${plan.actions.length}, response=${plan.response ? plan.response.substring(0, 100) + '...' : 'none'}`)\n\t\t}\n\n\t\tif (!plan) {\n\t\t\t// No Brain Paw configured — no-op Think\n\t\t\tlogger.debug('Think phase returned null (no Brain Paw)')\n\t\t\tbreak\n\t\t}\n\n\t\t// Handle Brain errors\n\t\tif (plan === 'BRAIN_ERROR') {\n\t\t\tconsecutiveBrainFailures++\n\t\t\tif (consecutiveBrainFailures >= MAX_BRAIN_FAILURES) {\n\t\t\t\tio.notify(\n\t\t\t\t\t`Brain Paw failed ${MAX_BRAIN_FAILURES} consecutive times. Halting task ${task.id}.`,\n\t\t\t\t)\n\t\t\t\ttask.error = `Brain failed ${MAX_BRAIN_FAILURES} consecutive times`\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tconsecutiveBrainFailures = 0\n\n\t\t// Check if the Brain says we're done\n\t\tif (plan.done) {\n\t\t\t// Detect if the Brain narrated tool calls instead of executing them\n\t\t\tif (plan.response && plan.actions.length === 0 && plan.response.startsWith('Calling tools:')) {\n\t\t\t\tlogger.warn('Brain narrated tool calls instead of executing them — forcing retry')\n\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\trole: 'error',\n\t\t\t\t\tcontent: 'You described tool calls as text instead of executing them. Use function calling to invoke tools — do not write tool calls as text. Try again.',\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t})\n\t\t\t\tplan.done = false\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (plan.response) {\n\t\t\t\ttask.result = plan.response\n\t\t\t\tio.notify(plan.response)\n\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\trole: 'brain',\n\t\t\t\t\tcontent: plan.response,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t})\n\t\t\t}\n\t\t\tlogger.info(`Task ${task.id} completed by Brain at iteration ${context.iteration + 1}`)\n\t\t\treturn\n\t\t}\n\n\t\t// If Brain has a response but also actions, show the response\n\t\tif (plan.response) {\n\t\t\tio.notify(plan.response)\n\t\t\tenrichedContext.messages.push({\n\t\t\t\trole: 'brain',\n\t\t\t\tcontent: plan.response,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t})\n\t\t}\n\n\t\t// === ACT ===\n\t\tlogger.debug(`Phase: ${PHASE_ORDER[2]}`)\n\t\tif (plan.actions.length > 0) {\n\t\t\t// Record the Brain's tool call intent in context so it sees its own reasoning on next iteration\n\t\t\tconst toolCallSummary = plan.actions.map((a) => `${a.tool}(${JSON.stringify(a.params)})`).join(', ')\n\t\t\tenrichedContext.messages.push({\n\t\t\t\trole: 'brain',\n\t\t\t\tcontent: plan.response || `Calling tools: ${toolCallSummary}`,\n\t\t\t\ttoolCall: plan.actions.length === 1\n\t\t\t\t\t? { name: plan.actions[0].tool, params: plan.actions[0].params }\n\t\t\t\t\t: { name: 'multiple', params: plan.actions.map((a) => ({ tool: a.tool, params: a.params })) },\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t})\n\t\t\t// Check tool execution rate limit\n\t\t\tif (rateLimiter && rateLimits?.toolExecutionsPerTask != null) {\n\t\t\t\tconst incoming = plan.actions.length\n\t\t\t\tif (toolExecutionCount + incoming > rateLimits.toolExecutionsPerTask) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`Rate limit hit: toolExecutionsPerTask (${toolExecutionCount + incoming}/${rateLimits.toolExecutionsPerTask})`,\n\t\t\t\t\t)\n\t\t\t\t\tbus.emit('rate:limited', { bucket: 'tools:per-task', source: task.source })\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Rate limit exceeded: tool executions per task (limit: ${rateLimits.toolExecutionsPerTask}, used: ${toolExecutionCount}). Stopping task.`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Filter actions by tool profile for this task source\n\t\t\tconst profile = toolProfiles?.[task.source]\n\t\t\tif (profile) {\n\t\t\t\tconst blocked: string[] = []\n\t\t\t\tplan.actions = plan.actions.filter((a) => {\n\t\t\t\t\tif (profile.allow && !profile.allow.includes(a.tool)) {\n\t\t\t\t\t\tblocked.push(a.tool)\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\tif (profile.deny?.includes(a.tool)) {\n\t\t\t\t\t\tblocked.push(a.tool)\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t})\n\t\t\t\tif (blocked.length > 0) {\n\t\t\t\t\tlogger.warn(`Blocked tools for source \"${task.source}\": ${blocked.join(', ')}`)\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: `Tools blocked by security profile for \"${task.source}\" source: ${blocked.join(', ')}`,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tif (plan.actions.length === 0) continue\n\t\t\t}\n\n\t\t\t// Log tool calls\n\t\t\tfor (const action of plan.actions) {\n\t\t\t\tlogger.info(`Tool call: ${action.tool}(${JSON.stringify(action.params)})`)\n\t\t\t}\n\n\t\t\t// Confirm before acting if configured\n\t\t\tif (config.confirmBeforeAct) {\n\t\t\t\tconst toolNames = plan.actions.map((a) => a.tool).join(', ')\n\t\t\t\tconst confirmed = await io.confirm(\n\t\t\t\t\t`Execute tools: ${toolNames}?`,\n\t\t\t\t)\n\t\t\t\tif (!confirmed) {\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: 'User declined to execute planned actions',\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst results = await runAct(\n\t\t\t\tplan.actions,\n\t\t\t\tplan.execution ?? 'sequential',\n\t\t\t\tenrichedContext,\n\t\t\t\ttoolRegistry,\n\t\t\t\tpawRegistry,\n\t\t\t)\n\n\t\t\t// Track tool executions for rate limiting\n\t\t\ttoolExecutionCount += results.length\n\n\t\t\t// === OBSERVE ===\n\t\t\tlogger.debug(`Phase: ${PHASE_ORDER[3]}`)\n\t\t\tfor (const result of results) {\n\t\t\t\t// Append to context\n\t\t\t\tif (result.success) {\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'tool_result',\n\t\t\t\t\t\tcontent: typeof result.output === 'string'\n\t\t\t\t\t\t\t? result.output\n\t\t\t\t\t\t\t: JSON.stringify(result.output),\n\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\tname: result.toolName,\n\t\t\t\t\t\t\tparams: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tenrichedContext.messages.push({\n\t\t\t\t\t\trole: 'error',\n\t\t\t\t\t\tcontent: result.error?.message ?? 'Unknown tool error',\n\t\t\t\t\t\ttoolCall: {\n\t\t\t\t\t\t\tname: result.toolName,\n\t\t\t\t\t\t\tparams: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// Fire observe hooks\n\t\t\t\tpawRegistry.runObserveHooks(result)\n\t\t\t}\n\t\t}\n\n\t\t// Update context for next iteration\n\t\tObject.assign(context, enrichedContext)\n\t}\n\n\tif (context.iteration >= config.maxIterations) {\n\t\tlogger.warn(\n\t\t\t`Task ${task.id} reached max iterations (${config.maxIterations})`,\n\t\t)\n\t\tio.notify(\n\t\t\t`Task reached maximum iterations (${config.maxIterations}). Stopping.`,\n\t\t)\n\t}\n}\n\n/** Run the Perceive phase — only global hooks (Paws without tools) */\nasync function runPerceive(\n\tcontext: AgentContext,\n\tpawRegistry: PawRegistry,\n\ttoolRegistry: ToolRegistry,\n\tskillRegistry: SkillRegistry,\n): Promise<AgentContext> {\n\t// Set available tools and active skills\n\tconst enriched = { ...context }\n\tenriched.availableTools = toolRegistry.summaries()\n\tenriched.activeSkills = buildActiveSkills(\n\t\tskillRegistry.list(),\n\t\ttoolRegistry,\n\t)\n\n\t// Only run global perceive hooks (Paws without tools — context enrichers)\n\t// Paws with tools use lazy perceive, called just before their tool executes\n\treturn pawRegistry.runGlobalPerceiveHooks(enriched)\n}\n\n/** Run the Think phase — ask the Brain for a plan */\nasync function runThink(\n\tcontext: AgentContext,\n\tpawRegistry: PawRegistry,\n): Promise<AgentPlan | null | 'BRAIN_ERROR'> {\n\ttry {\n\t\treturn await pawRegistry.think(context)\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\tlogger.error(`Brain error: ${message}`)\n\n\t\t// Add error to context for next iteration\n\t\tcontext.messages.push({\n\t\t\trole: 'error',\n\t\t\tcontent: `Brain error: ${message}`,\n\t\t\ttimestamp: Date.now(),\n\t\t})\n\n\t\treturn 'BRAIN_ERROR'\n\t}\n}\n\n/** Run the Act phase — execute tool calls with lazy perceive */\nasync function runAct(\n\tactions: PlannedAction[],\n\texecution: 'parallel' | 'sequential',\n\tcontext: AgentContext,\n\ttoolRegistry: ToolRegistry,\n\tpawRegistry: PawRegistry,\n): Promise<ActionResult[]> {\n\t// Collect unique Paw names from planned actions and run their lazy perceive\n\tconst pawNames = new Set<string>()\n\tfor (const action of actions) {\n\t\tconst tool = toolRegistry.get(action.tool)\n\t\tif (tool) pawNames.add(tool.pawName)\n\t}\n\n\t// Run lazy perceive for each involved Paw (before any tools execute)\n\tfor (const pawName of pawNames) {\n\t\tawait pawRegistry.runLazyPerceive(pawName, context)\n\t}\n\n\tif (execution === 'parallel') {\n\t\treturn Promise.all(\n\t\t\tactions.map((action) =>\n\t\t\t\texecuteSingleAction(action, toolRegistry, pawRegistry),\n\t\t\t),\n\t\t)\n\t}\n\n\t// Sequential execution\n\tconst results: ActionResult[] = []\n\tfor (const action of actions) {\n\t\tconst result = await executeSingleAction(action, toolRegistry, pawRegistry)\n\t\tresults.push(result)\n\t}\n\treturn results\n}\n\n/** Execute a single tool call */\nasync function executeSingleAction(\n\taction: PlannedAction,\n\ttoolRegistry: ToolRegistry,\n\tpawRegistry: PawRegistry,\n): Promise<ActionResult> {\n\tconst startTime = Date.now()\n\tconst tool = toolRegistry.get(action.tool)\n\n\tif (!tool) {\n\t\treturn failureResult(\n\t\t\taction.tool,\n\t\t\t'unknown',\n\t\t\tcreateActionError('TOOL_NOT_FOUND', `Tool \"${action.tool}\" not found`, {\n\t\t\t\ttoolName: action.tool,\n\t\t\t}),\n\t\t\tDate.now() - startTime,\n\t\t)\n\t}\n\n\t// Check if the owning Paw is healthy\n\tif (!tool.inProcess && !pawRegistry.isHealthy(tool.pawName)) {\n\t\treturn failureResult(\n\t\t\taction.tool,\n\t\t\ttool.pawName,\n\t\t\tcreateActionError('PAW_CRASHED', `Paw \"${tool.pawName}\" is not healthy`, {\n\t\t\t\ttoolName: action.tool,\n\t\t\t\tpawName: tool.pawName,\n\t\t\t}),\n\t\t\tDate.now() - startTime,\n\t\t)\n\t}\n\n\ttry {\n\t\t// Validate parameters if schema is a proper Zod schema\n\t\tif (tool.parameters && typeof tool.parameters.parse === 'function') {\n\t\t\ttool.parameters.parse(action.params)\n\t\t}\n\n\t\tconst output = await tool.execute(action.params)\n\t\treturn successResult(action.tool, tool.pawName, output, Date.now() - startTime)\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err)\n\n\t\t// Determine error code\n\t\tconst isTimeout = message.toLowerCase().includes('timeout')\n\t\tconst isPermission = message.toLowerCase().includes('permission')\n\t\tconst code = isTimeout\n\t\t\t? 'TOOL_TIMEOUT'\n\t\t\t: isPermission\n\t\t\t\t? 'PERMISSION_DENIED'\n\t\t\t\t: 'TOOL_EXCEPTION'\n\n\t\treturn failureResult(\n\t\t\taction.tool,\n\t\t\ttool.pawName,\n\t\t\tcreateActionError(code, message, {\n\t\t\t\ttoolName: action.tool,\n\t\t\t\tpawName: tool.pawName,\n\t\t\t\tdetails: err instanceof Error ? err.stack : undefined,\n\t\t\t}),\n\t\t\tDate.now() - startTime,\n\t\t)\n\t}\n}\n","/**\n * Hook phase definitions.\n *\n * The actual hook execution logic lives in PawRegistry (perceive/observe hooks)\n * and the agent loop (think/act orchestration). This module defines the hook\n * lifecycle constants and types used across the system.\n */\n\n/** The four phases of the agent loop */\nexport type LoopPhase = 'perceive' | 'think' | 'act' | 'observe'\n\n/** Phase ordering for logging and tracing */\nexport const PHASE_ORDER: readonly LoopPhase[] = [\n\t'perceive',\n\t'think',\n\t'act',\n\t'observe',\n] as const\n","import { createLogger } from './logger.js'\n\nconst logger = createLogger('rate-limiter')\n\n/**\n * Sliding window counter rate limiter.\n * Tracks timestamps per bucket and checks against limits.\n */\nexport class RateLimiter {\n\tprivate buckets = new Map<string, number[]>()\n\n\t/**\n\t * Try to consume one token from the bucket.\n\t * Returns true if the request is under the limit, false if rate-limited.\n\t */\n\ttryConsume(bucket: string, limit: number, windowMs: number): boolean {\n\t\tconst now = Date.now()\n\t\tthis.cleanup(bucket, now, windowMs)\n\n\t\tconst timestamps = this.buckets.get(bucket) ?? []\n\t\tif (timestamps.length >= limit) {\n\t\t\tlogger.debug(`Bucket \"${bucket}\" rate-limited: ${timestamps.length}/${limit} in ${windowMs}ms window`)\n\t\t\treturn false\n\t\t}\n\n\t\ttimestamps.push(now)\n\t\tthis.buckets.set(bucket, timestamps)\n\t\treturn true\n\t}\n\n\t/**\n\t * Returns the number of remaining tokens in the bucket for the current window.\n\t */\n\tremaining(bucket: string, limit: number, windowMs: number): number {\n\t\tconst now = Date.now()\n\t\tthis.cleanup(bucket, now, windowMs)\n\n\t\tconst timestamps = this.buckets.get(bucket) ?? []\n\t\treturn Math.max(0, limit - timestamps.length)\n\t}\n\n\t/**\n\t * Remove expired timestamps from a bucket.\n\t */\n\tprivate cleanup(bucket: string, now: number, windowMs: number): void {\n\t\tconst timestamps = this.buckets.get(bucket)\n\t\tif (!timestamps) return\n\n\t\tconst cutoff = now - windowMs\n\t\tconst filtered = timestamps.filter((t) => t > cutoff)\n\n\t\tif (filtered.length === 0) {\n\t\t\tthis.buckets.delete(bucket)\n\t\t} else {\n\t\t\tthis.buckets.set(bucket, filtered)\n\t\t}\n\t}\n}\n","import type { MessageBus } from '../core/bus.js'\nimport type { ToolRegistry } from '../tool/registry.js'\nimport type { PawConfig, PawInstance } from './types.js'\nimport { readPawManifest, resolvePawPath } from './manifest.js'\nimport { loadInProcessPaw, loadSubprocessPaw, shutdownPaw } from './loader.js'\nimport { validatePermissions } from './sandbox.js'\nimport type { IpcTransport } from '../core/ipc.js'\nimport type { AgentContext } from '../context/types.js'\nimport type { ActionResult } from '../core/errors.js'\nimport type { AgentPlan } from './types.js'\n\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-registry')\n\n/** Perceive hook config for ordering */\nexport interface PerceiveHookEntry {\n\tpawName: string\n\torder: number\n\tpipeline: boolean\n\t/** If true, this Paw has tools — its perceive runs lazily before tool execution, not every iteration */\n\thasTools: boolean\n}\n\n/** Interface for queryable registries (avoids circular imports) */\nexport interface QueryableSkillRegistry {\n\tlist(): Array<{ name: string; active: boolean; missingTools: string[]; definition: { description: string } }>\n}\n\nexport interface QueryableTaskQueue {\n\tlist(): Array<{ id: string; source: string; input: string; status: string; createdAt: number }>\n\tenqueue(input: string, source?: 'user' | 'schedule' | 'paw', options?: { sessionId?: string; metadata?: Record<string, unknown> }): { id: string }\n}\n\nexport interface QueryableScheduler {\n\tlist(): Array<{ id: string; input: string; cron: string; nextRun?: string; createdAt: number }>\n}\n\n/** Manages loaded Paws and their lifecycle */\nexport class PawRegistry {\n\tprivate paws = new Map<string, PawInstance>()\n\tprivate transports = new Map<string, IpcTransport>()\n\tprivate perceiveHooks: PerceiveHookEntry[] = []\n\tprivate observeHookPaws: string[] = []\n\tprivate bootstrapPaws: string[] = []\n\tprivate compactPaws: string[] = []\n\tprivate brainPawName: string | undefined\n\t/** Maps config path → manifest name (e.g. \"./paws/paw-ollama\" → \"@openvole/paw-ollama\") */\n\tprivate configToManifest = new Map<string, string>()\n\tprivate skillRegistry?: QueryableSkillRegistry\n\tprivate taskQueue?: QueryableTaskQueue\n\tprivate scheduler?: QueryableScheduler\n\n\tconstructor(\n\t\tprivate bus: MessageBus,\n\t\tprivate toolRegistry: ToolRegistry,\n\t\tprivate projectRoot: string,\n\t) {\n\t\t// Handle Paw crash events\n\t\tthis.bus.on('paw:crashed', ({ pawName }) => {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (instance) {\n\t\t\t\tinstance.healthy = false\n\t\t\t\tthis.toolRegistry.unregister(pawName)\n\t\t\t}\n\t\t})\n\t}\n\n\t/** Inject queryable registries (called after construction to avoid circular deps) */\n\tsetQuerySources(skills: QueryableSkillRegistry, tasks: QueryableTaskQueue, scheduler?: QueryableScheduler): void {\n\t\tthis.skillRegistry = skills\n\t\tthis.taskQueue = tasks\n\t\tthis.scheduler = scheduler\n\t}\n\n\t/** Load and register a Paw */\n\tasync load(config: PawConfig): Promise<boolean> {\n\t\tconst pawPath = resolvePawPath(config.name, this.projectRoot)\n\t\tconst manifest = await readPawManifest(pawPath)\n\n\t\tif (!manifest) {\n\t\t\tlogger.error(`Failed to read manifest for \"${config.name}\"`)\n\t\t\treturn false\n\t\t}\n\n\t\t// Use manifest name as identity, config name for resolution only\n\t\tconst pawName = manifest.name\n\n\t\tif (this.paws.has(pawName)) {\n\t\t\tlogger.warn(`Paw \"${pawName}\" is already loaded`)\n\t\t\treturn false\n\t\t}\n\n\t\t// Track config path → manifest name mapping\n\t\tthis.configToManifest.set(config.name, pawName)\n\n\t\t// Validate permissions\n\t\tvalidatePermissions(manifest, config)\n\n\t\ttry {\n\t\t\tlet instance: PawInstance\n\n\t\t\tif (manifest.inProcess) {\n\t\t\t\tinstance = await loadInProcessPaw(pawPath, manifest, config)\n\t\t\t\tthis.registerInProcessTools(instance)\n\t\t\t} else {\n\t\t\t\tconst result = await loadSubprocessPaw(pawPath, manifest, config)\n\t\t\t\tinstance = result.instance\n\t\t\t\tthis.transports.set(pawName, result.transport)\n\t\t\t\tthis.setupTransportHandlers(pawName, result.transport)\n\n\t\t\t\t// Wait for the Paw to register itself\n\t\t\t\tawait this.waitForRegistration(pawName, result.transport)\n\t\t\t}\n\n\t\t\tthis.paws.set(pawName, instance)\n\n\t\t\t// Track hooks\n\t\t\tif (instance.definition?.hooks?.onPerceive) {\n\t\t\t\tconst hookConfig = config.hooks?.perceive\n\t\t\t\tconst hasTools = (instance.definition?.tools?.length ?? 0) > 0 || manifest.tools.length > 0\n\t\t\t\tthis.perceiveHooks.push({\n\t\t\t\t\tpawName,\n\t\t\t\t\torder: hookConfig?.order ?? 100,\n\t\t\t\t\tpipeline: hookConfig?.pipeline ?? true,\n\t\t\t\t\thasTools,\n\t\t\t\t})\n\t\t\t\tthis.perceiveHooks.sort((a, b) => a.order - b.order)\n\t\t\t}\n\n\t\t\tif (instance.definition?.hooks?.onObserve) {\n\t\t\t\tthis.observeHookPaws.push(pawName)\n\t\t\t}\n\n\t\t\tif (instance.definition?.hooks?.onBootstrap) {\n\t\t\t\tthis.bootstrapPaws.push(pawName)\n\t\t\t}\n\n\t\t\tif (instance.definition?.hooks?.onCompact) {\n\t\t\t\tthis.compactPaws.push(pawName)\n\t\t\t}\n\n\t\t\tlogger.info(`Paw \"${pawName}\" loaded successfully`)\n\t\t\tthis.bus.emit('paw:registered', { pawName })\n\t\t\treturn true\n\t\t} catch (err) {\n\t\t\tlogger.error(`Failed to load Paw \"${pawName}\": ${err}`)\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/** Unload a Paw (accepts config path or manifest name) */\n\tasync unload(name: string): Promise<boolean> {\n\t\t// Resolve config path to manifest name if needed\n\t\tconst pawName = this.configToManifest.get(name) ?? name\n\t\tconst instance = this.paws.get(pawName)\n\t\tif (!instance) {\n\t\t\tlogger.warn(`Paw \"${pawName}\" is not loaded`)\n\t\t\treturn false\n\t\t}\n\t\t// Use resolved name from here\n\t\tname = pawName\n\n\t\t// Shutdown the Paw\n\t\tawait shutdownPaw(instance)\n\n\t\t// Clean up transport\n\t\tconst transport = this.transports.get(name)\n\t\tif (transport) {\n\t\t\ttransport.dispose()\n\t\t\tthis.transports.delete(name)\n\t\t}\n\n\t\t// Remove tools from registry\n\t\tthis.toolRegistry.unregister(name)\n\n\t\t// Remove hooks\n\t\tthis.perceiveHooks = this.perceiveHooks.filter((h) => h.pawName !== name)\n\t\tthis.observeHookPaws = this.observeHookPaws.filter((n) => n !== name)\n\t\tthis.bootstrapPaws = this.bootstrapPaws.filter((n) => n !== name)\n\t\tthis.compactPaws = this.compactPaws.filter((n) => n !== name)\n\n\t\tthis.paws.delete(name)\n\t\t// Clean up config→manifest mapping\n\t\tfor (const [configName, manifestName] of this.configToManifest) {\n\t\t\tif (manifestName === name) {\n\t\t\t\tthis.configToManifest.delete(configName)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tlogger.info(`Paw \"${name}\" unloaded`)\n\t\tthis.bus.emit('paw:unregistered', { pawName: name })\n\t\treturn true\n\t}\n\n\t/** Resolve a config name to its manifest name */\n\tresolveManifestName(configName: string): string {\n\t\treturn this.configToManifest.get(configName) ?? configName\n\t}\n\n\t/** Set the Brain Paw name (accepts config path or manifest name) */\n\tsetBrain(name: string): void {\n\t\tthis.brainPawName = this.configToManifest.get(name) ?? name\n\t}\n\n\t/** Get the Brain Paw name */\n\tgetBrainName(): string | undefined {\n\t\treturn this.brainPawName\n\t}\n\n\t/** Get a Paw instance */\n\tget(name: string): PawInstance | undefined {\n\t\treturn this.paws.get(name)\n\t}\n\n\t/** List all loaded Paws */\n\tlist(): PawInstance[] {\n\t\treturn Array.from(this.paws.values())\n\t}\n\n\t/** Check if a Paw is healthy */\n\tisHealthy(name: string): boolean {\n\t\treturn this.paws.get(name)?.healthy ?? false\n\t}\n\n\t/**\n\t * Run GLOBAL perceive hooks — only Paws without tools.\n\t * Paws with tools use lazy perceive (called just before their tool executes).\n\t */\n\tasync runGlobalPerceiveHooks(context: AgentContext): Promise<AgentContext> {\n\t\tlet chainedContext = { ...context }\n\n\t\t// Only run hooks from Paws that have NO tools (context-only Paws)\n\t\tconst globalChained = this.perceiveHooks.filter((h) => h.pipeline && !h.hasTools)\n\t\tconst globalUnchained = this.perceiveHooks.filter((h) => !h.pipeline && !h.hasTools)\n\n\t\t// Run chained hooks sequentially\n\t\tfor (const hook of globalChained) {\n\t\t\tconst instance = this.paws.get(hook.pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\ttry {\n\t\t\t\tchainedContext = await this.callPerceive(hook.pawName, chainedContext)\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Perceive hook error from \"${hook.pawName}\": ${err}`)\n\t\t\t}\n\t\t}\n\n\t\t// Run unchained hooks in parallel on the original context\n\t\tif (globalUnchained.length > 0) {\n\t\t\tconst results = await Promise.allSettled(\n\t\t\t\tglobalUnchained.map(async (hook) => {\n\t\t\t\t\tconst instance = this.paws.get(hook.pawName)\n\t\t\t\t\tif (!instance?.healthy) return null\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await this.callPerceive(hook.pawName, context)\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tlogger.error(`Unchained perceive error from \"${hook.pawName}\": ${err}`)\n\t\t\t\t\t\treturn null\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t)\n\n\t\t\tfor (const result of results) {\n\t\t\t\tif (result.status === 'fulfilled' && result.value) {\n\t\t\t\t\tObject.assign(chainedContext.metadata, result.value.metadata)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn chainedContext\n\t}\n\n\t/**\n\t * Run LAZY perceive for a specific Paw — called just before its tool executes.\n\t * Only runs if the Paw has an onPerceive hook registered.\n\t */\n\tasync runLazyPerceive(pawName: string, context: AgentContext): Promise<AgentContext> {\n\t\tconst hook = this.perceiveHooks.find((h) => h.pawName === pawName && h.hasTools)\n\t\tif (!hook) return context\n\n\t\tconst instance = this.paws.get(pawName)\n\t\tif (!instance?.healthy) return context\n\n\t\ttry {\n\t\t\tlogger.debug(`Lazy perceive for \"${pawName}\" before tool execution`)\n\t\t\treturn await this.callPerceive(pawName, context)\n\t\t} catch (err) {\n\t\t\tlogger.error(`Lazy perceive error from \"${pawName}\": ${err}`)\n\t\t\treturn context\n\t\t}\n\t}\n\n\t/** Run all Observe hooks concurrently (fire-and-forget) */\n\trunObserveHooks(result: ActionResult): void {\n\t\tfor (const pawName of this.observeHookPaws) {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\tthis.callObserve(pawName, result).catch((err) => {\n\t\t\t\tlogger.error(`Observe hook error from \"${pawName}\": ${err}`)\n\t\t\t})\n\t\t}\n\t}\n\n\t/** Run bootstrap hooks — called once at the start of a task */\n\tasync runBootstrapHooks(context: AgentContext): Promise<AgentContext> {\n\t\tlet ctx = { ...context }\n\n\t\tfor (const pawName of this.bootstrapPaws) {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\ttry {\n\t\t\t\tif (instance.inProcess && instance.definition?.hooks?.onBootstrap) {\n\t\t\t\t\tctx = await instance.definition.hooks.onBootstrap(ctx)\n\t\t\t\t} else {\n\t\t\t\t\tconst transport = this.transports.get(pawName)\n\t\t\t\t\tif (transport) {\n\t\t\t\t\t\tctx = (await transport.request('bootstrap', ctx)) as AgentContext\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Bootstrap hook error from \"${pawName}\": ${err}`)\n\t\t\t}\n\t\t}\n\n\t\treturn ctx\n\t}\n\n\t/**\n\t * Run compact hooks — called when context exceeds size threshold.\n\t * Paws can compress/summarize messages to free up context window space.\n\t */\n\tasync runCompactHooks(context: AgentContext): Promise<AgentContext> {\n\t\tlet ctx = { ...context }\n\n\t\tfor (const pawName of this.compactPaws) {\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (!instance?.healthy) continue\n\n\t\t\ttry {\n\t\t\t\tif (instance.inProcess && instance.definition?.hooks?.onCompact) {\n\t\t\t\t\tctx = await instance.definition.hooks.onCompact(ctx)\n\t\t\t\t} else {\n\t\t\t\t\tconst transport = this.transports.get(pawName)\n\t\t\t\t\tif (transport) {\n\t\t\t\t\t\tctx = (await transport.request('compact', ctx)) as AgentContext\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlogger.info(`Compact hook from \"${pawName}\" reduced messages from ${context.messages.length} to ${ctx.messages.length}`)\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(`Compact hook error from \"${pawName}\": ${err}`)\n\t\t\t}\n\t\t}\n\n\t\treturn ctx\n\t}\n\n\t/** Call the Brain Paw's think function */\n\tasync think(context: AgentContext): Promise<AgentPlan | null> {\n\t\tif (!this.brainPawName) return null\n\n\t\tconst instance = this.paws.get(this.brainPawName)\n\t\tif (!instance?.healthy) {\n\t\t\tlogger.error(`Brain Paw \"${this.brainPawName}\" is not healthy`)\n\t\t\treturn null\n\t\t}\n\n\t\tif (instance.inProcess && instance.definition?.think) {\n\t\t\treturn instance.definition.think(context)\n\t\t}\n\n\t\tconst transport = this.transports.get(this.brainPawName)\n\t\tif (!transport) {\n\t\t\tlogger.error(`No transport for Brain Paw \"${this.brainPawName}\"`)\n\t\t\treturn null\n\t\t}\n\n\t\treturn (await transport.request('think', context)) as AgentPlan\n\t}\n\n\t/** Execute a tool on a subprocess Paw */\n\tasync executeRemoteTool(\n\t\tpawName: string,\n\t\ttoolName: string,\n\t\tparams: unknown,\n\t): Promise<unknown> {\n\t\tconst transport = this.transports.get(pawName)\n\t\tif (!transport) {\n\t\t\tthrow new Error(`No transport for Paw \"${pawName}\"`)\n\t\t}\n\n\t\treturn transport.request('execute_tool', { toolName, params })\n\t}\n\n\tprivate async callPerceive(\n\t\tpawName: string,\n\t\tcontext: AgentContext,\n\t): Promise<AgentContext> {\n\t\tconst instance = this.paws.get(pawName)!\n\n\t\tif (instance.inProcess && instance.definition?.hooks?.onPerceive) {\n\t\t\treturn instance.definition.hooks.onPerceive(context)\n\t\t}\n\n\t\tconst transport = this.transports.get(pawName)\n\t\tif (transport) {\n\t\t\treturn (await transport.request('perceive', context)) as AgentContext\n\t\t}\n\n\t\treturn context\n\t}\n\n\tprivate async callObserve(\n\t\tpawName: string,\n\t\tresult: ActionResult,\n\t): Promise<void> {\n\t\tconst instance = this.paws.get(pawName)!\n\n\t\tif (instance.inProcess && instance.definition?.hooks?.onObserve) {\n\t\t\tawait instance.definition.hooks.onObserve(result)\n\t\t\treturn\n\t\t}\n\n\t\tconst transport = this.transports.get(pawName)\n\t\tif (transport) {\n\t\t\tawait transport.request('observe', result)\n\t\t}\n\t}\n\n\tprivate registerInProcessTools(instance: PawInstance): void {\n\t\tif (instance.definition?.tools) {\n\t\t\tthis.toolRegistry.register(\n\t\t\t\tinstance.name,\n\t\t\t\tinstance.definition.tools,\n\t\t\t\ttrue,\n\t\t\t)\n\t\t}\n\t}\n\n\tprivate setupTransportHandlers(\n\t\tpawName: string,\n\t\ttransport: IpcTransport,\n\t): void {\n\t\t// Handle Paw → Core: log\n\t\ttransport.onRequest('log', async (params) => {\n\t\t\tconst { level, message } = params as { level: string; message: string }\n\t\t\tconst prefix = `[${pawName}]`\n\t\t\tswitch (level) {\n\t\t\t\tcase 'error':\n\t\t\t\t\tconsole.error(prefix, message)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'warn':\n\t\t\t\t\tconsole.warn(prefix, message)\n\t\t\t\t\tbreak\n\t\t\t\tcase 'info':\n\t\t\t\t\tconsole.info(prefix, message)\n\t\t\t\t\tbreak\n\t\t\t\tdefault:\n\t\t\t\t\tconsole.debug(prefix, message)\n\t\t\t}\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: emit\n\t\ttransport.onRequest('emit', async (params) => {\n\t\t\tconst { event } = params as { event: string; data: unknown }\n\t\t\tlogger.info(`Paw \"${pawName}\" emitted event: ${event}`)\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: subscribe to bus events\n\t\ttransport.onRequest('subscribe', async (params) => {\n\t\t\tconst { events } = params as { events: string[] }\n\t\t\tconst instance = this.paws.get(pawName)\n\t\t\tif (instance) {\n\t\t\t\tinstance.subscriptions = events\n\t\t\t\tthis.setupBusForwarding(pawName, events, transport)\n\t\t\t\tlogger.info(`Paw \"${pawName}\" subscribed to events: ${events.join(', ')}`)\n\t\t\t}\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: query state\n\t\ttransport.onRequest('query', async (params) => {\n\t\t\tconst { type } = params as { type: 'tools' | 'paws' | 'skills' | 'tasks' }\n\t\t\treturn this.handleQuery(type)\n\t\t})\n\n\t\t// Handle Paw → Core: late tool registration (e.g. MCP tools discovered after initial registration)\n\t\ttransport.onRequest('register_tools', async (params) => {\n\t\t\tconst { tools } = params as { tools: Array<{ name: string; description: string }> }\n\t\t\tif (tools && tools.length > 0) {\n\t\t\t\tconst toolDefs = tools.map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tparameters: {} as import('zod').ZodSchema,\n\t\t\t\t\texecute: async (toolParams: unknown) =>\n\t\t\t\t\t\tthis.executeRemoteTool(pawName, t.name, toolParams),\n\t\t\t\t}))\n\t\t\t\tthis.toolRegistry.register(pawName, toolDefs, false)\n\t\t\t\tlogger.info(`Paw \"${pawName}\" late-registered ${tools.length} tool(s)`)\n\t\t\t}\n\t\t\treturn { ok: true }\n\t\t})\n\n\t\t// Handle Paw → Core: create a task (for channel Paws that receive inbound messages)\n\t\ttransport.onRequest('create_task', async (params) => {\n\t\t\tconst { input, source, sessionId, metadata } = params as {\n\t\t\t\tinput: string\n\t\t\t\tsource?: 'paw' | 'schedule'\n\t\t\t\tsessionId?: string\n\t\t\t\tmetadata?: Record<string, unknown>\n\t\t\t}\n\t\t\tif (!this.taskQueue) {\n\t\t\t\treturn { error: 'Task queue not available' }\n\t\t\t}\n\t\t\tconst task = this.taskQueue.enqueue(input, source ?? 'paw', { sessionId, metadata })\n\t\t\tlogger.info(`Paw \"${pawName}\" created task ${task.id}: \"${input.substring(0, 50)}\"`)\n\t\t\treturn { taskId: task.id }\n\t\t})\n\t}\n\n\t/** Forward bus events to a Paw that subscribed */\n\tprivate setupBusForwarding(\n\t\tpawName: string,\n\t\tevents: string[],\n\t\ttransport: IpcTransport,\n\t): void {\n\t\tfor (const eventName of events) {\n\t\t\t// Use the bus wildcard or specific events\n\t\t\tthis.bus.on(eventName as keyof import('../core/bus.js').BusEvents, (data) => {\n\t\t\t\tconst instance = this.paws.get(pawName)\n\t\t\t\tif (!instance?.healthy) return\n\n\t\t\t\ttransport.notify('bus_event', { event: eventName, data })\n\t\t\t})\n\t\t}\n\t}\n\n\t/** Handle state queries from Paws */\n\tprivate handleQuery(type: string): unknown {\n\t\tswitch (type) {\n\t\t\tcase 'tools':\n\t\t\t\treturn this.toolRegistry.list().map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tpawName: t.pawName,\n\t\t\t\t\tinProcess: t.inProcess,\n\t\t\t\t}))\n\t\t\tcase 'paws':\n\t\t\t\treturn Array.from(this.paws.values()).map((p) => ({\n\t\t\t\t\tname: p.name,\n\t\t\t\t\thealthy: p.healthy,\n\t\t\t\t\tinProcess: p.inProcess,\n\t\t\t\t\ttransport: p.transport,\n\t\t\t\t\ttoolCount: this.toolRegistry.toolsForPaw(p.name).length,\n\t\t\t\t}))\n\t\t\tcase 'skills':\n\t\t\t\treturn this.skillRegistry?.list().map((s) => ({\n\t\t\t\t\tname: s.name,\n\t\t\t\t\tactive: s.active,\n\t\t\t\t\tmissingTools: s.missingTools,\n\t\t\t\t\tdescription: s.definition.description,\n\t\t\t\t})) ?? []\n\t\t\tcase 'tasks':\n\t\t\t\treturn this.taskQueue?.list().map((t) => ({\n\t\t\t\t\tid: t.id,\n\t\t\t\t\tsource: t.source,\n\t\t\t\t\tinput: t.input,\n\t\t\t\t\tstatus: t.status,\n\t\t\t\t\tcreatedAt: t.createdAt,\n\t\t\t\t\tstartedAt: (t as Record<string, unknown>).startedAt,\n\t\t\t\t\tcompletedAt: (t as Record<string, unknown>).completedAt,\n\t\t\t\t})) ?? []\n\t\t\tcase 'schedules':\n\t\t\t\treturn this.scheduler?.list() ?? []\n\t\t\tdefault:\n\t\t\t\treturn { error: `Unknown query type: ${type}` }\n\t\t}\n\t}\n\n\tprivate async waitForRegistration(\n\t\tpawName: string,\n\t\ttransport: IpcTransport,\n\t): Promise<void> {\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => {\n\t\t\t\treject(new Error(`Paw \"${pawName}\" did not register within 10 seconds`))\n\t\t\t}, 10_000)\n\n\t\t\ttransport.onRequest('register', async (params) => {\n\t\t\t\tclearTimeout(timeout)\n\t\t\t\tconst registration = params as {\n\t\t\t\t\ttools?: Array<{ name: string; description: string }>\n\t\t\t\t\thooks?: {\n\t\t\t\t\t\tbootstrap?: boolean\n\t\t\t\t\t\tperceive?: boolean\n\t\t\t\t\t\tobserve?: boolean\n\t\t\t\t\t\tcompact?: boolean\n\t\t\t\t\t\tschedule?: string[]\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Register tools from subprocess Paw using manifest tool descriptions\n\t\t\t\t// The actual execute calls are routed through IPC\n\t\t\t\tif (registration.tools) {\n\t\t\t\t\tconst toolDefs = registration.tools.map((t) => ({\n\t\t\t\t\t\tname: t.name,\n\t\t\t\t\t\tdescription: t.description,\n\t\t\t\t\t\tparameters: {} as import('zod').ZodSchema, // Schema validated on Paw side\n\t\t\t\t\t\texecute: async (toolParams: unknown) =>\n\t\t\t\t\t\t\tthis.executeRemoteTool(pawName, t.name, toolParams),\n\t\t\t\t\t}))\n\t\t\t\t\tthis.toolRegistry.register(pawName, toolDefs, false)\n\t\t\t\t}\n\n\t\t\t\t// Track hooks for subprocess Paws\n\t\t\t\tif (registration.hooks?.bootstrap) {\n\t\t\t\t\tthis.bootstrapPaws.push(pawName)\n\t\t\t\t}\n\t\t\t\tif (registration.hooks?.perceive) {\n\t\t\t\t\tconst config = this.paws.get(pawName)?.config\n\t\t\t\t\tconst hookConfig = config?.hooks?.perceive\n\t\t\t\t\tconst hasTools = (registration.tools?.length ?? 0) > 0\n\t\t\t\t\tthis.perceiveHooks.push({\n\t\t\t\t\t\tpawName,\n\t\t\t\t\t\torder: hookConfig?.order ?? 100,\n\t\t\t\t\t\tpipeline: hookConfig?.pipeline ?? true,\n\t\t\t\t\t\thasTools,\n\t\t\t\t\t})\n\t\t\t\t\tthis.perceiveHooks.sort((a, b) => a.order - b.order)\n\t\t\t\t}\n\t\t\t\tif (registration.hooks?.observe) {\n\t\t\t\t\tthis.observeHookPaws.push(pawName)\n\t\t\t\t}\n\t\t\t\tif (registration.hooks?.compact) {\n\t\t\t\t\tthis.compactPaws.push(pawName)\n\t\t\t\t}\n\n\t\t\t\tlogger.info(`Paw \"${pawName}\" registered with ${registration.tools?.length ?? 0} tools`)\n\t\t\t\tresolve()\n\t\t\t\treturn { ok: true }\n\t\t\t})\n\t\t})\n\t}\n}\n","import * as path from 'node:path'\nimport { execa, type ResultPromise } from 'execa'\nimport type { PawConfig, PawDefinition, PawInstance, PawManifest } from './types.js'\nimport { createTransport, type IpcTransport } from '../core/ipc.js'\nimport { buildSandboxEnv, computeEffectivePermissions } from './sandbox.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-loader')\n\n/** Load an in-process Paw by importing its module */\nexport async function loadInProcessPaw(\n\tpawPath: string,\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): Promise<PawInstance> {\n\tconst entryPath = path.resolve(pawPath, manifest.entry)\n\n\tlogger.info(`Loading in-process Paw \"${manifest.name}\" from ${entryPath}`)\n\n\tconst module = await import(entryPath)\n\tconst definition: PawDefinition = module.default ?? module\n\n\tif (definition.onLoad) {\n\t\tawait definition.onLoad(config)\n\t}\n\n\treturn {\n\t\tname: manifest.name,\n\t\tmanifest,\n\t\tconfig,\n\t\thealthy: true,\n\t\ttransport: 'ipc',\n\t\tinProcess: true,\n\t\tdefinition,\n\t}\n}\n\n/** Spawn a subprocess Paw and set up IPC transport */\nexport async function loadSubprocessPaw(\n\tpawPath: string,\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): Promise<{ instance: PawInstance; transport: IpcTransport }> {\n\tconst entryPath = path.resolve(pawPath, manifest.entry)\n\tconst transport = manifest.transport ?? 'ipc'\n\tconst permissions = computeEffectivePermissions(manifest, config)\n\tconst env = buildSandboxEnv(permissions)\n\n\tlogger.info(\n\t\t`Spawning subprocess Paw \"${manifest.name}\" (transport: ${transport}) from ${entryPath}`,\n\t)\n\n\tconst stdioConfig =\n\t\ttransport === 'ipc'\n\t\t\t? (['pipe', 'pipe', 'pipe', 'ipc'] as const)\n\t\t\t: (['pipe', 'pipe', 'pipe'] as const)\n\n\tconst child = execa('node', [entryPath], {\n\t\tenv,\n\t\tstdio: stdioConfig,\n\t\treject: false,\n\t\tcleanup: true,\n\t})\n\n\t// Forward stderr for logging\n\tchild.stderr?.on('data', (data: Buffer) => {\n\t\tlogger.warn(`[${manifest.name}] ${data.toString().trimEnd()}`)\n\t})\n\n\tconst ipcTransport = createTransport(transport, child as unknown as import('node:child_process').ChildProcess)\n\n\tconst instance: PawInstance = {\n\t\tname: manifest.name,\n\t\tmanifest,\n\t\tconfig,\n\t\thealthy: true,\n\t\ttransport,\n\t\tinProcess: false,\n\t\tprocess: {\n\t\t\tkill: () => child.kill(),\n\t\t\tpid: child.pid,\n\t\t},\n\t\tsendRequest: (method, params) => ipcTransport.request(method, params),\n\t}\n\n\t// Handle subprocess exit\n\t;(child as ResultPromise).then?.((result) => {\n\t\tif (instance.healthy) {\n\t\t\tinstance.healthy = false\n\t\t\tlogger.error(\n\t\t\t\t`Paw \"${manifest.name}\" exited unexpectedly (code: ${result.exitCode})`,\n\t\t\t)\n\t\t}\n\t}).catch?.(() => {\n\t\t// execa with reject: false should not throw, but handle just in case\n\t\tinstance.healthy = false\n\t})\n\n\treturn { instance, transport: ipcTransport }\n}\n\n/** Send a graceful shutdown signal to a subprocess Paw */\nexport async function shutdownPaw(instance: PawInstance): Promise<void> {\n\tif (instance.inProcess) {\n\t\tif (instance.definition?.onUnload) {\n\t\t\tawait instance.definition.onUnload()\n\t\t}\n\t\treturn\n\t}\n\n\tif (instance.sendRequest) {\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tinstance.sendRequest('shutdown'),\n\t\t\t\tnew Promise((resolve) => setTimeout(resolve, 5_000)),\n\t\t\t])\n\t\t} catch {\n\t\t\tlogger.warn(`Shutdown request to \"${instance.name}\" failed, killing process`)\n\t\t}\n\t}\n\n\tinstance.process?.kill()\n\tinstance.healthy = false\n}\n","import type { ChildProcess } from 'node:child_process'\nimport type { Readable, Writable } from 'node:stream'\nimport * as crypto from 'node:crypto'\nimport type { TransportType } from '../paw/types.js'\n\nimport { createLogger } from './logger.js'\n\nconst logger = createLogger('ipc')\n\n/** JSON-RPC 2.0 message */\nexport interface IpcMessage {\n\tjsonrpc: '2.0'\n\tid?: string\n\tmethod?: string\n\tparams?: unknown\n\tresult?: unknown\n\terror?: { code: number; message: string; data?: unknown }\n}\n\n/** Pending request waiting for a response */\ninterface PendingRequest {\n\tresolve: (value: unknown) => void\n\treject: (error: Error) => void\n\ttimer: ReturnType<typeof setTimeout>\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000\n\n/** Transport abstraction that handles both Node IPC and stdio JSON-RPC */\nexport class IpcTransport {\n\tprivate pending = new Map<string, PendingRequest>()\n\tprivate handlers = new Map<string, (params: unknown) => Promise<unknown>>()\n\tprivate disposed = false\n\n\tconstructor(\n\t\tprivate type: TransportType,\n\t\tprivate childProcess: ChildProcess,\n\t\tprivate timeoutMs = DEFAULT_TIMEOUT_MS,\n\t) {\n\t\tif (type === 'ipc') {\n\t\t\tthis.setupIpcListeners()\n\t\t} else {\n\t\t\tthis.setupStdioListeners()\n\t\t}\n\t}\n\n\t/** Register a handler for incoming requests from the Paw */\n\tonRequest(method: string, handler: (params: unknown) => Promise<unknown>): void {\n\t\tthis.handlers.set(method, handler)\n\t}\n\n\t/** Send a request to the Paw and wait for a response */\n\tasync request(method: string, params?: unknown): Promise<unknown> {\n\t\tif (this.disposed) {\n\t\t\tthrow new Error('Transport has been disposed')\n\t\t}\n\n\t\tconst id = crypto.randomUUID()\n\t\tconst message: IpcMessage = { jsonrpc: '2.0', id, method, params }\n\t\tlogger.trace('Sending request: %s %s', method, JSON.stringify(params ?? '', null, 2))\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(id)\n\t\t\t\treject(new Error(`IPC request \"${method}\" timed out after ${this.timeoutMs}ms`))\n\t\t\t}, this.timeoutMs)\n\n\t\t\tthis.pending.set(id, { resolve, reject, timer })\n\t\t\tthis.send(message)\n\t\t})\n\t}\n\n\t/** Send a notification (no response expected) */\n\tnotify(method: string, params?: unknown): void {\n\t\tif (this.disposed) return\n\t\tconst message: IpcMessage = { jsonrpc: '2.0', method, params }\n\t\tthis.send(message)\n\t}\n\n\t/** Clean up resources */\n\tdispose(): void {\n\t\tthis.disposed = true\n\t\tfor (const [, pending] of this.pending) {\n\t\t\tclearTimeout(pending.timer)\n\t\t\tpending.reject(new Error('Transport disposed'))\n\t\t}\n\t\tthis.pending.clear()\n\t\tthis.handlers.clear()\n\t}\n\n\tprivate send(message: IpcMessage): void {\n\t\tif (this.disposed) return\n\t\tif (this.type === 'ipc') {\n\t\t\ttry {\n\t\t\t\tif (this.childProcess.connected) {\n\t\t\t\t\tthis.childProcess.send?.(message)\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Channel already closed — ignore\n\t\t\t}\n\t\t} else {\n\t\t\tconst json = JSON.stringify(message)\n\t\t\tconst header = `Content-Length: ${Buffer.byteLength(json)}\\r\\n\\r\\n`\n\t\t\tconst stdin = this.childProcess.stdin as Writable | null\n\t\t\tif (stdin?.writable) {\n\t\t\t\tstdin.write(header + json)\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate handleMessage(msg: IpcMessage): void {\n\t\tlogger.trace('Received message: %s %s', msg.method ?? msg.id ?? 'unknown', JSON.stringify(msg.params ?? msg.result ?? '', null, 2))\n\n\t\t// Response to a pending request\n\t\tif (msg.id && this.pending.has(msg.id)) {\n\t\t\tconst pending = this.pending.get(msg.id)!\n\t\t\tthis.pending.delete(msg.id)\n\t\t\tclearTimeout(pending.timer)\n\n\t\t\tif (msg.error) {\n\t\t\t\tpending.reject(new Error(`${msg.error.message} (code: ${msg.error.code})`))\n\t\t\t} else {\n\t\t\t\tpending.resolve(msg.result)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Incoming request from Paw\n\t\tif (msg.method && this.handlers.has(msg.method)) {\n\t\t\tconst handler = this.handlers.get(msg.method)!\n\t\t\thandler(msg.params)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tif (msg.id) {\n\t\t\t\t\t\tthis.send({ jsonrpc: '2.0', id: msg.id, result })\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch((err: unknown) => {\n\t\t\t\t\tconst errorMessage = err instanceof Error ? err.message : String(err)\n\t\t\t\t\tlogger.error('Handler error for \"%s\": %s', msg.method, errorMessage)\n\t\t\t\t\tif (msg.id) {\n\t\t\t\t\t\tthis.send({\n\t\t\t\t\t\t\tjsonrpc: '2.0',\n\t\t\t\t\t\t\tid: msg.id,\n\t\t\t\t\t\t\terror: { code: -32603, message: errorMessage },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t}\n\t}\n\n\tprivate setupIpcListeners(): void {\n\t\tthis.childProcess.on('message', (msg: unknown) => {\n\t\t\tthis.handleMessage(msg as IpcMessage)\n\t\t})\n\t}\n\n\tprivate setupStdioListeners(): void {\n\t\tconst stdout = this.childProcess.stdout as Readable | null\n\t\tif (!stdout) {\n\t\t\tlogger.error('No stdout stream available for stdio transport')\n\t\t\treturn\n\t\t}\n\n\t\tlet buffer = ''\n\n\t\tstdout.setEncoding('utf-8')\n\t\tstdout.on('data', (chunk: string) => {\n\t\t\tbuffer += chunk\n\n\t\t\t// Parse Content-Length framed messages\n\t\t\twhile (buffer.length > 0) {\n\t\t\t\tconst headerEnd = buffer.indexOf('\\r\\n\\r\\n')\n\t\t\t\tif (headerEnd === -1) break\n\n\t\t\t\tconst header = buffer.substring(0, headerEnd)\n\t\t\t\tconst match = header.match(/Content-Length:\\s*(\\d+)/i)\n\t\t\t\tif (!match) {\n\t\t\t\t\tlogger.error('Invalid header in stdio transport: %s', header)\n\t\t\t\t\tbuffer = buffer.substring(headerEnd + 4)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst contentLength = Number.parseInt(match[1], 10)\n\t\t\t\tconst bodyStart = headerEnd + 4\n\t\t\t\tif (buffer.length < bodyStart + contentLength) break\n\n\t\t\t\tconst body = buffer.substring(bodyStart, bodyStart + contentLength)\n\t\t\t\tbuffer = buffer.substring(bodyStart + contentLength)\n\n\t\t\t\ttry {\n\t\t\t\t\tconst msg = JSON.parse(body) as IpcMessage\n\t\t\t\t\tthis.handleMessage(msg)\n\t\t\t\t} catch (err) {\n\t\t\t\t\tlogger.error('Failed to parse stdio JSON-RPC message: %s', err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\n/** Create a transport for a Paw subprocess */\nexport function createTransport(\n\ttype: TransportType,\n\tchildProcess: ChildProcess,\n\ttimeoutMs?: number,\n): IpcTransport {\n\treturn new IpcTransport(type, childProcess, timeoutMs)\n}\n","import type { EffectivePermissions, PawConfig, PawManifest } from './types.js'\nimport { createLogger } from '../core/logger.js'\n\nconst logger = createLogger('paw-sandbox')\n\n/**\n * Compute effective permissions as the intersection of\n * what the manifest requests and what the config grants.\n */\nexport function computeEffectivePermissions(\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): EffectivePermissions {\n\tconst requested = manifest.permissions ?? { network: [], listen: [], filesystem: [], env: [] }\n\tconst granted = config.allow\n\n\t// If no allow block in config, treat as \"grant all requested\"\n\tif (!granted) {\n\t\treturn {\n\t\t\tnetwork: requested.network ?? [],\n\t\t\tlisten: requested.listen ?? [],\n\t\t\tfilesystem: requested.filesystem ?? [],\n\t\t\tenv: requested.env ?? [],\n\t\t}\n\t}\n\n\treturn {\n\t\tnetwork: intersectStrings(requested.network ?? [], granted.network ?? []),\n\t\tlisten: intersectNumbers(requested.listen ?? [], granted.listen ?? []),\n\t\tfilesystem: intersectStrings(requested.filesystem ?? [], granted.filesystem ?? []),\n\t\tenv: intersectStrings(requested.env ?? [], granted.env ?? []),\n\t}\n}\n\nfunction intersectStrings(a: string[], b: string[]): string[] {\n\tconst setB = new Set(b)\n\treturn a.filter((item) => setB.has(item))\n}\n\nfunction intersectNumbers(a: number[], b: number[]): number[] {\n\tconst setB = new Set(b)\n\treturn a.filter((item) => setB.has(item))\n}\n\n/**\n * Build the environment variables for a sandboxed Paw subprocess.\n * Only passes through env vars that are in the effective permissions.\n * Passes granted listen ports as VOLE_LISTEN_PORTS for the Paw to use.\n */\nexport function buildSandboxEnv(\n\tpermissions: EffectivePermissions,\n): Record<string, string | undefined> {\n\tconst env: Record<string, string | undefined> = {\n\t\t// Always pass NODE_ENV and PATH\n\t\tNODE_ENV: process.env.NODE_ENV,\n\t\tPATH: process.env.PATH,\n\t\t// Debug flag\n\t\tVOLE_LOG_LEVEL: process.env.VOLE_LOG_LEVEL,\n\t}\n\n\t// Pass granted listen ports so the Paw knows which ports it can bind\n\tif (permissions.listen.length > 0) {\n\t\tenv.VOLE_LISTEN_PORTS = permissions.listen.join(',')\n\t}\n\n\tfor (const key of permissions.env) {\n\t\tif (process.env[key] !== undefined) {\n\t\t\tenv[key] = process.env[key]\n\t\t} else {\n\t\t\tlogger.warn(`Env var \"${key}\" is permitted but not set in environment`)\n\t\t}\n\t}\n\n\treturn env\n}\n\n/**\n * Validate that a Paw's manifest permissions are reasonable.\n * Returns warnings (non-blocking) for review.\n */\nexport function validatePermissions(\n\tmanifest: PawManifest,\n\tconfig: PawConfig,\n): string[] {\n\tconst warnings: string[] = []\n\tconst effective = computeEffectivePermissions(manifest, config)\n\tconst requested = manifest.permissions ?? {}\n\n\tfor (const domain of requested.network ?? []) {\n\t\tif (!effective.network.includes(domain)) {\n\t\t\twarnings.push(\n\t\t\t\t`Network access to \"${domain}\" requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const port of requested.listen ?? []) {\n\t\tif (!effective.listen.includes(port)) {\n\t\t\twarnings.push(\n\t\t\t\t`Listen on port ${port} requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const fspath of requested.filesystem ?? []) {\n\t\tif (!effective.filesystem.includes(fspath)) {\n\t\t\twarnings.push(\n\t\t\t\t`Filesystem access to \"${fspath}\" requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tfor (const envVar of requested.env ?? []) {\n\t\tif (!effective.env.includes(envVar)) {\n\t\t\twarnings.push(\n\t\t\t\t`Env var \"${envVar}\" requested by ${manifest.name} but not granted in config`,\n\t\t\t)\n\t\t}\n\t}\n\n\tif (warnings.length > 0) {\n\t\tfor (const w of warnings) {\n\t\t\tlogger.info(w)\n\t\t}\n\t}\n\n\treturn warnings\n}\n","import * as readline from 'node:readline'\nimport type { VoleIO } from './types.js'\n\n/** Default TTY I/O implementation using stdin/stdout */\nexport function createTtyIO(): VoleIO {\n\treturn {\n\t\tasync confirm(message: string): Promise<boolean> {\n\t\t\tconst rl = readline.createInterface({\n\t\t\t\tinput: process.stdin,\n\t\t\t\toutput: process.stdout,\n\t\t\t})\n\t\t\ttry {\n\t\t\t\treturn await new Promise<boolean>((resolve) => {\n\t\t\t\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\t\t\t\tresolve(answer.trim().toLowerCase() === 'y')\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} finally {\n\t\t\t\trl.close()\n\t\t\t}\n\t\t},\n\n\t\tasync prompt(message: string): Promise<string> {\n\t\t\tconst rl = readline.createInterface({\n\t\t\t\tinput: process.stdin,\n\t\t\t\toutput: process.stdout,\n\t\t\t})\n\t\t\ttry {\n\t\t\t\treturn await new Promise<string>((resolve) => {\n\t\t\t\t\trl.question(`${message} `, (answer) => {\n\t\t\t\t\t\tresolve(answer.trim())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t} finally {\n\t\t\t\trl.close()\n\t\t\t}\n\t\t},\n\n\t\tnotify(message: string): void {\n\t\t\tprocess.stdout.write(`${message}\\n`)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AA2Ff,SAAS,mBAAmB,OAAsC;AACxE,MAAI,OAAO,UAAU,UAAU;AAC9B,WAAO,EAAE,MAAM,MAAM;AAAA,EACtB;AACA,SAAO;AACR;AAGO,SAAS,aAAa,QAAyC;AACrE,SAAO;AAAA,IACN,OAAO,OAAO;AAAA,IACd,MAAM,OAAO,QAAQ,CAAC;AAAA,IACtB,QAAQ,OAAO,UAAU,CAAC;AAAA,IAC1B,MAAM;AAAA,MACL,GAAG;AAAA,MACH,GAAG,OAAO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UAAQ,KAAK,CAAC;AACf,CAAC;","names":["fs","path","logger","fs","path","logger","fs","path","crypto","logger","logger","fs","path","logger","fs","path","logger","registry_exports","fs","path","logger","init_registry","fs","path","z","stat","path","logger","logger","path","crypto","logger","resolve","logger","logger","resolve","logger","resolve","init_registry","resolve","path","init_registry","fs","logger","readline","resolve","fs","normalizePawConfig","readPawManifest","resolvePawPath","SkillRegistry","createMessageBus","ToolRegistry","loadSkillFromDirectory","SchedulerStore","TaskQueue","createCoreTools","Vault"]}
|