adam-agent-server 1.12.0 → 1.13.0
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/dist/{adam-tools-ET23EDSQ.js → adam-tools-SQD2V4RJ.js} +1 -1
- package/dist/{audit-manager-7KPLFG2B.js → audit-manager-CWVHQAUI.js} +1 -1
- package/dist/{bree-engine-52CYOPIN.js → bree-engine-VGEYMVNP.js} +1 -1
- package/dist/chunk-2BXTT4P2.js +6 -0
- package/dist/{chunk-76IJC5WL.js → chunk-47COBMRF.js} +1 -1
- package/dist/chunk-6WRZJVQ2.js +1 -0
- package/dist/{chunk-CYQUP2RP.js → chunk-DZIEY4CH.js} +1 -1
- package/dist/{chunk-23Y7QFK3.js → chunk-E4WIUUL4.js} +1 -1
- package/dist/{chunk-SDT3PBHF.js → chunk-HDHMNT6D.js} +1 -1
- package/dist/{chunk-LPNJ4EW5.js → chunk-M3RZWIW3.js} +1 -1
- package/dist/chunk-OZL6VNOR.js +146 -0
- package/dist/{chunk-YFCFPB2Q.js → chunk-PXGK5H5C.js} +1 -1
- package/dist/{chunk-ETOTUZPB.js → chunk-Q2JQFDAK.js} +1 -1
- package/dist/{chunk-MQWYGDNT.js → chunk-SGIKNIC5.js} +1 -1
- package/dist/{chunk-25ZHHZQV.js → chunk-TI3AKKWZ.js} +3 -3
- package/dist/{chunk-IYJVHEQ4.js → chunk-YKYRNTPV.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/config-DRFRLIVN.js +1 -0
- package/dist/{external-api-MP4PAU7J.js → external-api-DOVGA3ML.js} +1 -1
- package/dist/index.js +11 -11
- package/dist/{presets-R3D4E6SK.js → presets-RMW3WO5P.js} +1 -1
- package/dist/{role-presets-7JIX34HF.js → role-presets-FAXQRBII.js} +1 -1
- package/dist/{runtime-G6DVR5OY.js → runtime-QA2DCZYQ.js} +1 -1
- package/dist/{session-manager-QC734QQA.js → session-manager-SOJXQHHY.js} +1 -1
- package/dist/task-templates-IS3DJCZB.js +1 -0
- package/dist/{workflow-executor-M6QOEUKC.js → workflow-executor-LOMKVFPV.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2WMUME2D.js +0 -146
- package/dist/chunk-D5LZGIJU.js +0 -6
- package/dist/chunk-N5FW6FUS.js +0 -1
- package/dist/config-GH6LQRYM.js +0 -1
- package/dist/task-templates-SNKZJ3DI.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as De}from"./chunk-
|
|
1
|
+
import{j as De}from"./chunk-PXGK5H5C.js";import{a as bt,c as P,d as b,e as L,f as Ee,g as wt,h as K,i as A,j as O,k as It,l as kt,m as Z,o as Tt,p as Rt,q as Dt}from"./chunk-JYHOGBCP.js";import{b as ht,c as _e,e as yt}from"./chunk-7T4B2MZ7.js";import{a as St,c as Ce,e as _t}from"./chunk-NPIXYK5G.js";import{g as vt}from"./chunk-X5V4VMET.js";import{a as B,b as st,c as at,d as lt,e as dt,f as ct,h as ut,i as ce,j as z,k as ue,l as pt,m as mt,n as Q,o as gt,p as U,q as Se}from"./chunk-DZIEY4CH.js";import{a as et,b as tt,c as le,d as rt,e as nt,f as ot,g as nr,h as it,i as x,k as de}from"./chunk-Q2ISNOBQ.js";import{a as ft}from"./chunk-S6OV7Z6K.js";import{b as Be}from"./chunk-AVM3O74V.js";import{b as $,c as Y,d as G}from"./chunk-R2WB5BKF.js";import{d as Re}from"./chunk-Y5FFL6UO.js";import{f as Ze}from"./chunk-Q2JQFDAK.js";import{e as we,f as se,g as He,i as Ie,j as ae}from"./chunk-RMGBR3XZ.js";import{a as X}from"./chunk-L7JP7DUO.js";import{c as ke,d as V,e as Ye,h as Qe,i as Te,j as Xe}from"./chunk-2BXTT4P2.js";import{d as D,j as Ge}from"./chunk-6WRZJVQ2.js";import{f as ze,g as be,i as rr,k as Ke,l as k,n as W,o as N,p as Je,q as ve,r as ie}from"./chunk-U2LBBBWO.js";import{b as E,d as Ve}from"./chunk-AQO6IIHV.js";import{d as ye,h as tr}from"./chunk-WBAPIPST.js";import{c as I,d as We,h as j}from"./chunk-MRTJFYPR.js";import{f as M}from"./chunk-FCV2DPZQ.js";import{createSdkMcpServer as Pr,tool as u}from"@anthropic-ai/claude-agent-sdk";import{z as i}from"zod";ie();ae();import{v4 as ee}from"uuid";j();var or=I("goal-manager");async function $n(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await ir(e)}let r=sr(t);return{goalState:t,validationResult:r,rawInput:e}}async function ir(e){let t=`Extract SMART goal fields from this natural language input.
|
|
2
2
|
|
|
3
3
|
Input: "${e}"
|
|
4
4
|
|
|
@@ -54,7 +54,7 @@ description: ${e.description}
|
|
|
54
54
|
${r}
|
|
55
55
|
## Instructions
|
|
56
56
|
${e.instructions}
|
|
57
|
-
`}async function R(e){let{listChannels:t}=await import("./channels-WFC26TED.js"),r=t(),{listSessions:n}=await import("./session-manager-QC734QQA.js"),o=[...n("active"),...n("archived")],a=[];for(let l of e)if(l.type==="session"&&l.sessionId)a.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,m=l.chatId;if(!d&&l.channelName){let c=r.find(g=>g.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!m){let c=o.find(g=>g.source.type==="channel"&&g.source.channelId===d&&g.source.chatId);c?.source.chatId?m=c.source.chatId:m=r.find(f=>f.id===d)?.config?.userId}d&&m?a.push({type:"channel",channelId:d,chatId:m}):H.warn({channelName:l.channelName,channelId:d,chatId:m},"Could not resolve channel notify target")}return a}async function Mr(e){let{listRoles:t}=await import("./roles-WNKRM6FD.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var $r={goalId:L},Nr={goalId:L,status:i.string().optional().describe("Filter by status (e.g., 'pending', 'running', 'completed', 'failed')."),currentValue:i.number().optional().describe("New current value for the goal's metric."),budgetUsd:i.number().optional().describe("Updated budget cap in USD."),notes:i.string().optional().describe("Free-form notes about the goal update.")},Ur={goalId:L,goalDescription:i.string().describe("Natural-language goal description used for LLM decomposition into subtasks."),maxSubtasks:i.number().optional().describe("Maximum number of subtasks to generate (default 5).")},C=i.union([i.object({type:i.literal("session"),sessionId:wt}),i.object({type:i.literal("channel"),channelName:i.string().describe("Channel display name (e.g., 'WeChat on iPad'). Use list_channels to find the exact name.")}),i.object({type:i.literal("channel"),channelId:Ee,chatId:i.string().describe("Chat / conversation ID inside the channel (channel-specific format).").optional()})]),Lr={prompt:i.string().describe("Task prompt \u2014 the natural-language instruction for the executor."),roleId:b.optional().describe("Role ID. Call list_roles(requirements) first to find the best role for the task."),requirements:B.optional().describe("Task requirements: tools, paths, OS capabilities, network access, plugins."),autoSelectRole:i.boolean().optional().describe("Auto-select the best role based on requirements (requires requirements field)."),deliverTo:i.array(C).optional().describe('Where to deliver the task output (result full text). E.g., send result to a specific channel. e.g., [{type:"channel", channelName:"iPad WeChat"}] when user says "\u53D1\u5230 iPad \u5FAE\u4FE1".'),reportTo:i.array(C).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:i.object({allowedTools:i.array(i.string()).optional().describe("Override: explicitly allow these tools (replaces inherited list)."),disallowedTools:i.array(i.string()).optional().describe("Override: explicitly deny these tools (adds to inherited denylist).")}).optional().describe("Tool permission overrides for this dispatch only (does not persist).")},Or={taskId:P,goalId:L.optional(),strategyId:kt.optional()},qr={roleId:b,taskType:i.string().describe("Task category label (e.g., 'web_search', 'code_review'). Used to bucket strategies."),name:i.string().optional().describe("Display name for the strategy (auto-generated if omitted).")},Fr={status:i.string().optional().describe("Filter by status (e.g., 'pending', 'running', 'completed', 'failed')."),limit:i.number().optional().describe("Max results to return (default 10).")},jr={taskId:P,roleId:b},Gr={taskId:P.optional(),status:i.string().optional().describe("Filter by status (e.g., 'pending', 'running', 'completed', 'failed')."),limit:i.number().optional().describe("Max results to return (default 10).")},Wr={roleId:b,allowedTools:i.array(i.string()).optional().describe("Explicitly allow these tools (additive to defaults)."),disallowedTools:i.array(i.string()).optional().describe("Explicitly deny these tools."),osCapabilities:i.array(i.object({id:i.string().min(1),targets:i.array(i.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:i.array(i.object({path:Z,mode:i.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:i.boolean().optional().describe("Inherit global plugins when accessing this directory."),inheritMcp:i.boolean().optional().describe("Inherit MCP servers when accessing this directory."),inheritPermissions:i.boolean().optional().describe("Inherit permission overrides when accessing this directory.")})).optional().describe("Extra directories the Role can access (beyond its workspace). Each entry grants sandboxed read/write access."),allowedChannels:i.array(i.string()).optional().describe("Channel names this Role is permitted to deliver to."),inheritUserSettings:i.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Vr={roleId:b.describe("Role ID to update."),name:i.string().min(1).optional().describe("Display name shown in lists and references."),cagPrompt:i.string().optional().describe("CAG prompt \u2014 Role's identity/personality directive."),learnedRules:i.array(i.string()).optional().describe("Learned behavioral rules for this Role (from past deviation events)."),status:i.enum(["active","inactive","retired"]).optional().describe("Role lifecycle status."),executionMode:i.enum(["isolated","inline"]).optional().describe("Execution mode: 'isolated' (separate process, sandboxed) or 'inline' (same process, unsandboxed)."),model:i.string().optional().describe("Anthropic model ID override (e.g., 'claude-sonnet-4-6'). Defaults to platform default."),maxBudgetUsd:i.number().optional().describe("Max USD budget per task for this Role."),approvalRequired:i.array(i.string()).optional().describe("Glob patterns for operations requiring user approval before execution."),preferences:i.object({model:i.string().optional().describe("Anthropic model ID override (e.g., 'claude-sonnet-4-6')."),effort:i.enum(["low","medium","high","max"]).optional(),maxTurns:i.number().optional()}).optional().describe("Execution preferences for this Role."),permissionMode:i.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional().describe("CLI permission behavior for this Role."),allowedBashPatterns:i.array(i.string()).optional().describe("Bash patterns that auto-execute without approval (e.g., 'git *', 'pnpm *')."),deniedBashPatterns:i.array(i.string()).optional().describe("Bash patterns that auto-reject without approval."),evaluationCriteria:i.record(i.string(),i.number()).optional().describe("Named quality thresholds the monitor uses to score this Role's outputs."),envVars:i.record(i.string(),i.string()).optional().describe("Environment variables injected into the Role's execution environment.")},Br={roleId:b.optional(),limit:i.number().optional().describe("Max results to return (default 10).")},zr={name:i.string().describe("Display name shown in lists and references."),cagPrompt:i.string().describe("CAG prompt \u2014 Role's identity/personality directive."),traits:i.array(i.string()).optional().describe("Behavioral trait tags for this Role (e.g., '\u4EE3\u7801\u8D28\u91CF\u4F18\u5148', '\u6D4B\u8BD5\u9A71\u52A8')."),allowedTools:i.array(i.string()).optional().describe("Tools this Role is permitted to use."),disallowedTools:i.array(i.string()).optional().describe("Tools this Role is explicitly denied from using."),osCapabilities:i.array(i.object({id:i.string().min(1),targets:i.array(i.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:i.array(i.object({path:Z,mode:i.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:i.boolean().optional().describe("Inherit global plugins when accessing this directory."),inheritMcp:i.boolean().optional().describe("Inherit MCP servers when accessing this directory."),inheritPermissions:i.boolean().optional().describe("Inherit permission overrides when accessing this directory.")})).optional().describe("Extra directories the Role can access (beyond its workspace). Each entry grants sandboxed read/write access.")},Kr={roleId:b,reason:i.string().optional().describe("Reason for the action (audit trail).")},Jr={name:i.string().describe("Display name shown in lists and references."),description:i.string().optional().describe("Free-form description."),roleId:b.optional(),metric:i.string().optional().describe("Metric type label (e.g., 'count', 'duration_ms', 'cost_usd')."),targetValue:i.number().optional().describe("Target metric value to reach (e.g., 100 for a count goal). Default 1."),deadline:i.number().optional().describe("Unix timestamp (ms) deadline. Default: 7 days from now."),budgetUsd:i.number().optional().describe("Max USD budget for this goal."),deliverTo:i.array(C).optional().describe("Where to deliver goal completion notifications.")},Hr={name:i.string().describe("Display name shown in lists and references."),description:i.string().optional().describe("Free-form description."),triggerType:i.enum(["cron","template_complete","workflow_complete","event"]).describe("How this template is triggered: 'cron' (scheduled), 'template_complete' (after another template finishes), 'workflow_complete' (after a workflow finishes), or 'event' (on a canonical event)."),triggerCron:i.string().optional().describe("Cron expression for recurring trigger (e.g., '0 9 * * *' for 9am daily)."),triggerEvent:i.string().optional().describe("For triggerType=template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. For cron/event: unused."),eventDefId:O.optional().describe("Required when triggerType='event'. Event def to bind this template to. Use list_event_defs to find or create_event_def to create one."),prompt:i.string().describe("Task prompt \u2014 the natural-language instruction for the executor."),roleId:b.optional().describe("Fixed role for this template. Use autoSelectRole instead for dynamic role selection."),requirements:B.optional().describe("Task requirements: tools, paths, OS capabilities, network access, plugins. Required when autoSelectRole is true."),autoSelectRole:i.boolean().optional().describe("Auto-select best role at dispatch time based on requirements."),enabled:i.boolean().optional().describe("Enable this template immediately (default true)."),goalIds:i.array(i.string()).optional().describe("Goal IDs to update on task completion (tracks goal progress)."),deliverTo:i.array(C).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(C).optional().describe("Where to send status reports (completion summary).")},Yr={status:i.enum(["active","retired","probation"]).optional().describe("Filter by role status."),limit:i.number().optional().describe("Max results to return (default 10)."),requirements:B.optional().describe("Task requirements to score and rank roles against.")},Qr={enabled:i.boolean().optional().describe("Filter by enabled status.")},Xr={},Zr={},en={prompt:i.string().describe("The task prompt to execute after the delay"),delayMinutes:i.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:i.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:b.describe("Role ID to assign the task to. Call list_roles first."),deliverTo:i.array(C).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(C).optional().describe("Where to send status reports (completion summary).")},tn={roleId:b.optional().describe("If provided, shows which plugins are installed in that role's workspace.")},rn={roleId:b.describe("Role ID to install the plugin under (project-scope)."),pluginId:A.describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},nn={roleId:b.describe("Role ID to uninstall the plugin from."),pluginId:A.describe("Plugin ID to uninstall.")},on={roleId:b.describe("Role ID to bind the MCP server to."),mcpName:i.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:i.record(i.string(),i.unknown()).describe("MCP server configuration object.")},sn={roleId:b.describe("Role ID to unbind the MCP server from."),mcpName:i.string().describe("Name of the MCP server to remove.")},an={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},ln={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},dn={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},cn={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},un={},pn={},mn={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},fn={roleId:b.describe("Role ID to associate scanned plugins with."),path:Z.describe("Directory path to scan for .claude/settings.json.")},gn={taskId:P.describe("Task ID to cancel.")},hn={taskId:P.describe("Task ID to get logs for."),limit:i.number().optional().describe("Max log entries (default 20).")},yn={roleId:b.describe("Role ID to delete.")},bn={},vn={updates:i.record(i.string(),i.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},wn={roleId:b.describe("Role ID to list memories for."),limit:i.number().optional().describe("Max results (default 20).")},In={templateId:K.describe("Template ID to update."),name:i.string().optional().describe("Display name shown in lists and references."),enabled:i.boolean().optional().describe("Filter by enabled status."),prompt:i.string().optional().describe("Task prompt \u2014 the natural-language instruction for the executor."),triggerType:i.enum(["cron","template_complete","workflow_complete","event"]).optional().describe("Explicit trigger type. Required when updating trigger settings."),triggerCron:i.string().optional().describe("Cron expression for recurring trigger (e.g., '0 9 * * *' for 9am daily)."),triggerEvent:i.string().optional().describe("For template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. Unused for cron/event."),eventDefId:O.optional().describe("Required when triggerType='event'. The event def UUID to bind this template to."),roleId:b.optional(),autoSelectRole:i.boolean().optional().describe("Step-level: if true, Adam picks the best-fit role at dispatch time. Write to the single-step template's step."),requirements:B.optional().describe("Step-level: required when autoSelectRole=true. Fields: tools, paths, osCapabilities, network, plugins.")},kn={templateId:K.describe("Template ID to delete. Obtain from list_templates."),mode:i.enum(["template_only","with_tasks"]).describe("REQUIRED. Deletion mode chosen by the user after you presented the dependent counts. 'template_only' removes the template + workflow_executions but keeps tasks as orphaned history records under the Tasks tab. 'with_tasks' additionally deletes every task created by this template and their role_scores + manager_decisions (chat_messages.task_id nulled). NEVER guess this value \u2014 the user must explicitly confirm which mode.")},Tn={templateId:K.describe("Template ID to inspect.")},Sn={templateId:K.describe("Template ID to run immediately.")},_n={enabled:i.boolean().optional().describe("Filter by enabled status.")},Rn={eventType:i.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:Ee.describe("Channel ID to deliver to."),format:i.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:i.record(i.string(),i.unknown()).optional().describe("JSON match criteria for event fields."),enabled:i.boolean().optional().describe("Enable this rule immediately (default true).")},Dn={ruleId:It.describe("Delivery rule ID to delete.")},En={roleId:b.optional().describe("Role ID to filter strategies by.")},Qt=[u("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",$r,async e=>{let t=z(e.goalId);if(!t)return s({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return s({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),u("update_goal_state","Update a goal's status, current value, or budget.",Nr,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),ue(e.goalId,t)),s({success:!0})}),u("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Ur,async e=>{let t=D(),r=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),l=`Decompose this goal into ${r} actionable subtasks.
|
|
57
|
+
`}async function R(e){let{listChannels:t}=await import("./channels-WFC26TED.js"),r=t(),{listSessions:n}=await import("./session-manager-SOJXQHHY.js"),o=[...n("active"),...n("archived")],a=[];for(let l of e)if(l.type==="session"&&l.sessionId)a.push({type:"session",sessionId:l.sessionId});else if(l.type==="channel"){let d=l.channelId,m=l.chatId;if(!d&&l.channelName){let c=r.find(g=>g.name.toLowerCase().includes(l.channelName.toLowerCase()));c&&(d=c.id)}if(d&&!m){let c=o.find(g=>g.source.type==="channel"&&g.source.channelId===d&&g.source.chatId);c?.source.chatId?m=c.source.chatId:m=r.find(f=>f.id===d)?.config?.userId}d&&m?a.push({type:"channel",channelId:d,chatId:m}):H.warn({channelName:l.channelName,channelId:d,chatId:m},"Could not resolve channel notify target")}return a}async function Mr(e){let{listRoles:t}=await import("./roles-WNKRM6FD.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var $r={goalId:L},Nr={goalId:L,status:i.string().optional().describe("Filter by status (e.g., 'pending', 'running', 'completed', 'failed')."),currentValue:i.number().optional().describe("New current value for the goal's metric."),budgetUsd:i.number().optional().describe("Updated budget cap in USD."),notes:i.string().optional().describe("Free-form notes about the goal update.")},Ur={goalId:L,goalDescription:i.string().describe("Natural-language goal description used for LLM decomposition into subtasks."),maxSubtasks:i.number().optional().describe("Maximum number of subtasks to generate (default 5).")},C=i.union([i.object({type:i.literal("session"),sessionId:wt}),i.object({type:i.literal("channel"),channelName:i.string().describe("Channel display name (e.g., 'WeChat on iPad'). Use list_channels to find the exact name.")}),i.object({type:i.literal("channel"),channelId:Ee,chatId:i.string().describe("Chat / conversation ID inside the channel (channel-specific format).").optional()})]),Lr={prompt:i.string().describe("Task prompt \u2014 the natural-language instruction for the executor."),roleId:b.optional().describe("Role ID. Call list_roles(requirements) first to find the best role for the task."),requirements:B.optional().describe("Task requirements: tools, paths, OS capabilities, network access, plugins."),autoSelectRole:i.boolean().optional().describe("Auto-select the best role based on requirements (requires requirements field)."),deliverTo:i.array(C).optional().describe('Where to deliver the task output (result full text). E.g., send result to a specific channel. e.g., [{type:"channel", channelName:"iPad WeChat"}] when user says "\u53D1\u5230 iPad \u5FAE\u4FE1".'),reportTo:i.array(C).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:i.object({allowedTools:i.array(i.string()).optional().describe("Override: explicitly allow these tools (replaces inherited list)."),disallowedTools:i.array(i.string()).optional().describe("Override: explicitly deny these tools (adds to inherited denylist).")}).optional().describe("Tool permission overrides for this dispatch only (does not persist).")},Or={taskId:P,goalId:L.optional(),strategyId:kt.optional()},qr={roleId:b,taskType:i.string().describe("Task category label (e.g., 'web_search', 'code_review'). Used to bucket strategies."),name:i.string().optional().describe("Display name for the strategy (auto-generated if omitted).")},Fr={status:i.string().optional().describe("Filter by status (e.g., 'pending', 'running', 'completed', 'failed')."),limit:i.number().optional().describe("Max results to return (default 10).")},jr={taskId:P,roleId:b},Gr={taskId:P.optional(),status:i.string().optional().describe("Filter by status (e.g., 'pending', 'running', 'completed', 'failed')."),limit:i.number().optional().describe("Max results to return (default 10).")},Wr={roleId:b,allowedTools:i.array(i.string()).optional().describe("Explicitly allow these tools (additive to defaults)."),disallowedTools:i.array(i.string()).optional().describe("Explicitly deny these tools."),osCapabilities:i.array(i.object({id:i.string().min(1),targets:i.array(i.string().min(1)).optional()})).optional().describe("Role-level OS capability grants. Use get_capabilities to inspect the runtime registry and valid target-scoped entries."),additionalDirectories:i.array(i.object({path:Z,mode:i.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:i.boolean().optional().describe("Inherit global plugins when accessing this directory."),inheritMcp:i.boolean().optional().describe("Inherit MCP servers when accessing this directory."),inheritPermissions:i.boolean().optional().describe("Inherit permission overrides when accessing this directory.")})).optional().describe("Extra directories the Role can access (beyond its workspace). Each entry grants sandboxed read/write access."),allowedChannels:i.array(i.string()).optional().describe("Channel names this Role is permitted to deliver to."),inheritUserSettings:i.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Vr={roleId:b.describe("Role ID to update."),name:i.string().min(1).optional().describe("Display name shown in lists and references."),cagPrompt:i.string().optional().describe("CAG prompt \u2014 Role's identity/personality directive."),learnedRules:i.array(i.string()).optional().describe("Learned behavioral rules for this Role (from past deviation events)."),status:i.enum(["active","inactive","retired"]).optional().describe("Role lifecycle status."),executionMode:i.enum(["isolated","inline"]).optional().describe("Execution mode: 'isolated' (separate process, sandboxed) or 'inline' (same process, unsandboxed)."),model:i.string().optional().describe("Anthropic model ID override (e.g., 'claude-sonnet-4-6'). Defaults to platform default."),maxBudgetUsd:i.number().optional().describe("Max USD budget per task for this Role."),approvalRequired:i.array(i.string()).optional().describe("Glob patterns for operations requiring user approval before execution."),preferences:i.object({model:i.string().optional().describe("Anthropic model ID override (e.g., 'claude-sonnet-4-6')."),effort:i.enum(["low","medium","high","max"]).optional(),maxTurns:i.number().optional()}).optional().describe("Execution preferences for this Role."),permissionMode:i.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional().describe("CLI permission behavior for this Role."),allowedBashPatterns:i.array(i.string()).optional().describe("Bash patterns that auto-execute without approval (e.g., 'git *', 'pnpm *')."),deniedBashPatterns:i.array(i.string()).optional().describe("Bash patterns that auto-reject without approval."),evaluationCriteria:i.record(i.string(),i.number()).optional().describe("Named quality thresholds the monitor uses to score this Role's outputs."),envVars:i.record(i.string(),i.string()).optional().describe("Environment variables injected into the Role's execution environment.")},Br={roleId:b.optional(),limit:i.number().optional().describe("Max results to return (default 10).")},zr={name:i.string().describe("Display name shown in lists and references."),cagPrompt:i.string().describe("CAG prompt \u2014 Role's identity/personality directive."),traits:i.array(i.string()).optional().describe("Behavioral trait tags for this Role (e.g., '\u4EE3\u7801\u8D28\u91CF\u4F18\u5148', '\u6D4B\u8BD5\u9A71\u52A8')."),allowedTools:i.array(i.string()).optional().describe("Tools this Role is permitted to use."),disallowedTools:i.array(i.string()).optional().describe("Tools this Role is explicitly denied from using."),osCapabilities:i.array(i.object({id:i.string().min(1),targets:i.array(i.string().min(1)).optional()})).optional().describe("Initial Role-level OS capability grants. Use get_capabilities to discover editable capability ids and target rules."),additionalDirectories:i.array(i.object({path:Z,mode:i.enum(["ro","rw"]).optional().describe("Read-only or read-write access. Default: rw. Enforced by OS sandbox."),inheritPlugins:i.boolean().optional().describe("Inherit global plugins when accessing this directory."),inheritMcp:i.boolean().optional().describe("Inherit MCP servers when accessing this directory."),inheritPermissions:i.boolean().optional().describe("Inherit permission overrides when accessing this directory.")})).optional().describe("Extra directories the Role can access (beyond its workspace). Each entry grants sandboxed read/write access.")},Kr={roleId:b,reason:i.string().optional().describe("Reason for the action (audit trail).")},Jr={name:i.string().describe("Display name shown in lists and references."),description:i.string().optional().describe("Free-form description."),roleId:b.optional(),metric:i.string().optional().describe("Metric type label (e.g., 'count', 'duration_ms', 'cost_usd')."),targetValue:i.number().optional().describe("Target metric value to reach (e.g., 100 for a count goal). Default 1."),deadline:i.number().optional().describe("Unix timestamp (ms) deadline. Default: 7 days from now."),budgetUsd:i.number().optional().describe("Max USD budget for this goal."),deliverTo:i.array(C).optional().describe("Where to deliver goal completion notifications.")},Hr={name:i.string().describe("Display name shown in lists and references."),description:i.string().optional().describe("Free-form description."),triggerType:i.enum(["cron","template_complete","workflow_complete","event"]).describe("How this template is triggered: 'cron' (scheduled), 'template_complete' (after another template finishes), 'workflow_complete' (after a workflow finishes), or 'event' (on a canonical event)."),triggerCron:i.string().optional().describe("Cron expression for recurring trigger (e.g., '0 9 * * *' for 9am daily)."),triggerEvent:i.string().optional().describe("For triggerType=template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. For cron/event: unused."),eventDefId:O.optional().describe("Required when triggerType='event'. Event def to bind this template to. Use list_event_defs to find or create_event_def to create one."),prompt:i.string().describe("Task prompt \u2014 the natural-language instruction for the executor."),roleId:b.optional().describe("Fixed role for this template. Use autoSelectRole instead for dynamic role selection."),requirements:B.optional().describe("Task requirements: tools, paths, OS capabilities, network access, plugins. Required when autoSelectRole is true."),autoSelectRole:i.boolean().optional().describe("Auto-select best role at dispatch time based on requirements."),enabled:i.boolean().optional().describe("Enable this template immediately (default true)."),goalIds:i.array(i.string()).optional().describe("Goal IDs to update on task completion (tracks goal progress)."),deliverTo:i.array(C).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(C).optional().describe("Where to send status reports (completion summary).")},Yr={status:i.enum(["active","retired","probation"]).optional().describe("Filter by role status."),limit:i.number().optional().describe("Max results to return (default 10)."),requirements:B.optional().describe("Task requirements to score and rank roles against.")},Qr={enabled:i.boolean().optional().describe("Filter by enabled status.")},Xr={},Zr={},en={prompt:i.string().describe("The task prompt to execute after the delay"),delayMinutes:i.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:i.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:b.describe("Role ID to assign the task to. Call list_roles first."),deliverTo:i.array(C).optional().describe("Where to deliver the task output (result full text)."),reportTo:i.array(C).optional().describe("Where to send status reports (completion summary).")},tn={roleId:b.optional().describe("If provided, shows which plugins are installed in that role's workspace.")},rn={roleId:b.describe("Role ID to install the plugin under (project-scope)."),pluginId:A.describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},nn={roleId:b.describe("Role ID to uninstall the plugin from."),pluginId:A.describe("Plugin ID to uninstall.")},on={roleId:b.describe("Role ID to bind the MCP server to."),mcpName:i.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:i.record(i.string(),i.unknown()).describe("MCP server configuration object.")},sn={roleId:b.describe("Role ID to unbind the MCP server from."),mcpName:i.string().describe("Name of the MCP server to remove.")},an={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},ln={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},dn={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},cn={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},un={},pn={},mn={pluginId:A.describe("Plugin ID (e.g., 'github@anthropic').")},fn={roleId:b.describe("Role ID to associate scanned plugins with."),path:Z.describe("Directory path to scan for .claude/settings.json.")},gn={taskId:P.describe("Task ID to cancel.")},hn={taskId:P.describe("Task ID to get logs for."),limit:i.number().optional().describe("Max log entries (default 20).")},yn={roleId:b.describe("Role ID to delete.")},bn={},vn={updates:i.record(i.string(),i.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},wn={roleId:b.describe("Role ID to list memories for."),limit:i.number().optional().describe("Max results (default 20).")},In={templateId:K.describe("Template ID to update."),name:i.string().optional().describe("Display name shown in lists and references."),enabled:i.boolean().optional().describe("Filter by enabled status."),prompt:i.string().optional().describe("Task prompt \u2014 the natural-language instruction for the executor."),triggerType:i.enum(["cron","template_complete","workflow_complete","event"]).optional().describe("Explicit trigger type. Required when updating trigger settings."),triggerCron:i.string().optional().describe("Cron expression for recurring trigger (e.g., '0 9 * * *' for 9am daily)."),triggerEvent:i.string().optional().describe("For template_complete: 'template_complete:<templateId>'. For workflow_complete: 'workflow_complete:<templateId>'. Unused for cron/event."),eventDefId:O.optional().describe("Required when triggerType='event'. The event def UUID to bind this template to."),roleId:b.optional(),autoSelectRole:i.boolean().optional().describe("Step-level: if true, Adam picks the best-fit role at dispatch time. Write to the single-step template's step."),requirements:B.optional().describe("Step-level: required when autoSelectRole=true. Fields: tools, paths, osCapabilities, network, plugins.")},kn={templateId:K.describe("Template ID to delete. Obtain from list_templates."),mode:i.enum(["template_only","with_tasks"]).describe("REQUIRED. Deletion mode chosen by the user after you presented the dependent counts. 'template_only' removes the template + workflow_executions but keeps tasks as orphaned history records under the Tasks tab. 'with_tasks' additionally deletes every task created by this template and their role_scores + manager_decisions (chat_messages.task_id nulled). NEVER guess this value \u2014 the user must explicitly confirm which mode.")},Tn={templateId:K.describe("Template ID to inspect.")},Sn={templateId:K.describe("Template ID to run immediately.")},_n={enabled:i.boolean().optional().describe("Filter by enabled status.")},Rn={eventType:i.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:Ee.describe("Channel ID to deliver to."),format:i.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:i.record(i.string(),i.unknown()).optional().describe("JSON match criteria for event fields."),enabled:i.boolean().optional().describe("Enable this rule immediately (default true).")},Dn={ruleId:It.describe("Delivery rule ID to delete.")},En={roleId:b.optional().describe("Role ID to filter strategies by.")},Qt=[u("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",$r,async e=>{let t=z(e.goalId);if(!t)return s({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return s({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),u("update_goal_state","Update a goal's status, current value, or budget.",Nr,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),ue(e.goalId,t)),s({success:!0})}),u("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",Ur,async e=>{let t=D(),r=Math.min(e.maxSubtasks??5,10);try{let{query:a}=await import("@anthropic-ai/claude-agent-sdk"),l=`Decompose this goal into ${r} actionable subtasks.
|
|
58
58
|
|
|
59
59
|
Goal: ${e.goalDescription}
|
|
60
60
|
|
|
@@ -77,4 +77,4 @@ Rules:
|
|
|
77
77
|
- Order from foundational to dependent
|
|
78
78
|
- Be specific about what each subtask should accomplish
|
|
79
79
|
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.
|
|
80
|
-
- Include tools and paths required for the subtask where known. If unknown, omit the field.`,d=a({prompt:l,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),m="";for await(let g of d){let f=g;f.type==="result"&&typeof f.result=="string"&&(m=f.result)}let c=m.match(/\[[\s\S]*\]/);if(c){let g=JSON.parse(c[0]),f=[];for(let h=0;h<Math.min(g.length,r);h++){let v=g[h],_=v.role,p=_?await Mr(_):void 0,y=await Se({prompt:v.prompt,roleId:p,requirements:v.requirements,config:t.defaults});if(!y.ok){f.push({id:`admission-failed-${h}`,description:v.description,prompt:v.prompt,dependencies:h>0&&f.length>0?[f[h-1].id]:[],estimatedComplexity:v.complexity??"medium",role:_,admissionError:`${y.code}: ${y.reason}`});continue}f.push({id:y.taskId,description:v.description,prompt:v.prompt,dependencies:h>0?[f[h-1].id]:[],estimatedComplexity:v.complexity??"medium",role:_})}if(f.length>0)return s({subtasks:f})}}catch(a){H.error({error:a},"LLM decomposition failed, using fallback")}let n=await ct({taskId:S(),roleId:void 0,autoSelectRole:!1}),o=[];return n.ok||o.push({id:"admission-blocked",description:`Decomposition fallback blocked: ${n.reason}`,prompt:e.goalDescription,dependencies:[],estimatedComplexity:"medium",admissionError:`${n.code}: ${n.reason}`}),s({subtasks:o})}),u("dispatch_task","Create and dispatch a task. Workflow: (1) call list_roles(requirements) to find candidate roles by fit; (2) call dispatch_task with requirements AND the chosen roleId. requirements is STRONGLY RECOMMENDED \u2014 when present, admission validates role fit before creation and returns structured mismatch diagnostics. If you cannot produce clear requirements from the user's message, ASK THE USER instead of dispatching. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Lr,async e=>{if(!e.roleId&&!e.autoSelectRole){let o=N("active",20,0).filter(a=>a.source!=="system").map(a=>({id:a.id,name:a.name,allowedTools:a.allowedTools??[],capabilitySummary:x(a)}));return s({error:"Must provide roleId or autoSelectRole=true with requirements.",availableRoles:o})}let t=e.deliverTo?await R(e.deliverTo):void 0,r=e.reportTo?await R(e.reportTo):void 0,n=await Se({prompt:e.prompt,roleId:e.roleId,requirements:e.requirements,autoSelectRole:e.autoSelectRole,deliverTo:t,reportTo:r,toolOverrides:e.toolOverrides});if(!n.ok){let o=(n.candidates??[]).map(l=>({id:l.roleId,name:l.name,fitScore:l.fitScore,missing:l.missing})),a=o.length>0?o:N("active",20,0).filter(l=>l.source!=="system").map(l=>({id:l.id,name:l.name,allowedTools:l.allowedTools??[],capabilitySummary:x(l)}));return s({error:n.reason,code:n.code,missing:n.missing,availableRoles:a})}return s({taskId:n.taskId,roleId:n.roleId,fitScore:n.fitScore,strategyId:n.strategyId,warnings:n.warnings})}),u("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:i.array(i.object({id:i.string().describe("Unique step identifier"),prompt:i.string().describe("Task prompt for this step"),roleId:b.optional().describe("Role ID for this step. Call list_roles first to find roles."),requirements:B.optional().describe("Task requirements for this step (D-012)."),autoSelectRole:i.boolean().optional().describe("Auto-select best role for this step (D-012)."),dependsOn:i.array(i.string()).optional().describe("Step IDs this step depends on"),config:i.object({timeout:i.number().optional(),maxTurns:i.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:i.string().optional().describe("Workflow name for tracking"),deliverTo:i.array(C).optional().describe("Where to deliver the aggregated workflow output"),reportTo:i.array(C).optional().describe("Where to send workflow status reports"),continueOnError:i.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let p of e.steps){if(!p.roleId&&!p.autoSelectRole){t.push(`${p.id} (needs roleId or autoSelectRole)`);continue}if(p.roleId){let y=k(p.roleId);(!y||y.status!=="active")&&t.push(`${p.id} (roleId ${p.roleId} invalid/inactive)`)}}if(t.length>0){let p=N("active",20,0).filter(y=>y.source!=="system").map(y=>({id:y.id,name:y.name,capabilitySummary:x(y)}));return s({error:`Steps missing roleId/autoSelectRole or with invalid roleIds: ${t.join("; ")}.`,availableRoles:p})}let r=new Set(e.steps.map(p=>p.id));for(let p of e.steps)if(p.dependsOn)for(let y of p.dependsOn){if(!r.has(y))return s({error:`Step "${p.id}" depends on unknown step "${y}"`});if(y===p.id)return s({error:`Step "${p.id}" cannot depend on itself`})}let n=new Set,o=new Set,a=new Map(e.steps.map(p=>[p.id,p.dependsOn??[]])),l=p=>{if(o.has(p))return!0;if(n.has(p))return!1;n.add(p),o.add(p);for(let y of a.get(p)??[])if(l(y))return!0;return o.delete(p),!1};for(let p of e.steps)if(l(p.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await R(e.deliverTo):void 0,m=e.reportTo?await R(e.reportTo):void 0,c=S(),g=D(),f={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(p=>({id:p.id,prompt:p.prompt,roleId:p.roleId,requirements:p.requirements,autoSelectRole:p.autoSelectRole,dependsOn:p.dependsOn,config:p.config})),enabled:!0,createdAt:Date.now(),config:{...g.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:m};try{ke(f)}catch(p){let{TemplateRoleConfigError:y}=await import("./task-templates-SNKZJ3DI.js");if(p instanceof y)return s({code:p.code,error:p.message,failingStepIds:p.failingStepIds,hint:"Each step must have roleId OR autoSelectRole=true (with requirements). Use list_roles to find an appropriate role."});throw p}let{WorkflowExecutor:h}=await import("./workflow-executor-M6QOEUKC.js");new h().execute(f,c).catch(p=>{H.error({executionId:c,error:p},"dispatch_workflow execution failed")});let _=e.steps.map(p=>{let y=p.roleId??(p.autoSelectRole?"[auto-selected]":"[no role]");return(p.roleId?k(p.roleId):void 0)?.name??y});return s({executionId:c,templateId:f.id,stepCount:e.steps.length,roles:[...new Set(_)],status:"started"})}),u("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Or,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=gt(t??"",r);return n&&t&&U.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:o.reward,metricL2Score:o.breakdown.L2||void 0,metricL3Score:o.breakdown.L3||void 0,source:o.source,reasoning:`Evaluated via ${o.source} with confidence ${o.confidence.toFixed(2)}`})}),u("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",qr,async e=>{let{roleId:t,taskType:r}=e;await pe.generateVariants(t,r,3,1);let n=U.getStrategies(t,r),o=n[n.length-1];return s(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),u("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",Fr,async e=>{let t=e.status;return s(pt(t,e.limit??10,0))}),u("delete_goal","Delete a goal by ID.",{goalId:L},async e=>z(e.goalId)?(mt(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),u("pause_goal","Pause an active goal.",{goalId:L},async e=>z(e.goalId)?(ue(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),u("assign_role","Assign a role to a pending task.",jr,async e=>{let{taskId:t,roleId:r}=e;if(!$(t))return s({error:`Task not found: ${t}`});let o=k(r);return o?(Y(t,{roleId:r}),H.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:r})):s({error:`Role not found: ${r}`})}),...Tt(),u("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",Gr,async e=>{if(e.taskId){let r=$(e.taskId);return s(r??{error:"Task not found"})}let t=e.status;return s(G(t,e.limit??100,0))}),u("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",Wr,async e=>{if(!k(e.roleId))return s({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{r.osCapabilities=be(e.osCapabilities)}catch(n){return s({error:n instanceof Error?n.message:String(n)})}return e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),W(e.roleId,r),s({success:!0})}),u("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Vr,async e=>{if(!k(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:r,...n}=e,o={...n,updatedAt:Date.now()};W(r,o);let a=k(r);if(!a)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=we(a.name);Yt(l)&&He(l,a)}return s({success:!0,role:a})}),u("view_audit_log","View the evolution audit log for role changes.",Br,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-M7FSYRQR.js"),r=t(e.limit??50);return s({entries:r})}),u("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks. Pass requirements to get ranked results with fitScore showing which roles best match the task.",Yr,async e=>{if(e.requirements){let n=e.requirements,a=dt(n).slice(0,e.limit??50).map(l=>{let d=l.role,m=de(d),c=m.plugins.map(w=>w.name),g=we(d.name),f=st(d,g),h=n.tools?(d.allowedTools??[]).filter(w=>n.tools.includes(w)):void 0,v=n.paths?n.paths.filter(w=>at(w,f)):void 0,_=new Set((d.osCapabilities??[]).map(w=>w.id)),p=n.osCapabilities?n.osCapabilities.filter(w=>_.has(w.id)).map(w=>w.id):void 0,y=new Set(c),je=n.plugins?n.plugins.filter(w=>y.has(w)):void 0,Xt=n.network===!0?(d.osCapabilities??[]).some(w=>w.id==="local-network"):void 0,Zt=l.missing?.osCapabilities,er=lt(d,n);return{id:d.id,name:d.name,status:d.status,allowedTools:d.allowedTools??[],disallowedTools:d.disallowedTools??[],osCapabilities:d.osCapabilities??[],additionalDirectories:d.additionalDirectories??[],cagPrompt:d.cagPrompt.slice(0,500)+(d.cagPrompt.length>500?"...":""),capabilitySummary:x(d,m),plugins:m.plugins.map(w=>({name:w.name,skills:w.skills.map(he=>he.name),agents:w.agents.map(he=>he.name)})),fitScore:l.fitScore,fits:l.evaluation.ok,matchedTools:h,matchedPaths:v,matchedOsCapabilities:p,matchedPlugins:je,matchedNetwork:Xt,missingCapabilities:l.missing?{tools:l.missing.tools,paths:l.missing.paths,osCapabilities:Zt?.map(w=>w.id),plugins:l.missing.plugins,network:l.missing.network}:void 0,warnings:er,why:l.evaluation.ok?`Role '${d.name}' satisfies all requirements (fitScore: ${l.fitScore.toFixed(2)})`:`Role '${d.name}' does not satisfy requirements: ${l.evaluation.ok?"unknown":l.evaluation.reason}`}});return s({roles:a})}let r=N(e.status,e.limit??50,0).map(n=>{let o=de(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],osCapabilities:n.osCapabilities??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:x(n,o),plugins:o.plugins.map(a=>({name:a.name,skills:a.skills.map(l=>l.name),agents:a.agents.map(l=>l.name)}))}});return s({roles:r})}),u("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",zr,async e=>{let t;try{t=be(e.osCapabilities)}catch(o){return s({error:o instanceof Error?o.message:String(o)})}let r=`role-${S().slice(0,8)}`,n={id:r,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${S().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return Ke(n),se(n),s({roleId:r,name:e.name,allowedTools:e.allowedTools,osCapabilities:n.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),u("retire_role","Retire a role (marks as retired, stops receiving tasks).",Kr,async e=>k(e.roleId)?(W(e.roleId,{status:"retired"}),H.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),u("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Jr,async e=>{let t=S(),r=Date.now(),n=r+10080*60*1e3,o={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await R(e.deliverTo):void 0};ce(o),Et(t,o.metricType);let a=z(t);return s({goalId:a.id,name:a.name,status:a.status})}),u("create_template","Create a recurring scheduled task. triggerType values: 'cron' (recurring via cron expression), 'template_complete' (fires when a specific template's task completes; set triggerEvent to 'template_complete:<templateId>'), 'workflow_complete' (similar), 'event' (fires when an Event def fires; set eventDefId to the event def UUID \u2014 use list_event_defs or create_event_def first). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Hr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-SNKZJ3DI.js"),r=S(),n=S();if(e.triggerType==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});if(e.triggerType!=="event"&&e.eventDefId)return s({error:"eventDefId only valid when triggerType='event'"});let o=e.deliverTo?await R(e.deliverTo):void 0,a=e.reportTo?await R(e.reportTo):void 0,l={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent,eventDefId:e.eventDefId},steps:[{id:n,prompt:e.prompt,...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:o,reportTo:a};try{t(l)}catch(d){let{TemplateRoleConfigError:m}=await import("./task-templates-SNKZJ3DI.js");if(d instanceof m)return s({code:d.code,error:d.message,failingStepIds:d.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object (e.g., {tools:['Read']}) on the template. Use list_roles to find an appropriate role."});throw d}return s({templateId:r,name:l.name,trigger:l.trigger})}),u("create_event_def","Create an Event definition \u2014 a user-configured source that fires on schedule/webhook/directory/manual. Event defs are the trigger half of the Event Slot; pair with create_template(triggerType='event', eventDefId=<returned id>) to bind work to the trigger. sourceType is validated at runtime against the installed source registry (currently: webhook, cron, directory_watch, manual \u2014 additional types may be registered at runtime). sourceConfig is per-type: cron \u2192 {cron: '0 9 * * *'}; directory_watch \u2192 {path: '/abs/path', glob?: '*.md'}; webhook/manual \u2192 {}.",{name:i.string().min(1).max(100).describe("Human-readable name (unique within workspace)."),sourceType:i.string().describe("Source type \u2014 validated against installed registry at call time. Currently: 'webhook' | 'cron' | 'directory_watch' | 'manual'. If the value is rejected, the error message lists the currently-registered types."),sourceConfig:i.record(i.string(),i.unknown()).describe("Per-sourceType configuration. See tool description."),enabled:i.boolean().optional().describe("Default true."),description:i.string().max(500).optional().describe("Free-form description of what this event represents.")},async e=>{if(!re().includes(e.sourceType))return s({error:`Unknown sourceType: '${e.sourceType}'. Currently registered: ${re().join(", ")}`});let t=Fe(e.sourceType,e.sourceConfig);if(!t.ok)return s({error:`Invalid sourceConfig: ${t.error}`});let r=S(),n=qt({id:r,name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled??!0,description:e.description});try{qe(n)}catch(o){Me(r);let a=o instanceof Error?o.message:String(o);return s({error:`Failed to start source: ${a}. Event def was not created.`})}return s({id:n.id,name:n.name,sourceType:n.sourceType,enabled:n.enabled})}),u("list_event_defs","List Event definitions. Use before create_template(triggerType='event') to find the eventDefId, or before fire_event_def / list_event_firings.",{sourceType:i.string().optional().describe("Filter by source type (e.g., 'cron', 'webhook')."),enabled:i.boolean().optional().describe("Filter by enabled flag.")},async e=>{let t=me({sourceType:e.sourceType,enabled:e.enabled});return s(t.map(r=>({id:r.id,name:r.name,sourceType:r.sourceType,sourceConfig:r.sourceConfig,enabled:r.enabled,description:r.description,createdAt:r.createdAt})))}),u("update_event_def","Update an Event definition. Changing `enabled` or `sourceConfig` on an active def automatically restarts the runtime source handler. Use list_event_defs first to get the id.",{id:O.describe("Event def id."),name:i.string().min(1).max(100).optional().describe("Human-readable name for this event definition."),sourceType:i.string().optional().describe("Only set when migrating to a different source type."),sourceConfig:i.record(i.string(),i.unknown()).optional().describe("Per-sourceType configuration. See tool description."),enabled:i.boolean().optional().describe("Enable or disable this event definition."),description:i.string().max(500).optional().describe("Free-form description of what this event represents.")},async e=>{let t=J(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});if(e.sourceType!==void 0||e.sourceConfig!==void 0){let l=e.sourceType??t.sourceType;if(!re().includes(l))return s({error:`Unknown sourceType: '${l}'`});let d=Fe(l,e.sourceConfig??t.sourceConfig);if(!d.ok)return s({error:`Invalid sourceConfig: ${d.error}`})}let r=t.enabled,n=e.enabled??t.enabled,o=e.sourceType!==void 0||e.sourceConfig!==void 0;r&&(!n||o)&&ge(t.id,t.sourceType);let a=Ae(e.id,{name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled,description:e.description});if(!a)return s({error:"Update failed"});if(n&&(!r||o))try{qe(a)}catch(l){Ae(e.id,{enabled:!1});let d=l instanceof Error?l.message:String(l);return s({error:`Failed to start source with new config: ${d}. Event def has been marked disabled to match runtime state.`})}return s({id:a.id,name:a.name,sourceType:a.sourceType,enabled:a.enabled})}),u("delete_event_def","Delete an Event definition. Stops the runtime source handler (cron/fswatch) first, then deletes the DB row. Templates bound to this event def become orphaned and will not fire.",{id:O.describe("Event def id.")},async e=>{let t=J(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});try{ge(t.id,t.sourceType)}catch(n){H.warn({defId:t.id,err:n},"stopEventDefSource failed during delete \u2014 proceeding with row deletion")}let r=Me(e.id);return s({ok:r,id:e.id})}),u("fire_event_def","Fire an Event definition now. For manual defs: creates a real manual event (same as clicking 'Fire now' in the UI). For any source type: with test=true, creates a synthetic test event (source='manual-test-<defId>') that flows through the EventDispatcher \u2014 useful for debugging why a Template bound to the event didn't fire. Payload is optional.",{id:O.describe("Event def id."),test:i.boolean().optional().describe("Test mode. Required (=true) when source type != 'manual'. Default false. In test mode the event does NOT collide with real firings' dedup keys."),payload:i.record(i.string(),i.unknown()).optional().describe("Optional event payload. Must be < 64 KB when JSON-serialized.")},async e=>{let t=J(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});let r=e.test===!0;if(t.sourceType!=="manual"&&!r)return s({error:`Can only directly fire manual event defs; this def has source type '${t.sourceType}'. Pass test=true to dry-run.`});if(e.payload){let n=Buffer.byteLength(JSON.stringify(e.payload),"utf8");if(n>65536)return s({error:`Payload exceeds 64 KB limit (got ${n} bytes)`})}try{let n=r?Le(t,e.payload):Ue(t,e.payload);return s({ok:!0,eventId:n.eventId,test:r})}catch(n){let o=n instanceof Error?n.message:String(n);return s({error:o})}}),u("list_event_firings","List recent firings of an Event definition \u2014 for debugging 'why didn't my automation fire' and inspecting event history. Returns id, occurredAt, type, source, dedupKey, confidence, and a truncated payload (500 char cap for display). For full payloads, use REST GET /event-defs/:id/firings.",{eventDefId:O.describe("Event def id. Use list_event_defs to find it."),since:i.string().optional().describe("ISO 8601 start timestamp (inclusive). Omit for unlimited range."),until:i.string().optional().describe("ISO 8601 end timestamp (inclusive)."),limit:i.number().int().positive().max(500).optional().describe("Max rows (default 50, max 500).")},async e=>{let t=J(e.eventDefId);if(!t)return s({error:`Event def '${e.eventDefId}' not found`});let r=Lt({eventDefId:e.eventDefId,since:e.since,until:e.until,limit:e.limit??50}),n=500;return s({eventDefName:t.name,sourceType:t.sourceType,count:r.length,firings:r.map(o=>{let a=Jt({payload:o.payload,trustLevel:o.trustLevel,source:o.source,maxBodyChars:n});return{id:o.id,occurredAt:o.occurredAt,type:o.type,source:o.source,dedupKey:o.dedupKey,confidence:o.confidence,trustLevel:o.trustLevel,payloadPreview:a,payloadTruncated:a.length>n}})})}),u("create_skill","Author a Claude Code Skill file under a target Role's workspace. The Skill becomes available next time the Role runs. Preset Roles (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator) require overwrite=true to replace an existing skill \u2014 first-time creation is unrestricted. Returns the written file path.",{roleId:b.describe("Role to target. Use list_roles to find it."),skillName:i.string().regex(/^[a-z0-9_][a-z0-9_-]{0,39}$/,"skillName must be 1-40 chars: lowercase letters, digits, underscores, optional hyphen in middle. No leading dot or dash.").describe("Skill directory name (used as the directory under .claude/skills/)."),description:i.string().max(500).describe("One-line description shown to the Role's LLM when choosing a Skill."),instructions:i.string().describe("The skill body: what it does and how to do it."),parameters:i.record(i.string(),i.object({type:i.string().describe("Parameter type name"),description:i.string().describe("Parameter description")})).optional().describe("Named input parameters and their types."),overwrite:i.boolean().optional().describe("Required (=true) to overwrite an existing SKILL.md under a preset Role (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator). First-time skill creation and non-preset Roles do not require this flag.")},async e=>{let{getRole:t}=await import("./roles-WNKRM6FD.js"),{ensureRoleWorkspace:r}=await import("./role-workspace-ISGPO25D.js"),{mkdir:n,writeFile:o}=await import("fs/promises"),{resolve:a}=await import("path"),l=t(e.roleId);if(!l)return s({error:`Role '${e.roleId}' not found`});let d=r(l),m=a(d,".claude","skills",e.skillName);if(Ze(l)){let{existsSync:h}=await import("fs"),v=a(m,"SKILL.md");if(h(v)&&e.overwrite!==!0)return s({error:`Role '${l.name}' is a preset. Skill '${e.skillName}' already exists at ${v}. Pass overwrite=true to replace, or choose a different skillName to add alongside.`,requiresOverwrite:!0,existingPath:v})}let c=a(d,".claude","skills");if(!m.startsWith(c+(process.platform==="win32"?"\\":"/")))return s({error:"Path traversal rejected"});await n(m,{recursive:!0});let g=Ar(e),f=a(m,"SKILL.md");return await o(f,g,"utf8"),s({ok:!0,path:f})}),u("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:i.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:i.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-SNKZJ3DI.js"),r=t(e.enabled,e.limit??50,0);return s(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),u("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:i.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:i.string().describe("The message content to send (text caption when sending media)"),mediaUrl:Z.optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:i.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!Yt(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await R([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-XDCGAXXW.js"),a=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:a.success,channelName:e.channelName,...a.error?{error:a.error}:{}})}),u("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Qr,async e=>{let t=Re(e.enabled),r=[...De("active"),...De("archived")],n=t.map(o=>{let a,l=r.find(d=>d.source.type==="channel"&&d.source.channelId===o.id&&d.source.chatId);return l?.source.chatId?a=l.source.chatId:a=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:a}});return s({channels:n})}),u("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Xr,async()=>{let e=D(),t=G("running"),r=G("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),u("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",en,async e=>{let t=k(e.roleId);if(!t||t.status!=="active"){let f=N("active",20,0).filter(h=>h.source!=="system").map(h=>({id:h.id,name:h.name,allowedTools:h.allowedTools??[],capabilitySummary:x(h)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:f})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(n<=r)return s({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return s({error:"Schedule exceeds maximum of 7 days"});let a=S(),l=new Date(n).toISOString(),d=e.deliverTo?await R(e.deliverTo):void 0,m=e.reportTo?await R(e.reportTo):void 0;ke({id:a,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...D().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:d,reportTo:m});let{getBreeEngine:c}=await import("./bree-engine-52CYOPIN.js"),g=c();return g&&g.scheduleOnceJob(a),s({templateId:a,executeAt:l,prompt:e.prompt})}),u("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:K.describe("The template ID returned by schedule_task")},async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Qe(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-52CYOPIN.js"),n=r();return n&&await n.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),u("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",tn,async e=>{let t=et(),r=le(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(ae(),M(Ie)),{getRole:a}=(ie(),M(ve)),{listInstalledPlugins:l}=(it(),M(nr)),d=a(e.roleId);if(!d)return[];let m=o(d.name);return l({scope:"project",projectPath:m}).map(c=>c.id)})():[];return s({plugins:r.map(o=>({id:o.id,name:o.name,scope:o.scope,projectPath:o.projectPath,enabled:o.enabled,globalEnabled:t[o.id]??o.enabled,isInstalledInRole:n.includes(o.id),description:o.version?`v${o.version}`:void 0}))})}),u("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",rn,async e=>{let{getRole:t}=(ie(),M(ve)),{getRoleWorkspacePath:r}=(ae(),M(Ie)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return xe(e.pluginId,"project",o),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(a){return s({error:`Failed to install plugin: ${a}`})}}),u("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",nn,async e=>{let{getRole:t}=(ie(),M(ve)),{getRoleWorkspacePath:r}=(ae(),M(Ie)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Pe(e.pluginId,"project",o),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(a){return s({error:`Failed to uninstall plugin: ${a}`})}}),u("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",on,async e=>{let t=k(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return W(e.roleId,{mcpServers:n}),se(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return s({error:`Failed to bind MCP server: ${o}`})}}),u("unbind_mcp_from_role","Remove an MCP server binding from a role.",sn,async e=>{let t=k(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return W(e.roleId,{mcpServers:r}),se(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return s({error:`Failed to unbind MCP server: ${n}`})}}),u("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",Zr,async()=>{let{listTaskTemplates:e}=await import("./task-templates-SNKZJ3DI.js"),t=D(),r=N(void 0,100,0),n=Re(),o=e(!0,100,0),a=G("running"),l=G("pending"),d=Rt(),m=await Dt();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let g=de(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:x(c,g),plugins:g.plugins.map(f=>({name:f.name,skills:f.skills.map(h=>h.name),agents:f.agents.map(h=>h.name)}))}}),retired:r.filter(c=>c.status==="retired").length,probation:r.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:m},registry:ze(d.platform,m)},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:le().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:a.length,queued:l.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),u("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",an,async e=>{try{return $t(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),u("disable_plugin","Disable a globally installed plugin (removes it from all roles).",ln,async e=>{try{return Nt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),u("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",dn,async e=>{try{return xe(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),u("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",cn,async e=>{try{return Pe(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),u("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",un,async()=>{try{let e=Mt(),t=le();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),u("list_marketplace_sources","List configured plugin marketplace sources.",pn,async()=>{let e=nt();return s({sources:e})}),u("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",mn,async e=>{let t=rt(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let r=tt(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),u("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",fn,async e=>{let{getRole:t}=await import("./roles-WNKRM6FD.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let n=ot(e.path);return s({roleId:e.roleId,path:e.path,config:n})}catch(n){return s({error:`Failed to scan directory: ${n}`})}}),u("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",gn,async e=>{let t=$(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let r=t.status;Y(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),u("view_task_logs","Retrieve step-by-step execution logs for a task.",hn,async e=>{let t=Be(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),u("delete_role","Delete a role by ID. This removes the role and its workspace.",yn,async e=>k(e.roleId)?(Je(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),u("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",bn,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-G6DVR5OY.js"),r=D(),n={};try{let d=D().server?.port??7100,m=await fetch(`http://127.0.0.1:${d}/config`);m.ok&&(n=await m.json())}catch{}let o=[...e,...t],a=[...t],l={};for(let d of o){let m=d.split("."),c=r;for(let g of m)if(c&&typeof c=="object")c=c[g];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),u("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",vn,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-G6DVR5OY.js"),{setConfigValue:r}=await import("./config-GKVOAMY2.js"),n=Ge(e.updates,r);if(e.updates["logging.level"]&&We(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(a=>({path:a,value:e.updates[a]}))})}return s(n)}),u("list_memories","List memories stored under a specific role.",wn,async e=>{let t=vt(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),u("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",In,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0||e.autoSelectRole!==void 0||e.requirements!==void 0){let o=t.steps?.length?[...t.steps]:[];o.length===0&&o.push({id:S(),prompt:e.prompt??""});let a=o[0];o[0]={...a,...e.prompt!==void 0?{prompt:e.prompt}:{},...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}},r.steps=o}if(e.triggerCron!==void 0||e.triggerEvent!==void 0||e.triggerType!==void 0||e.eventDefId!==void 0){let o=e.triggerType??(e.triggerEvent?e.triggerEvent.split(":")[0]:e.eventDefId?"event":"cron");if(o==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});r.trigger={type:o,...e.triggerCron!==void 0?{cron:e.triggerCron}:{},...e.triggerEvent!==void 0?{event:e.triggerEvent}:{},...e.eventDefId!==void 0?{eventDefId:e.eventDefId}:{}}}e.roleId!==void 0&&(r.rolePreference=e.roleId);try{Ye(e.templateId,r)}catch(o){let{TemplateRoleConfigError:a}=await import("./task-templates-SNKZJ3DI.js");if(o instanceof a)return s({code:o.code,error:o.message,failingStepIds:o.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object."});throw o}return s({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),u("get_template_dependents","Count workflow_executions and tasks that depend on a template. Use this BEFORE delete_template to show the user what will be affected. Returns { executionCount, taskCount, hasDependents }. If hasDependents is false, delete_template is safe with mode='template_only'. If true, you MUST ask the user whether to delete the template only (keeps tasks as history) or delete with its tasks (removes tasks and their score history). Never pick the mode yourself.",Tn,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r=Te(e.templateId);return s({templateId:e.templateId,templateName:t.name,executionCount:r.executionCount,taskCount:r.taskCount,hasDependents:r.executionCount>0||r.taskCount>0})}),u("delete_template","Delete a task template by ID. PRECONDITION: you must have called get_template_dependents first. If executionCount > 0 or taskCount > 0, you must have shown the user those counts and received explicit confirmation of which mode to use. Call this tool only after the user picks 'template_only' or 'with_tasks'. Passing a mode without user confirmation violates the skill's safety contract.",kn,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r=Te(e.templateId);return Xe(e.templateId,e.mode),s({success:!0,templateId:e.templateId,templateName:t.name,mode:e.mode,deleted:{template:1,workflowExecutions:r.executionCount,tasks:e.mode==="with_tasks"?r.taskCount:0}})}),u("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Sn,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let r=D().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:o}):s({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return s({error:`Failed to trigger template: ${r}`})}}),u("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",_n,async e=>{let t=Ce(e.enabled);return s({count:t.length,rules:t})}),u("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Rn,async e=>{let t=S(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return St(r),s({success:!0,ruleId:t,rule:r})}),u("delete_delivery_rule","Delete a delivery rule by ID.",Dn,async e=>Ce().find(n=>n.id===e.ruleId)?(_t(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),u("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",En,async e=>{let t;if(e.roleId)t=ut(e.roleId);else{let{getDb:r}=await import("./db-FACSMWEY.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(o=>({id:o.id,roleId:o.role_id,name:o.name,taskType:o.task_type,createdAt:o.created_at,updatedAt:o.updated_at??void 0,promptTemplate:o.prompt_template??"",alpha:o.alpha,beta:o.beta,totalTrials:o.trials,avgReward:o.total_reward&&o.trials>0?o.total_reward/o.trials:void 0,enabled:o.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),u("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:P,operationId:i.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:i.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=_e(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new oe().resolvePlanApproval(r.id,"allow",e.scope),s({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),u("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:P,operationId:i.string().optional().describe("ID of the specific operation. If omitted, denies the most recent pending operation."),reason:i.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=_e(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new oe().resolvePlanApproval(r.id,"deny","once",e.reason),s({success:!0,operationId:r.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function wi(){return Qt.map(e=>e.name).sort().join(",")}function Ii(){return Pr({name:"adam-tools",version:"1.0.0",tools:Qt})}export{oe as a,$n as b,Nn as c,Et as d,Mt as e,xe as f,Pe as g,$t as h,Nt as i,Wn as j,Vn as k,Bn as l,Lt as m,qt as n,J as o,me as p,Ae as q,Me as r,F as s,Ue as t,Le as u,qe as v,ge as w,To as x,re as y,Fe as z,Do as A,R as B,wi as C,Ii as D};
|
|
80
|
+
- Include tools and paths required for the subtask where known. If unknown, omit the field.`,d=a({prompt:l,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),m="";for await(let g of d){let f=g;f.type==="result"&&typeof f.result=="string"&&(m=f.result)}let c=m.match(/\[[\s\S]*\]/);if(c){let g=JSON.parse(c[0]),f=[];for(let h=0;h<Math.min(g.length,r);h++){let v=g[h],_=v.role,p=_?await Mr(_):void 0,y=await Se({prompt:v.prompt,roleId:p,requirements:v.requirements,config:t.defaults});if(!y.ok){f.push({id:`admission-failed-${h}`,description:v.description,prompt:v.prompt,dependencies:h>0&&f.length>0?[f[h-1].id]:[],estimatedComplexity:v.complexity??"medium",role:_,admissionError:`${y.code}: ${y.reason}`});continue}f.push({id:y.taskId,description:v.description,prompt:v.prompt,dependencies:h>0?[f[h-1].id]:[],estimatedComplexity:v.complexity??"medium",role:_})}if(f.length>0)return s({subtasks:f})}}catch(a){H.error({error:a},"LLM decomposition failed, using fallback")}let n=await ct({taskId:S(),roleId:void 0,autoSelectRole:!1}),o=[];return n.ok||o.push({id:"admission-blocked",description:`Decomposition fallback blocked: ${n.reason}`,prompt:e.goalDescription,dependencies:[],estimatedComplexity:"medium",admissionError:`${n.code}: ${n.reason}`}),s({subtasks:o})}),u("dispatch_task","Create and dispatch a task. Workflow: (1) call list_roles(requirements) to find candidate roles by fit; (2) call dispatch_task with requirements AND the chosen roleId. requirements is STRONGLY RECOMMENDED \u2014 when present, admission validates role fit before creation and returns structured mismatch diagnostics. If you cannot produce clear requirements from the user's message, ASK THE USER instead of dispatching. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",Lr,async e=>{if(!e.roleId&&!e.autoSelectRole){let o=N("active",20,0).filter(a=>a.source!=="system").map(a=>({id:a.id,name:a.name,allowedTools:a.allowedTools??[],capabilitySummary:x(a)}));return s({error:"Must provide roleId or autoSelectRole=true with requirements.",availableRoles:o})}let t=e.deliverTo?await R(e.deliverTo):void 0,r=e.reportTo?await R(e.reportTo):void 0,n=await Se({prompt:e.prompt,roleId:e.roleId,requirements:e.requirements,autoSelectRole:e.autoSelectRole,deliverTo:t,reportTo:r,toolOverrides:e.toolOverrides});if(!n.ok){let o=(n.candidates??[]).map(l=>({id:l.roleId,name:l.name,fitScore:l.fitScore,missing:l.missing})),a=o.length>0?o:N("active",20,0).filter(l=>l.source!=="system").map(l=>({id:l.id,name:l.name,allowedTools:l.allowedTools??[],capabilitySummary:x(l)}));return s({error:n.reason,code:n.code,missing:n.missing,availableRoles:a})}return s({taskId:n.taskId,roleId:n.roleId,fitScore:n.fitScore,strategyId:n.strategyId,warnings:n.warnings})}),u("dispatch_workflow","Create and execute a multi-role workflow. Use when the user's request decomposes into sequential or parallel steps handled by different roles. Each step is a complete task; roles handle conditions and decisions internally. Use {{stepId.result}} in prompts to reference prior step outputs. Minimum 2 steps.",{steps:i.array(i.object({id:i.string().describe("Unique step identifier"),prompt:i.string().describe("Task prompt for this step"),roleId:b.optional().describe("Role ID for this step. Call list_roles first to find roles."),requirements:B.optional().describe("Task requirements for this step (D-012)."),autoSelectRole:i.boolean().optional().describe("Auto-select best role for this step (D-012)."),dependsOn:i.array(i.string()).optional().describe("Step IDs this step depends on"),config:i.object({timeout:i.number().optional(),maxTurns:i.number().optional()}).optional()})).min(2).describe("Workflow steps (min 2)"),name:i.string().optional().describe("Workflow name for tracking"),deliverTo:i.array(C).optional().describe("Where to deliver the aggregated workflow output"),reportTo:i.array(C).optional().describe("Where to send workflow status reports"),continueOnError:i.boolean().optional().describe("Continue remaining steps if one fails (default false)")},async e=>{let t=[];for(let p of e.steps){if(!p.roleId&&!p.autoSelectRole){t.push(`${p.id} (needs roleId or autoSelectRole)`);continue}if(p.roleId){let y=k(p.roleId);(!y||y.status!=="active")&&t.push(`${p.id} (roleId ${p.roleId} invalid/inactive)`)}}if(t.length>0){let p=N("active",20,0).filter(y=>y.source!=="system").map(y=>({id:y.id,name:y.name,capabilitySummary:x(y)}));return s({error:`Steps missing roleId/autoSelectRole or with invalid roleIds: ${t.join("; ")}.`,availableRoles:p})}let r=new Set(e.steps.map(p=>p.id));for(let p of e.steps)if(p.dependsOn)for(let y of p.dependsOn){if(!r.has(y))return s({error:`Step "${p.id}" depends on unknown step "${y}"`});if(y===p.id)return s({error:`Step "${p.id}" cannot depend on itself`})}let n=new Set,o=new Set,a=new Map(e.steps.map(p=>[p.id,p.dependsOn??[]])),l=p=>{if(o.has(p))return!0;if(n.has(p))return!1;n.add(p),o.add(p);for(let y of a.get(p)??[])if(l(y))return!0;return o.delete(p),!1};for(let p of e.steps)if(l(p.id))return s({error:"Circular dependency detected in workflow steps"});let d=e.deliverTo?await R(e.deliverTo):void 0,m=e.reportTo?await R(e.reportTo):void 0,c=S(),g=D(),f={id:`workflow-${c}`,name:e.name??"Ad-hoc workflow",trigger:{type:"manual"},steps:e.steps.map(p=>({id:p.id,prompt:p.prompt,roleId:p.roleId,requirements:p.requirements,autoSelectRole:p.autoSelectRole,dependsOn:p.dependsOn,config:p.config})),enabled:!0,createdAt:Date.now(),config:{...g.defaults,continueOnError:e.continueOnError??!1},deliverTo:d,reportTo:m};try{ke(f)}catch(p){let{TemplateRoleConfigError:y}=await import("./task-templates-IS3DJCZB.js");if(p instanceof y)return s({code:p.code,error:p.message,failingStepIds:p.failingStepIds,hint:"Each step must have roleId OR autoSelectRole=true (with requirements). Use list_roles to find an appropriate role."});throw p}let{WorkflowExecutor:h}=await import("./workflow-executor-LOMKVFPV.js");new h().execute(f,c).catch(p=>{H.error({executionId:c,error:p},"dispatch_workflow execution failed")});let _=e.steps.map(p=>{let y=p.roleId??(p.autoSelectRole?"[auto-selected]":"[no role]");return(p.roleId?k(p.roleId):void 0)?.name??y});return s({executionId:c,templateId:f.id,stepCount:e.steps.length,roles:[...new Set(_)],status:"started"})}),u("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",Or,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=gt(t??"",r);return n&&t&&U.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),s({reward:o.reward,metricL2Score:o.breakdown.L2||void 0,metricL3Score:o.breakdown.L3||void 0,source:o.source,reasoning:`Evaluated via ${o.source} with confidence ${o.confidence.toFixed(2)}`})}),u("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",qr,async e=>{let{roleId:t,taskType:r}=e;await pe.generateVariants(t,r,3,1);let n=U.getStrategies(t,r),o=n[n.length-1];return s(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),u("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",Fr,async e=>{let t=e.status;return s(pt(t,e.limit??10,0))}),u("delete_goal","Delete a goal by ID.",{goalId:L},async e=>z(e.goalId)?(mt(e.goalId),s({success:!0,goalId:e.goalId})):s({error:"Goal not found"})),u("pause_goal","Pause an active goal.",{goalId:L},async e=>z(e.goalId)?(ue(e.goalId,{status:"paused",updatedAt:Date.now()}),s({success:!0,goalId:e.goalId,status:"paused"})):s({error:"Goal not found"})),u("assign_role","Assign a role to a pending task.",jr,async e=>{let{taskId:t,roleId:r}=e;if(!$(t))return s({error:`Task not found: ${t}`});let o=k(r);return o?(Y(t,{roleId:r}),H.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),s({success:!0,taskId:t,roleId:r})):s({error:`Role not found: ${r}`})}),...Tt(),u("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",Gr,async e=>{if(e.taskId){let r=$(e.taskId);return s(r??{error:"Task not found"})}let t=e.status;return s(G(t,e.limit??100,0))}),u("modify_role_permissions","Update a role's RBAC permissions (paths, tools, OS capabilities).",Wr,async e=>{if(!k(e.roleId))return s({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.osCapabilities!==void 0)try{r.osCapabilities=be(e.osCapabilities)}catch(n){return s({error:n instanceof Error?n.message:String(n)})}return e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),W(e.roleId,r),s({success:!0})}),u("update_role","Update a role's identity and config fields (name, CAG prompt, learned rules, status, model, execution mode, preferences, permission mode, bash patterns, evaluation criteria, env vars). For permission fields (allowedTools, disallowedTools, osCapabilities, additionalDirectories, allowedChannels, inheritUserSettings) use modify_role_permissions instead.",Vr,async e=>{if(!k(e.roleId))return s({error:`Role not found: ${e.roleId}`});let{roleId:r,...n}=e,o={...n,updatedAt:Date.now()};W(r,o);let a=k(r);if(!a)return s({error:"Role disappeared after update"});if(e.cagPrompt!==void 0||e.learnedRules!==void 0){let l=we(a.name);Yt(l)&&He(l,a)}return s({success:!0,role:a})}),u("view_audit_log","View the evolution audit log for role changes.",Br,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-M7FSYRQR.js"),r=t(e.limit??50);return s({entries:r})}),u("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks. Pass requirements to get ranked results with fitScore showing which roles best match the task.",Yr,async e=>{if(e.requirements){let n=e.requirements,a=dt(n).slice(0,e.limit??50).map(l=>{let d=l.role,m=de(d),c=m.plugins.map(w=>w.name),g=we(d.name),f=st(d,g),h=n.tools?(d.allowedTools??[]).filter(w=>n.tools.includes(w)):void 0,v=n.paths?n.paths.filter(w=>at(w,f)):void 0,_=new Set((d.osCapabilities??[]).map(w=>w.id)),p=n.osCapabilities?n.osCapabilities.filter(w=>_.has(w.id)).map(w=>w.id):void 0,y=new Set(c),je=n.plugins?n.plugins.filter(w=>y.has(w)):void 0,Xt=n.network===!0?(d.osCapabilities??[]).some(w=>w.id==="local-network"):void 0,Zt=l.missing?.osCapabilities,er=lt(d,n);return{id:d.id,name:d.name,status:d.status,allowedTools:d.allowedTools??[],disallowedTools:d.disallowedTools??[],osCapabilities:d.osCapabilities??[],additionalDirectories:d.additionalDirectories??[],cagPrompt:d.cagPrompt.slice(0,500)+(d.cagPrompt.length>500?"...":""),capabilitySummary:x(d,m),plugins:m.plugins.map(w=>({name:w.name,skills:w.skills.map(he=>he.name),agents:w.agents.map(he=>he.name)})),fitScore:l.fitScore,fits:l.evaluation.ok,matchedTools:h,matchedPaths:v,matchedOsCapabilities:p,matchedPlugins:je,matchedNetwork:Xt,missingCapabilities:l.missing?{tools:l.missing.tools,paths:l.missing.paths,osCapabilities:Zt?.map(w=>w.id),plugins:l.missing.plugins,network:l.missing.network}:void 0,warnings:er,why:l.evaluation.ok?`Role '${d.name}' satisfies all requirements (fitScore: ${l.fitScore.toFixed(2)})`:`Role '${d.name}' does not satisfy requirements: ${l.evaluation.ok?"unknown":l.evaluation.reason}`}});return s({roles:a})}let r=N(e.status,e.limit??50,0).map(n=>{let o=de(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],osCapabilities:n.osCapabilities??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:x(n,o),plugins:o.plugins.map(a=>({name:a.name,skills:a.skills.map(l=>l.name),agents:a.agents.map(l=>l.name)}))}});return s({roles:r})}),u("create_role","Create a new role with a name, CAG prompt, and optional tool permissions or OS capabilities.",zr,async e=>{let t;try{t=be(e.osCapabilities)}catch(o){return s({error:o instanceof Error?o.message:String(o)})}let r=`role-${S().slice(0,8)}`,n={id:r,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${S().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,osCapabilities:t,additionalDirectories:e.additionalDirectories};return Ke(n),se(n),s({roleId:r,name:e.name,allowedTools:e.allowedTools,osCapabilities:n.osCapabilities,additionalDirectories:e.additionalDirectories??[]})}),u("retire_role","Retire a role (marks as retired, stops receiving tasks).",Kr,async e=>k(e.roleId)?(W(e.roleId,{status:"retired"}),H.info({roleId:e.roleId,reason:e.reason},"Role retired"),s({success:!0})):s({error:`Role not found: ${e.roleId}`})),u("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Jr,async e=>{let t=S(),r=Date.now(),n=r+10080*60*1e3,o={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await R(e.deliverTo):void 0};ce(o),Et(t,o.metricType);let a=z(t);return s({goalId:a.id,name:a.name,status:a.status})}),u("create_template","Create a recurring scheduled task. triggerType values: 'cron' (recurring via cron expression), 'template_complete' (fires when a specific template's task completes; set triggerEvent to 'template_complete:<templateId>'), 'workflow_complete' (similar), 'event' (fires when an Event def fires; set eventDefId to the event def UUID \u2014 use list_event_defs or create_event_def first). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Hr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-IS3DJCZB.js"),r=S(),n=S();if(e.triggerType==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});if(e.triggerType!=="event"&&e.eventDefId)return s({error:"eventDefId only valid when triggerType='event'"});let o=e.deliverTo?await R(e.deliverTo):void 0,a=e.reportTo?await R(e.reportTo):void 0,l={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent,eventDefId:e.eventDefId},steps:[{id:n,prompt:e.prompt,...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:o,reportTo:a};try{t(l)}catch(d){let{TemplateRoleConfigError:m}=await import("./task-templates-IS3DJCZB.js");if(d instanceof m)return s({code:d.code,error:d.message,failingStepIds:d.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object (e.g., {tools:['Read']}) on the template. Use list_roles to find an appropriate role."});throw d}return s({templateId:r,name:l.name,trigger:l.trigger})}),u("create_event_def","Create an Event definition \u2014 a user-configured source that fires on schedule/webhook/directory/manual. Event defs are the trigger half of the Event Slot; pair with create_template(triggerType='event', eventDefId=<returned id>) to bind work to the trigger. sourceType is validated at runtime against the installed source registry (currently: webhook, cron, directory_watch, manual \u2014 additional types may be registered at runtime). sourceConfig is per-type: cron \u2192 {cron: '0 9 * * *'}; directory_watch \u2192 {path: '/abs/path', glob?: '*.md'}; webhook/manual \u2192 {}.",{name:i.string().min(1).max(100).describe("Human-readable name (unique within workspace)."),sourceType:i.string().describe("Source type \u2014 validated against installed registry at call time. Currently: 'webhook' | 'cron' | 'directory_watch' | 'manual'. If the value is rejected, the error message lists the currently-registered types."),sourceConfig:i.record(i.string(),i.unknown()).describe("Per-sourceType configuration. See tool description."),enabled:i.boolean().optional().describe("Default true."),description:i.string().max(500).optional().describe("Free-form description of what this event represents.")},async e=>{if(!re().includes(e.sourceType))return s({error:`Unknown sourceType: '${e.sourceType}'. Currently registered: ${re().join(", ")}`});let t=Fe(e.sourceType,e.sourceConfig);if(!t.ok)return s({error:`Invalid sourceConfig: ${t.error}`});let r=S(),n=qt({id:r,name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled??!0,description:e.description});try{qe(n)}catch(o){Me(r);let a=o instanceof Error?o.message:String(o);return s({error:`Failed to start source: ${a}. Event def was not created.`})}return s({id:n.id,name:n.name,sourceType:n.sourceType,enabled:n.enabled})}),u("list_event_defs","List Event definitions. Use before create_template(triggerType='event') to find the eventDefId, or before fire_event_def / list_event_firings.",{sourceType:i.string().optional().describe("Filter by source type (e.g., 'cron', 'webhook')."),enabled:i.boolean().optional().describe("Filter by enabled flag.")},async e=>{let t=me({sourceType:e.sourceType,enabled:e.enabled});return s(t.map(r=>({id:r.id,name:r.name,sourceType:r.sourceType,sourceConfig:r.sourceConfig,enabled:r.enabled,description:r.description,createdAt:r.createdAt})))}),u("update_event_def","Update an Event definition. Changing `enabled` or `sourceConfig` on an active def automatically restarts the runtime source handler. Use list_event_defs first to get the id.",{id:O.describe("Event def id."),name:i.string().min(1).max(100).optional().describe("Human-readable name for this event definition."),sourceType:i.string().optional().describe("Only set when migrating to a different source type."),sourceConfig:i.record(i.string(),i.unknown()).optional().describe("Per-sourceType configuration. See tool description."),enabled:i.boolean().optional().describe("Enable or disable this event definition."),description:i.string().max(500).optional().describe("Free-form description of what this event represents.")},async e=>{let t=J(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});if(e.sourceType!==void 0||e.sourceConfig!==void 0){let l=e.sourceType??t.sourceType;if(!re().includes(l))return s({error:`Unknown sourceType: '${l}'`});let d=Fe(l,e.sourceConfig??t.sourceConfig);if(!d.ok)return s({error:`Invalid sourceConfig: ${d.error}`})}let r=t.enabled,n=e.enabled??t.enabled,o=e.sourceType!==void 0||e.sourceConfig!==void 0;r&&(!n||o)&&ge(t.id,t.sourceType);let a=Ae(e.id,{name:e.name,sourceType:e.sourceType,sourceConfig:e.sourceConfig,enabled:e.enabled,description:e.description});if(!a)return s({error:"Update failed"});if(n&&(!r||o))try{qe(a)}catch(l){Ae(e.id,{enabled:!1});let d=l instanceof Error?l.message:String(l);return s({error:`Failed to start source with new config: ${d}. Event def has been marked disabled to match runtime state.`})}return s({id:a.id,name:a.name,sourceType:a.sourceType,enabled:a.enabled})}),u("delete_event_def","Delete an Event definition. Stops the runtime source handler (cron/fswatch) first, then deletes the DB row. Templates bound to this event def become orphaned and will not fire.",{id:O.describe("Event def id.")},async e=>{let t=J(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});try{ge(t.id,t.sourceType)}catch(n){H.warn({defId:t.id,err:n},"stopEventDefSource failed during delete \u2014 proceeding with row deletion")}let r=Me(e.id);return s({ok:r,id:e.id})}),u("fire_event_def","Fire an Event definition now. For manual defs: creates a real manual event (same as clicking 'Fire now' in the UI). For any source type: with test=true, creates a synthetic test event (source='manual-test-<defId>') that flows through the EventDispatcher \u2014 useful for debugging why a Template bound to the event didn't fire. Payload is optional.",{id:O.describe("Event def id."),test:i.boolean().optional().describe("Test mode. Required (=true) when source type != 'manual'. Default false. In test mode the event does NOT collide with real firings' dedup keys."),payload:i.record(i.string(),i.unknown()).optional().describe("Optional event payload. Must be < 64 KB when JSON-serialized.")},async e=>{let t=J(e.id);if(!t)return s({error:`Event def '${e.id}' not found`});let r=e.test===!0;if(t.sourceType!=="manual"&&!r)return s({error:`Can only directly fire manual event defs; this def has source type '${t.sourceType}'. Pass test=true to dry-run.`});if(e.payload){let n=Buffer.byteLength(JSON.stringify(e.payload),"utf8");if(n>65536)return s({error:`Payload exceeds 64 KB limit (got ${n} bytes)`})}try{let n=r?Le(t,e.payload):Ue(t,e.payload);return s({ok:!0,eventId:n.eventId,test:r})}catch(n){let o=n instanceof Error?n.message:String(n);return s({error:o})}}),u("list_event_firings","List recent firings of an Event definition \u2014 for debugging 'why didn't my automation fire' and inspecting event history. Returns id, occurredAt, type, source, dedupKey, confidence, and a truncated payload (500 char cap for display). For full payloads, use REST GET /event-defs/:id/firings.",{eventDefId:O.describe("Event def id. Use list_event_defs to find it."),since:i.string().optional().describe("ISO 8601 start timestamp (inclusive). Omit for unlimited range."),until:i.string().optional().describe("ISO 8601 end timestamp (inclusive)."),limit:i.number().int().positive().max(500).optional().describe("Max rows (default 50, max 500).")},async e=>{let t=J(e.eventDefId);if(!t)return s({error:`Event def '${e.eventDefId}' not found`});let r=Lt({eventDefId:e.eventDefId,since:e.since,until:e.until,limit:e.limit??50}),n=500;return s({eventDefName:t.name,sourceType:t.sourceType,count:r.length,firings:r.map(o=>{let a=Jt({payload:o.payload,trustLevel:o.trustLevel,source:o.source,maxBodyChars:n});return{id:o.id,occurredAt:o.occurredAt,type:o.type,source:o.source,dedupKey:o.dedupKey,confidence:o.confidence,trustLevel:o.trustLevel,payloadPreview:a,payloadTruncated:a.length>n}})})}),u("create_skill","Author a Claude Code Skill file under a target Role's workspace. The Skill becomes available next time the Role runs. Preset Roles (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator) require overwrite=true to replace an existing skill \u2014 first-time creation is unrestricted. Returns the written file path.",{roleId:b.describe("Role to target. Use list_roles to find it."),skillName:i.string().regex(/^[a-z0-9_][a-z0-9_-]{0,39}$/,"skillName must be 1-40 chars: lowercase letters, digits, underscores, optional hyphen in middle. No leading dot or dash.").describe("Skill directory name (used as the directory under .claude/skills/)."),description:i.string().max(500).describe("One-line description shown to the Role's LLM when choosing a Skill."),instructions:i.string().describe("The skill body: what it does and how to do it."),parameters:i.record(i.string(),i.object({type:i.string().describe("Parameter type name"),description:i.string().describe("Parameter description")})).optional().describe("Named input parameters and their types."),overwrite:i.boolean().optional().describe("Required (=true) to overwrite an existing SKILL.md under a preset Role (Engineer, Reviewer, Researcher, Writer, Chat Manager, adam-automator). First-time skill creation and non-preset Roles do not require this flag.")},async e=>{let{getRole:t}=await import("./roles-WNKRM6FD.js"),{ensureRoleWorkspace:r}=await import("./role-workspace-ISGPO25D.js"),{mkdir:n,writeFile:o}=await import("fs/promises"),{resolve:a}=await import("path"),l=t(e.roleId);if(!l)return s({error:`Role '${e.roleId}' not found`});let d=r(l),m=a(d,".claude","skills",e.skillName);if(Ze(l)){let{existsSync:h}=await import("fs"),v=a(m,"SKILL.md");if(h(v)&&e.overwrite!==!0)return s({error:`Role '${l.name}' is a preset. Skill '${e.skillName}' already exists at ${v}. Pass overwrite=true to replace, or choose a different skillName to add alongside.`,requiresOverwrite:!0,existingPath:v})}let c=a(d,".claude","skills");if(!m.startsWith(c+(process.platform==="win32"?"\\":"/")))return s({error:"Path traversal rejected"});await n(m,{recursive:!0});let g=Ar(e),f=a(m,"SKILL.md");return await o(f,g,"utf8"),s({ok:!0,path:f})}),u("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:i.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:i.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-IS3DJCZB.js"),r=t(e.enabled,e.limit??50,0);return s(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),u("send_to_channel","Send a message (text, image, voice, video, file) to a connected channel by name. Use this to deliver task results, media, or notifications to a specific channel (e.g., WeChat on iPad). For media: provide mediaUrl as an absolute local file path and mediaType. Do NOT use remote URLs \u2014 download files locally first.",{channelName:i.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:i.string().describe("The message content to send (text caption when sending media)"),mediaUrl:Z.optional().describe("Absolute local file path to the media file (e.g. /Users/.../file.png). Must exist on disk. Do NOT use remote URLs \u2014 download files locally first."),mediaType:i.enum(["image","audio","video","file"]).optional().describe("Type of the media file. Required when mediaUrl is provided")},async e=>{if(e.mediaUrl){if(e.mediaUrl.includes("://")&&!e.mediaUrl.startsWith("file://"))return s({error:`mediaUrl must be a local file path, not a remote URL. Got: ${e.mediaUrl.slice(0,80)}. Download the file to a local path first, then pass the local path.`});let l=e.mediaUrl.startsWith("file://")?new URL(e.mediaUrl).pathname:e.mediaUrl;if(!Yt(l))return s({error:`Media file not found: ${l}. Verify the file exists before sending.`});if(!e.mediaType)return s({error:"mediaType is required when mediaUrl is provided. Specify one of: image, audio, video, file."})}let t=await R([{type:"channel",channelName:e.channelName}]);if(t.length===0)return s({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return s({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-XDCGAXXW.js"),a=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver",mediaUrl:e.mediaUrl,mediaType:e.mediaType});return s({success:a.success,channelName:e.channelName,...a.error?{error:a.error}:{}})}),u("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Qr,async e=>{let t=Re(e.enabled),r=[...De("active"),...De("archived")],n=t.map(o=>{let a,l=r.find(d=>d.source.type==="channel"&&d.source.channelId===o.id&&d.source.chatId);return l?.source.chatId?a=l.source.chatId:a=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:a}});return s({channels:n})}),u("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Xr,async()=>{let e=D(),t=G("running"),r=G("pending");return s({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),u("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",en,async e=>{let t=k(e.roleId);if(!t||t.status!=="active"){let f=N("active",20,0).filter(h=>h.source!=="system").map(h=>({id:h.id,name:h.name,allowedTools:h.allowedTools??[],capabilitySummary:x(h)}));return s({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:f})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return s({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return s({error:"Invalid ISO 8601 timestamp in runAt"})}else return s({error:"Provide either delayMinutes or runAt"});if(n<=r)return s({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return s({error:"Schedule exceeds maximum of 7 days"});let a=S(),l=new Date(n).toISOString(),d=e.deliverTo?await R(e.deliverTo):void 0,m=e.reportTo?await R(e.reportTo):void 0;ke({id:a,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:l},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...D().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:d,reportTo:m});let{getBreeEngine:c}=await import("./bree-engine-VGEYMVNP.js"),g=c();return g&&g.scheduleOnceJob(a),s({templateId:a,executeAt:l,prompt:e.prompt})}),u("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:K.describe("The template ID returned by schedule_task")},async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return s({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Qe(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-VGEYMVNP.js"),n=r();return n&&await n.unscheduleJob(e.templateId),s({cancelled:!0,templateId:e.templateId})}),u("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",tn,async e=>{let t=et(),r=le(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(ae(),M(Ie)),{getRole:a}=(ie(),M(ve)),{listInstalledPlugins:l}=(it(),M(nr)),d=a(e.roleId);if(!d)return[];let m=o(d.name);return l({scope:"project",projectPath:m}).map(c=>c.id)})():[];return s({plugins:r.map(o=>({id:o.id,name:o.name,scope:o.scope,projectPath:o.projectPath,enabled:o.enabled,globalEnabled:t[o.id]??o.enabled,isInstalledInRole:n.includes(o.id),description:o.version?`v${o.version}`:void 0}))})}),u("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",rn,async e=>{let{getRole:t}=(ie(),M(ve)),{getRoleWorkspacePath:r}=(ae(),M(Ie)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return xe(e.pluginId,"project",o),s({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(a){return s({error:`Failed to install plugin: ${a}`})}}),u("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",nn,async e=>{let{getRole:t}=(ie(),M(ve)),{getRoleWorkspacePath:r}=(ae(),M(Ie)),n=t(e.roleId);if(!n)return s({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Pe(e.pluginId,"project",o),s({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(a){return s({error:`Failed to uninstall plugin: ${a}`})}}),u("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",on,async e=>{let t=k(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return W(e.roleId,{mcpServers:n}),se(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return s({error:`Failed to bind MCP server: ${o}`})}}),u("unbind_mcp_from_role","Remove an MCP server binding from a role.",sn,async e=>{let t=k(e.roleId);if(!t)return s({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return s({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return W(e.roleId,{mcpServers:r}),se(t),s({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return s({error:`Failed to unbind MCP server: ${n}`})}}),u("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, OS capability registry, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",Zr,async()=>{let{listTaskTemplates:e}=await import("./task-templates-IS3DJCZB.js"),t=D(),r=N(void 0,100,0),n=Re(),o=e(!0,100,0),a=G("running"),l=G("pending"),d=Rt(),m=await Dt();return s({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(c=>c.status==="active"&&c.source!=="system").map(c=>{let g=de(c);return{name:c.name,tools:c.allowedTools??[],osCapabilities:c.osCapabilities??[],mcpServers:Object.keys(c.mcpServers??{}),channels:c.allowedChannels??[],capabilitySummary:x(c,g),plugins:g.plugins.map(f=>({name:f.name,skills:f.skills.map(h=>h.name),agents:f.agents.map(h=>h.name)}))}}),retired:r.filter(c=>c.status==="retired").length,probation:r.filter(c=>c.status==="probation").length},osCapabilities:{description:"Role-level OS capability registry. Only editable entries can be assigned to roles on this runtime.",sandbox:{platform:d.platform,available:m},registry:ze(d.platform,m)},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(c=>c.enabled).map(c=>({name:c.name,platform:c.platform,status:c.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:le().filter(c=>c.enabled).map(c=>({name:c.name,scope:c.scope,description:c.version?`v${c.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(c=>({name:c.name,trigger:c.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:a.length,queued:l.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),u("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",an,async e=>{try{return $t(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to enable plugin: ${t}`})}}),u("disable_plugin","Disable a globally installed plugin (removes it from all roles).",ln,async e=>{try{return Nt(e.pluginId),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to disable plugin: ${t}`})}}),u("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",dn,async e=>{try{return xe(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return s({error:`Failed to install plugin: ${t}`})}}),u("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",cn,async e=>{try{return Pe(e.pluginId,"user"),s({success:!0,pluginId:e.pluginId})}catch(t){return s({error:`Failed to uninstall plugin: ${t}`})}}),u("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",un,async()=>{try{let e=Mt(),t=le();return s({available:e,installed:t})}catch(e){return s({error:`Failed to browse marketplace: ${e}`})}}),u("list_marketplace_sources","List configured plugin marketplace sources.",pn,async()=>{let e=nt();return s({sources:e})}),u("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",mn,async e=>{let t=rt(e.pluginId);if(!t)return s({error:`Plugin not found: ${e.pluginId}`});let r=tt(t.installPath);return s({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),u("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",fn,async e=>{let{getRole:t}=await import("./roles-WNKRM6FD.js");if(!t(e.roleId))return s({error:`Role not found: ${e.roleId}`});try{let n=ot(e.path);return s({roleId:e.roleId,path:e.path,config:n})}catch(n){return s({error:`Failed to scan directory: ${n}`})}}),u("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",gn,async e=>{let t=$(e.taskId);if(!t)return s({error:`Task not found: ${e.taskId}`});let r=t.status;Y(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),s({success:!0,taskId:e.taskId,status:"cancelled"})}),u("view_task_logs","Retrieve step-by-step execution logs for a task.",hn,async e=>{let t=Be(e.taskId,e.limit??20);return s({taskId:e.taskId,count:t.length,logs:t})}),u("delete_role","Delete a role by ID. This removes the role and its workspace.",yn,async e=>k(e.roleId)?(Je(e.roleId),s({success:!0,roleId:e.roleId})):s({error:`Role not found: ${e.roleId}`})),u("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",bn,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-QA2DCZYQ.js"),r=D(),n={};try{let d=D().server?.port??7100,m=await fetch(`http://127.0.0.1:${d}/config`);m.ok&&(n=await m.json())}catch{}let o=[...e,...t],a=[...t],l={};for(let d of o){let m=d.split("."),c=r;for(let g of m)if(c&&typeof c=="object")c=c[g];else{c=void 0;break}l[d]={value:c,mutable:!t.includes(d)}}return s({config:l,mutable:[...e],restartRequired:[...t]})}),u("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",vn,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-QA2DCZYQ.js"),{setConfigValue:r}=await import("./config-GKVOAMY2.js"),n=Ge(e.updates,r);if(e.updates["logging.level"]&&We(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(a=>({path:a,value:e.updates[a]}))})}return s(n)}),u("list_memories","List memories stored under a specific role.",wn,async e=>{let t=vt(e.roleId,e.limit??20);return s({roleId:e.roleId,count:t.length,memories:t})}),u("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",In,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0||e.autoSelectRole!==void 0||e.requirements!==void 0){let o=t.steps?.length?[...t.steps]:[];o.length===0&&o.push({id:S(),prompt:e.prompt??""});let a=o[0];o[0]={...a,...e.prompt!==void 0?{prompt:e.prompt}:{},...e.autoSelectRole!==void 0?{autoSelectRole:e.autoSelectRole}:{},...e.requirements!==void 0?{requirements:e.requirements}:{}},r.steps=o}if(e.triggerCron!==void 0||e.triggerEvent!==void 0||e.triggerType!==void 0||e.eventDefId!==void 0){let o=e.triggerType??(e.triggerEvent?e.triggerEvent.split(":")[0]:e.eventDefId?"event":"cron");if(o==="event"&&!e.eventDefId)return s({error:"eventDefId required when triggerType='event'"});r.trigger={type:o,...e.triggerCron!==void 0?{cron:e.triggerCron}:{},...e.triggerEvent!==void 0?{event:e.triggerEvent}:{},...e.eventDefId!==void 0?{eventDefId:e.eventDefId}:{}}}e.roleId!==void 0&&(r.rolePreference=e.roleId);try{Ye(e.templateId,r)}catch(o){let{TemplateRoleConfigError:a}=await import("./task-templates-IS3DJCZB.js");if(o instanceof a)return s({code:o.code,error:o.message,failingStepIds:o.failingStepIds,hint:"Set roleId (recommended) OR autoSelectRole=true with a requirements object."});throw o}return s({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),u("get_template_dependents","Count workflow_executions and tasks that depend on a template. Use this BEFORE delete_template to show the user what will be affected. Returns { executionCount, taskCount, hasDependents }. If hasDependents is false, delete_template is safe with mode='template_only'. If true, you MUST ask the user whether to delete the template only (keeps tasks as history) or delete with its tasks (removes tasks and their score history). Never pick the mode yourself.",Tn,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r=Te(e.templateId);return s({templateId:e.templateId,templateName:t.name,executionCount:r.executionCount,taskCount:r.taskCount,hasDependents:r.executionCount>0||r.taskCount>0})}),u("delete_template","Delete a task template by ID. PRECONDITION: you must have called get_template_dependents first. If executionCount > 0 or taskCount > 0, you must have shown the user those counts and received explicit confirmation of which mode to use. Call this tool only after the user picks 'template_only' or 'with_tasks'. Passing a mode without user confirmation violates the skill's safety contract.",kn,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});let r=Te(e.templateId);return Xe(e.templateId,e.mode),s({success:!0,templateId:e.templateId,templateName:t.name,mode:e.mode,deleted:{template:1,workflowExecutions:r.executionCount,tasks:e.mode==="with_tasks"?r.taskCount:0}})}),u("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Sn,async e=>{let t=V(e.templateId);if(!t)return s({error:`Template not found: ${e.templateId}`});try{let r=D().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?s({success:!0,templateId:e.templateId,templateName:t.name,response:o}):s({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return s({error:`Failed to trigger template: ${r}`})}}),u("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",_n,async e=>{let t=Ce(e.enabled);return s({count:t.length,rules:t})}),u("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Rn,async e=>{let t=S(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return St(r),s({success:!0,ruleId:t,rule:r})}),u("delete_delivery_rule","Delete a delivery rule by ID.",Dn,async e=>Ce().find(n=>n.id===e.ruleId)?(_t(e.ruleId),s({success:!0,ruleId:e.ruleId})):s({error:`Delivery rule not found: ${e.ruleId}`})),u("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",En,async e=>{let t;if(e.roleId)t=ut(e.roleId);else{let{getDb:r}=await import("./db-FACSMWEY.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(o=>({id:o.id,roleId:o.role_id,name:o.name,taskType:o.task_type,createdAt:o.created_at,updatedAt:o.updated_at??void 0,promptTemplate:o.prompt_template??"",alpha:o.alpha,beta:o.beta,totalTrials:o.trials,avgReward:o.total_reward&&o.trials>0?o.total_reward/o.trials:void 0,enabled:o.enabled===1}))}return s({roleId:e.roleId??null,count:t.length,strategies:t})}),u("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:P,operationId:i.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:i.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=_e(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new oe().resolvePlanApproval(r.id,"allow",e.scope),s({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):s({error:"No pending operation found for this task"})}),u("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:P,operationId:i.string().optional().describe("ID of the specific operation. If omitted, denies the most recent pending operation."),reason:i.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=_e(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new oe().resolvePlanApproval(r.id,"deny","once",e.reason),s({success:!0,operationId:r.id,decision:"deny"})):s({error:"No pending operation found for this task"})})];function wi(){return Qt.map(e=>e.name).sort().join(",")}function Ii(){return Pr({name:"adam-tools",version:"1.0.0",tools:Qt})}export{oe as a,$n as b,Nn as c,Et as d,Mt as e,xe as f,Pe as g,$t as h,Nt as i,Wn as j,Vn as k,Bn as l,Lt as m,qt as n,J as o,me as p,Ae as q,Me as r,F as s,Ue as t,Le as u,qe as v,ge as w,To as x,re as y,Fe as z,Do as A,R as B,wi as C,Ii as D};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as a}from"./chunk-
|
|
1
|
+
import{d as a}from"./chunk-6WRZJVQ2.js";function s(){try{let t=a().server?.timezone;return t==="system"||!t?void 0:t}catch{return}}function p(t){let e=s();return new Date(t).toLocaleTimeString(void 0,e?{timeZone:e}:void 0)}function l(t){let e=t??s(),r=new Date,i=r.toLocaleDateString("en-CA",e?{timeZone:e}:void 0);if(e){let n=(new Intl.DateTimeFormat("en-US",{timeZone:e,timeZoneName:"shortOffset"}).formatToParts(r).find(o=>o.type==="timeZoneName")?.value??"").match(/GMT([+-]?)(\d+)(?::(\d+))?/);if(n){let o=n[1]==="-"?-1:1,m=parseInt(n[2],10),c=parseInt(n[3]??"0",10),f=o*(m*60+c)*6e4;return new Date(`${i}T00:00:00Z`).getTime()-f}}return new Date(`${i}T00:00:00`).getTime()}export{p as a,l as b};
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as W,b as h,c as z,e as V}from"./chunk-PHT24MOV.js";import{a as B,b as J,d as G}from"./chunk-
|
|
2
|
+
import{a as W,b as h,c as z,e as V}from"./chunk-PHT24MOV.js";import{a as B,b as J,d as G}from"./chunk-SGIKNIC5.js";import{a as q}from"./chunk-YKYRNTPV.js";import"./chunk-2BXTT4P2.js";import{b as _}from"./chunk-7IFLU3CY.js";import"./chunk-6WRZJVQ2.js";import"./chunk-U2LBBBWO.js";import{c as M,e as K,g as de}from"./chunk-B44X7JAJ.js";import{b as H,c as j,d as ce}from"./chunk-AQO6IIHV.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";import{Command as we}from"commander";import{fork as ue}from"child_process";import{readFileSync as L,writeFileSync as me,existsSync as v,unlinkSync as $,mkdirSync as pe,openSync as ge}from"fs";import{join as D}from"path";import{homedir as fe}from"os";var P=D(fe(),".adam"),S=D(P,"adam.pid"),k=D(P,"adam.port"),b=D(P,"server.log");function he(){v(P)||pe(P,{recursive:!0})}function C(){if(!v(S))return null;let e=parseInt(L(S,"utf-8").trim(),10);return isNaN(e)?null:e}function ve(){if(!v(k))return null;let e=parseInt(L(k,"utf-8").trim(),10);return isNaN(e)?null:e}function A(e){try{return process.kill(e,0),!0}catch{return!1}}async function N(){he();let e=C();if(e&&A(e))throw new Error(`Server already running (PID ${e})`);v(S)&&$(S),v(k)&&$(k);let o=ge(b,"a"),t=D(B,"dist/index.js"),n=ue(t,[],{detached:!0,stdio:["ignore",o,o,"ipc"]}),l=await new Promise((i,c)=>{let g=setTimeout(()=>{n.kill(),c(new Error(`Server start timeout. Check logs: ${b}`))},1e4);n.on("message",a=>{if(a&&typeof a=="object"&&a.type==="ready"){clearTimeout(g);let s=a.port;s?i(s):c(new Error("Ready signal received but missing port"))}}),n.on("exit",a=>{clearTimeout(g);let s=v(b)?L(b,"utf-8").split(`
|
|
3
3
|
`).slice(-10).join(`
|
|
4
4
|
`):"";c(new Error(`Server exited with code ${a}.
|
|
5
5
|
${s?`Last log lines:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as b,b as c,d,e}from"./chunk-HDHMNT6D.js";import{a}from"./chunk-47COBMRF.js";import"./chunk-7IFLU3CY.js";import"./chunk-6WRZJVQ2.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as DEFAULT_CONFIG,e as getChatConfig,d as getDefaults,b as loadConfig,c as loadDefaultConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as i}from"./chunk-
|
|
1
|
+
import{a as i}from"./chunk-47COBMRF.js";import"./chunk-WBAPIPST.js";import{c as a,h as c}from"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";c();var u=a("agent");async function m(n){let e=f();if(e.length===0)return{scores:[],errors:[]};let s=[],r=[];for(let t of e)try{let o=await l(t);o!==null&&s.push({nodeId:n,score:o,source:t.name,fetchedAt:Date.now()})}catch(o){r.push(`External API "${t.name}" (${t.url}): ${o instanceof Error?o.message:String(o)}`),u.warn({endpoint:t.name,error:o},"External API fetch failed")}return{scores:s,errors:r}}async function l(n){let e=await fetch(n.url,{signal:AbortSignal.timeout(5e3),headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let s=await e.json(),r=p(s,n.scorePath);if(typeof r!="number"||isNaN(r))throw new Error(`Score at "${n.scorePath}" is not a number: ${JSON.stringify(r)}`);return Math.max(0,Math.min(1,r))}function p(n,e){let s=e.replace(/^\$\.?/,""),r=n;for(let t of s.split(".")){if(r==null||typeof r!="object")return;r=r[t]}return r}function f(){return i.externalApis??[]}export{m as collectExternalApiScores};
|