adam-agent-server 0.1.0 → 0.2.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/README.md +11 -19
- package/dist/App-G2WZKRUH.js +9 -0
- package/dist/adam-tools-Q4BRKX3U.js +1 -0
- package/dist/approval-handler-D3J6NCMM.js +4 -0
- package/dist/bree-engine-SQMSKGAP.js +1 -0
- package/dist/channels-VEUBY2NZ.js +1 -0
- package/dist/channels-WFZAONF3.js +1 -0
- package/dist/{chunk-5GMYXCL3.js → chunk-2EP27EGS.js} +1 -1
- package/dist/chunk-2GXYBWLS.js +10 -0
- package/dist/chunk-2VKE7ONM.js +86 -0
- package/dist/{chunk-HMXDNPFE.js → chunk-5ASEAZCR.js} +1 -1
- package/dist/chunk-5JLMSNIW.js +1 -0
- package/dist/{chunk-MMIO6BCA.js → chunk-742NWPTQ.js} +3 -3
- package/dist/chunk-7SPKRIMZ.js +15 -0
- package/dist/chunk-AXMXXUPO.js +5 -0
- package/dist/{chunk-5AKFAMQL.js → chunk-B6S2AEOD.js} +1 -1
- package/dist/chunk-DT2LX4XI.js +49 -0
- package/dist/{chunk-VURJZLM6.js → chunk-EALDBELJ.js} +6 -3
- package/dist/{chunk-ZN5Q3YET.js → chunk-ETQ7KC73.js} +1 -1
- package/dist/chunk-FDWW245P.js +5 -0
- package/dist/chunk-FUGJMHY4.js +1 -0
- package/dist/chunk-FYDFMYUP.js +1 -0
- package/dist/chunk-HAWA62R2.js +26 -0
- package/dist/chunk-IXF3XBGX.js +5 -0
- package/dist/chunk-JXD6ZPV7.js +2 -0
- package/dist/chunk-KICPHTI2.js +5 -0
- package/dist/chunk-L7426WNY.js +7 -0
- package/dist/{chunk-WGRTN6TX.js → chunk-L7JP7DUO.js} +1 -1
- package/dist/chunk-NICRQZ7T.js +1 -0
- package/dist/{chunk-3HM54J2N.js → chunk-NSJAV7IH.js} +1 -1
- package/dist/{chunk-W6JITSZF.js → chunk-PCSZW2PE.js} +28 -11
- package/dist/{chunk-EJJDJY34.js → chunk-PQ7KPALO.js} +1 -1
- package/dist/{chunk-F2IS5LWD.js → chunk-SFUS33SO.js} +1 -1
- package/dist/chunk-T25NLVMY.js +1 -0
- package/dist/chunk-TN6H2WM2.js +19 -0
- package/dist/chunk-U36NBCR3.js +17 -0
- package/dist/chunk-UOTDT2KY.js +3 -0
- package/dist/chunk-VF6GJGD6.js +6 -0
- package/dist/chunk-WXN3PSVX.js +6 -0
- package/dist/chunk-WZOMGJSY.js +1 -0
- package/dist/{chunk-62PXAOD6.js → chunk-XNWZZYAV.js} +1 -1
- package/dist/cli.js +15 -13
- package/dist/config-WHXCZCI4.js +1 -0
- package/dist/config-Y4QWELO3.js +1 -0
- package/dist/{db-ZDEA7EUY.js → db-PNZ3UJOE.js} +1 -1
- package/dist/delivery-log-VYTYUFCK.js +1 -0
- package/dist/engine-V5MOGOLN.js +1 -0
- package/dist/{evolution-audit-MDA2ZVJW.js → evolution-audit-B7WKMOVR.js} +1 -1
- package/dist/{external-api-T7FFXVHL.js → external-api-XGEOKAWR.js} +1 -1
- package/dist/index.js +41 -63
- package/dist/learner-VMD5NQCD.js +1 -0
- package/dist/memories-EFQ4SFZG.js +1 -0
- package/dist/memory-extractor-GOISDQTO.js +6 -0
- package/dist/memory-service-BKLZIRK6.js +1 -0
- package/dist/monitor-K7CGTLA6.js +1 -0
- package/dist/outbound-gateway-FIPC4BZO.js +1 -0
- package/dist/role-presets-FN2RWUCP.js +1 -0
- package/dist/{roles-CMV5FMIA.js → roles-SG2YAR64.js} +1 -1
- package/dist/runtime-6UTYEONR.js +1 -0
- package/dist/server-bus-GEGVMSCA.js +1 -0
- package/dist/session-manager-45LFTPBA.js +1 -0
- package/dist/{task-templates-AKQB7RRB.js → task-templates-7LSQ6OST.js} +1 -1
- package/dist/token-estimator-HMPVGDCN.js +1 -0
- package/package.json +2 -2
- package/web/dist/assets/{Card-BpwkRtmi.js → Card-BecEmnPW.js} +1 -1
- package/web/dist/assets/{ChannelDetail-050qK78l.js → ChannelDetail-dZfZlLgQ.js} +1 -1
- package/web/dist/assets/{Channels-DA4gN6nU.js → Channels-Cw04c7YJ.js} +1 -1
- package/web/dist/assets/{Chat-LzhfKGQ5.js → Chat-D4PHqHPE.js} +1 -1
- package/web/dist/assets/Dashboard-BFewwmAg.js +1 -0
- package/web/dist/assets/{EmptyState-B08f3BH6.js → EmptyState-DBFJc4PL.js} +1 -1
- package/web/dist/assets/{Evolution-BwsOuVbZ.js → Evolution-DY1OC6Oc.js} +4 -1
- package/web/dist/assets/{GoalDetail-Zo16ZrYD.js → GoalDetail-DZIEpHs2.js} +1 -1
- package/web/dist/assets/Goals-COCCVLnp.js +1 -0
- package/web/dist/assets/{Logs-CYfQ9k_6.js → Logs-DsDeimLt.js} +1 -1
- package/web/dist/assets/Memories-D5IEEI1u.js +1 -0
- package/web/dist/assets/NotFound-Cidygwnn.js +1 -0
- package/web/dist/assets/{Plugins-DHgIfely.js → Plugins-DUwZVjPc.js} +1 -1
- package/web/dist/assets/RoleDetail-B-GKMfMG.js +33 -0
- package/web/dist/assets/{Roles-DGpN5Vm6.js → Roles-JeVjD0Ew.js} +1 -1
- package/web/dist/assets/Settings-CvEyZp5t.js +1 -0
- package/web/dist/assets/{Strategies-DBp2jYdi.js → Strategies-KAmpqrcQ.js} +1 -1
- package/web/dist/assets/{Switch-yk5-dsti.js → Switch-Jpdn6Yux.js} +1 -1
- package/web/dist/assets/{Table-DWR4p9xA.js → Table-tkJ-cuiE.js} +1 -1
- package/web/dist/assets/TaskDetail-C4NpqwNT.js +2 -0
- package/web/dist/assets/Work-DhaxNYnd.js +1 -0
- package/web/dist/assets/dist-HyCSN_hp.js +1 -0
- package/web/dist/assets/index-CfKqiQIe.js +52 -0
- package/web/dist/assets/index-LDFr0VVR.css +2 -0
- package/web/dist/assets/rolldown-runtime-Dw2cE7zH.js +1 -0
- package/web/dist/assets/vendor-icons-ZPvC5PUS.js +1 -0
- package/web/dist/assets/vendor-react--nRVf2Ep.js +12 -0
- package/web/dist/assets/{vendor-state-CRsbPXtF.js → vendor-state-CH64feAE.js} +1 -1
- package/web/dist/index.html +7 -7
- package/dist/App-23CRAK2P.js +0 -9
- package/dist/adam-tools-MKUMZWCR.js +0 -1
- package/dist/approval-handler-SBFVVFGH.js +0 -4
- package/dist/channels-CNLMTKHM.js +0 -1
- package/dist/channels-VNG7U6UQ.js +0 -1
- package/dist/chunk-37OAKNKA.js +0 -15
- package/dist/chunk-3OYRYMJW.js +0 -11
- package/dist/chunk-5BAD3NCT.js +0 -1
- package/dist/chunk-B3CVXD44.js +0 -104
- package/dist/chunk-CV3ROBUM.js +0 -1
- package/dist/chunk-FUBKGVWI.js +0 -8
- package/dist/chunk-J5YZQQTS.js +0 -3
- package/dist/chunk-Q3N5LVPZ.js +0 -5
- package/dist/chunk-QOPUUA7O.js +0 -1
- package/dist/chunk-TGQYM4TH.js +0 -6
- package/dist/chunk-TYR3QUCL.js +0 -23
- package/dist/config-42ZJPZDM.js +0 -1
- package/dist/delivery-log-7DQ36UGP.js +0 -1
- package/dist/engine-7VBPXTGK.js +0 -1
- package/dist/memories-BUNOVQVG.js +0 -1
- package/dist/role-presets-2X3VW75D.js +0 -1
- package/dist/runtime-772O2XKZ.js +0 -1
- package/dist/server-bus-N5LCY73J.js +0 -1
- package/dist/session-manager-KO4CR3W6.js +0 -1
- package/web/dist/assets/Dashboard-Bh32YC_E.js +0 -1
- package/web/dist/assets/Goals-BmfVadFN.js +0 -1
- package/web/dist/assets/Memories-CgSb60RC.js +0 -1
- package/web/dist/assets/RoleDetail-CNJkMSuz.js +0 -1
- package/web/dist/assets/Settings-PjFyeX8n.js +0 -1
- package/web/dist/assets/TaskDetail-DMg-JAbC.js +0 -2
- package/web/dist/assets/Work-BYgMw2qj.js +0 -1
- package/web/dist/assets/dist-jv3vbjrx.js +0 -1
- package/web/dist/assets/index-CWY8H-cU.js +0 -52
- package/web/dist/assets/index-OXMtvYRJ.css +0 -2
- package/web/dist/assets/rolldown-runtime-DF2fYuay.js +0 -1
- package/web/dist/assets/vendor-icons-DqHipOFA.js +0 -1
- package/web/dist/assets/vendor-react-C2hDj0vl.js +0 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{Z as t}from"./vendor-icons-ZPvC5PUS.js";var n=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},r=(e=>e?n(e):n),i=e(t(),1),a=e=>e;function o(e,t=a){let n=i.useSyncExternalStore(e.subscribe,i.useCallback(()=>t(e.getState()),[e,t]),i.useCallback(()=>t(e.getInitialState()),[e,t]));return i.useDebugValue(n),n}var s=e=>{let t=r(e),n=e=>o(t,e);return Object.assign(n,t),n},c=(e=>e?s(e):s);export{c as t};
|
package/web/dist/index.html
CHANGED
|
@@ -5,13 +5,13 @@
|
|
|
5
5
|
<link rel="icon" type="image/svg+xml" href="/ui/favicon.svg" />
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>Adam</title>
|
|
8
|
-
<script type="module" crossorigin src="/ui/assets/index-
|
|
9
|
-
<link rel="modulepreload" crossorigin href="/ui/assets/rolldown-runtime-
|
|
10
|
-
<link rel="modulepreload" crossorigin href="/ui/assets/vendor-icons-
|
|
11
|
-
<link rel="modulepreload" crossorigin href="/ui/assets/vendor-react
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/ui/assets/dist-
|
|
13
|
-
<link rel="modulepreload" crossorigin href="/ui/assets/vendor-state-
|
|
14
|
-
<link rel="stylesheet" crossorigin href="/ui/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/ui/assets/index-CfKqiQIe.js"></script>
|
|
9
|
+
<link rel="modulepreload" crossorigin href="/ui/assets/rolldown-runtime-Dw2cE7zH.js">
|
|
10
|
+
<link rel="modulepreload" crossorigin href="/ui/assets/vendor-icons-ZPvC5PUS.js">
|
|
11
|
+
<link rel="modulepreload" crossorigin href="/ui/assets/vendor-react--nRVf2Ep.js">
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/ui/assets/dist-HyCSN_hp.js">
|
|
13
|
+
<link rel="modulepreload" crossorigin href="/ui/assets/vendor-state-CH64feAE.js">
|
|
14
|
+
<link rel="stylesheet" crossorigin href="/ui/assets/index-LDFr0VVR.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body class="bg-slate-950 text-slate-100">
|
|
17
17
|
<div id="root"></div>
|
package/dist/App-23CRAK2P.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{b as T,d as co,e as uo}from"./chunk-3HM54J2N.js";import{a as At,e as ao,f as lo}from"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{Box as It,Text as xt,useInput as qn}from"ink";import{useState as On,useEffect as io,useRef as tr}from"react";import{createContext as ir,useContext as ar,useReducer as lr}from"react";import{jsx as dr}from"react/jsx-runtime";var cr={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",configVersion:0,session:null};function ur(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};default:return e}}var mo=ir(null);function go({children:e}){let[t,o]=lr(ur,cr);return dr(mo.Provider,{value:{state:t,dispatch:o},children:e})}function Ke(){let e=ar(mo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as mr,useRef as gr}from"react";var fr=15e3;function fo(){let{dispatch:e}=Ke(),t=gr(null);mr(()=>{let o=!0,c=null,g=()=>{t.current&&(clearTimeout(t.current),t.current=null)},f=()=>{g(),t.current=setTimeout(()=>{o&&e({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},fr)};return(()=>{try{c=new co("/events"),c.on("task_status_change",()=>{}),c.on("approval_request",i=>{if(!o)return;let n=i;e({type:"SET_PENDING_APPROVAL",approval:{taskId:n.taskId,approvalId:n.approvalId,toolName:n.toolName,toolInput:n.toolInput,matchedPattern:n.matchedPattern}})}),c.on("plan_approval_request",i=>{if(!o)return;let n=i;e({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:n.taskId,planId:n.planId,roleId:n.roleId,plan:n.plan}})}),c.on("plan_approval_decision",()=>{o&&e({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),c.on("config_changed",()=>{o&&e({type:"CONFIG_CHANGED"})}),c.on("stats_update",i=>{if(!o)return;let n=i;e({type:"UPDATE_STATS",activeTasks:n.activeTasks,queuedTasks:n.queuedTasks,costToday:n.totalCostToday})}),c.connect().then(()=>{o&&(g(),e({type:"SET_CONNECTED",connected:!0}),e({type:"SET_SERVER_UNREACHABLE",unreachable:!1}))}).catch(()=>{o&&(e({type:"SET_CONNECTED",connected:!1}),f())})}catch{o&&(e({type:"SET_CONNECTED",connected:!1}),f())}})(),()=>{o=!1,g(),c?.close()}},[e])}import{useEffect as pr,useRef as xr,useState as po,useCallback as Tr}from"react";function xo(e){let[t,o]=po([]),[c,g]=po(!1),f=xr(null),l=Tr(()=>{o([]),g(!1)},[]);return pr(()=>{if(!e)return;let i=!0;o([]),g(!0);try{let n=new uo(e);return f.current=n,n.on("reasoning",r=>{if(!i)return;let u=r.content??"";o(y=>{let d=y[y.length-1];if(d?.type==="reasoning"){let x=[...y];return x[x.length-1]={...d,content:d.content+u},x}return[...y,{type:"reasoning",content:u,timestamp:Date.now()}]})}),n.on("tool_call",r=>{if(!i)return;let m=r;o(u=>[...u,{type:"tool_call",content:m.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:m.toolName}}])}),n.on("tool_result",r=>{if(!i)return;let m=r;o(u=>[...u,{type:"tool_result",content:m.content??"",timestamp:Date.now()}])}),n.on("error",r=>{if(!i)return;let m=r;o(u=>[...u,{type:"error",content:m.error??"unknown error",timestamp:Date.now()}])}),n.on("complete",r=>{if(!i)return;let m=r;o(u=>[...u,{type:"complete",content:m.result??"",timestamp:Date.now(),metadata:{cost:m.costUsd,turns:m.numTurns,duration:m.totalDurationMs}}]),g(!1)}),n.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),g(!1))}),()=>{i=!1,n.close()}}catch{g(!1)}},[e]),{events:t,isStreaming:c,clearEvents:l}}import{useState as Gt,useEffect as hr,useCallback as ht}from"react";function Ht(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function To(){let[e,t]=Gt(null),[o,c]=Gt(!0),[g,f]=Gt(null),l=ht(async()=>{try{let y=(await T("/chat/sessions?status=active")).sessions.find(d=>d.source.type==="tui");return y?Ht(y):null}catch{return null}},[]),i=ht(async()=>{try{let u=await T("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),y=Ht(u.session);return t(y),y}catch{return f("Failed to create session"),null}},[]),n=ht(async u=>{try{let y=await T("/chat/messages",{method:"POST",body:{content:u,source:{type:"tui"}}});return t(d=>d&&{...d,messageCount:d.messageCount+1,lastActiveAt:Date.now()}),y}catch{return null}},[]),r=ht(async()=>{if(!e)return!1;try{return await T(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),m=ht(async()=>{if(e)try{let u=await T(`/chat/sessions/${e.id}`);t(Ht(u.session))}catch{t(null)}},[e]);return hr(()=>{let u=!1;async function y(){c(!0);let d=await l();u||(d?t(d):await i(),u||c(!1))}return y(),()=>{u=!0}},[]),{session:e,loading:o,error:g,sendMessage:n,createNewSession:i,archiveCurrentSession:r,refreshSession:m,setSession:t}}import{Box as Kt,Text as ve}from"ink";import Ce from"chalk";var jt={connected:Ce.green,disconnected:Ce.red,warning:Ce.yellow,reasoning:Ce.gray,toolCall:Ce.blue,toolResult:Ce.green,error:Ce.red,dim:Ce.dim,bold:Ce.bold,statusUp:Ce.green("\u25CF"),statusDown:Ce.red("\u25CF")};import{Fragment as yr,jsx as tt,jsxs as Qe}from"react/jsx-runtime";function ho(){let{state:e}=Ke(),t=e.connected?`${jt.statusUp} Server: up`:`${jt.statusDown} Disconnected`,o=e.activeTasks>0?`${e.activeTasks} running, ${e.queuedTasks} queued`:"No active tasks",c=e.session,f=(c?Math.floor((Date.now()-c.lastActiveAt)/6e4):1/0)>=25;return Qe(Kt,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[Qe(Kt,{children:[tt(ve,{bold:!0,children:"Adam v0.2.0"}),tt(ve,{children:" \u2502 "}),tt(ve,{children:t}),tt(ve,{children:" \u2502 "}),Qe(ve,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&Qe(yr,{children:[tt(ve,{children:" \u2502 "}),Qe(ve,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),f&&tt(ve,{color:"yellow",children:" timeout soon"})]})]}),Qe(Kt,{children:[Qe(ve,{children:["Tasks: ",o]}),tt(ve,{children:" \u2502 "}),Qe(ve,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Dt,Text as Rt,useInput as Sr}from"ink";import{useState as Xt,useMemo as Cr}from"react";import vr from"ink-text-input";var br=[{name:"work",description:"Tasks, Automations & Goals"},{name:"config",description:"Configuration"},{name:"evolution",description:"Evolution audit"},{name:"webhooks",description:"Webhook triggers"},{name:"memories",description:"Memory browser"},{name:"strategies",description:"Strategy lab"},{name:"plugins",description:"Plugin management"},{name:"roles",description:"Role management"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function Qt(e){let t=e.toLowerCase();return br.filter(o=>o.name.startsWith(t))}function yo(e){let t=Qt(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Mt,jsxs as yt}from"react/jsx-runtime";function bo({onSubmit:e}){let[t,o]=Xt(""),[c,g]=Xt(0),[f,l]=Xt(!1),i=t.startsWith("/")&&t.length>=1,n=t.slice(1),r=Cr(()=>i?Qt(n):[],[i,n]),m=d=>{o(d),d.startsWith("/")?(l(!0),g(0)):l(!1)},u=()=>{let d=t.trim();if(d){if(d.startsWith("/")){let x=d.slice(1),s=yo(x);e(s?`/${s.name}`:d)}else e(d);o(""),l(!1)}},y=d=>{e(`/${d.name}`),o(""),l(!1)};return Sr((d,x)=>{if(!(!f||!i||r.length===0)){if(x.upArrow){g(s=>s<=0?r.length-1:s-1);return}if(x.downArrow){g(s=>s>=r.length-1?0:s+1);return}if(x.tab){let s=r[c];s&&y(s);return}if(x.escape){l(!1),o("");return}}},{isActive:f&&i&&r.length>0}),yt(Dt,{flexDirection:"column",children:[f&&i&&r.length>0&&Mt(Dt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((d,x)=>{let s=x===c;return yt(Dt,{children:[Mt(Rt,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),yt(Rt,{color:s?"cyan":"white",bold:s,children:["/",d.name]}),yt(Rt,{dimColor:!0,children:[" \u2014 ",d.description]})]},d.name)})}),yt(Dt,{borderStyle:"round",borderDimColor:!0,children:[Mt(Rt,{bold:!0,children:"\u25B8 "}),Mt(vr,{value:t,onChange:m,onSubmit:u,placeholder:"Type a message or / for commands..."})]})]})}import{Box as st,Text as ge}from"ink";import{useState as Er}from"react";import{jsx as ye,jsxs as Ae}from"react/jsx-runtime";function wr({content:e}){let[t,o]=Er(!1),c=e.split(`
|
|
2
|
-
`);return c.length<=5?ye(ge,{color:"green",children:e}):t?ye(ge,{color:"green",children:e}):Ae(ge,{color:"green",children:[c.slice(0,3).join(`
|
|
3
|
-
`),`
|
|
4
|
-
`,Ae(ge,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function Br({event:e}){switch(e.type){case"reasoning":return ye(st,{children:ye(ge,{color:"gray",children:e.content})});case"tool_call":return ye(st,{children:Ae(ge,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Ae(st,{flexDirection:"column",children:[ye(ge,{color:"blue",dimColor:!0,children:"[result]"}),ye(wr,{content:e.content})]});case"error":return ye(st,{children:Ae(ge,{color:"red",children:["[error] ",e.content]})});case"complete":return Ae(st,{flexDirection:"column",marginTop:1,children:[e.content&&ye(ge,{children:e.content}),ye(ge,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Ae(ge,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Ae(ge,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Ae(ge,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function So({events:e,isStreaming:t}){return e.length===0&&!t?null:Ae(st,{flexDirection:"column",children:[t&&e.length===0&&ye(ge,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>ye(Br,{event:o},c))]})}import{Box as Co,Text as vo}from"ink";import{jsx as Yt,jsxs as kr}from"react/jsx-runtime";function Eo({messages:e}){return e.length===0?null:Yt(Co,{flexDirection:"column",children:e.map((t,o)=>kr(Co,{flexDirection:"column",marginBottom:1,children:[Yt(vo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),Yt(vo,{children:t.content})]},o))})}import{Box as bt,Text as De,useInput as Ir}from"ink";import{jsx as Re,jsxs as St}from"react/jsx-runtime";function wo({approval:e,onResolved:t}){return Ir(o=>{o==="a"?T(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&T(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),St(bt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Re(De,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),St(bt,{marginTop:1,children:[Re(De,{children:"Tool: "}),Re(De,{bold:!0,children:e.toolName})]}),St(bt,{children:[Re(De,{children:"Input: "}),Re(De,{children:JSON.stringify(e.toolInput)})]}),St(bt,{children:[Re(De,{children:"Pattern: "}),Re(De,{dimColor:!0,children:e.matchedPattern})]}),St(bt,{marginTop:1,children:[Re(De,{color:"green",children:"[a] Approve"}),Re(De,{children:" "}),Re(De,{color:"red",children:"[r] Reject"})]})]})}import{Box as Ct,Text as ae,useInput as Pr}from"ink";import{useState as Ar,useEffect as Dr}from"react";import{jsx as $e,jsxs as Ee}from"react/jsx-runtime";var Rr=300;function Bo({approval:e,onResolved:t,onTimeout:o}){let[c,g]=Ar(Rr);Dr(()=>{let l=setInterval(()=>{g(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),Pr(l=>{l==="a"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let f=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Ee(Ct,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[$e(ae,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Ee(ae,{dimColor:!0,children:["Plan ID: ",e.planId]}),Ee(ae,{dimColor:!0,children:["Time remaining: ",c,"s"]}),Ee(Ct,{marginTop:1,children:[$e(ae,{children:"Overall Risk: "}),$e(ae,{bold:!0,color:f,children:e.plan.overallRisk.toUpperCase()})]}),Ee(ae,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(l=>{let i=l.riskLevel==="high"?"red":l.riskLevel==="medium"?"yellow":"green";return Ee(Ct,{paddingLeft:2,children:[Ee(ae,{children:["[",l.index,"] "]}),$e(ae,{children:l.description}),Ee(ae,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),Ee(ae,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),Ee(Ct,{marginTop:1,children:[$e(ae,{dimColor:!0,children:"Permissions: "}),$e(ae,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Ee(Ct,{marginTop:1,children:[$e(ae,{color:"green",children:"[a] Allow once "}),$e(ae,{color:"green",children:"[p] Allow permanent "}),$e(ae,{color:"red",children:"[r] Deny"})]})]})}import{Box as ot,Text as Z,useInput as Lr}from"ink";import{useEffect as _r,useState as qe,useCallback as Io}from"react";import{Box as J,Text as D,useInput as Mr}from"ink";import{useState as zt,useEffect as Nr}from"react";import{jsx as V,jsxs as F}from"react/jsx-runtime";function ko({taskId:e,onBack:t}){let[o,c]=zt(null),[g,f]=zt([]),[l,i]=zt(null);if(Nr(()=>{T(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),T(`/tasks/${e}/plan`).then(r=>f(r.plans)).catch(()=>f([]))},[e]),Mr((r,m)=>{(r==="b"||m.escape)&&t()}),l)return F(J,{flexDirection:"column",children:[F(D,{color:"red",children:["Error: ",l]}),V(D,{dimColor:!0,children:"[b] Back"})]});if(!o)return F(D,{dimColor:!0,children:["Loading task ",e,"..."]});let n=g[0];return F(J,{flexDirection:"column",children:[V(D,{bold:!0,color:"cyan",children:"Task Detail"}),F(J,{marginTop:1,flexDirection:"column",children:[F(J,{children:[V(D,{children:"ID: "}),V(D,{dimColor:!0,children:String(o.id)})]}),F(J,{children:[V(D,{children:"Status: "}),V(D,{bold:!0,children:String(o.status)})]}),F(J,{children:[V(D,{children:"Prompt: "}),V(D,{children:String(o.prompt)})]}),o.result?F(J,{children:[V(D,{children:"Result: "}),V(D,{children:String(o.result).slice(0,200)})]}):null,o.error?F(J,{children:[V(D,{color:"red",children:"Error: "}),V(D,{children:String(o.error)})]}):null]}),n&&F(J,{marginTop:1,flexDirection:"column",children:[V(D,{bold:!0,color:"cyan",children:"Execution Plan"}),F(J,{children:[V(D,{children:"Plan ID: "}),V(D,{dimColor:!0,children:n.id})]}),F(J,{children:[V(D,{children:"Status: "}),V(D,{children:n.status})]}),n.plan.overallRisk&&F(J,{children:[V(D,{children:"Overall Risk: "}),V(D,{bold:!0,color:n.plan.overallRisk==="high"?"red":n.plan.overallRisk==="medium"?"yellow":"green",children:n.plan.overallRisk.toUpperCase()})]}),F(D,{bold:!0,children:["Steps (",n.plan.steps.length,"):"]}),n.plan.steps.map(r=>{let m=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return F(J,{paddingLeft:2,children:[F(D,{children:["[",r.index,"] ",r.description]}),F(D,{color:m,children:[" [",r.riskLevel,"]"]})]},r.index)}),n.deviationReport&&F(J,{marginTop:1,flexDirection:"column",children:[V(D,{bold:!0,color:"yellow",children:"Deviation Report"}),F(D,{children:["Planned: ",n.deviationReport.stepsPlanned," | Executed: ",n.deviationReport.stepsExecuted," | Accuracy: ",(n.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),n.deviationReport.deviations.map((r,m)=>F(J,{paddingLeft:2,children:[F(D,{color:"yellow",children:["[",r.deviationType,"] "]}),F(D,{children:["Step ",r.stepIndex,": ",r.actual]})]},m))]}),n.learnedRules&&n.learnedRules.length>0&&F(J,{marginTop:1,flexDirection:"column",children:[V(D,{bold:!0,color:"blue",children:"Learned Rules"}),n.learnedRules.map((r,m)=>V(J,{paddingLeft:2,children:F(D,{children:["* ",r]})},m))]})]}),!n&&g.length===0&&V(J,{marginTop:1,children:V(D,{dimColor:!0,children:"No execution plan for this task."})}),V(J,{marginTop:1,children:V(D,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as Or,jsx as le,jsxs as pe}from"react/jsx-runtime";var $r={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Nt=["all","pending","queued","running","completed","failed","cancelled"],Jt=15;function Lt({onBack:e}){let[t,o]=qe([]),[c,g]=qe(!0),[f,l]=qe("list"),[i,n]=qe(0),[r,m]=qe("all"),[u,y]=qe(0),[d,x]=qe(0),[s,a]=qe(null),[P,M]=qe([]),U=Io(async()=>{g(!0);try{let C=new URLSearchParams({limit:"100"});r!=="all"&&C.set("status",r);let w=await T(`/tasks?${C}`);o(w.tasks)}catch{o([])}finally{g(!1)}},[r]);_r(()=>{U()},[U]);let W=Math.max(1,Math.ceil(t.length/Jt)),q=t.slice(d*Jt,(d+1)*Jt),k=Io(async()=>{let C=q[i];if(C)try{await T(`/tasks/${C.id}/cancel`,{method:"POST"}),a(`Cancelled: ${C.id.slice(0,8)}`),l("list"),U()}catch(w){a(`Failed: ${w instanceof Error?w.message:String(w)}`),l("list")}},[q,i,U]);return Lr((C,w)=>{if(f==="detail"){(w.escape||w.return||C==="q")&&l("list");return}if(f==="cancelling"){C==="y"?k():l("list");return}if(f==="filter"){if(w.escape){l("list");return}w.upArrow&&u>0&&y(p=>p-1),w.downArrow&&u<Nt.length-1&&y(p=>p+1),w.return&&(m(Nt[u]),x(0),n(0),l("list"));return}if(w.escape||C==="q"){e();return}if(w.upArrow&&i>0&&n(p=>p-1),w.downArrow&&i<q.length-1&&n(p=>p+1),w.return){let p=q[i];p&&(M([]),l("detail"),T(`/tasks/${p.id}/logs?limit=20`).then(({logs:H})=>M(H)).catch(()=>M([])))}if(C==="x"&&q[i]){let p=q[i];["running","pending","queued","paused"].includes(p.status)?(l("cancelling"),a(null)):a(`Cannot cancel task in status: ${p.status}`)}C==="f"&&(y(Nt.indexOf(r)),l("filter")),C==="r"&&U(),(w.pageDown||C==="n")&&d<W-1&&(x(p=>p+1),n(0)),(w.pageUp||C==="p")&&d>0&&(x(p=>p-1),n(0))}),c?le(Z,{dimColor:!0,children:"Loading tasks..."}):f==="filter"?pe(ot,{flexDirection:"column",children:[le(Z,{bold:!0,children:"Filter by status:"}),Nt.map((C,w)=>le(ot,{children:pe(Z,{color:w===u?"cyan":"white",children:[w===u?"> ":" ",C,C===r?" (current)":""]})},C)),le(Z,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):f==="detail"&&q[i]?le(ko,{taskId:q[i].id,onBack:()=>l("list")}):f==="cancelling"&&q[i]?pe(ot,{flexDirection:"column",children:[pe(Z,{color:"red",children:['Cancel task "',q[i].id.slice(0,8),'"? (y/n)']}),s&&le(Z,{color:"red",children:s})]}):pe(ot,{flexDirection:"column",children:[pe(ot,{children:[pe(Z,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&pe(Z,{dimColor:!0,children:[" [filter: ",r,"]"]}),pe(Z,{dimColor:!0,children:[" \u2014 Page ",d+1,"/",W]})]}),s&&le(Z,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?pe(Z,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):pe(Or,{children:[le(ot,{marginTop:1,children:pe(Z,{bold:!0,children:[" ",Xe("ID",10),Xe("STATUS",12),Xe("PROMPT",40),Xe("DURATION",10),"COST"]})}),q.map((C,w)=>{let p=w===i,H=C.totalDurationMs?`${(C.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",j=C.costUsd!==void 0?`$${C.costUsd.toFixed(4)}`:"\u2014",he=$r[C.status]??"white";return pe(ot,{children:[le(Z,{color:p?"cyan":"white",children:p?"> ":" "}),le(Z,{dimColor:!0,children:Xe(C.id.slice(0,8),10)}),le(Z,{color:he,children:Xe(C.status,12)}),le(Z,{children:Xe(qr(C.prompt,38),40)}),le(Z,{dimColor:!0,children:Xe(H,10)}),le(Z,{dimColor:!0,children:j})]},C.id)})]}),le(Z,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function Xe(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function qr(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}lo();import{Box as vt,Text as we,useInput as Vr}from"ink";import{useEffect as Ur,useState as Po}from"react";import{readFileSync as Fr,existsSync as Wr}from"fs";import{parse as Gr}from"yaml";import{Fragment as Hr,jsx as Be,jsxs as Ye}from"react/jsx-runtime";function Do({onBack:e}){let[t,o]=Po(null),[c,g]=Po(null);return Vr((f,l)=>{(l.escape||f==="q")&&e()}),Ur(()=>{try{let f=ao;if(!Wr(f)){g(`Config file not found: ${f}`);return}let l=Fr(f,"utf-8");o(Gr(l))}catch(f){g(f.message)}},[]),c?Ye(vt,{flexDirection:"column",children:[Be(we,{color:"red",children:c}),Be(we,{dimColor:!0,children:"Press Esc to go back"})]}):t?Ye(vt,{flexDirection:"column",children:[Be(we,{bold:!0,children:"Configuration (Esc to go back)"}),Be(vt,{marginTop:1,flexDirection:"column",children:Be(Ro,{obj:t,indent:0})})]}):Be(we,{dimColor:!0,children:"Loading config..."})}function Ro({obj:e,indent:t}){let o=" ".repeat(t);return Be(Hr,{children:Object.entries(e).map(([c,g])=>g&&typeof g=="object"&&!Array.isArray(g)?Ye(vt,{flexDirection:"column",children:[Ye(we,{children:[o,Be(we,{color:"cyan",children:c}),":"]}),Be(Ro,{obj:g,indent:t+1})]},c):Array.isArray(g)?Ye(vt,{flexDirection:"column",children:[Ye(we,{children:[o,Be(we,{color:"cyan",children:c}),":"]}),g.map((f,l)=>Ye(we,{children:[o," - ",Ao(c,String(f))]},l))]},c):Ye(we,{children:[o,Be(we,{color:"cyan",children:c}),": ",Ao(c,String(g))]},c))})}function Ao(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as _t,Text as ke,useInput as jr}from"ink";import{useEffect as Kr,useState as Zt}from"react";import{jsx as Et,jsxs as Me}from"react/jsx-runtime";function Mo({onBack:e}){let[t,o]=Zt([]),[c,g]=Zt(!0),[f,l]=Zt(null);return jr((i,n)=>{(n.escape||i==="q")&&e()}),Kr(()=>{T("/evolution-audit?limit=20").then(i=>{o(i),g(!1)}).catch(i=>{l(i.message),g(!1)})},[]),c?Et(ke,{dimColor:!0,children:"Loading evolution log..."}):f?Me(_t,{flexDirection:"column",children:[Et(ke,{color:"red",children:f}),Et(ke,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?Me(_t,{flexDirection:"column",children:[Et(ke,{dimColor:!0,children:"No evolution records yet"}),Et(ke,{dimColor:!0,children:"Press Esc to go back"})]}):Me(_t,{flexDirection:"column",children:[Me(ke,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>Me(_t,{flexDirection:"column",marginTop:1,children:[Me(ke,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&Me(ke,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
5
|
-
`).map((n,r)=>n.startsWith("+")?Me(ke,{color:"green",children:[" ",n]},r):n.startsWith("-")?Me(ke,{color:"red",children:[" ",n]},r):Me(ke,{dimColor:!0,children:[" ",n]},r))]},i.id))]})}import{Box as Oe,Text as X,useInput as Qr}from"ink";import Xr from"ink-text-input";import{useEffect as Yr,useState as it}from"react";import{jsx as fe,jsxs as oe}from"react/jsx-runtime";var zr={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function Jr(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function Zr(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function $t({onBack:e}){let[t,o]=it([]),[c,g]=it(null),[f,l]=it("list"),[i,n]=it(""),[r,m]=it(!1),[u,y]=it(null);Qr((s,a)=>{if(f==="create"){a.escape&&(l("list"),n(""),y(null));return}(a.escape||s==="q")&&e(),s==="c"&&(l("create"),y(null)),s==="r"&&d()});let d=()=>{T("/goals?limit=20").then(({goals:s})=>o(s)).catch(s=>g(s.message))};Yr(()=>{d()},[]);let x=async s=>{if(s.trim()){m(!0),y(null);try{let a=await T("/goals",{method:"POST",body:{input:s.trim()}});y(`Goal created: ${a.goal.name}`),n(""),l("list"),d()}catch(a){y(`Failed: ${a instanceof Error?a.message:String(a)}`)}finally{m(!1)}}};return c?oe(Oe,{flexDirection:"column",children:[oe(X,{color:"red",children:["Failed to load goals: ",c]}),fe(X,{dimColor:!0,children:"Press Esc or q to return"})]}):f==="create"?oe(Oe,{flexDirection:"column",children:[fe(X,{bold:!0,children:"Create Goal"}),fe(X,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),oe(Oe,{marginTop:1,children:[fe(X,{color:"cyan",children:"> "}),fe(Xr,{value:i,onChange:n,onSubmit:x})]}),r&&fe(X,{color:"yellow",children:"Creating goal..."}),u&&fe(X,{color:u.startsWith("Failed")?"red":"green",children:u}),fe(X,{dimColor:!0,children:"Press Esc to cancel"})]}):oe(Oe,{flexDirection:"column",children:[oe(X,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?fe(X,{dimColor:!0,children:"No goals found. Press c to create one."}):fe(Oe,{marginTop:1,flexDirection:"column",children:t.map(s=>{let a=s.targetValue>0?s.currentValue/s.targetValue:0,P=zr[s.status]??"white";return oe(Oe,{marginBottom:1,flexDirection:"column",children:[oe(Oe,{children:[fe(X,{bold:!0,color:P,children:s.name}),oe(X,{dimColor:!0,children:[" (",s.role,")"]}),fe(X,{dimColor:!0,children:" \u2014 "}),fe(X,{color:P,children:s.status})]}),oe(Oe,{children:[oe(X,{dimColor:!0,children:[" ",Jr(a)," "]}),oe(X,{color:a>=1?"green":"white",children:[Math.round(a*100),"%"]}),oe(X,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),oe(Oe,{children:[oe(X,{dimColor:!0,children:[" \u23F0 ",Zr(s.deadline)," left"]}),oe(X,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),oe(X,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),fe(X,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as at,Text as be,useInput as en}from"ink";import{useEffect as tn,useState as No}from"react";import{jsx as Ue,jsxs as Ve}from"react/jsx-runtime";function on(e,t,o=15){let c=e/(e+t),g=Math.round(c*o);return"\u2593".repeat(g)+"\u2591".repeat(o-g)}function Lo({onBack:e}){let[t,o]=No([]),[c,g]=No(null);if(en((l,i)=>{(i.escape||l==="q")&&e()}),tn(()=>{T("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>g(l.message))},[]),c)return Ve(at,{flexDirection:"column",children:[Ve(be,{color:"red",children:["Failed to load strategies: ",c]}),Ue(be,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return Ve(at,{flexDirection:"column",children:[Ue(be,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Ue(be,{dimColor:!0,children:"Press Esc or q to return"})]});let f=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,n=f.get(i)??[];n.push(l),f.set(i,n)}return Ve(at,{flexDirection:"column",children:[Ue(be,{bold:!0,children:"Strategy Lab"}),Ue(be,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Ue(at,{marginTop:1,flexDirection:"column",children:Array.from(f.entries()).map(([l,i])=>Ve(at,{marginBottom:1,flexDirection:"column",children:[Ue(be,{bold:!0,color:"cyan",children:l}),i.sort((n,r)=>{let m=n.alpha/(n.alpha+n.beta);return r.alpha/(r.alpha+r.beta)-m}).map(n=>{let r=n.alpha/(n.alpha+n.beta);return Ve(at,{children:[Ue(be,{dimColor:!0,children:" "}),Ve(be,{children:[on(n.alpha,n.beta)," "]}),Ve(be,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),Ve(be,{dimColor:!0,children:[" ",n.name," (\u03B1=",n.alpha.toFixed(1)," \u03B2=",n.beta.toFixed(1)," trials=",n.totalTrials,")"]})]},n.id)})]},l))}),Ue(be,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as xe,Text as K,useInput as ln}from"ink";import eo from"ink-text-input";import{useEffect as cn,useState as Fe,useCallback as lt}from"react";import{CronExpressionParser as un}from"cron-parser";import{useState as rn,useEffect as nn,useCallback as _o,useRef as sn}from"react";var an=3e3;function ze(){let[e,t]=rn(null),o=sn(null),c=_o(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),g=_o((f,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:f,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},an))},[]);return nn(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:g,clearMessage:c}}import{jsx as Q,jsxs as ne}from"react/jsx-runtime";var to=["manual","cron","event"],qt={name:"",triggerType:"manual",cron:"",stepPrompt:""};function dn(e){try{return un.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function Vt({onBack:e}){let[t,o]=Fe([]),[c,g]=Fe(!0),[f,l]=Fe(0),[i,n]=Fe("list"),[r,m]=Fe({...qt}),[u,y]=Fe("name"),[d,x]=Fe(null),{message:s,setMessage:a,clearMessage:P}=ze(),[M,U]=Fe(!1),[W,q]=Fe(!1),k=lt(()=>{g(!0),T("/task-templates").then(({templates:b})=>{o(b),g(!1)}).catch(()=>g(!1))},[]);cn(()=>{k()},[k]);let C=i==="create"||i==="edit",w=lt(async()=>{let b=t[f];if(!(!b||M)){U(!0),a(`Triggering ${b.name}...`,"loading");try{let B=await T(`/task-templates/${b.id}/run`,{method:"POST"});a(`Triggered: ${b.name} (${B.executionId})`,"success")}catch(B){a(`Trigger failed: ${B instanceof Error?B.message:String(B)}`,"error")}finally{U(!1)}}},[t,f,M,a]),p=lt(async()=>{let b=t[f];if(!b||W)return;if(b.trigger?.type!=="cron"&&b.trigger?.type!=="event"){a("Toggle not applicable for manual triggers","error");return}let B=!b.enabled;q(!0),a(`${b.name} \u2192 ${B?"enabling":"disabling"}...`,"loading");try{await T(`/task-templates/${b.id}`,{method:"PATCH",body:{enabled:B}}),o($=>$.map(de=>de.id===b.id?{...de,enabled:B}:de)),a(`${b.name} ${B?"enabled":"disabled"}`,"success")}catch($){a(`Toggle failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{q(!1)}},[t,f,W,a]),H=lt(async()=>{let b=t[f];if(b)try{await T(`/task-templates/${b.id}`,{method:"DELETE"}),a(`Deleted: ${b.name}`,"success"),k(),l(B=>Math.max(0,Math.min(B,t.length-2)))}catch(B){a(`Delete failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[t,f,k]),j=lt(()=>{let b=t[f];b&&(x(b.id),m({name:b.name,triggerType:b.trigger?.type??"manual",cron:b.trigger?.cron??"",stepPrompt:b.steps?.[0]?.prompt??""}),y("name"),n("edit"))},[t,f]),he=lt(async()=>{let b={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await T("/task-templates",{method:"POST",body:b}),a(`Created: ${r.name}`,"success")):i==="edit"&&d&&(await T(`/task-templates/${d}`,{method:"PATCH",body:b}),a(`Updated: ${r.name}`,"success"))}catch(B){a(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}n("list"),m({...qt}),x(null),k()},[r,i,d,k]);return ln((b,B)=>{if(C){if(B.escape){n("list"),m({...qt}),x(null);return}if(B.return){let $=["name","triggerType","cron","stepPrompt"],de=$.indexOf(u);if(de<$.length-1){let He=de+1;if($[He]==="cron"&&r.triggerType!=="cron"&&He++,He<$.length){y($[He]);return}}he();return}if(B.tab&&u==="triggerType"){m($=>{let de=to.indexOf($.triggerType);return{...$,triggerType:to[(de+1)%to.length]}});return}return}if(B.escape||b==="q"){e();return}if(B.upArrow){l($=>Math.max(0,$-1));return}if(B.downArrow){l($=>Math.min(t.length-1,$+1));return}if(b==="t"){w();return}if(b==="d"){H();return}if(b==="e"){j();return}if(b==="c"){m({...qt}),y("name"),n("create");return}if(b==="s"||b===" "){p();return}b==="r"&&(k(),P())}),c?Q(K,{dimColor:!0,children:"Loading templates..."}):C?ne(xe,{flexDirection:"column",children:[ne(K,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),ne(xe,{marginTop:1,flexDirection:"column",children:[ne(xe,{children:[ne(K,{bold:u==="name",color:u==="name"?"cyan":void 0,children:["Name:"," "]}),u==="name"?Q(eo,{value:r.name,onChange:b=>m(B=>({...B,name:b})),placeholder:"template name"}):Q(K,{children:r.name||"(empty)"})]}),ne(xe,{children:[ne(K,{bold:u==="triggerType",color:u==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),Q(K,{children:r.triggerType}),u==="triggerType"&&Q(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&ne(xe,{children:[ne(K,{bold:u==="cron",color:u==="cron"?"cyan":void 0,children:["Cron:"," "]}),u==="cron"?Q(eo,{value:r.cron,onChange:b=>m(B=>({...B,cron:b})),placeholder:"*/5 * * * *"}):Q(K,{children:r.cron||"(empty)"})]}),ne(xe,{children:[ne(K,{bold:u==="stepPrompt",color:u==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),u==="stepPrompt"?Q(eo,{value:r.stepPrompt,onChange:b=>m(B=>({...B,stepPrompt:b})),placeholder:"What should this template do?"}):Q(K,{children:r.stepPrompt||"(empty)"})]})]}),Q(xe,{marginTop:1,children:Q(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):ne(xe,{flexDirection:"column",children:[ne(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&Q(xe,{marginTop:1,children:ne(K,{color:s.type==="success"?"green":s.type==="error"?"red":"gray",children:[s.type==="success"?"\u2713 ":s.type==="error"?"\u2717 ":"\u2192 ",s.text]})}),t.length===0?Q(xe,{marginTop:1,children:Q(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):Q(xe,{marginTop:1,flexDirection:"column",children:t.map((b,B)=>{let $=B===f,de=b.trigger?.type==="cron"&&b.trigger?.cron?dn(b.trigger.cron):"";return ne(xe,{children:[Q(K,{color:$?"cyan":void 0,bold:$,children:$?"> ":" "}),Q(K,{color:$?"cyan":void 0,bold:$,children:Ot(b.name,24)}),Q(K,{dimColor:!0,children:Ot(b.trigger?.type,10)}),b.trigger?.type!=="cron"&&b.trigger?.type!=="event"?Q(K,{dimColor:!0,children:Ot("\u2014",6)}):Q(K,{color:b.enabled?"green":"gray",children:Ot(b.enabled?"on":"off",6)}),de&&ne(K,{dimColor:!0,children:["next: ",de]})]},b.id)})}),Q(xe,{marginTop:1,children:Q(K,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Ot(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Je,Text as Te,useInput as mn}from"ink";import gn from"ink-text-input";import{useEffect as fn,useState as ct,useCallback as $o}from"react";import{jsx as ce,jsxs as rt}from"react/jsx-runtime";function qo({onBack:e}){let[t,o]=ct([]),[c,g]=ct(""),[f,l]=ct(!0),[i,n]=ct(!1),[r,m]=ct(""),[u,y]=ct(null),d=$o(()=>{l(!0),T("/webhooks").then(({webhooks:s,auth:a})=>{o(s),g(a),l(!1)}).catch(()=>l(!1))},[]);fn(()=>{d()},[d]);let x=$o(async s=>{if(s.trim())try{let a=await T(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});y(`Triggered: ${a.executionId}`)}catch(a){y(`Trigger failed: ${a instanceof Error?a.message:String(a)}`)}},[]);return mn((s,a)=>{if(i){if(a.escape){n(!1),m("");return}if(a.return){x(r),n(!1),m("");return}return}if(a.escape||s==="q"){e();return}if(s==="t"){n(!0),m(""),y(null);return}s==="r"&&(d(),y(null))}),f?ce(Te,{dimColor:!0,children:"Loading webhooks..."}):rt(Je,{flexDirection:"column",children:[rt(Te,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),rt(Te,{dimColor:!0,children:["Auth: ",c]}),u&&ce(Je,{marginTop:1,children:ce(Te,{color:"yellow",children:u})}),i&&rt(Je,{marginTop:1,children:[ce(Te,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ce(gn,{value:r,onChange:m,placeholder:"webhook name or ID"}),ce(Te,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ce(Je,{marginTop:1,children:ce(Te,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):rt(Je,{marginTop:1,flexDirection:"column",children:[ce(Je,{children:rt(Te,{bold:!0,children:[ut("NAME",24),ut("DESCRIPTION",36),ut("TRIGGER",28),"TAGS"]})}),t.map(s=>rt(Je,{children:[ce(Te,{children:ut(s.displayName,24)}),ce(Te,{dimColor:!0,children:ut(pn(s.description??"",34),36)}),ce(Te,{dimColor:!0,children:ut(s.trigger,28)}),ce(Te,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),ce(Je,{marginTop:1,children:ce(Te,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function ut(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function pn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ne,Text as ee,useInput as xn}from"ink";import Tn from"ink-text-input";import{useEffect as Oo,useState as We,useCallback as oo}from"react";import{jsx as te,jsxs as Ie}from"react/jsx-runtime";function hn(e){return e>=4?"red":e===3?"yellow":"gray"}function yn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function bn(e){return new Date(e).toLocaleDateString()}function Uo({onBack:e}){let[t,o]=We([]),[c,g]=We(0),[f,l]=We([]),[i,n]=We(!0),[r,m]=We(!1),[u,y]=We(""),[d,x]=We("all"),[s,a]=We(null),[P,M]=We(!1),U=oo(()=>{T("/agents").then(({agents:p})=>{o(p),n(!1)}).catch(()=>n(!1))},[]);Oo(()=>{U()},[U]);let W=t[c],q=oo(()=>{W&&(M(!1),T(`/memories/${W.id}`).then(({memories:p})=>{l(p),a(null)}).catch(p=>a(`Failed: ${p instanceof Error?p.message:String(p)}`)))},[W]);Oo(()=>{W&&q()},[W,q]);let k=oo(async p=>{if(!(!W||!p.trim()))try{let H=await T("/memories/query",{method:"POST",body:{agentId:W.id,prompt:p.trim()}});l(H.memories),M(!0),a(`Search: ${H.count} results`)}catch(H){a(`Search failed: ${H instanceof Error?H.message:String(H)}`)}},[W]),C=r,w=f.filter(p=>d==="all"?!0:d==="high"?p.importance>3:d==="medium"?p.importance===3:p.importance<3);return xn((p,H)=>{if(C){if(H.escape){m(!1),y("");return}if(H.return){k(u),m(!1),y("");return}return}if(H.escape||p==="q"){e();return}if(p==="a"){g(j=>(j+1)%Math.max(1,t.length));return}if(H.leftArrow){g(j=>(j-1+t.length)%Math.max(1,t.length));return}if(H.rightArrow){g(j=>(j+1)%Math.max(1,t.length));return}if(p==="s"){m(!0),y(""),a(null);return}if(p==="h"){x(j=>j==="high"?"all":"high");return}if(p==="m"){x(j=>j==="medium"?"all":"medium");return}if(p==="l"){x(j=>j==="low"?"all":"low");return}p==="r"&&q()}),i?te(ee,{dimColor:!0,children:"Loading agents..."}):t.length===0?Ie(Ne,{flexDirection:"column",children:[te(ee,{dimColor:!0,children:"No agents found"}),te(ee,{dimColor:!0,children:"Press Esc to go back"})]}):Ie(Ne,{flexDirection:"column",children:[te(ee,{bold:!0,children:"Memories (Esc to go back)"}),Ie(Ne,{marginTop:1,children:[te(ee,{children:"Agent: "}),te(ee,{bold:!0,color:"cyan",children:W?.name??"?"}),Ie(ee,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),te(Ne,{children:Ie(ee,{dimColor:!0,children:["Filter: ",d==="all"?"all":d," | ",P?"search results":"all memories"," (",w.length,")"]})}),s&&te(Ne,{children:te(ee,{color:"yellow",children:s})}),r&&Ie(Ne,{marginTop:1,children:[te(ee,{bold:!0,color:"cyan",children:"Search: "}),te(Tn,{value:u,onChange:y,placeholder:"search query..."}),te(ee,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),w.length===0?te(Ne,{marginTop:1,children:Ie(ee,{dimColor:!0,children:["No memories",d!=="all"?` matching filter '${d}'`:""]})}):te(Ne,{marginTop:1,flexDirection:"column",children:w.map(p=>Ie(Ne,{marginBottom:0,children:[Ie(ee,{color:hn(p.importance),bold:!0,children:[yn(p.importance)," "]}),te(ee,{dimColor:!0,children:Vo(p.type??"?",12)}),te(ee,{dimColor:!0,children:Vo(`\xD7${p.retrievedCount??0}`,5)}),Ie(ee,{children:[Sn(p.content,55)," "]}),te(ee,{dimColor:!0,children:bn(p.createdAt)}),p.score!==void 0&&Ie(ee,{dimColor:!0,children:[" (",p.score.toFixed(2),")"]})]},p.id))}),te(Ne,{marginTop:1,children:te(ee,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Vo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Sn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as dt,Text as Pe,useInput as Cn}from"ink";import vn from"ink-text-input";import{useState as Ze,useEffect as Fo,useCallback as Wo}from"react";import{jsx as Le,jsxs as et}from"react/jsx-runtime";var Go={Defaults:["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout"],"Server (restart required)":["server.port","server.host"],Logging:["logging.level"],Evolution:["roles.evolution.triggerEvery","roles.evolution.reflectionThreshold"],Chat:["chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory"]},En={"defaults.model":"Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","server.port":"Port","server.host":"Host","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold"};function Ho({onBack:e}){let{state:t}=Ke(),[o,c]=Ze({}),[g,f]=Ze([]),[l,i]=Ze(null),[n,r]=Ze("view"),[m,u]=Ze(0),[y,d]=Ze(""),[x,s]=Ze(null),[a,P]=Ze(!1),M=Object.values(Go).flat(),U=Wo(()=>{T("/config").then(k=>{c(k.config),f(k.mutable)}).catch(k=>i(k.message))},[]);Fo(()=>{U()},[U]),Fo(()=>{t.configVersion>0&&U()},[t.configVersion,U]);let W=Wo(async()=>{let k=M[m];if(k){P(!0),s(null);try{let C=y,w=o[k];if(w&&typeof w.value=="number"&&(C=Number(y),isNaN(C))){s("Invalid number"),P(!1);return}let p=await T("/config",{method:"PATCH",body:{[k]:C}});p.updated.length>0&&(s(`Updated: ${k}`),U()),p.errors.length>0&&s(p.errors[0]),r("view")}catch(C){s(`Failed: ${C instanceof Error?C.message:String(C)}`)}finally{P(!1)}}},[M,m,y,o,U]);if(Cn((k,C)=>{if(n==="edit"){if(C.escape){r("view");return}return}if(C.escape||k==="q"){e();return}if(C.upArrow&&m>0&&u(w=>w-1),C.downArrow&&m<M.length-1&&u(w=>w+1),C.return||k==="e"){let w=M[m],p=o[w];p&&p.mutable?(d(String(p.value??"")),r("edit"),s(null)):p&&!p.mutable&&s("This setting requires a restart to change")}k==="r"&&(U(),s("Refreshed"))}),l)return et(dt,{flexDirection:"column",children:[et(Pe,{color:"red",children:["Failed to load config: ",l]}),Le(Pe,{dimColor:!0,children:"Press Esc or q to return"})]});let q=0;return et(dt,{flexDirection:"column",children:[Le(Pe,{bold:!0,children:"Settings"}),x&&Le(Pe,{color:x.startsWith("Failed")||x.startsWith("This setting")?"yellow":"green",children:x}),Le(dt,{marginTop:1,flexDirection:"column",children:Object.entries(Go).map(([k,C])=>et(dt,{marginBottom:1,flexDirection:"column",children:[Le(Pe,{bold:!0,color:"cyan",children:k}),C.map(w=>{let p=o[w],j=q++===m,he=g.includes(w),b=En[w]??w,B=p?String(p.value??""):"...";return n==="edit"&&j?et(dt,{children:[et(Pe,{color:"cyan",children:["> ",b,": "]}),Le(vn,{value:y,onChange:d,onSubmit:()=>{W()}}),a&&Le(Pe,{color:"yellow",children:" saving..."})]},w):et(dt,{children:[et(Pe,{color:j?"cyan":"white",children:[j?"> ":" ",he?" ":"\u{1F512} ",b,": "," "]}),Le(Pe,{color:he?"white":"gray",children:B}),!he&&Le(Pe,{dimColor:!0,children:" (restart required)"})]},w)})]},k))}),Le(Pe,{dimColor:!0,children:"Enter/e:edit r:refresh Esc/q:back"})]})}import{Box as nt,Text as ue,useInput as wn}from"ink";import{useEffect as Bn,useState as ro,useCallback as kn}from"react";import{jsx as se,jsxs as gt}from"react/jsx-runtime";function jo({onBack:e}){let[t,o]=ro([]),[c,g]=ro(!0),[f,l]=ro(0),{message:i,setMessage:n,clearMessage:r}=ze(),m=kn(()=>{g(!0),T("/plugins").then(({plugins:u})=>{o(u),g(!1)}).catch(()=>g(!1))},[]);return Bn(()=>{m()},[m]),wn((u,y)=>{if(y.escape||u==="q"){e();return}if(y.upArrow){l(d=>Math.max(0,d-1));return}if(y.downArrow){l(d=>Math.min(t.length-1,d+1));return}u==="r"&&(m(),r())}),c?se(ue,{dimColor:!0,children:"Loading plugins..."}):gt(nt,{flexDirection:"column",children:[gt(ue,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&se(nt,{marginTop:1,children:gt(ue,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?se(nt,{marginTop:1,children:se(ue,{dimColor:!0,children:"No plugins installed."})}):gt(nt,{marginTop:1,flexDirection:"column",children:[gt(nt,{children:[se(ue,{dimColor:!0,children:" "}),se(ue,{dimColor:!0,children:mt("Name",24)}),se(ue,{dimColor:!0,children:mt("Scope",8)}),se(ue,{dimColor:!0,children:mt("User",6)}),se(ue,{dimColor:!0,children:"Path"})]}),t.map((u,y)=>{let d=y===f,x=u.id.split("@")[0];return gt(nt,{children:[se(ue,{color:d?"cyan":void 0,bold:d,children:d?"> ":" "}),se(ue,{color:d?"cyan":void 0,bold:d,children:mt(x,24)}),se(ue,{color:d?"cyan":void 0,bold:d,children:mt(u.scope,8)}),se(ue,{color:u.globalEnabled?"green":"gray",children:mt(u.globalEnabled?"on":"off",6)}),se(ue,{dimColor:!0,children:u.installPath})]},u.id)})]}),se(nt,{marginTop:1,children:se(ue,{dimColor:!0,children:"r:refresh"})})]})}function mt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ut,Text as Ko,useInput as In}from"ink";import{useState as Pn}from"react";import{jsx as ft,jsxs as no}from"react/jsx-runtime";var An=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function Qo({onBack:e}){let[t,o]=Pn("tasks");return In((c,g)=>{if(g.escape||c==="q"){e();return}if(c==="1"){o("tasks");return}if(c==="2"){o("automations");return}if(c==="3"){o("goals");return}}),no(Ut,{flexDirection:"column",children:[no(Ut,{gap:1,marginBottom:1,children:[An.map(c=>{let g=t===c.id;return ft(Ut,{children:no(Ko,{color:g?"cyan":"gray",bold:g,underline:g,children:["[",c.key,":",c.label,"]"]})},c.id)}),ft(Ut,{flexGrow:1}),ft(Ko,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&ft(Lt,{onBack:e}),t==="automations"&&ft(Vt,{onBack:e}),t==="goals"&&ft($t,{onBack:e})]})}import{Box as G,Text as N,useInput as Dn}from"ink";import{useEffect as Rn,useState as wt}from"react";import{jsx as I,jsxs as re}from"react/jsx-runtime";var Xo={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Yo({onBack:e}){let[t,o]=wt([]),[c,g]=wt(!0),[f,l]=wt(0),[i,n]=wt(null),[r,m]=wt("");Rn(()=>{u()},[]);async function u(){try{let x=await T("/channels");o(x.channels)}catch{}g(!1)}async function y(x){if(t.find(a=>a.id===x)?.platform==="wechat")try{m("Starting WeChat QR login...");let a=await T(`/channels/${x}/wechat/qr-start`,{method:"POST"});if(a.qrcodeUrl){m(`Scan QR: ${a.qrcodeUrl}
|
|
6
|
-
Waiting for scan...`);let P=await T(`/channels/${x}/wechat/qr-wait`,{method:"POST",body:{sessionKey:a.sessionKey,timeoutMs:12e4}});m(P.message)}else m(a.message);u()}catch{m("WeChat connect failed")}else try{await T(`/channels/${x}/connect`,{method:"POST"}),m("Connecting..."),u()}catch{m("Connect failed")}}async function d(x){try{await T(`/channels/${x}/disconnect`,{method:"POST"}),m("Disconnected"),u()}catch{m("Disconnect failed")}}return Dn((x,s)=>{if(i){if(s.escape||x==="q"){n(null);return}if(x==="c"){y(i.id);return}if(x==="d"){d(i.id);return}return}if(s.escape){e();return}if(s.upArrow){l(a=>Math.max(0,a-1));return}if(s.downArrow){l(a=>Math.min(t.length-1,a+1));return}if(s.return&&t[f]){n(t[f]),m("");return}}),c?I(G,{flexDirection:"column",children:I(N,{dimColor:!0,children:"Loading channels..."})}):i?re(G,{flexDirection:"column",children:[re(G,{marginBottom:1,children:[re(N,{bold:!0,children:["Channel: ",i.name]}),I(N,{dimColor:!0,children:" (Esc to go back)"})]}),re(G,{flexDirection:"column",gap:0,children:[re(N,{children:["ID: ",i.id]}),re(N,{children:["Platform: ",i.platform]}),re(N,{children:["Status: ",I(N,{color:Xo[i.status]??"white",children:i.status})]}),re(N,{children:["Enabled: ",i.enabled?"yes":"no"]}),re(N,{children:["Messages: ",i.messageCount]}),re(N,{children:["Config: ",JSON.stringify(i.config)]})]}),I(G,{marginTop:1,children:I(N,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&I(N,{color:"yellow",children:r})]}):re(G,{flexDirection:"column",children:[re(G,{marginBottom:1,children:[I(N,{bold:!0,children:"Channels"}),re(N,{dimColor:!0,children:[" (",t.length," total) "]}),I(N,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?I(N,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):re(G,{flexDirection:"column",children:[re(G,{children:[I(G,{width:3,children:I(N,{dimColor:!0,children:" "})}),I(G,{width:12,children:I(N,{bold:!0,dimColor:!0,children:"ID"})}),I(G,{width:16,children:I(N,{bold:!0,dimColor:!0,children:"Name"})}),I(G,{width:12,children:I(N,{bold:!0,dimColor:!0,children:"Platform"})}),I(G,{width:14,children:I(N,{bold:!0,dimColor:!0,children:"Status"})}),I(G,{width:10,children:I(N,{bold:!0,dimColor:!0,children:"Enabled"})}),I(G,{width:10,children:I(N,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((x,s)=>re(G,{children:[I(G,{width:3,children:I(N,{children:s===f?">":" "})}),I(G,{width:12,children:I(N,{inverse:s===f,children:x.id.slice(0,8)})}),I(G,{width:16,children:I(N,{children:x.name})}),I(G,{width:12,children:I(N,{children:x.platform})}),I(G,{width:14,children:re(N,{color:Xo[x.status]??"white",children:[x.status==="connected"?"\u25CF":x.status==="error"?"\u2717":"\u25CB"," ",x.status]})}),I(G,{width:10,children:I(N,{color:x.enabled?"green":"gray",children:x.enabled?"yes":"no"})}),I(G,{width:10,children:I(N,{children:x.messageCount})})]},x.id))]})]})}import{Box as pt,Text as Ge,useInput as Nn}from"ink";import{useEffect as Ln,useState as kt,useCallback as _n}from"react";import{Box as L,Text as E,useInput as Mn}from"ink";import Ft from"ink-text-input";import{useEffect as zo,useState as ie,useCallback as Bt}from"react";lo();import{Fragment as Jo,jsx as v,jsxs as A}from"react/jsx-runtime";function Zo({roleId:e,onBack:t}){let[o,c]=ie(null),[g,f]=ie([]),[l,i]=ie(!0),[n,r]=ie("view"),[m,u]=ie(""),[y,d]=ie(0),[x,s]=ie(""),[a,P]=ie([]),[M,U]=ie(0),[W,q]=ie(new Set),[k,C]=ie("inline"),[w,p]=ie(""),[H,j]=ie(""),[he,b]=ie([]),[B,$]=ie(new Set),[de,He]=ie(0),{message:O,setMessage:Y}=ze(),me=Bt(()=>{i(!0),T(`/roles/${e}`).then(({role:h,boundPlugins:R})=>{c(h),f(R??[]),u(h.cagPrompt??""),q(new Set(h.allowedTools??[])),C(h.executionMode??"inline"),p(h.model??""),j(h.maxBudgetUsd!=null?String(h.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);zo(()=>{me()},[me]),zo(()=>{C(o?.executionMode??"inline"),p(o?.model??""),j(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):"")},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd]);let or=Bt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:m}}),Y("CAG prompt saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,m,me,Y]),rr=Bt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:_e}}),Y("Directories saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,me,Y]),nr=Bt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(W)}}),Y("Tool permissions saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,W,me,Y]),sr=Bt(async()=>{if(!o)return;let h={executionMode:k};w!==void 0&&(h.model=w);let R=parseFloat(H);isNaN(R)||(h.maxBudgetUsd=R);try{await T(`/roles/${o.id}`,{method:"PATCH",body:h}),Y("Execution config saved","success"),r("view"),me()}catch(S){Y(`Save failed: ${S instanceof Error?S.message:String(S)}`,"error")}},[o,k,w,H,me,Y]),_e=o?.additionalDirectories??[];return Mn((h,R)=>{if(R.escape){r("view");return}if(h==="r"){me();return}switch(n){case"view":{if(h==="c"){r("edit-cag");return}if(h==="d"){r("edit-dirs"),d(0),s("");return}if(h==="t"){r("edit-tools");return}if(h==="x"){r("edit-exec");return}if(h==="h"){T("/channels?enabled=true").then(({channels:S})=>{b(S.map(z=>({name:z.name,id:z.id}))),$(new Set(o?.allowedChannels??[])),He(0),r("edit-channels")}).catch(()=>Y("Failed to load channels","error"));return}if(h==="i"){if(!o)return;let S=!o.inheritUserSettings;T(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:S}}).then(()=>{Y(`Inherit user settings: ${S?"ON":"OFF"}`,"success"),me()}).catch(()=>Y("Failed to toggle","error"));return}break}case"edit-cag":{if(R.ctrl&&h==="s"){or();return}break}case"edit-dirs":{if(h==="s"){rr();return}if(h==="a"){r("edit-dirs-add");return}if(h==="x"&&_e.length>0){c(S=>S&&{...S,additionalDirectories:_e.filter((z,je)=>je!==y)}),d(S=>Math.max(0,Math.min(S,_e.length-2)));return}if(R.upArrow){d(S=>Math.max(0,S-1));return}if(R.downArrow){d(S=>Math.min(_e.length-1,S+1));return}break}case"edit-dirs-add":{if(R.escape){r("edit-dirs"),s(""),P([]);return}if(R.return&&a.length>0){let S=a[M];S&&(s(S.endsWith("/")?S:S+"/"),P([]));return}if(R.return){let S=x.trim();S&&S.startsWith("/")?(c(z=>z&&{...z,additionalDirectories:[...z.additionalDirectories??[],{path:S}]}),s(""),P([]),r("edit-dirs")):Y("Path must be absolute (must start with /)","error");return}if(R.tab){let S=x.trim();if(!S||!S.startsWith("/"))return;T(`/fs/suggest-dirs?prefix=${encodeURIComponent(S)}`).then(({suggestions:z})=>{z.length===1?(s(z[0]+"/"),P([])):z.length>1&&(P(z),U(0))}).catch(()=>{P([])});return}if(R.upArrow&&a.length>0){U(S=>Math.max(0,S-1));return}if(R.downArrow&&a.length>0){U(S=>Math.min(a.length-1,S+1));return}break}case"edit-tools":{if(h==="s"){nr();return}let S=parseInt(h,10)-1;if(!isNaN(S)&&S>=0&&S<At.length){let z=At[S];q(je=>{let Pt=new Set(je);return Pt.has(z)?Pt.delete(z):Pt.add(z),Pt});return}break}case"edit-exec":{if(h==="s"){sr();return}if(R.tab){C(S=>S==="inline"?"isolated":"inline");return}break}case"edit-channels":{if(h==="s"){if(!o)return;let S=B.size>0?Array.from(B):[];T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:S}}).then(()=>{Y("Channels saved","success"),r("view"),me()}).catch(()=>Y("Save failed","error"));return}if(h==="u"){if(!o)return;T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{Y("Channels: unrestricted","success"),r("view"),me()}).catch(()=>Y("Save failed","error"));return}if(h===" "){let S=he[de];S&&$(z=>{let je=new Set(z);return je.has(S.name)?je.delete(S.name):je.add(S.name),je});return}if(R.upArrow){He(S=>Math.max(0,S-1));return}if(R.downArrow){He(S=>Math.min(he.length-1,S+1));return}break}}}),l?v(E,{dimColor:!0,children:"Loading role..."}):o?n==="edit-cag"?A(L,{flexDirection:"column",children:[v(E,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),v(Ft,{value:m,onChange:u,placeholder:"Character And Guidance prompt..."}),O&&v(L,{marginTop:1,children:v(E,{color:O.type==="error"?"red":"green",children:O.text})})]}):n==="edit-dirs-add"?A(L,{flexDirection:"column",children:[v(E,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),v(Ft,{value:x,onChange:h=>{s(h),P([])},placeholder:"/absolute/path/to/directory"}),a.length>0&&A(L,{flexDirection:"column",marginTop:1,children:[a.map((h,R)=>A(E,{color:R===M?"cyan":void 0,dimColor:R!==M,children:[R===M?"> ":" ",h,"/"]},h)),v(E,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),O&&v(L,{marginTop:1,children:v(E,{color:O.type==="error"?"red":"green",children:O.text})})]}):n==="edit-dirs"?A(L,{flexDirection:"column",children:[v(E,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add x:remove s:save Esc:cancel)"}),O&&v(L,{children:v(E,{color:O.type==="error"?"red":O.type==="success"?"green":"gray",children:O.text})}),_e.length===0?v(E,{dimColor:!0,children:"No directories. Press a to add one."}):_e.map((h,R)=>A(L,{children:[v(E,{color:R===y?"cyan":void 0,bold:R===y,children:R===y?"> ":" "}),v(E,{color:R===y?"cyan":void 0,children:h.path})]},h.path))]}):n==="edit-tools"?A(L,{flexDirection:"column",children:[v(E,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),O&&v(L,{children:v(E,{color:O.type==="error"?"red":O.type==="success"?"green":"gray",children:O.text})}),At.map((h,R)=>{let S=W.has(h);return A(L,{children:[A(E,{dimColor:!0,children:[R+1,". "]}),v(E,{color:S?"green":"red",children:S?"[ON] ":"[OFF] "}),v(E,{children:h})]},h)})]}):n==="edit-exec"?A(L,{flexDirection:"column",children:[v(E,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),A(L,{children:[v(E,{bold:!0,children:" Mode: "}),v(E,{color:"cyan",children:k}),v(E,{dimColor:!0,children:" (Tab to toggle)"})]}),A(L,{children:[v(E,{bold:!0,children:" Model: "}),v(Ft,{value:w,onChange:p,placeholder:"sonnet, opus, haiku, or blank"})]}),A(L,{children:[v(E,{bold:!0,children:" Max Budget (USD): "}),v(Ft,{value:H,onChange:j,placeholder:"0 = unlimited"})]}),O&&v(L,{children:v(E,{color:O.type==="error"?"red":O.type==="success"?"green":"gray",children:O.text})})]}):n==="edit-channels"?A(L,{flexDirection:"column",children:[v(E,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),he.length===0?v(E,{dimColor:!0,children:"No channels available"}):he.map((h,R)=>A(L,{children:[A(E,{children:[R===de?">":" "," "]}),A(E,{color:B.has(h.name)?"green":"gray",children:["[",B.has(h.name)?"x":" ","] ",h.name]})]},h.id)),A(E,{dimColor:!0,children:["Selected: ",B.size>0?Array.from(B).join(", "):"none (= block all)"]}),O&&v(L,{children:v(E,{color:O.type==="error"?"red":O.type==="success"?"green":"gray",children:O.text})})]}):A(L,{flexDirection:"column",children:[A(E,{bold:!0,children:["Role: ",o.name]}),A(L,{children:[v(E,{dimColor:!0,children:"ID: "}),v(E,{children:o.id})]}),A(L,{children:[v(E,{dimColor:!0,children:"Status: "}),v(E,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&A(L,{children:[v(E,{dimColor:!0,children:"Score: "}),A(E,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),A(L,{children:[v(E,{dimColor:!0,children:"Created: "}),v(E,{children:new Date(o.createdAt).toLocaleString()})]}),A(L,{children:[v(E,{dimColor:!0,children:"Execution: "}),A(E,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),_e.length>0&&A(Jo,{children:[v(E,{bold:!0,children:"Additional Directories:"}),_e.map(h=>A(E,{dimColor:!0,children:[" ",h.path]},h.path))]}),A(L,{children:[v(E,{dimColor:!0,children:"Channels: "}),v(E,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),A(L,{children:[v(E,{dimColor:!0,children:"Inherit User Settings: "}),v(E,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&A(Jo,{children:[v(E,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(h=>A(E,{dimColor:!0,children:[" - ",h]},h))]}),O&&v(L,{children:v(E,{color:O.type==="error"?"red":O.type==="success"?"green":"gray",children:O.text})}),v(L,{marginTop:1,children:v(E,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec h:channels i:inherit r:refresh Esc:back"})})]}):v(E,{dimColor:!0,children:"Role not found."})}import{jsx as Se,jsxs as Wt}from"react/jsx-runtime";function er({onBack:e}){let[t,o]=kt([]),[c,g]=kt(!0),[f,l]=kt(0),[i,n]=kt("list"),[r,m]=kt(null),{message:u,setMessage:y,clearMessage:d}=ze(),x=_n(()=>{g(!0),T("/roles").then(({roles:s})=>{o(s.map(a=>({id:a.id,name:a.name,status:a.status,performanceScore:a.performanceScore,createdAt:a.createdAt}))),g(!1)}).catch(()=>g(!1))},[]);return Ln(()=>{x()},[x]),Nn((s,a)=>{if(a.escape||s==="q"){e();return}if(a.upArrow){l(P=>Math.max(0,P-1));return}if(a.downArrow){l(P=>Math.min(t.length-1,P+1));return}if(s==="r"&&(x(),d()),s===`
|
|
7
|
-
`||s==="o"||s==="e"){t.length>0&&(m(t[f].id),n("detail"));return}}),c?Se(Ge,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Se(Zo,{roleId:r,onBack:()=>n("list")}):Wt(pt,{flexDirection:"column",children:[Wt(Ge,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),u&&Se(pt,{marginTop:1,children:Wt(Ge,{color:u.type==="success"?"green":u.type==="error"?"red":"gray",children:[u.type==="success"?"\u2713 ":u.type==="error"?"\u2717 ":"\u2192 ",u.text]})}),t.length===0?Se(pt,{marginTop:1,children:Se(Ge,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Se(pt,{marginTop:1,flexDirection:"column",children:t.map((s,a)=>{let P=a===f,M=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014";return Wt(pt,{children:[Se(Ge,{color:P?"cyan":void 0,bold:P,children:P?"> ":" "}),Se(Ge,{color:P?"cyan":void 0,bold:P,children:so(s.name,24)}),Se(Ge,{color:$n(s.status),children:so(s.status,12)}),Se(Ge,{dimColor:!0,children:so(M,8)})]},s.id)})}),Se(pt,{marginTop:1,children:Se(Ge,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function $n(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function so(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as Wn,jsx as _,jsxs as Tt}from"react/jsx-runtime";function Vn(){let{state:e,dispatch:t}=Ke(),{session:o,sendMessage:c,createNewSession:g,archiveCurrentSession:f}=To(),[l,i]=On([]);io(()=>{t({type:"SET_SESSION",session:o})},[o,t]),fo();let{events:n,isStreaming:r,clearEvents:m}=xo(e.activeTaskId),u=n[n.length-1],y=u?.type==="complete"&&!r,d=tr(null),x=tr("");io(()=>{x.current=n.filter(a=>a.type==="reasoning").map(a=>a.content).join("")},[n]),io(()=>{if(y&&e.activeTaskId!==d.current){d.current=e.activeTaskId;let a=u?.content||x.current;a&&i(P=>[...P,{role:"assistant",content:a}])}},[y,u,e.activeTaskId]);let s=async a=>{if(a.startsWith("/")){let M=a.slice(1),U={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"};M==="quit"&&process.exit(0);let W=U[M];if(W){t({type:"SET_VIEW",view:W});return}if(M==="new"){if(await f()){let k=await g();i([]),m(),k&&i([{role:"assistant",content:`Session archived. New session started: ${k.id.slice(0,8)}`}])}return}if(M==="session"){let q=o?`Session: ${o.id}
|
|
8
|
-
Turns: ${o.messageCount}
|
|
9
|
-
Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(k=>[...k,{role:"assistant",content:q}]);return}}i(M=>[...M,{role:"user",content:a}]),m();let P=await c(a);if(!P){i(M=>[...M,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}t({type:"SET_ACTIVE_TASK",taskId:P.taskId}),t({type:"TASK_SUBMITTED"})};return Tt(It,{flexDirection:"column",paddingX:1,children:[_(ho,{}),Tt(It,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Tt(Wn,{children:[_(Eo,{messages:l}),_(So,{events:n,isStreaming:r}),!e.connected&&!e.serverUnreachable&&_(It,{children:_(xt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Tt(It,{flexDirection:"column",children:[_(xt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),_(xt,{dimColor:!0,children:"Check: adam server logs"}),_(xt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&_(Qo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&_(Lt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&_(Do,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&_(Mo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&_($t,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&_(Lo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&_(Vt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&_(qo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&_(Uo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&_(jo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&_(er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&_(Ho,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&_(Yo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?_(Bo,{approval:e.pendingPlanApproval,onResolved:()=>t({type:"SET_PENDING_PLAN_APPROVAL",approval:null}),onTimeout:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:e.pendingPlanApproval.planId})}):e.pendingApproval?_(wo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):_(bo,{onSubmit:s}),e.planTimeoutNotice&&_(Un,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function Un({planId:e,onDismiss:t}){return qn(o=>{o==="d"&&t()}),Tt(It,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Tt(xt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),_(xt,{dimColor:!0,children:" [d] Dismiss"})]})}function Fn(){return _(go,{children:_(Vn,{})})}export{Fn as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{I as a,J as b}from"./chunk-B3CVXD44.js";import"./chunk-3OYRYMJW.js";import"./chunk-EJJDJY34.js";import"./chunk-QOPUUA7O.js";import"./chunk-HMXDNPFE.js";import"./chunk-MMIO6BCA.js";import"./chunk-WGRTN6TX.js";import"./chunk-TYR3QUCL.js";import"./chunk-TGQYM4TH.js";import"./chunk-CV3ROBUM.js";import"./chunk-ZN5Q3YET.js";import"./chunk-5BAD3NCT.js";import"./chunk-FUBKGVWI.js";import"./chunk-62PXAOD6.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{b as m}from"./chunk-EJJDJY34.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import{c as f}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var l=f("channels"),c=new Map,y=3e5,h=new Set(["telegram"]);function v(n){let s=n.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!s)return null;let[,p,d]=s,i=["yes","y","\u662F","\u5141\u8BB8"].includes(p);return{requestId:d,decision:i?"allow":"deny"}}function A(n){let r=m(n);return r?h.has(r.platform):!1}async function P(n,r,s,p,d,i,o=y){let e=s;c.set(e,{planId:s,taskId:p,channelId:n,chatId:r,requestId:e,timestamp:Date.now(),timeoutMs:o});let a=A(n);if(a){let t=`\u{1F510} Plan approval requested
|
|
2
|
-
|
|
3
|
-
${d.slice(0,200)}`;await i.sendMessage(n,r,{content:t,replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${e}`},{text:"\u274C Deny",callbackData:`no ${e}`}]]}})}else{let t=["\u{1F510} Plan approval requested",d.slice(0,200),"",`Reply 'yes ${e}' or 'no ${e}'`].join(`
|
|
4
|
-
`);await i.sendMessage(n,r,{content:t})}setTimeout(()=>{let t=c.get(e);if(t&&Date.now()-t.timestamp>=t.timeoutMs){c.delete(e),l.warn({requestId:e,taskId:p},"Approval timed out, auto-denying"),i.sendMessage(t.channelId,t.chatId,{content:`\u23F0 Approval ${e} timed out (5 min). Plan denied.`}).catch(u=>l.error({requestId:e,error:u},"Failed to notify timeout"));let g=process.env.ADAM_PORT??"7100";fetch(`http://localhost:${g}/tasks/${t.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:t.planId,decision:"deny"})}).catch(u=>l.error({requestId:e,error:u},"Failed to auto-deny"))}},o+1e3),l.info({channelId:n,chatId:r,planId:s,requestId:e,interactive:a},"Interactive approval sent to channel")}async function C(n,r,s,p){let i=v(p??s);if(!i)return!1;let{requestId:o,decision:e}=i,a=c.get(o);if(!a)return!1;if(a.channelId!==n||a.chatId!==r)return l.debug({requestId:o,expectedChannel:a.channelId,gotChannel:n},"Approval reply from different channel"),!1;c.delete(o),l.info({requestId:o,decision:e},"Channel approval reply received");try{let t=process.env.ADAM_PORT??"7100",g=await fetch(`http://localhost:${t}/tasks/${a.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:a.planId,decision:e}),signal:AbortSignal.timeout(1e4)});g.ok||l.error({requestId:o,status:g.status},"Failed to forward approval to API")}catch(t){l.error({requestId:o,error:t},"Error forwarding approval to API")}return!0}function T(){return[...c.keys()]}export{T as getPendingApprovalRequestIds,C as handleInboundForApproval,v as parseApprovalReply,P as sendApprovalToChannel};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a,c as b,d as c}from"./chunk-5GMYXCL3.js";import"./chunk-EJJDJY34.js";import"./chunk-MMIO6BCA.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"./chunk-EJJDJY34.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
|
package/dist/chunk-37OAKNKA.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import{b as s,f as h}from"./chunk-FUBKGVWI.js";import{e as i,f as g,i as p,l as R}from"./chunk-62PXAOD6.js";import{c as f}from"./chunk-3DAK2XWP.js";R();h();import{v4 as c}from"uuid";var t=f("store"),a="role-chat-manager",l=[{name:"\u5BA1\u614E\u8005",cagPrompt:`\u4F60\u662F\u5BA1\u614E\u8005\u2014\u2014\u4E00\u4E2A\u8FFD\u6C42\u4EE3\u7801\u8D28\u91CF\u548C\u5B89\u5168\u7684\u5DE5\u7A0B\u5E08\u578B\u89D2\u8272\u3002
|
|
2
|
-
\u884C\u4E8B\u98CE\u683C\uFF1A\u6DF1\u601D\u719F\u8651\uFF0C\u5148\u60F3\u6E05\u695A\u518D\u52A8\u624B\uFF1B\u9AD8\u5EA6\u91CD\u89C6\u4EE3\u7801\u8D28\u91CF\u3001\u5B89\u5168\u6027\u548C\u8FB9\u754C\u6761\u4EF6\u3002
|
|
3
|
-
\u5DE5\u4F5C\u65B9\u5F0F\uFF1A\u5148\u5206\u6790\u9700\u6C42\u548C\u6F5C\u5728\u98CE\u9669\uFF0C\u518D\u5236\u5B9A\u6267\u884C\u8BA1\u5212\uFF1B\u4EE3\u7801\u5FC5\u987B\u901A\u8FC7\u6D4B\u8BD5\u5E76\u7B26\u5408\u6700\u4F73\u5B9E\u8DF5\u3002
|
|
4
|
-
\u884C\u4E3A\u51C6\u5219\uFF1A\u4E0D\u7A33\u5B9A\u56E0\u7D20\u4E0D\u653E\u8FC7\uFF0C\u5B89\u5168\u98CE\u9669\u5FC5\u987B\u62A5\u544A\uFF0C\u4EE3\u7801\u5BA1\u67E5\u5FC5\u987B\u5F7B\u5E95\u3002`,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],evaluationCriteria:{code_quality:4,test_pass:3,build_success:3,bug_detection_rate:4},executionMode:"isolated"},{name:"\u654F\u6377\u8005",cagPrompt:`\u4F60\u662F\u654F\u6377\u8005\u2014\u2014\u4E00\u4E2A\u8FFD\u6C42\u901F\u5EA6\u548C\u5FEB\u901F\u8FED\u4EE3\u7684\u89D2\u8272\u3002
|
|
5
|
-
\u884C\u4E8B\u98CE\u683C\uFF1A\u5FEB\u901F\u54CD\u5E94\uFF0C\u5FEB\u901F\u6267\u884C\uFF1B\u4F18\u5148\u4EA4\u4ED8\u53EF\u7528\u6210\u679C\uFF0C\u518D\u9010\u6B65\u5B8C\u5584\u3002
|
|
6
|
-
\u5DE5\u4F5C\u65B9\u5F0F\uFF1A\u77ED\u5468\u671F\u8FED\u4EE3\uFF0C\u9891\u7E41\u9A8C\u8BC1\uFF1B\u5148\u8DD1\u8D77\u6765\uFF0C\u518D\u4F18\u5316\u7EC6\u8282\u3002
|
|
7
|
-
\u884C\u4E3A\u51C6\u5219\uFF1A\u6548\u7387\u4F18\u5148\uFF0C\u5FEB\u901F\u8BD5\u9519\uFF1B\u53EF\u7528\u7684\u4E1C\u897F\u4F18\u4E8E\u5B8C\u7F8E\u7684\u8BBE\u8BA1\u3002`,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],evaluationCriteria:{code_quality:4,test_pass:3,build_success:3,engagement:4},executionMode:"isolated"},{name:"\u63A2\u7D22\u8005",cagPrompt:`\u4F60\u662F\u63A2\u7D22\u8005\u2014\u2014\u4E00\u4E2A\u4E13\u6CE8\u4E8E\u7814\u7A76\u548C\u5206\u6790\u7684\u89D2\u8272\u3002
|
|
8
|
-
\u884C\u4E8B\u98CE\u683C\uFF1A\u597D\u5947\u5FC3\u9A71\u52A8\uFF0C\u6DF1\u5165\u8C03\u7814\uFF1B\u4E0D\u6EE1\u8DB3\u4E8E\u8868\u9762\u7B54\u6848\uFF0C\u8FFD\u95EE\u6839\u672C\u539F\u56E0\u3002
|
|
9
|
-
\u5DE5\u4F5C\u65B9\u5F0F\uFF1A\u5E7F\u6CDB\u641C\u7D22\uFF0C\u6DF1\u5165\u9605\u8BFB\uFF0C\u63D0\u70BC\u6D1E\u5BDF\uFF1B\u7528\u6570\u636E\u8BF4\u8BDD\uFF0C\u7528\u8BC1\u636E\u652F\u6491\u7ED3\u8BBA\u3002
|
|
10
|
-
\u884C\u4E3A\u51C6\u5219\uFF1A\u7CBE\u786E\u6027\u9AD8\u4E8E\u901F\u5EA6\uFF1B\u5206\u6790\u5FC5\u987B\u5168\u9762\uFF0C\u7ED3\u8BBA\u5FC5\u987B\u6709\u636E\u53EF\u67E5\u3002`,allowedTools:["Glob","Grep","Read","WebSearch","WebFetch"],evaluationCriteria:{insight_quality:5,data_accuracy:5},executionMode:"isolated"},{name:"\u5320\u4EBA",cagPrompt:`\u4F60\u662F\u5320\u4EBA\u2014\u2014\u4E00\u4E2A\u4E13\u6CE8\u4E8E\u7CBE\u96D5\u7EC6\u7422\u548C\u6781\u81F4\u54C1\u8D28\u7684\u89D2\u8272\u3002
|
|
11
|
-
\u884C\u4E8B\u98CE\u683C\uFF1A\u8FFD\u6C42\u5353\u8D8A\uFF0C\u6CE8\u91CD\u7EC6\u8282\uFF1B\u4E0D\u6EE1\u8DB3\u4E8E\u300C\u80FD\u7528\u300D\uFF0C\u8981\u8FFD\u6C42\u300C\u597D\u7528\u300D\u548C\u300C\u4F18\u96C5\u300D\u3002
|
|
12
|
-
\u5DE5\u4F5C\u65B9\u5F0F\uFF1A\u6DF1\u5165\u6253\u78E8\u6BCF\u4E2A\u7EC6\u8282\uFF0C\u53CD\u590D\u4F18\u5316\u76F4\u5230\u6EE1\u610F\uFF1B\u4EE3\u7801\u5373\u4F5C\u54C1\u3002
|
|
13
|
-
\u884C\u4E3A\u51C6\u5219\uFF1A\u8D28\u91CF\u91CD\u4E8E\u901F\u5EA6\uFF1B\u6BCF\u4E2A\u7EC6\u8282\u90FD\u503C\u5F97\u7528\u5FC3\uFF0C\u6BCF\u4E2A\u95EE\u9898\u90FD\u503C\u5F97\u5F7B\u5E95\u89E3\u51B3\u3002`,allowedTools:["Read","Write","Edit","Bash","Grep","Glob"],evaluationCriteria:{code_quality:4,test_pass:3,build_success:3},executionMode:"isolated"}];function y(){x();let n=p(void 0,1e3,0),o=new Set(l.map(e=>e.name)),d=n.filter(e=>o.has(e.name));if(d.length>0)return t.info({count:d.length},"Default roles already exist, skipping"),n;t.info({count:l.length},"Creating default roles");let u=[];for(let e of l){let m=`role-${c().slice(0,8)}`,r={id:m,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,evaluationCriteria:e.evaluationCriteria,executionMode:e.executionMode};i(r),u.push(r),s(r),t.info({roleId:m,name:e.name},"Created default role")}return u}function x(){if(g(a)){t.debug({roleId:a},"ChatManager system role already exists");return}let o={id:a,name:"Chat Manager",cagPrompt:`You are the Chat Manager \u2014 orchestrating conversations and managing agent interactions.
|
|
14
|
-
You coordinate between user requests and agent execution, maintaining conversation context
|
|
15
|
-
and routing tasks to the appropriate roles. You have broad memory access across all roles.`,learnedRules:[],memoryStreamId:`mem-${c().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now()};i(o),s(o),t.info({roleId:a},"Created ChatManager system role")}export{a,y as b};
|
package/dist/chunk-3OYRYMJW.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{b as s,d}from"./chunk-W6JITSZF.js";d();function u(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,sourceSessionId:e.source_session_id??void 0,notifyTargets:e.notify_targets?JSON.parse(e.notify_targets):void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0}}function c(e){s().prepare(`
|
|
2
|
-
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
|
-
sdk_session_id, template_id, role_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
|
-
created_at, started_at, completed_at,
|
|
5
|
-
cost_usd, token_usage, num_turns, total_duration_ms)
|
|
6
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
-
`).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.sourceSessionId??null,e.notifyTargets?JSON.stringify(e.notifyTargets):null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null)}function m(e){let i=s().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return i?u(i):void 0}function T(e,t){let i=s(),r=[],n=[],o={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms"};for(let[a,l]of Object.entries(o))a in t&&(r.push(`${l} = ?`),n.push(t[a]??null));"config"in t&&(r.push("config = ?"),n.push(JSON.stringify(t.config))),"tokenUsage"in t&&(r.push("token_usage = ?"),n.push(t.tokenUsage?JSON.stringify(t.tokenUsage):null)),"notifyTargets"in t&&(r.push("notify_targets = ?"),n.push(t.notifyTargets?JSON.stringify(t.notifyTargets):null)),"deliverTo"in t&&(r.push("deliver_to = ?"),n.push(t.deliverTo?JSON.stringify(t.deliverTo):null)),"reportTo"in t&&(r.push("report_to = ?"),n.push(t.reportTo?JSON.stringify(t.reportTo):null)),r.length!==0&&(n.push(e),i.prepare(`UPDATE tasks SET ${r.join(", ")} WHERE id = ?`).run(...n))}function y(e,t=100,i=0,r){let n=s(),o="SELECT * FROM tasks",a=[],l=[];return e&&(a.push("status = ?"),l.push(e)),r&&(a.push("role_id = ?"),l.push(r)),a.length>0&&(o+=" WHERE "+a.join(" AND ")),o+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",l.push(t,i),n.prepare(o).all(...l).map(u)}function R(e){return s().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(u)}d();function p(e){return{id:e.id,eventType:e.event_type,matchCriteria:JSON.parse(e.match_criteria),target:JSON.parse(e.target),formatTemplate:e.format_template??void 0,maxPerMinute:e.max_per_minute,skipOriginChannel:e.skip_origin_channel===1,enabled:e.enabled===1,createdAt:e.created_at,createdBy:e.created_by??void 0}}function v(e){s().prepare(`
|
|
8
|
-
INSERT INTO delivery_rules (id, event_type, match_criteria, target, format_template,
|
|
9
|
-
max_per_minute, skip_origin_channel, enabled, created_at, created_by)
|
|
10
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
11
|
-
`).run(e.id,e.eventType,JSON.stringify(e.matchCriteria),JSON.stringify(e.target),e.formatTemplate??null,e.maxPerMinute,e.skipOriginChannel?1:0,e.enabled?1:0,e.createdAt,e.createdBy??null)}function S(e){let i=s().prepare("SELECT * FROM delivery_rules WHERE id = ?").get(e);return i?p(i):void 0}function f(e){let t=s(),i="SELECT * FROM delivery_rules",r=[];return e!==void 0&&(i+=" WHERE enabled = ?",r.push(e?1:0)),i+=" ORDER BY created_at DESC",t.prepare(i).all(...r).map(p)}function b(e,t){let i=s(),r=[],n=[];t.eventType!==void 0&&(r.push("event_type = ?"),n.push(t.eventType)),t.matchCriteria!==void 0&&(r.push("match_criteria = ?"),n.push(JSON.stringify(t.matchCriteria))),t.target!==void 0&&(r.push("target = ?"),n.push(JSON.stringify(t.target))),t.formatTemplate!==void 0&&(r.push("format_template = ?"),n.push(t.formatTemplate)),t.maxPerMinute!==void 0&&(r.push("max_per_minute = ?"),n.push(t.maxPerMinute)),t.skipOriginChannel!==void 0&&(r.push("skip_origin_channel = ?"),n.push(t.skipOriginChannel?1:0)),t.enabled!==void 0&&(r.push("enabled = ?"),n.push(t.enabled?1:0)),r.length!==0&&(n.push(e),i.prepare(`UPDATE delivery_rules SET ${r.join(", ")} WHERE id = ?`).run(...n))}function k(e){let t=s();t.prepare("DELETE FROM delivery_log WHERE rule_id = ?").run(e),t.prepare("DELETE FROM delivery_rules WHERE id = ?").run(e)}function D(e,t){return f(!0).filter(r=>{if(r.eventType!=="*"&&r.eventType!==e)return!1;let n=r.matchCriteria;if(n.templateId&&n.templateId!==t.templateId||n.roleId&&n.roleId!==t.roleId||n.taskStatus&&n.taskStatus!==t.taskStatus)return!1;if(n.promptPattern)try{if(!new RegExp(n.promptPattern,"i").test(t.prompt??""))return!1}catch{return!1}return!0})}export{c as a,m as b,T as c,y as d,R as e,v as f,S as g,f as h,b as i,k as j,D as k};
|
package/dist/chunk-5BAD3NCT.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var u=["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","logging.level","roles.evolution.triggerEvery","roles.evolution.reflectionThreshold","chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory","server.timezone"],a=["server.port","server.host"],i=null;function p(t){i=JSON.parse(JSON.stringify(t))}function l(){if(!i)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return i}function h(t){let o=l(),r=[],n=[];for(let[e,s]of Object.entries(t)){if(!c(e)){g(e)?n.push(`"${e}" requires restart. Cannot modify at runtime.`):n.push(`"${e}" is not a recognized config path.`);continue}f(o,e,s)&&r.push(e)}return{success:n.length===0,updated:r,errors:n}}function f(t,o,r){let n=o.split("."),e=t;for(let s=0;s<n.length-1;s++)if(e&&typeof e=="object")e=e[n[s]];else return!1;return e&&typeof e=="object"?(e[n[n.length-1]]=r,!0):!1}function m(t,o){let r=o.split("."),n=t;for(let e of r)if(n&&typeof n=="object")n=n[e];else return;return n}function c(t){return u.includes(t)}function g(t){return a.includes(t)}export{u as a,a as b,p as c,l as d,h as e,m as f,c as g,g as h};
|
package/dist/chunk-B3CVXD44.js
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import{a as N,b,c as j,d as L,f as We,h as be,j as Be}from"./chunk-3OYRYMJW.js";import{d as fe}from"./chunk-EJJDJY34.js";import{a as De,l as he}from"./chunk-QOPUUA7O.js";import{a as ge}from"./chunk-WGRTN6TX.js";import{c as Ne,e as je,i as Oe,k as Fe,l as $e,m as Ue,o as Ge}from"./chunk-TYR3QUCL.js";import{b as te,c as Ve,g as Je}from"./chunk-TGQYM4TH.js";import{d as _,e as Le}from"./chunk-5BAD3NCT.js";import{b as Z,e as me,f as ee}from"./chunk-FUBKGVWI.js";import{e as xe,f as T,h as O,i as F,j as Ae,k as pe,l as X}from"./chunk-62PXAOD6.js";import{b as f,d as M}from"./chunk-W6JITSZF.js";import{c as y,d as Ce}from"./chunk-3DAK2XWP.js";import{c as Pt,e as Et,f as R}from"./chunk-FCV2DPZQ.js";var ut={};Et(ut,{getGlobalEnabledState:()=>B,getInstalledPlugin:()=>Te,getPluginManifest:()=>_e,listInstalledPlugins:()=>q,listMarketplaceSources:()=>Ie,resolvePluginPaths:()=>qt,scanDirectoryConfig:()=>ke});import{existsSync as E,readFileSync as J,readdirSync as ct}from"fs";import{join as h}from"path";import dt from"os";function x(e){try{if(!E(e))return null;let t=J(e,"utf-8");return JSON.parse(t)}catch{return null}}function B(){return x(Bt())?.enabledPlugins??{}}function _e(e){let t=e;function r(n,o){let a={};try{if(!E(n))return a;let l=J(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let d of o){let u=new RegExp(`^${d}:\\s*(.+)$`,"m"),p=l.match(u);p&&(a[d]=p[1].trim())}}catch{}return a}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},o=h(t,".claude-plugin","plugin.json");if(E(o))try{let u=JSON.parse(J(o,"utf-8"));n.name=u.name??"",n.version=u.version,n.description=u.description,Array.isArray(u.lspServers)&&(n.lspServers=u.lspServers),Array.isArray(u.mcpServers)&&(n.mcpServers=u.mcpServers),Array.isArray(u.hooks)&&(n.hooks=u.hooks)}catch{}let a=h(t,"skills");if(E(a)){let u=ct(a,{withFileTypes:!0});for(let p of u){if(!p.isFile()||!p.name.endsWith(".md"))continue;let g=r(h(a,p.name),["name","description"]);g.name&&n.skills.push({name:g.name,description:g.description??""})}}let i=h(t,"agents");if(E(i)){let u=ct(i,{withFileTypes:!0});for(let p of u){if(!p.isFile()||!p.name.endsWith(".md"))continue;let g=r(h(i,p.name),["name","description"]);g.name&&n.agents.push({name:g.name,description:g.description??""})}}let l=h(t,".mcp.json");if(E(l))try{let u=JSON.parse(J(l,"utf-8"));u.mcpServers&&typeof u.mcpServers=="object"&&(n.mcpServers=Object.keys(u.mcpServers))}catch{}let d=h(t,"hooks","hooks.json");if(E(d))try{let u=JSON.parse(J(d,"utf-8"));Array.isArray(u)&&(n.hooks=u.map(p=>typeof p=="object"&&p!==null&&"event"in p?String(p.event):String(p)))}catch{}return n}catch{return null}}function q(e){let t=x(Se());if(!t?.plugins)return[];let r=B(),n=[];for(let[o,a]of Object.entries(t.plugins))if(!(!Array.isArray(a)||a.length===0))for(let i of a){let l=i.scope??"user";e?.scope&&l!==e.scope||e?.projectPath&&i.projectPath!==e.projectPath||n.push({id:o,name:o.split("@")[0],version:i.version??"",scope:l,projectPath:i.projectPath,installPath:i.installPath??h(W(),o),enabled:r[o]??i.enabled??!0,installedAt:i.installedAt??"",lastUpdated:i.lastUpdated??""})}return n}function Te(e){let t=x(Se());if(!t?.plugins?.[e])return null;let r=t.plugins[e];if(!Array.isArray(r)||r.length===0)return null;let n=r[0],o=B();return{id:e,name:e.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??h(W(),e),enabled:o[e]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function qt(e){let t=x(Se()),r=new Map;for(let n of e){let o=t?.plugins?.[n];Array.isArray(o)&&o.length>0&&r.set(n,o[0].installPath??h(W(),n))}return r}function Ie(){return x(Wt())?.marketplaces??[]}function ke(e){let t=h(e,".claude","settings.json"),r=x(t);return{enabledPlugins:r?.enabledPlugins??{},mcpServers:r?.mcpServers??{},allowedTools:r?.allowedTools??[],disallowedTools:r?.disallowedTools??[]}}var W,Se,Wt,Bt,Re=Pt(()=>{"use strict";W=()=>h(dt.homedir(),".claude","plugins"),Se=()=>h(W(),"installed_plugins.json"),Wt=()=>h(W(),"known_marketplaces.json"),Bt=()=>h(dt.homedir(),".claude","settings.json")});import{createSdkMcpServer as tr,tool as m}from"@anthropic-ai/claude-agent-sdk";import{z as s}from"zod";M();function qe(e){return{id:e.id,name:e.name,description:e.description??void 0,roleId:e.role,metricType:e.metric_type,targetValue:e.target_value,currentValue:e.current_value,deadline:e.deadline,budgetUsd:e.budget_usd,status:e.status,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,notifyTargets:e.notify_targets?JSON.parse(e.notify_targets):void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0}}function re(e){f().prepare(`
|
|
2
|
-
INSERT INTO goals (id, name, description, role, metric_type, target_value,
|
|
3
|
-
current_value, deadline, budget_usd, status, created_at, updated_at,
|
|
4
|
-
source_session_id, notify_targets, deliver_to)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`).run(e.id,e.name,e.description??null,e.roleId,e.metricType,e.targetValue,e.currentValue,e.deadline,e.budgetUsd,e.status,e.createdAt,e.updatedAt??null,e.sourceSessionId??null,e.notifyTargets?JSON.stringify(e.notifyTargets):null,e.deliverTo?JSON.stringify(e.deliverTo):null)}function I(e){let r=f().prepare("SELECT * FROM goals WHERE id = ?").get(e);return r?qe(r):void 0}function ne(e,t){let r=f(),n=[],o=[],a={name:"name",description:"description",roleId:"role",metricType:"metric_type",targetValue:"target_value",currentValue:"current_value",deadline:"deadline",budgetUsd:"budget_usd",status:"status",updatedAt:"updated_at",sourceSessionId:"source_session_id"};for(let[i,l]of Object.entries(a))i in t&&(n.push(`${l} = ?`),o.push(t[i]??null));"notifyTargets"in t&&(n.push("notify_targets = ?"),o.push(JSON.stringify(t.notifyTargets))),"deliverTo"in t&&(n.push("deliver_to = ?"),o.push(JSON.stringify(t.deliverTo))),n.length!==0&&(o.push(e),r.prepare(`UPDATE goals SET ${n.join(", ")} WHERE id = ?`).run(...o))}function He(e,t=100,r=0){let n=f(),o="SELECT * FROM goals",a=[];return e&&(o+=" WHERE status = ?",a.push(e)),o+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",a.push(t,r),n.prepare(o).all(...a).map(qe)}function Ye(e){f().prepare("DELETE FROM goals WHERE id = ?").run(e)}X();ee();import{v4 as U}from"uuid";M();function Lt(e){return{id:e.id,goalId:e.goal_id,level:e.level,parentId:e.parent_id??void 0,name:e.name,description:e.description??void 0,weight:e.weight,calibrationFactor:e.calibration_factor,createdAt:e.created_at}}function $(e){f().prepare(`
|
|
7
|
-
INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
|
|
8
|
-
weight, calibration_factor, created_at)
|
|
9
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
10
|
-
`).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function Ke(e){return f().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(Lt)}import{query as xt}from"@anthropic-ai/claude-agent-sdk";import*as Qe from"fs/promises";import*as Xe from"path";import*as Ze from"os";var rn=y("manager"),ze=Xe.join(Ze.homedir(),".adam","llm-eval");async function oe(e,t){await Qe.mkdir(ze,{recursive:!0});let r={cwd:ze,maxTurns:3,maxBudgetUsd:.05};t&&(r.systemPrompt=t);let n=xt({prompt:e,options:r}),o="";for await(let a of n){let i=a;i.type==="result"&&typeof i.result=="string"&&(o=i.result)}return o}var At=y("goal-manager");async function dn(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 Ct(e)}let r=Dt(t);return{goalState:t,validationResult:r,rawInput:e}}async function Ct(e){let t=`Extract SMART goal fields from this natural language input.
|
|
11
|
-
|
|
12
|
-
Input: "${e}"
|
|
13
|
-
|
|
14
|
-
Respond ONLY with a JSON object:
|
|
15
|
-
{
|
|
16
|
-
"name": "short goal name (max 100 chars)",
|
|
17
|
-
"description": "detailed description of what the goal aims to achieve",
|
|
18
|
-
"metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
|
|
19
|
-
"targetValue": <number, the target to reach>,
|
|
20
|
-
"deadline_days": <number, days from now to complete>,
|
|
21
|
-
"budget": <number, estimated budget in USD>,
|
|
22
|
-
"role": "<best matching role: engineer | analyst | content_creator | reviewer>"
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
Rules:
|
|
26
|
-
- name: concise, actionable title
|
|
27
|
-
- metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
|
|
28
|
-
- targetValue: realistic target for the metric; use 1 for binary goals
|
|
29
|
-
- deadline_days: reasonable timeframe; default 7 if unclear
|
|
30
|
-
- budget: estimated cost in USD; default 5 if unclear
|
|
31
|
-
- role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await oe(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let o=JSON.parse(n[0]),a=o.deadline_days??7;return{name:(o.name??e.slice(0,100)).slice(0,100),description:o.description??e,metric:o.metric??"completion",targetValue:o.targetValue??1,currentValue:0,deadline:Date.now()+a*24*60*60*1e3,budget:o.budget??5,roleId:o.roleId??"engineer",status:"active"}}}catch(r){At.warn({error:r},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function Dt(e){let t=[],r=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&r.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:r}}function un(e,t){let r=U(),n=Date.now(),o={id:r,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:n,notifyTargets:t};return re(o),o}function et(e,t){let r=Date.now(),n=[],o={id:U(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(o),$(o);let a={id:U(),goalId:e,level:"L1",parentId:o.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(a),$(a);let i={id:U(),goalId:e,level:"L2",parentId:a.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(i),$(i);let l={id:U(),goalId:e,level:"L3",parentId:i.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),$(l),n}M();function Nt(e){return{id:e.id,taskId:e.task_id,index:e.index,type:e.type,content:e.content,toolName:e.tool_name??void 0,toolInput:e.tool_input?JSON.parse(e.tool_input):void 0,toolOutput:e.tool_output??void 0,truncated:e.truncated===1,timestamp:e.timestamp,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,planStepIndex:e.plan_step_index??void 0}}function gn(e){f().prepare(`
|
|
32
|
-
INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
|
|
33
|
-
tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
|
|
34
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
35
|
-
`).run(e.id,e.taskId,e.index,e.type,e.content,e.toolName??null,e.toolInput?JSON.stringify(e.toolInput):null,e.toolOutput??null,e.truncated?1:0,e.timestamp,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.planStepIndex??null)}function se(e,t=100,r=0){return f().prepare('SELECT * FROM step_logs WHERE task_id = ? ORDER BY "index" ASC LIMIT ? OFFSET ?').all(e,t,r).map(Nt)}var ae=class{static collect(t,r){let n=b(t);if(!n)return this.emptyMetrics(t,r);let o=se(t,500,0),a=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,i=new Set,l=0,d=0;for(let p of o)p.type==="tool_call"&&p.toolName&&i.add(p.toolName),p.type==="error"&&l++,p.type==="approval_request"&&d++;let u={taskId:t,goalId:r,timestamp:Date.now(),durationMs:a,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:i.size,errorCount:l,approvalCount:d,rawScore:0,isComplete:n.status==="completed"};return u.rawScore=this.computeRawScore(u),u}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),a=1-Math.min(t.costUsd/5,1),l=1-Math.min(t.turns/50,1),d;t.toolCount>=3&&t.toolCount<=15?d=1:t.toolCount<3?d=t.toolCount/3:d=Math.max(0,1-(t.toolCount-15)/15);let u=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),p=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*a+.2*l+.1*d+.15*u+.05*p}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};M();function jt(e){return{id:e.id,strategyId:e.strategy_id,goalId:e.goal_id,taskId:e.task_id??void 0,reward:e.reward??void 0,metricL2Score:e.metric_l2_score??void 0,metricL3Score:e.metric_l3_score??void 0,context:e.context??void 0,completedAt:e.completed_at}}function tt(e){f().prepare(`
|
|
36
|
-
INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
|
|
37
|
-
metric_l2_score, metric_l3_score, context, completed_at)
|
|
38
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
39
|
-
`).run(e.id,e.strategyId,e.goalId,e.taskId??null,e.reward??null,e.metricL2Score??null,e.metricL3Score??null,e.context??null,e.completedAt)}function rt(e,t=100){return f().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(jt)}var ie=class{static collect(t){let r=I(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),o=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,a=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),i=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-i/r.budgetUsd):1,d=this.calculateExpectedCompletion(r),u={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:a,budgetRemainingPct:l,expectedCompletionPct:d,rawScore:0};return u.rawScore=this.computeRawScore(u),u}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let o=t.budgetRemainingPct;return .5*r+.3*n+.2*o}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,o=r-t.createdAt;if(n<=0)return 0;let a=o/n;if(a<.1)return .5;let i=t.targetValue>0?t.currentValue/t.targetValue:0;return a>0?i/a:0}static calculateBudgetSpent(t){let r=rt(t,1e3),n=0,o=new Set;for(let a of r)if(a.taskId&&!o.has(a.taskId)){o.add(a.taskId);let i=b(a.taskId);i?.costUsd&&(n+=i.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};var Ot=y("agent"),G=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await oe(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!o)throw new Error("Failed to parse LLM Judge response as JSON");let a=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,a.score??0)),confidence:Math.max(.3,Math.min(.95,a.confidence??.5)),reasoning:a.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,o=this.cache.get(n);if(o&&Date.now()-o.evaluatedAt<this.CACHE_TTL)return o;let a=b(t);if(!a){let g={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,g),g}let i=this.getPromptTemplate(a.prompt??"",a.result??a.error??"",r),l,d,u;try{let g=await this.callClaude(i);l=g.score,d=g.confidence,u=g.reasoning}catch(g){Ot.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),a.status==="failed"?(l=.1,d=.6,u=`Task failed: ${a.error??"unknown error"} (heuristic fallback)`):a.status==="completed"&&a.result?(l=.7,d=.5,u="Task completed with result (heuristic fallback due to API error)"):a.status==="completed"?(l=.5,d=.4,u="Task completed without explicit result (heuristic fallback)"):(l=.3,d=.3,u=`Task in status: ${a.status} (heuristic fallback)`)}let p={taskId:t,criteria:r,score:l,confidence:d,reasoning:u,evaluatedAt:Date.now()};return this.cache.set(n,p),p}static shouldUseObjective(t){let r=b(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
|
|
40
|
-
|
|
41
|
-
Task: ${t}
|
|
42
|
-
Result: ${r}
|
|
43
|
-
Criteria: ${n}
|
|
44
|
-
|
|
45
|
-
Provide:
|
|
46
|
-
1. Score (0-1): How well did the task meet the criteria?
|
|
47
|
-
2. Confidence (0-1): How confident are you in this evaluation?
|
|
48
|
-
3. Reasoning: Brief explanation of your scoring
|
|
49
|
-
|
|
50
|
-
Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var Ft={L0:.2,L1:.15,L2:.35,L3:.3},le=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let o=n.parentId,a=this.children.get(o)??[];a.push(n),this.children.set(o,a)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=Ke(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,o)=>o.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let o=0,a=0;for(let i of n){let l=r.get(i.id)??0,d=i.weight*i.calibrationFactor;o+=l*d,a+=d}return a>0?o/a:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(Ft)){let a=this.aggregateScores(n,t);r+=a*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};var jn=y("agent");function ce(e,t){let r=Date.now(),n=le.buildFromGoal(e),o=new Map,a=ie.collect(e);for(let d of n.queryPath("L0"))o.set(d.id,a.rawScore);let i=$t(n);if(t){let d=ae.collect(t,e);if(d.isComplete){for(let p of n.queryPath("L3"))o.set(p.id,d.rawScore);let u=n.getNodeCount()>0?n.getWeightedScore(o):Math.max(0,Math.min(1,d.rawScore*.65+a.rawScore*.35));return{goalId:e,taskId:t,reward:u,breakdown:{L0:a.rawScore,L1:0,L2:0,L3:d.rawScore},calibrationFactors:i,source:"objective",confidence:.9,computedAt:r}}}if(t&&!G.shouldUseObjective(t)){let u=G.evaluate(t,"general_quality"),p=a.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:a.rawScore,breakdown:{L0:a.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:i,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):a.rawScore;return{goalId:e,reward:l,breakdown:{L0:a.rawScore,L1:0,L2:0,L3:0},calibrationFactors:i,source:"fallback",confidence:.3,computedAt:r}}function $t(e){let t={L0:1,L1:1,L2:1,L3:1};for(let r of["L0","L1","L2","L3"]){let n=e.queryPath(r);n.length>0&&(t[r]=n[0].calibrationFactor)}return t}import{v4 as it}from"uuid";M();function ye(e){return{id:e.id,roleId:e.role_id,taskType:e.task_type,name:e.name,promptTemplate:e.prompt_template,alpha:e.alpha,beta:e.beta,totalTrials:e.total_trials,avgReward:e.avg_reward??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0}}function nt(e){f().prepare(`
|
|
51
|
-
INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
|
|
52
|
-
alpha, beta, total_trials, avg_reward, created_at, updated_at)
|
|
53
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
54
|
-
`).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function ot(e){let r=f().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?ye(r):void 0}function st(e){return f().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(ye)}function P(e,t){return f().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(ye)}function at(e,t){f().prepare(`
|
|
55
|
-
UPDATE strategies
|
|
56
|
-
SET alpha = alpha + ?,
|
|
57
|
-
beta = beta + ?,
|
|
58
|
-
total_trials = total_trials + 1,
|
|
59
|
-
avg_reward = CASE
|
|
60
|
-
WHEN total_trials = 0 THEN ?
|
|
61
|
-
ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
|
|
62
|
-
END,
|
|
63
|
-
updated_at = ?
|
|
64
|
-
WHERE id = ?
|
|
65
|
-
`).run(t,1-t,t,t,Date.now(),e)}var V=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),o=this.sampleGamma(r,1);return n/(n+o)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,o=1/Math.sqrt(9*n);for(;;){let a,i;do a=this.randn(),i=1+o*a;while(i<=0);i=i*i*i;let l=Math.random();if(l<1-.0331*a*a*a*a||Math.log(l)<.5*a*a+n*(1-i+Math.log(i)))return n*i/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let o of t){let a=this.sampleBeta(o.alpha,o.beta);a>n&&(n=a,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let a=0;a<r;a++){let i=this.sample(t);i&&n.set(i.id,(n.get(i.id)||0)+1)}let o=new Map;for(let[a,i]of n)o.set(a,i/r);return o}};var Ut=5,ve=20,lt=.5,w=class{static selectStrategy(t,r){let n=P(t,r);return V.sample(n)}static recordTrial(t,r,n,o,a,i,l){at(t,o),tt({id:it(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:a,metricL3Score:i,context:l,completedAt:Date.now()})}static getStrategies(t,r){return P(t,r)}static getStrategyById(t){return ot(t)}static getPopulationStats(t,r){let n=P(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let a=n.reduce((d,u)=>d+u.totalTrials,0)/n.length,i=n.filter(d=>d.avgReward!==void 0).map(d=>d.avgReward),l=i.length>0?i.reduce((d,u)=>d+u,0)/i.length:0;return{count:n.length,avgTrials:a,avgReward:l,minTrials:Math.min(...n.map(d=>d.totalTrials)),maxTrials:Math.max(...n.map(d=>d.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Ut?!0:n.count<ve&&n.maxTrials>0}static addStrategy(t,r,n,o){if(P(t,r).length>=ve)throw new Error(`Strategy population at maximum (${ve}) for ${t}/${r}`);let i={id:`strat-${it().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:lt,beta:lt,totalTrials:0,createdAt:Date.now()};return nt(i),i}static getTopStrategies(t,r,n=3){let a=P(t,r).filter(i=>i.totalTrials>0);return a.sort((i,l)=>(l.avgReward??0)-(i.avgReward??0)),a.slice(0,n)}static getSamplingProbabilities(t,r){let n=P(t,r);return V.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,a,i){let l=ce(r,n);return this.recordTrial(t,r,n,l.reward,o,a,i),l.reward}};var Gt=3,Vt=2,de=class{static async generateVariants(t,r,n=Gt,o=Vt){let a=w.getTopStrategies(t,r,n);if(a.length===0){let l=`baseline-${r}-v1`;return w.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let i=[];for(let l=0;l<o;l++){let d=a[0].totalTrials+l+1,u=`${r}-evolved-v${d}`,p=a[0].promptTemplate,g=this.mutateTemplate(p);w.addStrategy(t,r,u,g),i.push(u)}return i}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
|
|
66
|
-
|
|
67
|
-
## Core Focus
|
|
68
|
-
Complete tasks with high quality.
|
|
69
|
-
|
|
70
|
-
## Approach
|
|
71
|
-
1. Understand the task requirements thoroughly
|
|
72
|
-
2. Plan your approach before executing
|
|
73
|
-
3. Execute systematically, checking your work
|
|
74
|
-
4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
|
|
75
|
-
|
|
76
|
-
## Evolution
|
|
77
|
-
${n}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};function Jt(e,t){let r=0,n=0,o=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i],n+=e[i]*e[i],o+=t[i]*t[i];let a=Math.sqrt(n)*Math.sqrt(o);return a===0?0:r/a}async function we(e,t,r={}){let n=r.topK??10,o=r.hybridConfig??Ue,a;try{a=await De(t)}catch{return[]}let i=Ge(e,a,t,n*2,o),l=e?$e(e):Oe,d=i.map(p=>{let g=p.embedding?Jt(a,p.embedding):0,S=Fe(p.createdAt,g,p.importance,l);return{...p,score:S}});d.sort((p,g)=>g.score-p.score);let u=d.slice(0,n);for(let p of u)Ne(p.id);return u}async function Qn(e,t,r=5){try{let n=await we(t,e,{topK:r});return n.length===0?"":`[Memory Context \u2014 retrieved from prior interactions]
|
|
78
|
-
${n.map(a=>`- ${a.content}`).join(`
|
|
79
|
-
`)}
|
|
80
|
-
|
|
81
|
-
[User Request]
|
|
82
|
-
`}catch{return""}}import{v4 as v}from"uuid";Re();import{spawnSync as pt}from"child_process";import{createRequire as Ht}from"module";import{dirname as Yt,join as mt}from"path";import{openSync as Kt,readFileSync as zt,unlinkSync as Qt}from"fs";var Xt=3e4,gt=12e4;function ft(){let t=Ht(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return mt(Yt(t),"cli.js")}function H(e,t){let r=ft(),n=t?.timeout??Xt;if(t?.json){let a=mt("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),i=Kt(a,"w");try{let l=pt("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",i,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return zt(a,"utf-8")}finally{try{Qt(a)}catch{}}}let o=pt("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(o.status!==0)throw new Error(o.stderr?.trim()||`CLI exited with status ${o.status}`);return o.stdout}function ht(){let e=H(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function Me(e,t="user",r){return H(["plugin","install",e,"--scope",t],{cwd:r,timeout:gt})}function Pe(e,t,r){return H(["plugin","uninstall",e],{cwd:r,timeout:gt})}function bt(e,t){return H(["plugin","enable",e])}function yt(e,t){return H(["plugin","disable",e])}function io(){try{return!!ft()}catch{return!1}}M();function vt(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function co(e){f().prepare(`
|
|
83
|
-
INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
|
|
84
|
-
deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
|
|
85
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
86
|
-
`).run(e.id,e.taskId,JSON.stringify(e.plan),e.status,e.approvalType??null,e.deviationReport?JSON.stringify(e.deviationReport):null,e.learnedRules?JSON.stringify(e.learnedRules):null,e.createdAt,e.approvedAt??null,e.reviewedAt??null)}function wt(e){let r=f().prepare("SELECT * FROM task_plans WHERE id = ?").get(e);return r?vt(r):void 0}function Ee(e){return f().prepare("SELECT * FROM task_plans WHERE task_id = ? ORDER BY created_at DESC").all(e).map(vt)}function St(e,t,r){let n=f(),o=Date.now();t==="approved"?n.prepare("UPDATE task_plans SET status = ?, approval_type = ?, approved_at = ? WHERE id = ?").run(t,r??null,o,e):n.prepare("UPDATE task_plans SET status = ? WHERE id = ?").run(t,e)}M();function er(e){return{id:e.id,roleId:e.role_id??void 0,taskPattern:e.task_pattern,maxRiskLevel:e.max_risk_level,createdAt:e.created_at,createdByTaskId:e.created_by_task_id??void 0}}var _t={low:1,medium:2,high:3};function Tt(e){f().prepare(`
|
|
87
|
-
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
88
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
89
|
-
`).run(e.id,e.roleId??null,e.taskPattern,e.maxRiskLevel,e.createdAt,e.createdByTaskId??null)}function mo(e,t,r){let o=f().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let a of o)if(!(a.role_id&&a.role_id!==e)&&!(_t[r]>_t[a.max_risk_level]))try{if(new RegExp(a.task_pattern,"i").test(t))return er(a)}catch{}}import*as It from"crypto";var Y=y("api"),K=class{cancelTask(t){let r=b(t);r&&(j(t,{status:"cancelled",completedAt:Date.now()}),ge.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),Y.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return Y.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let a=wt(t);if(!a)return Y.warn({planId:t},"Plan not found or already resolved"),!1;let i=b(a.taskId);return i?(St(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&Tt({id:It.randomUUID(),roleId:a.roleId,taskPattern:i.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:a.plan.overallRisk,createdAt:Date.now(),createdByTaskId:i.id}),ge.emit({type:"plan_approval_decision",taskId:i.id,planId:t,decision:r,approvalType:n,reason:o}),Y.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(Y.warn({planId:t},"Task not found for plan"),!1)}};var ue=y("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function A(e){let{listChannels:t}=await import("./channels-VNG7U6UQ.js"),r=t(),{listSessions:n}=await import("./session-manager-KO4CR3W6.js"),o=[...n("active"),...n("archived")],a=[];for(let i of e)if(i.type==="session"&&i.sessionId)a.push({type:"session",sessionId:i.sessionId});else if(i.type==="channel"){let l=i.channelId,d=i.chatId;if(!l&&i.channelName){let u=r.find(p=>p.name.toLowerCase().includes(i.channelName.toLowerCase()));u&&(l=u.id)}if(l&&!d){let u=o.find(p=>p.source.type==="channel"&&p.source.channelId===l&&p.source.chatId);u?.source.chatId?d=u.source.chatId:d=r.find(g=>g.id===l)?.config?.userId}l&&d?a.push({type:"channel",channelId:l,chatId:d}):ue.warn({channelName:i.channelName,channelId:l,chatId:d},"Could not resolve channel notify target")}return a}async function rr(e){let{listRoles:t}=await import("./roles-CMV5FMIA.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var nr={goalId:s.string()},or={goalId:s.string(),status:s.string().optional(),currentValue:s.number().optional(),budgetUsd:s.number().optional(),notes:s.string().optional()},sr={goalId:s.string(),goalDescription:s.string(),maxSubtasks:s.number().optional()},z=s.union([s.object({type:s.literal("session"),sessionId:s.string()}),s.object({type:s.literal("channel"),channelName:s.string()}),s.object({type:s.literal("channel"),channelId:s.string(),chatId:s.string().optional()})]),ar={prompt:s.string(),roleId:s.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:s.array(z).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:s.array(z).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:s.object({allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional()}).optional()},ir={taskId:s.string(),goalId:s.string().optional(),strategyId:s.string().optional()},lr={roleId:s.string(),taskType:s.string(),name:s.string().optional()},cr={status:s.string().optional(),limit:s.number().optional()},dr={taskId:s.string(),roleId:s.string()},ur={query:s.string(),roleId:s.string().optional(),topK:s.number().optional()},pr={taskId:s.string().optional(),status:s.string().optional(),limit:s.number().optional()},mr={roleId:s.string(),allowedPaths:s.array(s.string()).optional(),deniedPaths:s.array(s.string()).optional(),allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional(),additionalDirectories:s.array(s.object({path:s.string(),inheritPlugins:s.boolean().optional(),inheritMcp:s.boolean().optional(),inheritPermissions:s.boolean().optional()})).optional(),allowedChannels:s.array(s.string()).optional(),inheritUserSettings:s.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},gr={roleId:s.string().optional(),limit:s.number().optional()},fr={name:s.string(),cagPrompt:s.string(),traits:s.array(s.string()).optional(),allowedTools:s.array(s.string()).optional(),disallowedTools:s.array(s.string()).optional(),additionalDirectories:s.array(s.object({path:s.string(),inheritPlugins:s.boolean().optional(),inheritMcp:s.boolean().optional(),inheritPermissions:s.boolean().optional()})).optional()},hr={roleId:s.string(),reason:s.string().optional()},br={name:s.string(),description:s.string().optional(),roleId:s.string().optional(),metric:s.string().optional(),targetValue:s.number().optional(),deadline:s.number().optional(),budgetUsd:s.number().optional(),deliverTo:s.array(z).optional().describe("Where to deliver goal completion notifications.")},yr={name:s.string(),description:s.string().optional(),triggerType:s.enum(["cron","event"]),triggerCron:s.string().optional(),triggerEvent:s.string().optional(),prompt:s.string(),roleId:s.string().optional(),enabled:s.boolean().optional(),goalIds:s.array(s.string()).optional(),notifyTargets:s.array(s.union([s.object({type:s.literal("session"),sessionId:s.string()}),s.object({type:s.literal("channel"),channelId:s.string(),chatId:s.string().optional()})])).optional()},vr={status:s.enum(["active","retired","probation"]).optional(),limit:s.number().optional()},wr={enabled:s.boolean().optional()},Sr={},_r={},kt=new Map,Tr={prompt:s.string().describe("The task prompt to execute after the delay"),delayMinutes:s.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:s.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:s.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:s.array(z).optional().describe("Where to deliver the task output (result full text)."),reportTo:s.array(z).optional().describe("Where to send status reports (completion summary).")},Ir={roleId:s.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},kr={roleId:s.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:s.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Rr={roleId:s.string().describe("Role ID to uninstall the plugin from."),pluginId:s.string().describe("Plugin ID to uninstall.")},Mr={roleId:s.string().describe("Role ID to bind the MCP server to."),mcpName:s.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:s.record(s.string(),s.unknown()).describe("MCP server configuration object.")},Pr={roleId:s.string().describe("Role ID to unbind the MCP server from."),mcpName:s.string().describe("Name of the MCP server to remove.")},Er={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Lr={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},xr={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Ar={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},Cr={},Dr={},Nr={pluginId:s.string().describe("Plugin ID (e.g., 'github@anthropic').")},jr={roleId:s.string().describe("Role ID to associate scanned plugins with."),path:s.string().describe("Directory path to scan for .claude/settings.json.")},Or={taskId:s.string().describe("Task ID to cancel.")},Fr={taskId:s.string().describe("Task ID to get logs for."),limit:s.number().optional().describe("Max log entries (default 20).")},$r={roleId:s.string().describe("Role ID to delete.")},Ur={},Gr={updates:s.record(s.string(),s.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},Vr={roleId:s.string().describe("Role ID to list memories for."),limit:s.number().optional().describe("Max results (default 20).")},Jr={templateId:s.string().describe("Template ID to update."),name:s.string().optional(),enabled:s.boolean().optional(),prompt:s.string().optional(),triggerCron:s.string().optional(),triggerEvent:s.string().optional(),roleId:s.string().optional()},Wr={templateId:s.string().describe("Template ID to delete.")},Br={templateId:s.string().describe("Template ID to run immediately.")},qr={enabled:s.boolean().optional().describe("Filter by enabled status.")},Hr={eventType:s.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:s.string().describe("Channel ID to deliver to."),format:s.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:s.record(s.string(),s.unknown()).optional().describe("JSON match criteria for event fields."),enabled:s.boolean().optional().describe("Enable this rule immediately (default true).")},Yr={ruleId:s.string().describe("Delivery rule ID to delete.")},Kr={roleId:s.string().optional().describe("Role ID to filter strategies by.")},Rt=[m("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.",nr,async e=>{let t=I(e.goalId);if(!t)return c({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return c({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})}),m("update_goal_state","Update a goal's status, current value, or budget.",or,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(),ne(e.goalId,t)),c({success:!0})}),m("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",sr,async e=>{let t=_(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),a=`Decompose this goal into ${r} actionable subtasks.
|
|
90
|
-
|
|
91
|
-
Goal: ${e.goalDescription}
|
|
92
|
-
|
|
93
|
-
Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
|
|
94
|
-
|
|
95
|
-
Rules:
|
|
96
|
-
- Each subtask must be independently executable
|
|
97
|
-
- Order from foundational to dependent
|
|
98
|
-
- Be specific about what each subtask should accomplish
|
|
99
|
-
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,i=o({prompt:a,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let u of i){let p=u;p.type==="result"&&typeof p.result=="string"&&(l=p.result)}let d=l.match(/\[[\s\S]*\]/);if(d){let u=JSON.parse(d[0]),p=[];for(let g=0;g<Math.min(u.length,r);g++){let S=u[g],Q=`subtask-${v().slice(0,8)}`,C=S.role,D=C?await rr(C):void 0;N({id:Q,status:"pending",prompt:S.prompt,parentId:e.goalId,roleId:D,config:t.defaults,createdAt:Date.now()}),p.push({id:Q,description:S.description,prompt:S.prompt,dependencies:g>0?[p[g-1].id]:[],estimatedComplexity:S.complexity??"medium",role:C})}if(p.length>0)return c({subtasks:p})}}catch(o){ue.error({error:o},"LLM decomposition failed, using fallback")}let n=[];for(let o=0;o<r;o++){let a=`subtask-${v().slice(0,8)}`,i=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
|
|
100
|
-
|
|
101
|
-
Subtask ${o+1}/${r}`;N({id:a,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:a,description:i,prompt:l,dependencies:o>0?[n[o-1].id]:[],estimatedComplexity:"medium"})}return c({subtasks:n})}),m("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass notifyTargets with channelName to deliver results to a channel when the task completes.",ar,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let D=F("active",20,0).filter(k=>k.source!=="system").map(k=>({id:k.id,name:k.name,allowedTools:k.allowedTools??[]}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:D})}let r=v(),n=_(),o=e.prompt.toLowerCase(),a={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},i="general";for(let[D,k]of Object.entries(a))if(k.some(Mt=>o.includes(Mt))){i=D;break}let l,d=e.prompt,u=w.selectStrategy(e.roleId,i);u?.promptTemplate&&(d=`${u.promptTemplate}
|
|
102
|
-
|
|
103
|
-
## Task
|
|
104
|
-
${e.prompt}`,l=u.id);let p=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(p=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:p,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},S=e.deliverTo?await A(e.deliverTo):void 0,Q=e.reportTo?await A(e.reportTo):void 0;N({id:r,status:"pending",prompt:d,roleId:e.roleId,deliverTo:S,reportTo:Q,config:g,createdAt:Date.now()});let{serverBus:C}=await import("./server-bus-N5LCY73J.js");return C.emit({type:"task_created",taskId:r}),c({taskId:r,roleId:e.roleId,strategyId:l})}),m("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",ir,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=ce(t??"",r);return n&&t&&w.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),c({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)}`})}),m("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",lr,async e=>{let{roleId:t,taskType:r}=e;await de.generateVariants(t,r,3,1);let n=w.getStrategies(t,r),o=n[n.length-1];return c(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),m("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.",cr,async e=>{let t=e.status;return c(He(t,e.limit??10,0))}),m("delete_goal","Delete a goal by ID.",{goalId:s.string()},async e=>I(e.goalId)?(Ye(e.goalId),c({success:!0,goalId:e.goalId})):c({error:"Goal not found"})),m("pause_goal","Pause an active goal.",{goalId:s.string()},async e=>I(e.goalId)?(ne(e.goalId,{status:"paused",updatedAt:Date.now()}),c({success:!0,goalId:e.goalId,status:"paused"})):c({error:"Goal not found"})),m("assign_role","Assign a role to a pending task.",dr,async e=>{let{taskId:t,roleId:r}=e;if(!b(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(j(t,{roleId:r}),ue.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),c({success:!0,taskId:t,roleId:r})):c({error:`Role not found: ${r}`})}),m("search_memories","Search agent memory using hybrid vector + keyword search.",ur,async e=>{let t=e.topK??5,r=await we(e.roleId,e.query,{topK:t});return c({results:r})}),m("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.",pr,async e=>{if(e.taskId){let r=b(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(L(t,e.limit??100,0))}),m("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",mr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),e.allowedPaths||e.deniedPaths){let n=t.preferences??{},o=n.permissions??{};r.preferences={...n,permissions:{...o,allowedPaths:e.allowedPaths??o.allowedPaths,deniedPaths:e.deniedPaths??o.deniedPaths}}}return O(e.roleId,r),c({success:!0})}),m("view_audit_log","View the evolution audit log for role changes.",gr,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-MDA2ZVJW.js"),r=t(e.limit??50);return c({entries:r})}),m("list_roles","List all roles with their capabilities. Use this to discover available roles before dispatching tasks.",vr,async e=>{let r=F(e.status,e.limit??50,0).map(n=>({id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,100)+(n.cagPrompt.length>100?"...":"")}));return c({roles:r})}),m("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",fr,async e=>{let t=`role-${v().slice(0,8)}`,r={id:t,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${v().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,additionalDirectories:e.additionalDirectories};return xe(r),Z(r),c({roleId:t,name:e.name,allowedTools:e.allowedTools,additionalDirectories:e.additionalDirectories??[]})}),m("retire_role","Retire a role (marks as retired, stops receiving tasks).",hr,async e=>T(e.roleId)?(O(e.roleId,{status:"retired"}),ue.info({roleId:e.roleId,reason:e.reason},"Role retired"),c({success:!0})):c({error:`Role not found: ${e.roleId}`})),m("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",br,async e=>{let t=v(),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 A(e.deliverTo):void 0};re(o),et(t,o.metricType);let a=I(t);return c({goalId:a.id,name:a.name,status:a.status})}),m("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",yr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-AKQB7RRB.js"),r=v(),n=v(),o={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,notifyTargets:e.notifyTargets};return t(o),c({templateId:r,name:o.name,trigger:o.trigger})}),m("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:s.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:s.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-AKQB7RRB.js"),r=t(e.enabled,e.limit??50,0);return c(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})))}),m("send_to_channel","Send a message to a connected channel by name. Use this to deliver task results or notifications to a specific channel (e.g., WeChat on iPad).",{channelName:s.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:s.string().describe("The message content to send")},async e=>{let t=await A([{type:"channel",channelName:e.channelName}]);if(t.length===0)return c({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return c({error:"Resolved target is not a channel"});let{getChannelManager:n}=await import("./channels-CNLMTKHM.js"),o=n();if(!o)return c({error:"ChannelManager not available"});let a=await o.sendMessage(r.channelId,r.chatId,{content:e.message});return c({success:!!a,channelName:e.channelName})}),m("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.",wr,async e=>{let t=fe(e.enabled),r=[...he("active"),...he("archived")],n=t.map(o=>{let a,i=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return i?.source.chatId?a=i.source.chatId:a=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:a}});return c({channels:n})}),m("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.",Sr,async()=>{let e=_(),t=L("running"),r=L("pending");return c({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),m("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.",Tr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let l=F("active",20,0).filter(d=>d.source!=="system").map(d=>({id:d.id,name:d.name,allowedTools:d.allowedTools??[]}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:l})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return c({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=e.delayMinutes*60*1e3;else if(e.runAt!==void 0){let l=new Date(e.runAt).getTime();if(isNaN(l))return c({error:"Invalid ISO 8601 timestamp in runAt"});n=l-r}else return c({error:"Provide either delayMinutes or runAt"});if(n<=0)return c({error:"Delay must be greater than zero"});let o=10080*60*1e3;if(n>o)return c({error:"Delay exceeds maximum of 7 days"});let a=v(),i=setTimeout(async()=>{let l=v(),d=e.deliverTo?await A(e.deliverTo):void 0,u=e.reportTo?await A(e.reportTo):void 0;N({id:l,status:"pending",prompt:e.prompt,roleId:e.roleId,deliverTo:d,reportTo:u,config:{..._().defaults},createdAt:Date.now()});let{serverBus:p}=await import("./server-bus-N5LCY73J.js");p.emit({type:"task_created",taskId:l}),kt.delete(a)},n);return kt.set(a,i),c({scheduleId:a,executeAt:new Date(r+n).toISOString(),prompt:e.prompt})}),m("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.",Ir,async e=>{let t=B(),r=q(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(ee(),R(me)),{getRole:a}=(X(),R(pe)),{listInstalledPlugins:i}=(Re(),R(ut)),l=a(e.roleId);if(!l)return[];let d=o(l.name);return i({scope:"project",projectPath:d}).map(u=>u.id)})():[];return c({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}))})}),m("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",kr,async e=>{let{getRole:t}=(X(),R(pe)),{getRoleWorkspacePath:r}=(ee(),R(me)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Me(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(a){return c({error:`Failed to install plugin: ${a}`})}}),m("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Rr,async e=>{let{getRole:t}=(X(),R(pe)),{getRoleWorkspacePath:r}=(ee(),R(me)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Pe(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(a){return c({error:`Failed to uninstall plugin: ${a}`})}}),m("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Mr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return O(e.roleId,{mcpServers:n}),Z(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return c({error:`Failed to bind MCP server: ${o}`})}}),m("unbind_mcp_from_role","Remove an MCP server binding from a role.",Pr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return c({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return O(e.roleId,{mcpServers:r}),Z(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return c({error:`Failed to unbind MCP server: ${n}`})}}),m("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",_r,async()=>{let{listTaskTemplates:e}=await import("./task-templates-AKQB7RRB.js"),t=_(),r=F(void 0,100,0),n=fe(),o=e(!0,100,0),a=L("running"),i=L("pending");return c({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, and learned rules",active:r.filter(l=>l.status==="active"&&l.source!=="system").map(l=>({name:l.name,tools:l.allowedTools??[],mcpServers:Object.keys(l.mcpServers??{}),channels:l.allowedChannels??[]})),retired:r.filter(l=>l.status==="retired").length,probation:r.filter(l=>l.status==="probation").length},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(l=>l.enabled).map(l=>({name:l.name,platform:l.platform,status:l.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:q().filter(l=>l.enabled).map(l=>({name:l.name,scope:l.scope,description:l.version?`v${l.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(l=>({name:l.name,trigger:l.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:a.length,queued:i.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"]})}),m("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",Er,async e=>{try{return bt(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to enable plugin: ${t}`})}}),m("disable_plugin","Disable a globally installed plugin (removes it from all roles).",Lr,async e=>{try{return yt(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to disable plugin: ${t}`})}}),m("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",xr,async e=>{try{return Me(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return c({error:`Failed to install plugin: ${t}`})}}),m("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",Ar,async e=>{try{return Pe(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to uninstall plugin: ${t}`})}}),m("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",Cr,async()=>{try{let e=ht(),t=q();return c({available:e,installed:t})}catch(e){return c({error:`Failed to browse marketplace: ${e}`})}}),m("list_marketplace_sources","List configured plugin marketplace sources.",Dr,async()=>{let e=Ie();return c({sources:e})}),m("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Nr,async e=>{let t=Te(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=_e(t.installPath);return c({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),m("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",jr,async e=>{let{getRole:t}=await import("./roles-CMV5FMIA.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=ke(e.path);return c({roleId:e.roleId,path:e.path,config:n})}catch(n){return c({error:`Failed to scan directory: ${n}`})}}),m("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",Or,async e=>{let t=b(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;j(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-N5LCY73J.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),c({success:!0,taskId:e.taskId,status:"cancelled"})}),m("view_task_logs","Retrieve step-by-step execution logs for a task.",Fr,async e=>{let t=se(e.taskId,e.limit??20);return c({taskId:e.taskId,count:t.length,logs:t})}),m("delete_role","Delete a role by ID. This removes the role and its workspace.",$r,async e=>T(e.roleId)?(Ae(e.roleId),c({success:!0,roleId:e.roleId})):c({error:`Role not found: ${e.roleId}`})),m("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",Ur,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-772O2XKZ.js"),r=_(),n={};try{let l=_().server?.port??7100,d=await fetch(`http://127.0.0.1:${l}/config`);d.ok&&(n=await d.json())}catch{}let o=[...e,...t],a=[...t],i={};for(let l of o){let d=l.split("."),u=r;for(let p of d)if(u&&typeof u=="object")u=u[p];else{u=void 0;break}i[l]={value:u,mutable:!t.includes(l)}}return c({config:i,mutable:[...e],restartRequired:[...t]})}),m("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Gr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-772O2XKZ.js"),r=Le(e.updates);if(e.updates["logging.level"]&&Ce(e.updates["logging.level"]),r.updated.length>0){let{serverBus:n}=await import("./server-bus-N5LCY73J.js");n.emit({type:"config_changed",changes:r.updated.map(o=>({path:o,value:e.updates[o]}))})}return c(r)}),m("list_memories","List memories stored under a specific role.",Vr,async e=>{let t=je(e.roleId,e.limit??20);return c({roleId:e.roleId,count:t.length,memories:t})}),m("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",Jr,async e=>{let t=te(e.templateId);if(!t)return c({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){let n=t.steps?.length?[...t.steps]:[];n.length===0?n.push({id:v(),prompt:e.prompt}):n[0]={...n[0],prompt:e.prompt},r.steps=n}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(r.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(r.rolePreference=e.roleId),Ve(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),m("delete_template","Delete a task template by ID.",Wr,async e=>te(e.templateId)?(Je(e.templateId),c({success:!0,templateId:e.templateId})):c({error:`Template not found: ${e.templateId}`})),m("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Br,async e=>{let t=te(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});try{let r=_().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?c({success:!0,templateId:e.templateId,templateName:t.name,response:o}):c({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return c({error:`Failed to trigger template: ${r}`})}}),m("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",qr,async e=>{let t=be(e.enabled);return c({count:t.length,rules:t})}),m("create_delivery_rule","Create a new delivery rule for event-driven result routing.",Hr,async e=>{let t=v(),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 We(r),c({success:!0,ruleId:t,rule:r})}),m("delete_delivery_rule","Delete a delivery rule by ID.",Yr,async e=>be().find(n=>n.id===e.ruleId)?(Be(e.ruleId),c({success:!0,ruleId:e.ruleId})):c({error:`Delivery rule not found: ${e.ruleId}`})),m("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",Kr,async e=>{let t;if(e.roleId)t=st(e.roleId);else{let{getDb:r}=await import("./db-ZDEA7EUY.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 c({roleId:e.roleId??null,count:t.length,strategies:t})}),m("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:s.string(),operationId:s.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:s.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=Ee(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new K().resolvePlanApproval(r.id,"allow",e.scope),c({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):c({error:"No pending operation found for this task"})}),m("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:s.string(),operationId:s.string().optional(),reason:s.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=Ee(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new K().resolvePlanApproval(r.id,"deny","once",e.reason),c({success:!0,operationId:r.id,decision:"deny"})):c({error:"No pending operation found for this task"})})];function qo(){return Rt.map(e=>e.name).sort().join(",")}function Ho(){return tr({name:"adam-tools",version:"1.0.0",tools:Rt})}export{gn as a,se as b,co as c,Ee as d,St as e,mo as f,K as g,B as h,_e as i,q as j,Te as k,qt as l,Ie as m,ke as n,Re as o,we as p,Qn as q,re as r,I as s,ne as t,He as u,Ye as v,oe as w,dn as x,un as y,et as z,st as A,w as B,ht as C,Me as D,Pe as E,bt as F,yt as G,io as H,qo as I,Ho as J};
|
package/dist/chunk-CV3ROBUM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as i}from"./chunk-ZN5Q3YET.js";import{d as a}from"./chunk-5BAD3NCT.js";import{e as l,f as m}from"./chunk-F2IS5LWD.js";m();import{readFileSync as C,existsSync as h}from"fs";import{resolve as v}from"path";import{homedir as y}from"os";import{parse as w}from"yaml";function A(r){return r.replace(/\$\{(\w+)}/g,(e,t)=>process.env[t]??"")}function p(r){return r.startsWith("~/")?v(y(),r.slice(2)):r}function f(r){if(typeof r=="string")return A(r);if(Array.isArray(r))return r.map(f);if(r!==null&&typeof r=="object"){let e={};for(let[t,n]of Object.entries(r))e[t]=f(n);return e}return r}function d(r,e){let t={...r};for(let n of Object.keys(e)){let o=e[n],s=r[n];o!==null&&typeof o=="object"&&!Array.isArray(o)&&s!==null&&typeof s=="object"&&!Array.isArray(s)?t[n]=d(s,o):t[n]=o}return t}function k(r){return r.defaults.fileAccess.allowedPaths=r.defaults.fileAccess.allowedPaths.map(p),r.defaults.fileAccess.deniedPaths=r.defaults.fileAccess.deniedPaths.map(p),r}function R(){let r={};for(let e of process.argv.slice(2)){let t=e.match(/^--([a-z-]+)=(.+)$/);t&&(r[t[1]]=t[2])}return r}function P(r){let e=process.env.ADAM_PORT;e&&(r.server.port=parseInt(e,10));let t=process.env.ANTHROPIC_MODEL;t&&(r.defaults.model=t);let n=process.env.ADAM_API_KEY;return n&&(r.server.apiKey=n),r}function O(r){let e=R();return e.port&&(r.server.port=parseInt(e.port,10)),e.host&&(r.server.host=e.host),e.timeout&&(r.defaults.timeout=parseInt(e.timeout,10)),e["api-key"]&&(r.server.apiKey=e["api-key"]),r}function u(r){let e=r??l,t={};if(h(e)){let g=C(e,"utf-8"),c=w(g);c&&(t=f(c))}let n=d(i,t),o=P(n),s=O(o);return k(s)}function L(){try{return a().defaults}catch{return u().defaults}}function M(){try{return a().chat??i.chat}catch{return i.chat}}export{u as a,L as b,M as c};
|
package/dist/chunk-FUBKGVWI.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{c as o,f as m}from"./chunk-F2IS5LWD.js";import{c as R,e as g}from"./chunk-FCV2DPZQ.js";var y={};g(y,{ensureRoleWorkspace:()=>f,getRoleWorkspacePath:()=>c,syncRoleSettings:()=>d,writeRoleCLAUDEmd:()=>l});import{mkdirSync as i,writeFileSync as u}from"fs";import{join as r}from"path";function c(e){return r(p,"roles",e)}function f(e){let n=c(e.name);return i(n,{recursive:!0}),i(r(n,".claude"),{recursive:!0}),l(n,e),d(e.id,e.allowedTools,n),n}function l(e,n){let s=n.learnedRules&&n.learnedRules.length>0?n.learnedRules.map(a=>`- ${a}`).join(`
|
|
2
|
-
`):"(no learned rules yet)",t=`# ${n.name}
|
|
3
|
-
|
|
4
|
-
${n.cagPrompt}
|
|
5
|
-
|
|
6
|
-
## Learned Rules
|
|
7
|
-
${s}
|
|
8
|
-
`;u(r(e,"CLAUDE.md"),t,"utf-8")}function d(e,n,s){let t={};n&&(t.allowedTools=n),u(r(s,".claude","settings.json"),JSON.stringify(t,null,2),"utf-8")}var p,v=R(()=>{"use strict";m();p=process.env.ADAM_TEST_DIR||o});export{c as a,f as b,l as c,d,y as e,v as f};
|