adam-agent-server 0.5.0 → 1.0.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 +2 -4
- package/dist/App-SCPYTYGQ.js +9 -0
- package/dist/adam-tools-FNJJT7AA.js +1 -0
- package/dist/{approval-handler-HK7GQPHU.js → approval-handler-UDWAC5MF.js} +2 -2
- package/dist/audit-manager-SCX53YJT.js +1 -0
- package/dist/bree-engine-2DB2QECM.js +1 -0
- package/dist/channels-NAPXRIOX.js +1 -0
- package/dist/channels-PQCV74ZI.js +1 -0
- package/dist/{chunk-2GXYBWLS.js → chunk-2C5U3CNX.js} +1 -1
- package/dist/chunk-2CMR5AG7.js +1 -0
- package/dist/chunk-35DBEYMG.js +49 -0
- package/dist/chunk-3TIHZZMK.js +1 -0
- package/dist/{chunk-VF6GJGD6.js → chunk-42RHY3Q3.js} +1 -1
- package/dist/{chunk-742NWPTQ.js → chunk-4TBGFHYX.js} +1 -1
- package/dist/chunk-5V36ACKZ.js +1 -0
- package/dist/{chunk-PQ7KPALO.js → chunk-64FIXWFL.js} +1 -1
- package/dist/chunk-6KLG4APZ.js +1 -0
- package/dist/chunk-6VPL5CXB.js +4 -0
- package/dist/{chunk-T7WVM27S.js → chunk-7KCBFM2C.js} +6 -6
- package/dist/chunk-BCELBB5Q.js +3 -0
- package/dist/{chunk-5ASEAZCR.js → chunk-BONI2HUN.js} +1 -1
- package/dist/chunk-CFTWJZVX.js +67 -0
- package/dist/{chunk-PCSZW2PE.js → chunk-CREHL4BN.js} +7 -7
- package/dist/chunk-FXFHGIY6.js +8 -0
- package/dist/{chunk-KICPHTI2.js → chunk-GA7GEIXB.js} +1 -1
- package/dist/{chunk-HAWA62R2.js → chunk-I5RUEOSQ.js} +1 -1
- package/dist/chunk-INNDBLZE.js +1 -0
- package/dist/chunk-IZQI6QQ7.js +1 -0
- package/dist/{chunk-WXN3PSVX.js → chunk-KHPXEUSY.js} +1 -1
- package/dist/{chunk-IXF3XBGX.js → chunk-NFSXJNPD.js} +1 -1
- package/dist/chunk-NQHTOFQP.js +1 -0
- package/dist/{chunk-B6S2AEOD.js → chunk-PT55643Q.js} +1 -1
- package/dist/chunk-QC6QVNKP.js +83 -0
- package/dist/chunk-QMKQBU3R.js +2 -0
- package/dist/chunk-REKCZ3GY.js +1 -0
- package/dist/{chunk-L7426WNY.js → chunk-ROSOI75V.js} +1 -1
- package/dist/{chunk-FDWW245P.js → chunk-TEMWI6U5.js} +1 -1
- package/dist/{chunk-U36NBCR3.js → chunk-U3XVAAXA.js} +1 -1
- package/dist/chunk-VRP4LTHY.js +1 -0
- package/dist/chunk-WBAPIPST.js +1 -0
- package/dist/{chunk-AXMXXUPO.js → chunk-X26NKAXY.js} +1 -1
- package/dist/{chunk-TN6H2WM2.js → chunk-XFTRKHH2.js} +3 -3
- package/dist/{chunk-FUGJMHY4.js → chunk-YEV5YTS3.js} +1 -1
- package/dist/cli.js +4 -4
- package/dist/config-L4R273R3.js +1 -0
- package/dist/config-N2GMLTPU.js +1 -0
- package/dist/db-S6HDMJ3B.js +1 -0
- package/dist/delivery-log-VAI35G5V.js +1 -0
- package/dist/engine-E67UAI3G.js +1 -0
- package/dist/evolution-audit-KCFDGNSM.js +1 -0
- package/dist/external-api-I6CENLIS.js +1 -0
- package/dist/index.js +12 -57
- package/dist/learner-ABYVK33T.js +1 -0
- package/dist/logger-QCJUU7GV.js +1 -0
- package/dist/memories-3ZAV55YZ.js +1 -0
- package/dist/{memory-extractor-GOISDQTO.js → memory-extractor-BHHKD7X7.js} +2 -2
- package/dist/memory-service-5QHTKIUU.js +1 -0
- package/dist/outbound-gateway-ZFKSN2UT.js +1 -0
- package/dist/role-presets-OTU2M37Y.js +1 -0
- package/dist/roles-LXRHEVUK.js +1 -0
- package/dist/{runtime-6UTYEONR.js → runtime-UCOE6LNN.js} +1 -1
- package/dist/session-manager-RPXFZKMY.js +1 -0
- package/dist/task-templates-XQNKAA4U.js +1 -0
- package/package.json +1 -1
- package/web/dist/assets/{ChannelDetail-dZfZlLgQ.js → ChannelDetail-BajTUEU0.js} +1 -1
- package/web/dist/assets/{Channels-Cw04c7YJ.js → Channels-Bhy6rP_t.js} +1 -1
- package/web/dist/assets/{Chat-D4PHqHPE.js → Chat-Dvt_Oo7d.js} +1 -1
- package/web/dist/assets/{Dashboard-BFewwmAg.js → Dashboard-DlrAor-C.js} +1 -1
- package/web/dist/assets/{Evolution-DY1OC6Oc.js → Evolution-Dlsnnr4G.js} +1 -1
- package/web/dist/assets/{GoalDetail-DZIEpHs2.js → GoalDetail-BuUxwYdd.js} +1 -1
- package/web/dist/assets/{Goals-COCCVLnp.js → Goals-CkPQOev6.js} +1 -1
- package/web/dist/assets/{Logs-DsDeimLt.js → Logs-D33PqDAd.js} +1 -1
- package/web/dist/assets/{Memories-D5IEEI1u.js → Memories-D31dbUM6.js} +1 -1
- package/web/dist/assets/{Plugins-DUwZVjPc.js → Plugins-XlBr07x8.js} +1 -1
- package/web/dist/assets/RoleDetail-rZFlgXzh.js +33 -0
- package/web/dist/assets/{Roles-JeVjD0Ew.js → Roles-d29AC6Kh.js} +1 -1
- package/web/dist/assets/Settings-Bjh_RXYf.js +1 -0
- package/web/dist/assets/{Strategies-KAmpqrcQ.js → Strategies-Cf4ghknk.js} +1 -1
- package/web/dist/assets/{Switch-Jpdn6Yux.js → Switch-CxzUYL49.js} +1 -1
- package/web/dist/assets/{TaskDetail-C4NpqwNT.js → TaskDetail-jMBJbaRU.js} +1 -1
- package/web/dist/assets/{Work-DhaxNYnd.js → Work-CCLTkitf.js} +1 -1
- package/web/dist/assets/index-CVubgAlC.css +2 -0
- package/web/dist/assets/{index-CfKqiQIe.js → index-Ds41VvOC.js} +2 -2
- package/web/dist/index.html +2 -2
- package/dist/App-XZABZ2AF.js +0 -9
- package/dist/adam-tools-BB7WQGVT.js +0 -1
- package/dist/bree-engine-25VACELK.js +0 -1
- package/dist/channels-JEBBMFUQ.js +0 -1
- package/dist/channels-VEUBY2NZ.js +0 -1
- package/dist/chunk-3DAK2XWP.js +0 -1
- package/dist/chunk-5JLMSNIW.js +0 -1
- package/dist/chunk-7SPKRIMZ.js +0 -15
- package/dist/chunk-BREBCBG4.js +0 -49
- package/dist/chunk-D6WM2OQS.js +0 -86
- package/dist/chunk-DWMMWYLD.js +0 -1
- package/dist/chunk-ETQ7KC73.js +0 -1
- package/dist/chunk-FYDFMYUP.js +0 -1
- package/dist/chunk-JXD6ZPV7.js +0 -2
- package/dist/chunk-NSJAV7IH.js +0 -1
- package/dist/chunk-NXTTKAQX.js +0 -3
- package/dist/chunk-SFUS33SO.js +0 -1
- package/dist/chunk-T25NLVMY.js +0 -1
- package/dist/chunk-URW2DJQF.js +0 -1
- package/dist/chunk-WZOMGJSY.js +0 -1
- package/dist/chunk-XNWZZYAV.js +0 -7
- package/dist/config-WHXCZCI4.js +0 -1
- package/dist/config-Y4QWELO3.js +0 -1
- package/dist/db-PNZ3UJOE.js +0 -1
- package/dist/delivery-log-VYTYUFCK.js +0 -1
- package/dist/engine-3PNNEZNK.js +0 -1
- package/dist/evolution-audit-B7WKMOVR.js +0 -1
- package/dist/external-api-XGEOKAWR.js +0 -1
- package/dist/learner-VMD5NQCD.js +0 -1
- package/dist/logger-BEG4WFIM.js +0 -1
- package/dist/memories-EFQ4SFZG.js +0 -1
- package/dist/memory-service-BKLZIRK6.js +0 -1
- package/dist/monitor-K7CGTLA6.js +0 -1
- package/dist/outbound-gateway-DZTXBUTP.js +0 -1
- package/dist/role-presets-FN2RWUCP.js +0 -1
- package/dist/roles-SG2YAR64.js +0 -1
- package/dist/session-manager-45LFTPBA.js +0 -1
- package/dist/task-templates-7LSQ6OST.js +0 -1
- package/web/dist/assets/RoleDetail-B-GKMfMG.js +0 -33
- package/web/dist/assets/Settings-CvEyZp5t.js +0 -1
- package/web/dist/assets/index-LDFr0VVR.css +0 -2
package/README.md
CHANGED
|
@@ -182,10 +182,8 @@ defaults:
|
|
|
182
182
|
effort: high # low | medium | high | max
|
|
183
183
|
model: claude-sonnet-4-6
|
|
184
184
|
settingSources: ["user", "project"]
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
deniedPaths: ["~/.ssh", "~/.aws", "~/.config"]
|
|
188
|
-
approvalRequired: ["rm -rf", "git push", "git reset"]
|
|
185
|
+
deniedReadPaths: ["~/.ssh", "~/.aws", "~/.gnupg", "/etc/shadow"]
|
|
186
|
+
approvalRequired: ["rm -rf *", "git push*", "git reset*"]
|
|
189
187
|
approvalTimeout: 300
|
|
190
188
|
|
|
191
189
|
execution:
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{b as h,d as $t,e as bo}from"./chunk-VRP4LTHY.js";import{a as _t,f as ho,h as yo}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as Rt,Text as bt,useInput as Jn}from"ink";import{useState as Zn,useEffect as zt,useRef as xo}from"react";import{createContext as br,useContext as Sr,useReducer as Cr}from"react";import{jsx as Br}from"react/jsx-runtime";var vr={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,version:null};function wr(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};case"SET_VERSION":return{...e,version:t.version};default:return e}}var So=br(null);function Co({children:e}){let[t,o]=Cr(wr,vr);return Br(So.Provider,{value:{state:t,dispatch:o},children:e})}function ze(){let e=Sr(So);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as vo,useRef as wo}from"react";var Er=15e3;function Bo(){let{state:e,dispatch:t}=ze(),o=wo(null),c=wo(null);vo(()=>{c.current=e.session?.id??null},[e.session?.id]),vo(()=>{let u=!0,m=null,l=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{l(),o.current=setTimeout(()=>{u&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},Er)};return(()=>{try{m=new $t("/events"),m.on("task_status_change",()=>{}),m.on("approval_request",r=>{if(!u)return;let a=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:a.taskId,approvalId:a.approvalId,toolName:a.toolName,toolInput:a.toolInput,matchedPattern:a.matchedPattern}})}),m.on("plan_approval_request",r=>{if(!u)return;let a=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:a.taskId,planId:a.planId,roleId:a.roleId,plan:a.plan}})}),m.on("plan_approval_decision",()=>{u&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),m.on("config_changed",()=>{u&&t({type:"CONFIG_CHANGED"})}),m.on("execution_task_start",r=>{if(!u)return;let a=r,d=c.current;d&&(async()=>{try{let C=await h(`/tasks/${a.taskId}`);u&&C.sourceSessionId===d&&t({type:"SET_ACTIVE_TASK",taskId:a.taskId})}catch{}})()}),m.on("stats_update",r=>{if(!u)return;let a=r;t({type:"UPDATE_STATS",activeTasks:a.activeTasks,queuedTasks:a.queuedTasks,costToday:a.totalCostToday})}),m.connect().then(async()=>{if(u){l(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let r=await h("/version");t({type:"SET_VERSION",version:r.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{u&&(t({type:"SET_CONNECTED",connected:!1}),i())})}catch{u&&(t({type:"SET_CONNECTED",connected:!1}),i())}})(),()=>{u=!1,l(),m?.close()}},[t])}import{useEffect as Ir,useRef as kr,useState as Eo,useCallback as Pr}from"react";function Io(e){let[t,o]=Eo([]),[c,u]=Eo(!1),m=kr(null),l=Pr(()=>{o([]),u(!1)},[]);return Ir(()=>{if(!e)return;let i=!0;o([]),u(!0);try{let s=new bo(e);return m.current=s,s.on("reasoning",r=>{if(!i)return;let d=r.content??"";o(C=>{let f=C[C.length-1];if(f?.type==="reasoning"){let y=[...C];return y[y.length-1]={...f,content:f.content+d},y}return[...C,{type:"reasoning",content:d,timestamp:Date.now()}]})}),s.on("tool_call",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_call",content:a.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:a.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_result",content:a.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"error",content:a.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"complete",content:a.result??"",timestamp:Date.now(),metadata:{cost:a.costUsd,turns:a.numTurns,duration:a.totalDurationMs}}]),u(!1)}),s.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),u(!1))}),()=>{i=!1,s.close()}}catch{u(!1)}},[e]),{events:t,isStreaming:c,clearEvents:l}}import{useState as Zt,useEffect as Ar,useCallback as vt}from"react";function eo(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function ko(){let[e,t]=Zt(null),[o,c]=Zt(!0),[u,m]=Zt(null),l=vt(async()=>{try{let C=(await h("/chat/sessions?status=active")).sessions.find(f=>f.source.type==="tui");return C?eo(C):null}catch{return null}},[]),i=vt(async()=>{try{let d=await h("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),C=eo(d.session);return t(C),C}catch{return m("Failed to create session"),null}},[]),s=vt(async d=>{try{let C=await h("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(f=>f&&{...f,messageCount:f.messageCount+1,lastActiveAt:Date.now()}),C}catch{return null}},[]),r=vt(async()=>{if(!e)return!1;try{return await h(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),a=vt(async()=>{if(e)try{let d=await h(`/chat/sessions/${e.id}`);t(eo(d.session))}catch{t(null)}},[e]);return Ar(()=>{let d=!1;async function C(){c(!0);let f=await l();d||(f?t(f):await i(),d||c(!1))}return C(),()=>{d=!0}},[]),{session:e,loading:o,error:u,sendMessage:s,createNewSession:i,archiveCurrentSession:r,refreshSession:a,setSession:t}}import{useEffect as Po,useRef as Dr,useState as Rr}from"react";function Ao(e){let[t,o]=Rr(null),c=Dr(new Set);return Po(()=>{if(!e)return;let u=!0,m=null;try{m=new $t("/chat/stream"),m.on("chat_message",l=>{if(!u)return;let s=l.message;s&&s.sessionId===e&&s.role==="assistant"&&(c.current.has(s.id)||(c.current.add(s.id),o(s)))}),m.connect().catch(()=>{})}catch{}return()=>{u=!1,m?.close()}},[e]),Po(()=>{c.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as oo,Text as Be}from"ink";import we from"chalk";var to={connected:we.green,disconnected:we.red,warning:we.yellow,reasoning:we.gray,toolCall:we.blue,toolResult:we.green,error:we.red,dim:we.dim,bold:we.bold,statusUp:we.green("\u25CF"),statusDown:we.red("\u25CF")};import{Fragment as Mr,jsx as ot,jsxs as Ye}from"react/jsx-runtime";function Do(){let{state:e}=ze(),t=e.connected?`${to.statusUp} Server: up`:`${to.statusDown} Disconnected`,o=e.activeTasks>0?`${e.activeTasks} running, ${e.queuedTasks} queued`:"No active tasks",c=e.session,m=(c?Math.floor((Date.now()-c.lastActiveAt)/6e4):1/0)>=25;return Ye(oo,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[Ye(oo,{children:[ot(Be,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),ot(Be,{children:" \u2502 "}),ot(Be,{children:t}),ot(Be,{children:" \u2502 "}),Ye(Be,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&Ye(Mr,{children:[ot(Be,{children:" \u2502 "}),Ye(Be,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),m&&ot(Be,{color:"yellow",children:" timeout soon"})]})]}),Ye(oo,{children:[Ye(Be,{children:["Tasks: ",o]}),ot(Be,{children:" \u2502 "}),Ye(Be,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Ot,Text as Vt,useInput as Lr}from"ink";import{useState as no,useMemo as _r}from"react";import $r from"ink-text-input";var Nr=[{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 ro(e){let t=e.toLowerCase();return Nr.filter(o=>o.name.startsWith(t))}function Ro(e){let t=ro(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as qt,jsxs as wt}from"react/jsx-runtime";function Mo({onSubmit:e}){let[t,o]=no(""),[c,u]=no(0),[m,l]=no(!1),i=t.startsWith("/")&&t.length>=1,s=t.slice(1),r=_r(()=>i?ro(s):[],[i,s]),a=f=>{o(f),f.startsWith("/")?(l(!0),u(0)):l(!1)},d=()=>{let f=t.trim();if(f){if(f.startsWith("/")){let y=f.slice(1),n=Ro(y);e(n?`/${n.name}`:f)}else e(f);o(""),l(!1)}},C=f=>{e(`/${f.name}`),o(""),l(!1)};return Lr((f,y)=>{if(!(!m||!i||r.length===0)){if(y.upArrow){u(n=>n<=0?r.length-1:n-1);return}if(y.downArrow){u(n=>n>=r.length-1?0:n+1);return}if(y.tab){let n=r[c];n&&C(n);return}if(y.escape){l(!1),o("");return}}},{isActive:m&&i&&r.length>0}),wt(Ot,{flexDirection:"column",children:[m&&i&&r.length>0&&qt(Ot,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((f,y)=>{let n=y===c;return wt(Ot,{children:[qt(Vt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),wt(Vt,{color:n?"cyan":"white",bold:n,children:["/",f.name]}),wt(Vt,{dimColor:!0,children:[" \u2014 ",f.description]})]},f.name)})}),wt(Ot,{borderStyle:"round",borderDimColor:!0,children:[qt(Vt,{bold:!0,children:"\u25B8 "}),qt($r,{value:t,onChange:a,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as lt,Text as ge}from"ink";import{useState as Or}from"react";import{jsx as be,jsxs as Me}from"react/jsx-runtime";function Vr({content:e}){let[t,o]=Or(!1),c=e.split(`
|
|
2
|
+
`);return c.length<=5?be(ge,{color:"green",children:e}):t?be(ge,{color:"green",children:e}):Me(ge,{color:"green",children:[c.slice(0,3).join(`
|
|
3
|
+
`),`
|
|
4
|
+
`,Me(ge,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function qr({event:e}){switch(e.type){case"reasoning":return be(lt,{children:be(ge,{color:"gray",children:e.content})});case"tool_call":return be(lt,{children:Me(ge,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Me(lt,{flexDirection:"column",children:[be(ge,{color:"blue",dimColor:!0,children:"[result]"}),be(Vr,{content:e.content})]});case"error":return be(lt,{children:Me(ge,{color:"red",children:["[error] ",e.content]})});case"complete":return Me(lt,{flexDirection:"column",marginTop:1,children:[e.content&&be(ge,{children:e.content}),be(ge,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Me(ge,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Me(ge,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Me(ge,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function No({events:e,isStreaming:t}){return e.length===0&&!t?null:Me(lt,{flexDirection:"column",children:[t&&e.length===0&&be(ge,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>be(qr,{event:o},c))]})}import{Box as Lo,Text as _o}from"ink";import{jsx as so,jsxs as Fr}from"react/jsx-runtime";function $o({messages:e}){return e.length===0?null:so(Lo,{flexDirection:"column",children:e.map((t,o)=>Fr(Lo,{flexDirection:"column",marginBottom:1,children:[so(_o,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),so(_o,{children:t.content})]},o))})}import{Box as Bt,Text as Ne,useInput as Ur}from"ink";import{jsx as Le,jsxs as Et}from"react/jsx-runtime";function Oo({approval:e,onResolved:t}){return Ur(o=>{o==="a"?h(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&h(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Et(Bt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Le(Ne,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Et(Bt,{marginTop:1,children:[Le(Ne,{children:"Tool: "}),Le(Ne,{bold:!0,children:e.toolName})]}),Et(Bt,{children:[Le(Ne,{children:"Input: "}),Le(Ne,{children:JSON.stringify(e.toolInput)})]}),Et(Bt,{children:[Le(Ne,{children:"Pattern: "}),Le(Ne,{dimColor:!0,children:e.matchedPattern})]}),Et(Bt,{marginTop:1,children:[Le(Ne,{color:"green",children:"[a] Approve"}),Le(Ne,{children:" "}),Le(Ne,{color:"red",children:"[r] Reject"})]})]})}import{Box as It,Text as ce,useInput as Wr}from"ink";import{useState as Gr,useEffect as Hr}from"react";import{jsx as qe,jsxs as Ee}from"react/jsx-runtime";var jr=300;function Vo({approval:e,onResolved:t,onTimeout:o}){let[c,u]=Gr(jr);Hr(()=>{let l=setInterval(()=>{u(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),Wr(l=>{l==="a"?h(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?h(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&h(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let m=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Ee(It,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[qe(ce,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Ee(ce,{dimColor:!0,children:["Plan ID: ",e.planId]}),Ee(ce,{dimColor:!0,children:["Time remaining: ",c,"s"]}),Ee(It,{marginTop:1,children:[qe(ce,{children:"Overall Risk: "}),qe(ce,{bold:!0,color:m,children:e.plan.overallRisk.toUpperCase()})]}),Ee(ce,{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(It,{paddingLeft:2,children:[Ee(ce,{children:["[",l.index,"] "]}),qe(ce,{children:l.description}),Ee(ce,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),Ee(ce,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),Ee(It,{marginTop:1,children:[qe(ce,{dimColor:!0,children:"Permissions: "}),qe(ce,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Ee(It,{marginTop:1,children:[qe(ce,{color:"green",children:"[a] Allow once "}),qe(ce,{color:"green",children:"[p] Allow permanent "}),qe(ce,{color:"red",children:"[r] Deny"})]})]})}import{Box as rt,Text as Z,useInput as Xr}from"ink";import{useEffect as zr,useState as Fe,useCallback as Fo}from"react";import{Box as z,Text as N,useInput as Kr}from"ink";import{useState as io,useEffect as Qr}from"react";import{jsx as q,jsxs as W}from"react/jsx-runtime";function qo({taskId:e,onBack:t}){let[o,c]=io(null),[u,m]=io([]),[l,i]=io(null);if(Qr(()=>{h(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),h(`/tasks/${e}/plan`).then(r=>m(r.plans)).catch(()=>m([]))},[e]),Kr((r,a)=>{(r==="b"||a.escape)&&t()}),l)return W(z,{flexDirection:"column",children:[W(N,{color:"red",children:["Error: ",l]}),q(N,{dimColor:!0,children:"[b] Back"})]});if(!o)return W(N,{dimColor:!0,children:["Loading task ",e,"..."]});let s=u[0];return W(z,{flexDirection:"column",children:[q(N,{bold:!0,color:"cyan",children:"Task Detail"}),W(z,{marginTop:1,flexDirection:"column",children:[W(z,{children:[q(N,{children:"ID: "}),q(N,{dimColor:!0,children:String(o.id)})]}),W(z,{children:[q(N,{children:"Status: "}),q(N,{bold:!0,children:String(o.status)})]}),W(z,{children:[q(N,{children:"Prompt: "}),q(N,{children:String(o.prompt)})]}),o.result?W(z,{children:[q(N,{children:"Result: "}),q(N,{children:String(o.result).slice(0,200)})]}):null,o.error?W(z,{children:[q(N,{color:"red",children:"Error: "}),q(N,{children:String(o.error)})]}):null,o.deliverTo?.length?W(z,{children:[q(N,{children:"DeliverTo: "}),q(N,{dimColor:!0,children:o.deliverTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null,o.reportTo?.length?W(z,{children:[q(N,{children:"ReportTo: "}),q(N,{dimColor:!0,children:o.reportTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null]}),s&&W(z,{marginTop:1,flexDirection:"column",children:[q(N,{bold:!0,color:"cyan",children:"Execution Plan"}),W(z,{children:[q(N,{children:"Plan ID: "}),q(N,{dimColor:!0,children:s.id})]}),W(z,{children:[q(N,{children:"Status: "}),q(N,{children:s.status})]}),s.plan.overallRisk&&W(z,{children:[q(N,{children:"Overall Risk: "}),q(N,{bold:!0,color:s.plan.overallRisk==="high"?"red":s.plan.overallRisk==="medium"?"yellow":"green",children:s.plan.overallRisk.toUpperCase()})]}),W(N,{bold:!0,children:["Steps (",s.plan.steps.length,"):"]}),s.plan.steps.map(r=>{let a=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return W(z,{paddingLeft:2,children:[W(N,{children:["[",r.index,"] ",r.description]}),W(N,{color:a,children:[" [",r.riskLevel,"]"]})]},r.index)}),s.deviationReport&&W(z,{marginTop:1,flexDirection:"column",children:[q(N,{bold:!0,color:"yellow",children:"Deviation Report"}),W(N,{children:["Planned: ",s.deviationReport.stepsPlanned," | Executed: ",s.deviationReport.stepsExecuted," | Accuracy: ",(s.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),s.deviationReport.deviations.map((r,a)=>W(z,{paddingLeft:2,children:[W(N,{color:"yellow",children:["[",r.deviationType,"] "]}),W(N,{children:["Step ",r.stepIndex,": ",r.actual]})]},a))]}),s.learnedRules&&s.learnedRules.length>0&&W(z,{marginTop:1,flexDirection:"column",children:[q(N,{bold:!0,color:"blue",children:"Learned Rules"}),s.learnedRules.map((r,a)=>q(z,{paddingLeft:2,children:W(N,{children:["* ",r]})},a))]})]}),!s&&u.length===0&&q(z,{marginTop:1,children:q(N,{dimColor:!0,children:"No execution plan for this task."})}),q(z,{marginTop:1,children:q(N,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as Zr,jsx as de,jsxs as xe}from"react/jsx-runtime";var Yr={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Ft=["all","pending","queued","running","completed","failed","cancelled"],ao=15;function Ut({onBack:e}){let[t,o]=Fe([]),[c,u]=Fe(!0),[m,l]=Fe("list"),[i,s]=Fe(0),[r,a]=Fe("all"),[d,C]=Fe(0),[f,y]=Fe(0),[n,g]=Fe(null),[_,A]=Fe([]),K=Fo(async()=>{u(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let w=await h(`/tasks?${I}`);o(w.tasks)}catch{o([])}finally{u(!1)}},[r]);zr(()=>{K()},[K]);let G=Math.max(1,Math.ceil(t.length/ao)),P=t.slice(f*ao,(f+1)*ao),oe=Fo(async()=>{let I=P[i];if(I)try{await h(`/tasks/${I.id}/cancel`,{method:"POST"}),g(`Cancelled: ${I.id.slice(0,8)}`),l("list"),K()}catch(w){g(`Failed: ${w instanceof Error?w.message:String(w)}`),l("list")}},[P,i,K]);return Xr((I,w)=>{if(m==="detail"){(w.escape||w.return||I==="q")&&l("list");return}if(m==="cancelling"){I==="y"?oe():l("list");return}if(m==="filter"){if(w.escape){l("list");return}w.upArrow&&d>0&&C(p=>p-1),w.downArrow&&d<Ft.length-1&&C(p=>p+1),w.return&&(a(Ft[d]),y(0),s(0),l("list"));return}if(w.escape||I==="q"){e();return}if(w.upArrow&&i>0&&s(p=>p-1),w.downArrow&&i<P.length-1&&s(p=>p+1),w.return){let p=P[i];p&&(A([]),l("detail"),h(`/tasks/${p.id}/logs?limit=20`).then(({logs:D})=>A(D)).catch(()=>A([])))}if(I==="x"&&P[i]){let p=P[i];["running","pending","queued","paused"].includes(p.status)?(l("cancelling"),g(null)):g(`Cannot cancel task in status: ${p.status}`)}I==="f"&&(C(Ft.indexOf(r)),l("filter")),I==="r"&&K(),(w.pageDown||I==="n")&&f<G-1&&(y(p=>p+1),s(0)),(w.pageUp||I==="p")&&f>0&&(y(p=>p-1),s(0))}),c?de(Z,{dimColor:!0,children:"Loading tasks..."}):m==="filter"?xe(rt,{flexDirection:"column",children:[de(Z,{bold:!0,children:"Filter by status:"}),Ft.map((I,w)=>de(rt,{children:xe(Z,{color:w===d?"cyan":"white",children:[w===d?"> ":" ",I,I===r?" (current)":""]})},I)),de(Z,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):m==="detail"&&P[i]?de(qo,{taskId:P[i].id,onBack:()=>l("list")}):m==="cancelling"&&P[i]?xe(rt,{flexDirection:"column",children:[xe(Z,{color:"red",children:['Cancel task "',P[i].id.slice(0,8),'"? (y/n)']}),n&&de(Z,{color:"red",children:n})]}):xe(rt,{flexDirection:"column",children:[xe(rt,{children:[xe(Z,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&xe(Z,{dimColor:!0,children:[" [filter: ",r,"]"]}),xe(Z,{dimColor:!0,children:[" \u2014 Page ",f+1,"/",G]})]}),n&&de(Z,{color:n.startsWith("Failed")||n.startsWith("Cannot")?"red":"green",children:n}),t.length===0?xe(Z,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):xe(Zr,{children:[de(rt,{marginTop:1,children:xe(Z,{bold:!0,children:[" ",Je("ID",10),Je("STATUS",12),Je("PROMPT",40),Je("DURATION",10),"COST"]})}),P.map((I,w)=>{let p=w===i,D=I.totalDurationMs?`${(I.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",$=I.costUsd!==void 0?`$${I.costUsd.toFixed(4)}`:"\u2014",Ve=Yr[I.status]??"white";return xe(rt,{children:[de(Z,{color:p?"cyan":"white",children:p?"> ":" "}),de(Z,{dimColor:!0,children:Je(I.id.slice(0,8),10)}),de(Z,{color:Ve,children:Je(I.status,12)}),de(Z,{children:Je(Jr(I.prompt,38),40)}),de(Z,{dimColor:!0,children:Je(D,10)}),de(Z,{dimColor:!0,children:$})]},I.id)})]}),de(Z,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function Je(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Jr(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}yo();import{Box as kt,Text as Ie,useInput as en}from"ink";import{useEffect as tn,useState as Uo}from"react";import{readFileSync as on,existsSync as rn}from"fs";import{parse as nn}from"yaml";import{Fragment as sn,jsx as ke,jsxs as Ze}from"react/jsx-runtime";function Go({onBack:e}){let[t,o]=Uo(null),[c,u]=Uo(null);return en((m,l)=>{(l.escape||m==="q")&&e()}),tn(()=>{try{let m=ho;if(!rn(m)){u(`Config file not found: ${m}`);return}let l=on(m,"utf-8");o(nn(l))}catch(m){u(m.message)}},[]),c?Ze(kt,{flexDirection:"column",children:[ke(Ie,{color:"red",children:c}),ke(Ie,{dimColor:!0,children:"Press Esc to go back"})]}):t?Ze(kt,{flexDirection:"column",children:[ke(Ie,{bold:!0,children:"Configuration (Esc to go back)"}),ke(kt,{marginTop:1,flexDirection:"column",children:ke(Ho,{obj:t,indent:0})})]}):ke(Ie,{dimColor:!0,children:"Loading config..."})}function Ho({obj:e,indent:t}){let o=" ".repeat(t);return ke(sn,{children:Object.entries(e).map(([c,u])=>u&&typeof u=="object"&&!Array.isArray(u)?Ze(kt,{flexDirection:"column",children:[Ze(Ie,{children:[o,ke(Ie,{color:"cyan",children:c}),":"]}),ke(Ho,{obj:u,indent:t+1})]},c):Array.isArray(u)?Ze(kt,{flexDirection:"column",children:[Ze(Ie,{children:[o,ke(Ie,{color:"cyan",children:c}),":"]}),u.map((m,l)=>Ze(Ie,{children:[o," - ",Wo(c,String(m))]},l))]},c):Ze(Ie,{children:[o,ke(Ie,{color:"cyan",children:c}),": ",Wo(c,String(u))]},c))})}function Wo(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as Wt,Text as Pe,useInput as an}from"ink";import{useEffect as ln,useState as lo}from"react";import{jsx as Pt,jsxs as _e}from"react/jsx-runtime";function jo({onBack:e}){let[t,o]=lo([]),[c,u]=lo(!0),[m,l]=lo(null);return an((i,s)=>{(s.escape||i==="q")&&e()}),ln(()=>{h("/evolution-audit?limit=20").then(i=>{o(i),u(!1)}).catch(i=>{l(i.message),u(!1)})},[]),c?Pt(Pe,{dimColor:!0,children:"Loading evolution log..."}):m?_e(Wt,{flexDirection:"column",children:[Pt(Pe,{color:"red",children:m}),Pt(Pe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?_e(Wt,{flexDirection:"column",children:[Pt(Pe,{dimColor:!0,children:"No evolution records yet"}),Pt(Pe,{dimColor:!0,children:"Press Esc to go back"})]}):_e(Wt,{flexDirection:"column",children:[_e(Pe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>_e(Wt,{flexDirection:"column",marginTop:1,children:[_e(Pe,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&_e(Pe,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
5
|
+
`).map((s,r)=>s.startsWith("+")?_e(Pe,{color:"green",children:[" ",s]},r):s.startsWith("-")?_e(Pe,{color:"red",children:[" ",s]},r):_e(Pe,{dimColor:!0,children:[" ",s]},r))]},i.id))]})}import{Box as Ue,Text as Y,useInput as cn}from"ink";import dn from"ink-text-input";import{useEffect as un,useState as ct}from"react";import{jsx as fe,jsxs as re}from"react/jsx-runtime";var mn={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function gn(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function fn(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function Gt({onBack:e}){let[t,o]=ct([]),[c,u]=ct(null),[m,l]=ct("list"),[i,s]=ct(""),[r,a]=ct(!1),[d,C]=ct(null);cn((n,g)=>{if(m==="create"){g.escape&&(l("list"),s(""),C(null));return}(g.escape||n==="q")&&e(),n==="c"&&(l("create"),C(null)),n==="r"&&f()});let f=()=>{h("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>u(n.message))};un(()=>{f()},[]);let y=async n=>{if(n.trim()){a(!0),C(null);try{let g=await h("/goals",{method:"POST",body:{input:n.trim()}});C(`Goal created: ${g.goal.name}`),s(""),l("list"),f()}catch(g){C(`Failed: ${g instanceof Error?g.message:String(g)}`)}finally{a(!1)}}};return c?re(Ue,{flexDirection:"column",children:[re(Y,{color:"red",children:["Failed to load goals: ",c]}),fe(Y,{dimColor:!0,children:"Press Esc or q to return"})]}):m==="create"?re(Ue,{flexDirection:"column",children:[fe(Y,{bold:!0,children:"Create Goal"}),fe(Y,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),re(Ue,{marginTop:1,children:[fe(Y,{color:"cyan",children:"> "}),fe(dn,{value:i,onChange:s,onSubmit:y})]}),r&&fe(Y,{color:"yellow",children:"Creating goal..."}),d&&fe(Y,{color:d.startsWith("Failed")?"red":"green",children:d}),fe(Y,{dimColor:!0,children:"Press Esc to cancel"})]}):re(Ue,{flexDirection:"column",children:[re(Y,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?fe(Y,{dimColor:!0,children:"No goals found. Press c to create one."}):fe(Ue,{marginTop:1,flexDirection:"column",children:t.map(n=>{let g=n.targetValue>0?n.currentValue/n.targetValue:0,_=mn[n.status]??"white";return re(Ue,{marginBottom:1,flexDirection:"column",children:[re(Ue,{children:[fe(Y,{bold:!0,color:_,children:n.name}),re(Y,{dimColor:!0,children:[" (",n.role,")"]}),fe(Y,{dimColor:!0,children:" \u2014 "}),fe(Y,{color:_,children:n.status})]}),re(Ue,{children:[re(Y,{dimColor:!0,children:[" ",gn(g)," "]}),re(Y,{color:g>=1?"green":"white",children:[Math.round(g*100),"%"]}),re(Y,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),re(Ue,{children:[re(Y,{dimColor:!0,children:[" \u23F0 ",fn(n.deadline)," left"]}),re(Y,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),re(Y,{dimColor:!0,children:[" | ID: ",n.id.slice(0,8)]})]})]},n.id)})}),fe(Y,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as dt,Text as Se,useInput as pn}from"ink";import{useEffect as xn,useState as Ko}from"react";import{jsx as Ge,jsxs as We}from"react/jsx-runtime";function Tn(e,t,o=15){let c=e/(e+t),u=Math.round(c*o);return"\u2593".repeat(u)+"\u2591".repeat(o-u)}function Qo({onBack:e}){let[t,o]=Ko([]),[c,u]=Ko(null);if(pn((l,i)=>{(i.escape||l==="q")&&e()}),xn(()=>{h("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>u(l.message))},[]),c)return We(dt,{flexDirection:"column",children:[We(Se,{color:"red",children:["Failed to load strategies: ",c]}),Ge(Se,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return We(dt,{flexDirection:"column",children:[Ge(Se,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Ge(Se,{dimColor:!0,children:"Press Esc or q to return"})]});let m=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,s=m.get(i)??[];s.push(l),m.set(i,s)}return We(dt,{flexDirection:"column",children:[Ge(Se,{bold:!0,children:"Strategy Lab"}),Ge(Se,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Ge(dt,{marginTop:1,flexDirection:"column",children:Array.from(m.entries()).map(([l,i])=>We(dt,{marginBottom:1,flexDirection:"column",children:[Ge(Se,{bold:!0,color:"cyan",children:l}),i.sort((s,r)=>{let a=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-a}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return We(dt,{children:[Ge(Se,{dimColor:!0,children:" "}),We(Se,{children:[Tn(s.alpha,s.beta)," "]}),We(Se,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),We(Se,{dimColor:!0,children:[" ",s.name," (\u03B1=",s.alpha.toFixed(1)," \u03B2=",s.beta.toFixed(1)," trials=",s.totalTrials,")"]})]},s.id)})]},l))}),Ge(Se,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as Te,Text as Q,useInput as Cn}from"ink";import co from"ink-text-input";import{useEffect as vn,useState as He,useCallback as ut}from"react";import{CronExpressionParser as wn}from"cron-parser";import{useState as hn,useEffect as yn,useCallback as Xo,useRef as bn}from"react";var Sn=3e3;function et(){let[e,t]=hn(null),o=bn(null),c=Xo(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),u=Xo((m,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:m,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},Sn))},[]);return yn(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:u,clearMessage:c}}import{jsx as X,jsxs as ae}from"react/jsx-runtime";var uo=["manual","cron","event"],Ht={name:"",triggerType:"manual",cron:"",stepPrompt:""};function Bn(e){try{return wn.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function Kt({onBack:e}){let[t,o]=He([]),[c,u]=He(!0),[m,l]=He(0),[i,s]=He("list"),[r,a]=He({...Ht}),[d,C]=He("name"),[f,y]=He(null),{message:n,setMessage:g,clearMessage:_}=et(),[A,K]=He(!1),[G,P]=He(!1),oe=ut(()=>{u(!0),h("/task-templates").then(({templates:v})=>{o(v),u(!1)}).catch(()=>u(!1))},[]);vn(()=>{oe()},[oe]);let I=i==="create"||i==="edit",w=ut(async()=>{let v=t[m];if(!(!v||A)){K(!0),g(`Triggering ${v.name}...`,"loading");try{let B=await h(`/task-templates/${v.id}/run`,{method:"POST"});g(`Triggered: ${v.name} (${B.executionId})`,"success")}catch(B){g(`Trigger failed: ${B instanceof Error?B.message:String(B)}`,"error")}finally{K(!1)}}},[t,m,A,g]),p=ut(async()=>{let v=t[m];if(!v||G)return;if(v.trigger?.type!=="cron"&&v.trigger?.type!=="event"){g("Toggle not applicable for manual triggers","error");return}let B=!v.enabled;P(!0),g(`${v.name} \u2192 ${B?"enabling":"disabling"}...`,"loading");try{await h(`/task-templates/${v.id}`,{method:"PATCH",body:{enabled:B}}),o(O=>O.map(se=>se.id===v.id?{...se,enabled:B}:se)),g(`${v.name} ${B?"enabled":"disabled"}`,"success")}catch(O){g(`Toggle failed: ${O instanceof Error?O.message:String(O)}`,"error")}finally{P(!1)}},[t,m,G,g]),D=ut(async()=>{let v=t[m];if(v)try{await h(`/task-templates/${v.id}`,{method:"DELETE"}),g(`Deleted: ${v.name}`,"success"),oe(),l(B=>Math.max(0,Math.min(B,t.length-2)))}catch(B){g(`Delete failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[t,m,oe]),$=ut(()=>{let v=t[m];v&&(y(v.id),a({name:v.name,triggerType:v.trigger?.type??"manual",cron:v.trigger?.cron??"",stepPrompt:v.steps?.[0]?.prompt??""}),C("name"),s("edit"))},[t,m]),Ve=ut(async()=>{let v={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 h("/task-templates",{method:"POST",body:v}),g(`Created: ${r.name}`,"success")):i==="edit"&&f&&(await h(`/task-templates/${f}`,{method:"PATCH",body:v}),g(`Updated: ${r.name}`,"success"))}catch(B){g(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}s("list"),a({...Ht}),y(null),oe()},[r,i,f,oe]);return Cn((v,B)=>{if(I){if(B.escape){s("list"),a({...Ht}),y(null);return}if(B.return){let O=["name","triggerType","cron","stepPrompt"],se=O.indexOf(d);if(se<O.length-1){let Xe=se+1;if(O[Xe]==="cron"&&r.triggerType!=="cron"&&Xe++,Xe<O.length){C(O[Xe]);return}}Ve();return}if(B.tab&&d==="triggerType"){a(O=>{let se=uo.indexOf(O.triggerType);return{...O,triggerType:uo[(se+1)%uo.length]}});return}return}if(B.escape||v==="q"){e();return}if(B.upArrow){l(O=>Math.max(0,O-1));return}if(B.downArrow){l(O=>Math.min(t.length-1,O+1));return}if(v==="t"){w();return}if(v==="d"){D();return}if(v==="e"){$();return}if(v==="c"){a({...Ht}),C("name"),s("create");return}if(v==="s"||v===" "){p();return}v==="r"&&(oe(),_())}),c?X(Q,{dimColor:!0,children:"Loading templates..."}):I?ae(Te,{flexDirection:"column",children:[ae(Q,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),ae(Te,{marginTop:1,flexDirection:"column",children:[ae(Te,{children:[ae(Q,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?X(co,{value:r.name,onChange:v=>a(B=>({...B,name:v})),placeholder:"template name"}):X(Q,{children:r.name||"(empty)"})]}),ae(Te,{children:[ae(Q,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),X(Q,{children:r.triggerType}),d==="triggerType"&&X(Q,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&ae(Te,{children:[ae(Q,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?X(co,{value:r.cron,onChange:v=>a(B=>({...B,cron:v})),placeholder:"*/5 * * * *"}):X(Q,{children:r.cron||"(empty)"})]}),ae(Te,{children:[ae(Q,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?X(co,{value:r.stepPrompt,onChange:v=>a(B=>({...B,stepPrompt:v})),placeholder:"What should this template do?"}):X(Q,{children:r.stepPrompt||"(empty)"})]})]}),X(Te,{marginTop:1,children:X(Q,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):ae(Te,{flexDirection:"column",children:[ae(Q,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&X(Te,{marginTop:1,children:ae(Q,{color:n.type==="success"?"green":n.type==="error"?"red":"gray",children:[n.type==="success"?"\u2713 ":n.type==="error"?"\u2717 ":"\u2192 ",n.text]})}),t.length===0?X(Te,{marginTop:1,children:X(Q,{dimColor:!0,children:"No templates found. Press c to create one."})}):X(Te,{marginTop:1,flexDirection:"column",children:t.map((v,B)=>{let O=B===m,se=v.trigger?.type==="cron"&&v.trigger?.cron?Bn(v.trigger.cron):"";return ae(Te,{children:[X(Q,{color:O?"cyan":void 0,bold:O,children:O?"> ":" "}),X(Q,{color:O?"cyan":void 0,bold:O,children:jt(v.name,24)}),X(Q,{dimColor:!0,children:jt(v.trigger?.type,10)}),v.trigger?.type!=="cron"&&v.trigger?.type!=="event"?X(Q,{dimColor:!0,children:jt("\u2014",6)}):X(Q,{color:v.enabled?"green":"gray",children:jt(v.enabled?"on":"off",6)}),se&&ae(Q,{dimColor:!0,children:["next: ",se]})]},v.id)})}),X(Te,{marginTop:1,children:X(Q,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function jt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as tt,Text as he,useInput as En}from"ink";import In from"ink-text-input";import{useEffect as kn,useState as mt,useCallback as zo}from"react";import{jsx as ue,jsxs as nt}from"react/jsx-runtime";function Yo({onBack:e}){let[t,o]=mt([]),[c,u]=mt(""),[m,l]=mt(!0),[i,s]=mt(!1),[r,a]=mt(""),[d,C]=mt(null),f=zo(()=>{l(!0),h("/webhooks").then(({webhooks:n,auth:g})=>{o(n),u(g),l(!1)}).catch(()=>l(!1))},[]);kn(()=>{f()},[f]);let y=zo(async n=>{if(n.trim())try{let g=await h(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});C(`Triggered: ${g.executionId}`)}catch(g){C(`Trigger failed: ${g instanceof Error?g.message:String(g)}`)}},[]);return En((n,g)=>{if(i){if(g.escape){s(!1),a("");return}if(g.return){y(r),s(!1),a("");return}return}if(g.escape||n==="q"){e();return}if(n==="t"){s(!0),a(""),C(null);return}n==="r"&&(f(),C(null))}),m?ue(he,{dimColor:!0,children:"Loading webhooks..."}):nt(tt,{flexDirection:"column",children:[nt(he,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),nt(he,{dimColor:!0,children:["Auth: ",c]}),d&&ue(tt,{marginTop:1,children:ue(he,{color:"yellow",children:d})}),i&&nt(tt,{marginTop:1,children:[ue(he,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ue(In,{value:r,onChange:a,placeholder:"webhook name or ID"}),ue(he,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ue(tt,{marginTop:1,children:ue(he,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):nt(tt,{marginTop:1,flexDirection:"column",children:[ue(tt,{children:nt(he,{bold:!0,children:[gt("NAME",24),gt("DESCRIPTION",36),gt("TRIGGER",28),"TAGS"]})}),t.map(n=>nt(tt,{children:[ue(he,{children:gt(n.displayName,24)}),ue(he,{dimColor:!0,children:gt(Pn(n.description??"",34),36)}),ue(he,{dimColor:!0,children:gt(n.trigger,28)}),ue(he,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),ue(tt,{marginTop:1,children:ue(he,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function gt(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 $e,Text as ee,useInput as An}from"ink";import Dn from"ink-text-input";import{useEffect as Jo,useState as je,useCallback as mo}from"react";import{jsx as te,jsxs as Ae}from"react/jsx-runtime";function Rn(e){return e>=4?"red":e===3?"yellow":"gray"}function Mn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function Nn(e){return new Date(e).toLocaleDateString()}function er({onBack:e}){let[t,o]=je([]),[c,u]=je(0),[m,l]=je([]),[i,s]=je(!0),[r,a]=je(!1),[d,C]=je(""),[f,y]=je("all"),[n,g]=je(null),[_,A]=je(!1),K=mo(()=>{h("/agents").then(({agents:p})=>{o(p),s(!1)}).catch(()=>s(!1))},[]);Jo(()=>{K()},[K]);let G=t[c],P=mo(()=>{G&&(A(!1),h(`/memories/${G.id}`).then(({memories:p})=>{l(p),g(null)}).catch(p=>g(`Failed: ${p instanceof Error?p.message:String(p)}`)))},[G]);Jo(()=>{G&&P()},[G,P]);let oe=mo(async p=>{if(!(!G||!p.trim()))try{let D=await h("/memories/query",{method:"POST",body:{agentId:G.id,prompt:p.trim()}});l(D.memories),A(!0),g(`Search: ${D.count} results`)}catch(D){g(`Search failed: ${D instanceof Error?D.message:String(D)}`)}},[G]),I=r,w=m.filter(p=>f==="all"?!0:f==="high"?p.importance>3:f==="medium"?p.importance===3:p.importance<3);return An((p,D)=>{if(I){if(D.escape){a(!1),C("");return}if(D.return){oe(d),a(!1),C("");return}return}if(D.escape||p==="q"){e();return}if(p==="a"){u($=>($+1)%Math.max(1,t.length));return}if(D.leftArrow){u($=>($-1+t.length)%Math.max(1,t.length));return}if(D.rightArrow){u($=>($+1)%Math.max(1,t.length));return}if(p==="s"){a(!0),C(""),g(null);return}if(p==="h"){y($=>$==="high"?"all":"high");return}if(p==="m"){y($=>$==="medium"?"all":"medium");return}if(p==="l"){y($=>$==="low"?"all":"low");return}p==="r"&&P()}),i?te(ee,{dimColor:!0,children:"Loading agents..."}):t.length===0?Ae($e,{flexDirection:"column",children:[te(ee,{dimColor:!0,children:"No agents found"}),te(ee,{dimColor:!0,children:"Press Esc to go back"})]}):Ae($e,{flexDirection:"column",children:[te(ee,{bold:!0,children:"Memories (Esc to go back)"}),Ae($e,{marginTop:1,children:[te(ee,{children:"Agent: "}),te(ee,{bold:!0,color:"cyan",children:G?.name??"?"}),Ae(ee,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),te($e,{children:Ae(ee,{dimColor:!0,children:["Filter: ",f==="all"?"all":f," | ",_?"search results":"all memories"," (",w.length,")"]})}),n&&te($e,{children:te(ee,{color:"yellow",children:n})}),r&&Ae($e,{marginTop:1,children:[te(ee,{bold:!0,color:"cyan",children:"Search: "}),te(Dn,{value:d,onChange:C,placeholder:"search query..."}),te(ee,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),w.length===0?te($e,{marginTop:1,children:Ae(ee,{dimColor:!0,children:["No memories",f!=="all"?` matching filter '${f}'`:""]})}):te($e,{marginTop:1,flexDirection:"column",children:w.map(p=>Ae($e,{marginBottom:0,children:[Ae(ee,{color:Rn(p.importance),bold:!0,children:[Mn(p.importance)," "]}),te(ee,{dimColor:!0,children:Zo(p.type??"?",12)}),te(ee,{dimColor:!0,children:Zo(`\xD7${p.retrievedCount??0}`,5)}),Ae(ee,{children:[Ln(p.content,55)," "]}),te(ee,{dimColor:!0,children:Nn(p.createdAt)}),p.score!==void 0&&Ae(ee,{dimColor:!0,children:[" (",p.score.toFixed(2),")"]})]},p.id))}),te($e,{marginTop:1,children:te(ee,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Zo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Ln(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as st,Text as ye,useInput as _n}from"ink";import $n from"ink-text-input";import{useState as Ke,useEffect as tr,useCallback as or}from"react";import{jsx as De,jsxs as Oe}from"react/jsx-runtime";var rr={Anthropic:["anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel"],Defaults:["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","defaults.approvalTimeout"],Server:["server.port","server.host","server.apiKey","server.timezone"],Logging:["logging.level"],Evolution:["roles.evolution.triggerEvery","roles.evolution.reflectionThreshold"],Chat:["chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory"]},On={"anthropic.apiKey":"API Key","anthropic.baseUrl":"Base URL","anthropic.model":"Model","anthropic.defaultOpusModel":"Default Opus","anthropic.defaultSonnetModel":"Default Sonnet","anthropic.defaultHaikuModel":"Default Haiku","anthropic.smallFastModel":"Small Fast","defaults.model":"Default Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","defaults.approvalTimeout":"Approval Timeout (sec)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","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 nr({onBack:e}){let{state:t}=ze(),[o,c]=Ke({}),[u,m]=Ke([]),[l,i]=Ke(null),[s,r]=Ke("view"),[a,d]=Ke(0),[C,f]=Ke(""),[y,n]=Ke(null),[g,_]=Ke(!1),[A,K]=Ke([]),G=Object.values(rr).flat(),P=or(()=>{h("/config").then(w=>{c(w.config),m(w.mutable)}).catch(w=>i(w.message)),h("/config/env-diff").then(w=>{K(w.diffs)}).catch(()=>{})},[]);tr(()=>{P()},[P]),tr(()=>{t.configVersion>0&&P()},[t.configVersion,P]);let oe=or(async()=>{let w=G[a];if(w){_(!0),n(null);try{let p=C,D=o[w];if(D&&typeof D.value=="number"&&(p=Number(C),isNaN(p))){n("Invalid number"),_(!1);return}let $=await h("/config",{method:"PATCH",body:{[w]:p}});$.updated.length>0&&(n(`Updated: ${w}`),P()),$.errors.length>0&&n($.errors[0]),r("view")}catch(p){n(`Failed: ${p instanceof Error?p.message:String(p)}`)}finally{_(!1)}}},[G,a,C,o,P]);if(_n((w,p)=>{if(s==="edit"){if(p.escape){r("view");return}return}if(p.escape||w==="q"){e();return}if(p.upArrow&&a>0&&d(D=>D-1),p.downArrow&&a<G.length-1&&d(D=>D+1),p.return||w==="e"){let D=G[a],$=o[D];$&&$.mutable?(f(String($.value??"")),r("edit"),n(null)):$&&!$.mutable&&n("This setting requires a restart to change")}w==="r"&&(P(),n("Refreshed")),w==="s"&&A.length>0&&h("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),K([]),P()}),w==="l"&&A.length>0&&h("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),P()})}),l)return Oe(st,{flexDirection:"column",children:[Oe(ye,{color:"red",children:["Failed to load config: ",l]}),De(ye,{dimColor:!0,children:"Press Esc or q to return"})]});let I=0;return Oe(st,{flexDirection:"column",children:[De(ye,{bold:!0,children:"Settings"}),y&&De(ye,{color:y.startsWith("Failed")||y.startsWith("This setting")?"yellow":"green",children:y}),A&&A.length>0&&Oe(st,{flexDirection:"column",marginBottom:1,children:[Oe(ye,{color:"yellow",children:[".env differs from DB (",A.length," key(s)): ",A.map(w=>w.envKey).join(", ")]}),De(ye,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),De(st,{marginTop:1,flexDirection:"column",children:Object.entries(rr).map(([w,p])=>Oe(st,{marginBottom:1,flexDirection:"column",children:[De(ye,{bold:!0,color:"cyan",children:w}),p.map(D=>{let $=o[D],v=I++===a,B=u.includes(D),O=On[D]??D,se=$?String($.value??""):"...";return s==="edit"&&v?Oe(st,{children:[Oe(ye,{color:"cyan",children:["> ",O,": "]}),De($n,{value:C,onChange:f,onSubmit:()=>{oe()}}),g&&De(ye,{color:"yellow",children:" saving..."})]},D):Oe(st,{children:[Oe(ye,{color:v?"cyan":"white",children:[v?"> ":" ",B?" ":"\u{1F512} ",O,": "," "]}),De(ye,{color:B?"white":"gray",children:se}),!B&&De(ye,{dimColor:!0,children:" (restart required)"})]},D)})]},w))}),De(ye,{dimColor:!0,children:"Enter/e:edit r:refresh Esc/q:back"})]})}import{Box as it,Text as me,useInput as Vn}from"ink";import{useEffect as qn,useState as go,useCallback as Fn}from"react";import{jsx as le,jsxs as pt}from"react/jsx-runtime";function sr({onBack:e}){let[t,o]=go([]),[c,u]=go(!0),[m,l]=go(0),{message:i,setMessage:s,clearMessage:r}=et(),a=Fn(()=>{u(!0),h("/plugins").then(({plugins:d})=>{o(d),u(!1)}).catch(()=>u(!1))},[]);return qn(()=>{a()},[a]),Vn((d,C)=>{if(C.escape||d==="q"){e();return}if(C.upArrow){l(f=>Math.max(0,f-1));return}if(C.downArrow){l(f=>Math.min(t.length-1,f+1));return}d==="r"&&(a(),r())}),c?le(me,{dimColor:!0,children:"Loading plugins..."}):pt(it,{flexDirection:"column",children:[pt(me,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&le(it,{marginTop:1,children:pt(me,{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?le(it,{marginTop:1,children:le(me,{dimColor:!0,children:"No plugins installed."})}):pt(it,{marginTop:1,flexDirection:"column",children:[pt(it,{children:[le(me,{dimColor:!0,children:" "}),le(me,{dimColor:!0,children:ft("Name",24)}),le(me,{dimColor:!0,children:ft("Scope",8)}),le(me,{dimColor:!0,children:ft("User",6)}),le(me,{dimColor:!0,children:"Path"})]}),t.map((d,C)=>{let f=C===m,y=d.id.split("@")[0];return pt(it,{children:[le(me,{color:f?"cyan":void 0,bold:f,children:f?"> ":" "}),le(me,{color:f?"cyan":void 0,bold:f,children:ft(y,24)}),le(me,{color:f?"cyan":void 0,bold:f,children:ft(d.scope,8)}),le(me,{color:d.globalEnabled?"green":"gray",children:ft(d.globalEnabled?"on":"off",6)}),le(me,{dimColor:!0,children:d.installPath})]},d.id)})]}),le(it,{marginTop:1,children:le(me,{dimColor:!0,children:"r:refresh"})})]})}function ft(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Qt,Text as ir,useInput as Un}from"ink";import{useState as Wn}from"react";import{jsx as xt,jsxs as fo}from"react/jsx-runtime";var Gn=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function ar({onBack:e}){let[t,o]=Wn("tasks");return Un((c,u)=>{if(u.escape||c==="q"){e();return}if(c==="1"){o("tasks");return}if(c==="2"){o("automations");return}if(c==="3"){o("goals");return}}),fo(Qt,{flexDirection:"column",children:[fo(Qt,{gap:1,marginBottom:1,children:[Gn.map(c=>{let u=t===c.id;return xt(Qt,{children:fo(ir,{color:u?"cyan":"gray",bold:u,underline:u,children:["[",c.key,":",c.label,"]"]})},c.id)}),xt(Qt,{flexGrow:1}),xt(ir,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&xt(Ut,{onBack:e}),t==="automations"&&xt(Kt,{onBack:e}),t==="goals"&&xt(Gt,{onBack:e})]})}import{Box as j,Text as F,useInput as Hn}from"ink";import{useEffect as jn,useState as At}from"react";import{jsx as R,jsxs as ne}from"react/jsx-runtime";var lr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function cr({onBack:e}){let[t,o]=At([]),[c,u]=At(!0),[m,l]=At(0),[i,s]=At(null),[r,a]=At("");jn(()=>{d()},[]);async function d(){try{let y=await h("/channels");o(y.channels)}catch{}u(!1)}async function C(y){if(t.find(g=>g.id===y)?.platform==="wechat")try{a("Starting WeChat QR login...");let g=await h(`/channels/${y}/wechat/qr-start`,{method:"POST"});if(g.qrcodeUrl){a(`Scan QR: ${g.qrcodeUrl}
|
|
6
|
+
Waiting for scan...`);let _=await h(`/channels/${y}/wechat/qr-wait`,{method:"POST",body:{sessionKey:g.sessionKey,timeoutMs:12e4}});a(_.message)}else a(g.message);d()}catch{a("WeChat connect failed")}else try{await h(`/channels/${y}/connect`,{method:"POST"}),a("Connecting..."),d()}catch{a("Connect failed")}}async function f(y){try{await h(`/channels/${y}/disconnect`,{method:"POST"}),a("Disconnected"),d()}catch{a("Disconnect failed")}}return Hn((y,n)=>{if(i){if(n.escape||y==="q"){s(null);return}if(y==="c"){C(i.id);return}if(y==="d"){f(i.id);return}return}if(n.escape){e();return}if(n.upArrow){l(g=>Math.max(0,g-1));return}if(n.downArrow){l(g=>Math.min(t.length-1,g+1));return}if(n.return&&t[m]){s(t[m]),a("");return}}),c?R(j,{flexDirection:"column",children:R(F,{dimColor:!0,children:"Loading channels..."})}):i?ne(j,{flexDirection:"column",children:[ne(j,{marginBottom:1,children:[ne(F,{bold:!0,children:["Channel: ",i.name]}),R(F,{dimColor:!0,children:" (Esc to go back)"})]}),ne(j,{flexDirection:"column",gap:0,children:[ne(F,{children:["ID: ",i.id]}),ne(F,{children:["Platform: ",i.platform]}),ne(F,{children:["Status: ",R(F,{color:lr[i.status]??"white",children:i.status})]}),ne(F,{children:["Enabled: ",i.enabled?"yes":"no"]}),ne(F,{children:["Messages: ",i.messageCount]}),ne(F,{children:["Config: ",JSON.stringify(i.config)]})]}),R(j,{marginTop:1,children:R(F,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&R(F,{color:"yellow",children:r})]}):ne(j,{flexDirection:"column",children:[ne(j,{marginBottom:1,children:[R(F,{bold:!0,children:"Channels"}),ne(F,{dimColor:!0,children:[" (",t.length," total) "]}),R(F,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?R(F,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):ne(j,{flexDirection:"column",children:[ne(j,{children:[R(j,{width:3,children:R(F,{dimColor:!0,children:" "})}),R(j,{width:12,children:R(F,{bold:!0,dimColor:!0,children:"ID"})}),R(j,{width:16,children:R(F,{bold:!0,dimColor:!0,children:"Name"})}),R(j,{width:12,children:R(F,{bold:!0,dimColor:!0,children:"Platform"})}),R(j,{width:14,children:R(F,{bold:!0,dimColor:!0,children:"Status"})}),R(j,{width:10,children:R(F,{bold:!0,dimColor:!0,children:"Enabled"})}),R(j,{width:10,children:R(F,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((y,n)=>ne(j,{children:[R(j,{width:3,children:R(F,{children:n===m?">":" "})}),R(j,{width:12,children:R(F,{inverse:n===m,children:y.id.slice(0,8)})}),R(j,{width:16,children:R(F,{children:y.name})}),R(j,{width:12,children:R(F,{children:y.platform})}),R(j,{width:14,children:ne(F,{color:lr[y.status]??"white",children:[y.status==="connected"?"\u25CF":y.status==="error"?"\u2717":"\u25CB"," ",y.status]})}),R(j,{width:10,children:R(F,{color:y.enabled?"green":"gray",children:y.enabled?"yes":"no"})}),R(j,{width:10,children:R(F,{children:y.messageCount})})]},y.id))]})]})}import{Box as yt,Text as Qe,useInput as Qn}from"ink";import{useEffect as Xn,useState as Dt,useCallback as zn}from"react";import{Box as M,Text as S,useInput as Kn}from"ink";import Tt from"ink-text-input";import{useEffect as dr,useState as J,useCallback as ht}from"react";yo();import{Fragment as ur,jsx as b,jsxs as k}from"react/jsx-runtime";function mr({roleId:e,onBack:t}){let[o,c]=J(null),[u,m]=J([]),[l,i]=J(!0),[s,r]=J("view"),[a,d]=J(""),[C,f]=J(0),[y,n]=J(""),[g,_]=J([]),[A,K]=J(0),[G,P]=J(new Set),[oe,I]=J("inline"),[w,p]=J(""),[D,$]=J(""),[Ve,v]=J([]),[B,O]=J(new Set),[se,Xe]=J(0),[Ct,Mt]=J("default"),[Nt,Yt]=J(""),[Lt,Jt]=J(""),[at,To]=J("mode"),{message:V,setMessage:H}=et(),ie=ht(()=>{i(!0),h(`/roles/${e}`).then(({role:T,boundPlugins:E})=>{c(T),m(E??[]),d(T.cagPrompt??""),P(new Set(T.allowedTools??[])),I(T.executionMode??"inline"),p(T.model??""),$(T.maxBudgetUsd!=null?String(T.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);dr(()=>{ie()},[ie]),dr(()=>{I(o?.executionMode??"inline"),p(o?.model??""),$(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),Mt(o?.permissionMode??"default"),Yt((o?.allowedBashPatterns??[]).join(", ")),Jt((o?.deniedBashPatterns??[]).join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns]);let fr=ht(async()=>{if(o)try{await h(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:a}}),H("CAG prompt saved","success"),r("view"),ie()}catch(T){H(`Save failed: ${T instanceof Error?T.message:String(T)}`,"error")}},[o,a,ie,H]),pr=ht(async()=>{if(o)try{await h(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:ve}}),H("Directories saved","success"),r("view"),ie()}catch(T){H(`Save failed: ${T instanceof Error?T.message:String(T)}`,"error")}},[o,ie,H]),xr=ht(async()=>{if(o)try{await h(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(G)}}),H("Tool permissions saved","success"),r("view"),ie()}catch(T){H(`Save failed: ${T instanceof Error?T.message:String(T)}`,"error")}},[o,G,ie,H]),Tr=ht(async()=>{if(!o)return;let T={executionMode:oe};w!==void 0&&(T.model=w);let E=parseFloat(D);isNaN(E)||(T.maxBudgetUsd=E);try{await h(`/roles/${o.id}`,{method:"PATCH",body:T}),H("Execution config saved","success"),r("view"),ie()}catch(x){H(`Save failed: ${x instanceof Error?x.message:String(x)}`,"error")}},[o,oe,w,D,ie,H]),hr=ht(async()=>{if(!o)return;let T={permissionMode:Ct},E=Nt.split(",").map(L=>L.trim()).filter(Boolean),x=Lt.split(",").map(L=>L.trim()).filter(Boolean);T.allowedBashPatterns=E.length>0?E:[],T.deniedBashPatterns=x.length>0?x:[];try{await h(`/roles/${o.id}`,{method:"PATCH",body:T}),H("Permission config saved","success"),r("view"),ie()}catch(L){H(`Save failed: ${L instanceof Error?L.message:String(L)}`,"error")}},[o,Ct,Nt,Lt,ie,H]),ve=o?.additionalDirectories??[];return Kn((T,E)=>{if(E.escape){r("view");return}if(T==="r"){ie();return}switch(s){case"view":{if(T==="c"){r("edit-cag");return}if(T==="d"){r("edit-dirs"),f(0),n("");return}if(T==="t"){r("edit-tools");return}if(T==="x"){r("edit-exec");return}if(T==="h"){h("/channels?enabled=true").then(({channels:x})=>{v(x.map(L=>({name:L.name,id:L.id}))),O(new Set(o?.allowedChannels??[])),Xe(0),r("edit-channels")}).catch(()=>H("Failed to load channels","error"));return}if(T==="p"){Mt(o?.permissionMode??"default"),Yt((o?.allowedBashPatterns??[]).join(", ")),Jt((o?.deniedBashPatterns??[]).join(", ")),To("mode"),r("edit-permissions");return}if(T==="i"){if(!o)return;let x=!o.inheritUserSettings;h(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:x}}).then(()=>{H(`Inherit user settings: ${x?"ON":"OFF"}`,"success"),ie()}).catch(()=>H("Failed to toggle","error"));return}break}case"edit-cag":{if(E.ctrl&&T==="s"){fr();return}break}case"edit-dirs":{if(T==="s"){pr();return}if(T==="a"){r("edit-dirs-add");return}if(T==="m"&&ve.length>0){let x=ve[C];if(x){c(pe=>pe&&{...pe,additionalDirectories:pe.additionalDirectories?.map((Re,yr)=>yr===C?{...typeof Re=="string"?{path:Re}:Re,mode:Re.mode==="ro"?"rw":"ro"}:Re)});let L=x.mode==="ro"?"rw":"ro";H(`Mode set to ${L.toUpperCase()}`,"success")}return}if(T==="x"&&ve.length>0){c(x=>x&&{...x,additionalDirectories:ve.filter((L,pe)=>pe!==C)}),f(x=>Math.max(0,Math.min(x,ve.length-2)));return}if(E.upArrow){f(x=>Math.max(0,x-1));return}if(E.downArrow){f(x=>Math.min(ve.length-1,x+1));return}break}case"edit-dirs-add":{if(E.escape){r("edit-dirs"),n(""),_([]);return}if(E.return&&g.length>0){let x=g[A];x&&(n(x.endsWith("/")?x:x+"/"),_([]));return}if(E.return){let x=y.trim();x&&x.startsWith("/")?(c(L=>L&&{...L,additionalDirectories:[...L.additionalDirectories??[],{path:x,mode:"rw"}]}),n(""),_([]),r("edit-dirs")):H("Path must be absolute (must start with /)","error");return}if(E.tab){let x=y.trim();if(!x||!x.startsWith("/"))return;h(`/fs/suggest-dirs?prefix=${encodeURIComponent(x)}`).then(({suggestions:L})=>{L.length===1?(n(L[0]+"/"),_([])):L.length>1&&(_(L),K(0))}).catch(()=>{_([])});return}if(E.upArrow&&g.length>0){K(x=>Math.max(0,x-1));return}if(E.downArrow&&g.length>0){K(x=>Math.min(g.length-1,x+1));return}break}case"edit-tools":{if(T==="s"){xr();return}let x=parseInt(T,10)-1;if(!isNaN(x)&&x>=0&&x<_t.length){let L=_t[x];P(pe=>{let Re=new Set(pe);return Re.has(L)?Re.delete(L):Re.add(L),Re});return}break}case"edit-exec":{if(T==="s"){Tr();return}if(E.tab){I(x=>x==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(T==="s"){hr();return}if(E.tab){To(x=>x==="mode"?"allowed":x==="allowed"?"denied":"mode");return}if(at==="mode"&&(E.upArrow||E.downArrow)){let x=["default","acceptEdits","dontAsk","bypassPermissions"],L=x.indexOf(Ct);E.upArrow&&Mt(x[Math.max(0,L-1)]),E.downArrow&&Mt(x[Math.min(x.length-1,L+1)]);return}break}case"edit-channels":{if(T==="s"){if(!o)return;let x=B.size>0?Array.from(B):[];h(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:x}}).then(()=>{H("Channels saved","success"),r("view"),ie()}).catch(()=>H("Save failed","error"));return}if(T==="u"){if(!o)return;h(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{H("Channels: unrestricted","success"),r("view"),ie()}).catch(()=>H("Save failed","error"));return}if(T===" "){let x=Ve[se];x&&O(L=>{let pe=new Set(L);return pe.has(x.name)?pe.delete(x.name):pe.add(x.name),pe});return}if(E.upArrow){Xe(x=>Math.max(0,x-1));return}if(E.downArrow){Xe(x=>Math.min(Ve.length-1,x+1));return}break}}}),l?b(S,{dimColor:!0,children:"Loading role..."}):o?s==="edit-cag"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),b(Tt,{value:a,onChange:d,placeholder:"Character And Guidance prompt..."}),V&&b(M,{marginTop:1,children:b(S,{color:V.type==="error"?"red":"green",children:V.text})})]}):s==="edit-dirs-add"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),b(Tt,{value:y,onChange:T=>{n(T),_([])},placeholder:"/absolute/path/to/directory"}),g.length>0&&k(M,{flexDirection:"column",marginTop:1,children:[g.map((T,E)=>k(S,{color:E===A?"cyan":void 0,dimColor:E!==A,children:[E===A?"> ":" ",T,"/"]},T)),b(S,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),V&&b(M,{marginTop:1,children:b(S,{color:V.type==="error"?"red":"green",children:V.text})})]}):s==="edit-dirs"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),V&&b(M,{children:b(S,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),ve.length===0?b(S,{dimColor:!0,children:"No directories. Press a to add one."}):ve.map((T,E)=>{let x=typeof T=="string"?{path:T,mode:"rw"}:T,L=x.mode!=="ro";return k(M,{children:[b(S,{color:E===C?"cyan":void 0,bold:E===C,children:E===C?"> ":" "}),k(S,{color:L?"green":"yellow",children:["[",L?"RW":"RO","]"," "]}),b(S,{color:E===C?"cyan":void 0,children:x.path})]},x.path)})]}):s==="edit-tools"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),V&&b(M,{children:b(S,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),_t.map((T,E)=>{let x=G.has(T);return k(M,{children:[k(S,{dimColor:!0,children:[E+1,". "]}),b(S,{color:x?"green":"red",children:x?"[ON] ":"[OFF] "}),b(S,{children:T})]},T)})]}):s==="edit-exec"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),k(M,{children:[b(S,{bold:!0,children:" Mode: "}),b(S,{color:"cyan",children:oe}),b(S,{dimColor:!0,children:" (Tab to toggle)"})]}),k(M,{children:[b(S,{bold:!0,children:" Model: "}),b(Tt,{value:w,onChange:p,placeholder:"sonnet, opus, haiku, or blank"})]}),k(M,{children:[b(S,{bold:!0,children:" Max Budget (USD): "}),b(Tt,{value:D,onChange:$,placeholder:"0 = unlimited"})]}),V&&b(M,{children:b(S,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]}):s==="edit-permissions"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),k(M,{children:[b(S,{bold:!0,color:at==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(E=>k(S,{color:E===Ct?"green":"gray",children:[E===Ct?`[${E}]`:` ${E} `," "]},E))]}),k(M,{children:[b(S,{bold:!0,color:at==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),at==="allowed"?b(Tt,{value:Nt,onChange:Yt,placeholder:"git add *, pnpm test*"}):b(S,{children:Nt||"(none)"})]}),k(M,{children:[b(S,{bold:!0,color:at==="denied"?"cyan":void 0,children:" Denied Bash: "}),at==="denied"?b(Tt,{value:Lt,onChange:Jt,placeholder:"rm -rf *, ssh *"}):b(S,{children:Lt||"(none)"})]}),b(S,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),V&&b(M,{children:b(S,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]}):s==="edit-channels"?k(M,{flexDirection:"column",children:[b(S,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Ve.length===0?b(S,{dimColor:!0,children:"No channels available"}):Ve.map((T,E)=>k(M,{children:[k(S,{children:[E===se?">":" "," "]}),k(S,{color:B.has(T.name)?"green":"gray",children:["[",B.has(T.name)?"x":" ","] ",T.name]})]},T.id)),k(S,{dimColor:!0,children:["Selected: ",B.size>0?Array.from(B).join(", "):"none (= block all)"]}),V&&b(M,{children:b(S,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]}):k(M,{flexDirection:"column",children:[k(S,{bold:!0,children:["Role: ",o.name]}),k(M,{children:[b(S,{dimColor:!0,children:"ID: "}),b(S,{children:o.id})]}),k(M,{children:[b(S,{dimColor:!0,children:"Status: "}),b(S,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&k(M,{children:[b(S,{dimColor:!0,children:"Score: "}),k(S,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),k(M,{children:[b(S,{dimColor:!0,children:"Created: "}),b(S,{children:new Date(o.createdAt).toLocaleString()})]}),k(M,{children:[b(S,{dimColor:!0,children:"Execution: "}),k(S,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),ve.length>0&&k(ur,{children:[b(S,{bold:!0,children:"Additional Directories:"}),ve.map(T=>k(S,{dimColor:!0,children:[" ",T.path]},T.path))]}),k(M,{children:[b(S,{dimColor:!0,children:"Permission: "}),b(S,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&k(M,{children:[b(S,{dimColor:!0,children:" Bash Allow: "}),b(S,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&k(M,{children:[b(S,{dimColor:!0,children:" Bash Deny: "}),b(S,{children:o.deniedBashPatterns.join(", ")})]}),k(M,{children:[b(S,{dimColor:!0,children:"Channels: "}),b(S,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),k(M,{children:[b(S,{dimColor:!0,children:"Inherit User Settings: "}),b(S,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&k(ur,{children:[b(S,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(T=>k(S,{dimColor:!0,children:[" - ",T]},T))]}),V&&b(M,{children:b(S,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),b(M,{marginTop:1,children:b(S,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec p:perms h:channels i:inherit r:refresh Esc:back"})})]}):b(S,{dimColor:!0,children:"Role not found."})}import{jsx as Ce,jsxs as Xt}from"react/jsx-runtime";function gr({onBack:e}){let[t,o]=Dt([]),[c,u]=Dt(!0),[m,l]=Dt(0),[i,s]=Dt("list"),[r,a]=Dt(null),{message:d,setMessage:C,clearMessage:f}=et(),y=zn(()=>{u(!0),h("/roles").then(({roles:n})=>{o(n.map(g=>({id:g.id,name:g.name,status:g.status,performanceScore:g.performanceScore,createdAt:g.createdAt}))),u(!1)}).catch(()=>u(!1))},[]);return Xn(()=>{y()},[y]),Qn((n,g)=>{if(g.escape||n==="q"){e();return}if(g.upArrow){l(_=>Math.max(0,_-1));return}if(g.downArrow){l(_=>Math.min(t.length-1,_+1));return}if(n==="r"&&(y(),f()),n===`
|
|
7
|
+
`||n==="o"||n==="e"){t.length>0&&(a(t[m].id),s("detail"));return}}),c?Ce(Qe,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Ce(mr,{roleId:r,onBack:()=>s("list")}):Xt(yt,{flexDirection:"column",children:[Xt(Qe,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&Ce(yt,{marginTop:1,children:Xt(Qe,{color:d.type==="success"?"green":d.type==="error"?"red":"gray",children:[d.type==="success"?"\u2713 ":d.type==="error"?"\u2717 ":"\u2192 ",d.text]})}),t.length===0?Ce(yt,{marginTop:1,children:Ce(Qe,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Ce(yt,{marginTop:1,flexDirection:"column",children:t.map((n,g)=>{let _=g===m,A=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return Xt(yt,{children:[Ce(Qe,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),Ce(Qe,{color:_?"cyan":void 0,bold:_,children:po(n.name,24)}),Ce(Qe,{color:Yn(n.status),children:po(n.status,12)}),Ce(Qe,{dimColor:!0,children:po(A,8)})]},n.id)})}),Ce(yt,{marginTop:1,children:Ce(Qe,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function Yn(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function po(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as rs,jsx as U,jsxs as St}from"react/jsx-runtime";function es(){let{state:e,dispatch:t}=ze(),{session:o,sendMessage:c,createNewSession:u,archiveCurrentSession:m}=ko(),[l,i]=Zn([]);zt(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Bo();let{latestMessage:s}=Ao(o?.id??null),r=xo(null);zt(()=>{s&&s.id!==r.current&&(r.current=s.id,i(A=>[...A,{role:"assistant",content:s.content}]))},[s]);let{events:a,isStreaming:d,clearEvents:C}=Io(e.activeTaskId),f=a[a.length-1],y=f?.type==="complete"&&!d,n=xo(null),g=xo("");zt(()=>{g.current=a.filter(A=>A.type==="reasoning").map(A=>A.content).join("")},[a]),zt(()=>{if(y&&e.activeTaskId!==n.current){n.current=e.activeTaskId;let A=f?.content||g.current;A&&i(K=>[...K,{role:"assistant",content:A}])}},[y,f,e.activeTaskId]);let _=async A=>{let K=A.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(K)&&process.exit(0),A.startsWith("/")){let P=A.slice(1),I={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"}[P];if(I){t({type:"SET_VIEW",view:I});return}if(P==="new"){if(await m()){let p=await u();i([]),C(),p&&i([{role:"assistant",content:`Session archived. New session started: ${p.id.slice(0,8)}`}])}return}if(P==="session"){let w=o?`Session: ${o.id}
|
|
8
|
+
Turns: ${o.messageCount}
|
|
9
|
+
Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(p=>[...p,{role:"assistant",content:w}]);return}}if(i(P=>[...P,{role:"user",content:A}]),C(),!await c(A)){i(P=>[...P,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}};return St(Rt,{flexDirection:"column",paddingX:1,children:[U(Do,{}),St(Rt,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&St(rs,{children:[U($o,{messages:l}),U(No,{events:a,isStreaming:d}),!e.connected&&!e.serverUnreachable&&U(Rt,{children:U(bt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&St(Rt,{flexDirection:"column",children:[U(bt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),U(bt,{dimColor:!0,children:"Check: adam server logs"}),U(bt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&U(ar,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&U(Ut,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&U(Go,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&U(jo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&U(Gt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&U(Qo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&U(Kt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&U(Yo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&U(er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&U(sr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&U(gr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&U(nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&U(cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?U(Vo,{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?U(Oo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):U(Mo,{onSubmit:_}),e.planTimeoutNotice&&U(ts,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function ts({planId:e,onDismiss:t}){return Jn(o=>{o==="d"&&t()}),St(Rt,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[St(bt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),U(bt,{dimColor:!0,children:" [d] Dismiss"})]})}function os(){return U(Co,{children:U(es,{})})}export{os as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as a,o as b}from"./chunk-QC6QVNKP.js";import"./chunk-5V36ACKZ.js";import"./chunk-6VPL5CXB.js";import"./chunk-NFSXJNPD.js";import"./chunk-X26NKAXY.js";import"./chunk-GA7GEIXB.js";import"./chunk-KHPXEUSY.js";import"./chunk-ROSOI75V.js";import"./chunk-YEV5YTS3.js";import"./chunk-BONI2HUN.js";import"./chunk-4TBGFHYX.js";import"./chunk-64FIXWFL.js";import"./chunk-U3XVAAXA.js";import"./chunk-L7JP7DUO.js";import"./chunk-2C5U3CNX.js";import"./chunk-2CMR5AG7.js";import"./chunk-I5RUEOSQ.js";import"./chunk-42RHY3Q3.js";import"./chunk-3TIHZZMK.js";import"./chunk-6KLG4APZ.js";import"./chunk-REKCZ3GY.js";import"./chunk-FXFHGIY6.js";import"./chunk-QMKQBU3R.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as y}from"./chunk-
|
|
1
|
+
import{b as y}from"./chunk-BCELBB5Q.js";import{b as m}from"./chunk-64FIXWFL.js";import"./chunk-TEMWI6U5.js";import"./chunk-L7JP7DUO.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import{c as f,h}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";h();var s=f("channels"),c=new Map,v=3e5,A=new Set(["telegram"]);function I(n){let a=n.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!a)return null;let[,p,d]=a,i=["yes","y","\u662F","\u5141\u8BB8"].includes(p);return{requestId:d,decision:i?"allow":"deny"}}function w(n){let r=m(n);return r?A.has(r.platform):!1}async function C(n,r,a,p,d,i=v){let e=a;c.set(e,{planId:a,taskId:p,channelId:n,chatId:r,requestId:e,timestamp:Date.now(),timeoutMs:i});let l=y(),o=w(n);if(o){let t=`\u{1F510} Plan approval requested
|
|
2
2
|
|
|
3
3
|
${d.slice(0,200)}`;await l.send({channelId:n,chatId:r,content:t,messageType:"approval",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 l.send({channelId:n,chatId:r,content:t,messageType:"approval"})}setTimeout(()=>{let t=c.get(e);if(t&&Date.now()-t.timestamp>=t.timeoutMs){c.delete(e),s.warn({requestId:e,taskId:p},"Approval timed out, auto-denying"),l.send({channelId:t.channelId,chatId:t.chatId,content:`\u23F0 Approval ${e} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(u=>s.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=>s.error({requestId:e,error:u},"Failed to auto-deny"))}},i+1e3),s.info({channelId:n,chatId:r,planId:a,requestId:e,interactive:o},"Interactive approval sent to channel")}async function
|
|
4
|
+
`);await l.send({channelId:n,chatId:r,content:t,messageType:"approval"})}setTimeout(()=>{let t=c.get(e);if(t&&Date.now()-t.timestamp>=t.timeoutMs){c.delete(e),s.warn({requestId:e,taskId:p},"Approval timed out, auto-denying"),l.send({channelId:t.channelId,chatId:t.chatId,content:`\u23F0 Approval ${e} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(u=>s.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=>s.error({requestId:e,error:u},"Failed to auto-deny"))}},i+1e3),s.info({channelId:n,chatId:r,planId:a,requestId:e,interactive:o},"Interactive approval sent to channel")}async function $(n,r,a,p){let i=I(p??a);if(!i)return!1;let{requestId:e,decision:l}=i,o=c.get(e);if(!o)return!1;if(o.channelId!==n||o.chatId!==r)return s.debug({requestId:e,expectedChannel:o.channelId,gotChannel:n},"Approval reply from different channel"),!1;c.delete(e),s.info({requestId:e,decision:l},"Channel approval reply received");try{let t=process.env.ADAM_PORT??"7100",g=await fetch(`http://localhost:${t}/tasks/${o.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:o.planId,decision:l}),signal:AbortSignal.timeout(1e4)});g.ok||s.error({requestId:e,status:g.status},"Failed to forward approval to API")}catch(t){s.error({requestId:e,error:t},"Error forwarding approval to API")}return!0}function k(){return[...c.keys()]}export{k as getPendingApprovalRequestIds,$ as handleInboundForApproval,I as parseApprovalReply,C as sendApprovalToChannel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as a,j as b,k as c,l as d,m as e}from"./chunk-CFTWJZVX.js";import"./chunk-PT55643Q.js";import"./chunk-6VPL5CXB.js";import"./chunk-NFSXJNPD.js";import"./chunk-X26NKAXY.js";import"./chunk-ROSOI75V.js";import"./chunk-XFTRKHH2.js";import"./chunk-U3XVAAXA.js";import"./chunk-TEMWI6U5.js";import"./chunk-L7JP7DUO.js";import"./chunk-2C5U3CNX.js";import"./chunk-2CMR5AG7.js";import"./chunk-I5RUEOSQ.js";import"./chunk-REKCZ3GY.js";import"./chunk-FXFHGIY6.js";import"./chunk-QMKQBU3R.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as evaluateTaskCompletion,e as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-35DBEYMG.js";import"./chunk-KHPXEUSY.js";import"./chunk-ROSOI75V.js";import"./chunk-L7JP7DUO.js";import"./chunk-I5RUEOSQ.js";import"./chunk-42RHY3Q3.js";import"./chunk-3TIHZZMK.js";import"./chunk-6KLG4APZ.js";import"./chunk-REKCZ3GY.js";import"./chunk-FXFHGIY6.js";import"./chunk-QMKQBU3R.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f}from"./chunk-64FIXWFL.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c}from"./chunk-IZQI6QQ7.js";import"./chunk-4TBGFHYX.js";import"./chunk-64FIXWFL.js";import"./chunk-CREHL4BN.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as l}from"./chunk-
|
|
1
|
+
import{a as l}from"./chunk-2CMR5AG7.js";import{d as f,k as g,m as p,n as h,o as M,q as b}from"./chunk-I5RUEOSQ.js";function v(t,n){let i=0,s=0,m=0;for(let e=0;e<t.length;e++)i+=t[e]*n[e],s+=t[e]*t[e],m+=n[e]*n[e];let o=Math.sqrt(s)*Math.sqrt(m);return o===0?0:i/o}async function S(t,n,i={}){let s=i.topK??10,m=i.hybridConfig??M,o;try{o=await l(n)}catch{}let e=o??new Float32Array(384),a=b(t,e,n,s*2,m,{excludeSuperseded:!0}),d=t?h(t):g,y=a.map(r=>{let u=r.embedding?v(e,r.embedding):0,C=Math.min(.3,(r.retrievedCount??0)*.05),x=p(r.createdAt,u,r.importance,d)+C;return{...r,score:x}});y.sort((r,u)=>u.score-r.score);let c=y.slice(0,s);for(let r of c)f(r.id);return c}async function T(t,n,i=5,s=2e3){try{let{estimateTokens:m}=await import("./token-estimator-HMPVGDCN.js"),o=await S(n,t,{topK:i});if(o.length===0)return"";let e=[],a=0,d=m(`[Memory Context \u2014 retrieved from prior interactions]
|
|
2
2
|
|
|
3
3
|
[User Request]
|
|
4
4
|
`);for(let c of o){let r=m(`- [${c.tier??"episodic"}] ${c.content}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as S,h as x}from"./chunk-INNDBLZE.js";x();import*as s from"fs";import*as l from"path";import{homedir as F}from"os";var v=S("embedding"),M=null,A=!1;async function L(){if(A)throw new Error("onnxruntime-node native binding not available. Embedding disabled.");if(!M)try{M=await import("./dist-CDWBOTZS.js")}catch(e){throw A=!0,v.warn({error:e.message},"onnxruntime-node not available"),new Error("onnxruntime-node native binding not available. Embedding disabled.")}return M}var P=l.join(F(),".adam","models"),N="all-MiniLM-L6-v2",T="model.onnx",B="tokenizer.json",O="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/onnx/model_quantized.onnx",j="https://huggingface.co/Xenova/all-MiniLM-L6-v2/resolve/main/tokenizer.json",R=384,y=null,k=null;function z(){let e=l.join(P,N);return s.existsSync(e)||s.mkdirSync(e,{recursive:!0}),e}async function _(e,t){if(s.existsSync(t))return;v.info({file:l.basename(t)},"Downloading model file");let f=await fetch(e);if(!f.ok)throw new Error(`Failed to download ${e}: ${f.status}`);let i=Buffer.from(await f.arrayBuffer());s.writeFileSync(t,i),v.info({file:l.basename(t),sizeMb:(i.length/1024/1024).toFixed(1)},"Model file downloaded")}async function U(){let e=z(),t=l.join(e,T),f=l.join(e,B);return await _(O,t),await _(j,f),t}function $(){if(k)return k;let e=l.join(z(),B);if(!s.existsSync(e))throw new Error("Tokenizer not found. Run generateEmbedding first to download.");return k=JSON.parse(s.readFileSync(e,"utf-8")),k}function q(e,t=128){let i=$().model.vocab,w=i["[CLS]"]??101,I=i["[SEP]"]??102,u=i["[UNK]"]??100,E=i["[PAD]"]??0,p=e.toLowerCase().replace(/[^\w\s\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff]/g," ").split(/\s+/).filter(Boolean),r=[w];for(let o of p){if(r.length>=t-1)break;if(i[o]!==void 0){r.push(i[o]);continue}let d=!1,n=o,m=!0;for(;n.length>0&&r.length<t-1;){let D=!1;for(let g=n.length;g>0;g--){let b=m?n.slice(0,g):`##${n.slice(0,g)}`;if(i[b]!==void 0){r.push(i[b]),n=n.slice(g),m=!1,D=!0,d=!0;break}}if(!D)if(n.length>=2){let g=n.slice(0,2),b=i[g]??i[`##${g}`]??u;r.push(b),n=n.slice(2),d=!0}else r.push(u),n=""}d||r.push(u)}r.push(I);let h=new BigInt64Array(t),a=new BigInt64Array(t),c=new BigInt64Array(t);for(let o=0;o<t;o++)o<r.length?(h[o]=BigInt(r[o]),a[o]=1n):(h[o]=BigInt(E),a[o]=0n),c[o]=0n;return{inputIds:h,attentionMask:a,tokenTypeIds:c}}async function C(){if(y)return y;let e=await L(),t=await U();return y=await e.InferenceSession.create(t,{executionProviders:["cpu"]}),y}async function Z(e){let t=await L(),f=await C(),{inputIds:i,attentionMask:w,tokenTypeIds:I}=q(e),u=i.length,E={input_ids:new t.Tensor("int64",i,[1,u]),attention_mask:new t.Tensor("int64",w,[1,u]),token_type_ids:new t.Tensor("int64",I,[1,u])},p=await f.run(E),h=(p.last_hidden_state??p[Object.keys(p)[0]]).data,a=R,c=new Float32Array(a),o=0;for(let n=0;n<u;n++)if(w[n]===1n){o++;for(let m=0;m<a;m++)c[m]+=h[n*a+m]}if(o>0)for(let n=0;n<a;n++)c[n]/=o;let d=0;for(let n=0;n<a;n++)d+=c[n]*c[n];if(d=Math.sqrt(d),d>0)for(let n=0;n<a;n++)c[n]/=d;return c}function G(){let e=l.join(z(),T);return s.existsSync(e)}export{Z as a,G as b};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import{a as S,b as P}from"./chunk-KHPXEUSY.js";import{a as k,b as m}from"./chunk-ROSOI75V.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as I}from"./chunk-I5RUEOSQ.js";import{a as C,b as c,d as y,f as R}from"./chunk-42RHY3Q3.js";import{d as T}from"./chunk-3TIHZZMK.js";import{h as x,k as J}from"./chunk-FXFHGIY6.js";import{c as h,h as b}from"./chunk-INNDBLZE.js";b();J();import{v4 as l}from"uuid";import{CronExpressionParser as D}from"cron-parser";b();import{v4 as M}from"uuid";var g=h("scheduler"),v=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let o=T(),r={timeout:e.config?.timeout??o.timeout,approvalRequired:o.approvalRequired,approvalTimeout:o.approvalTimeout,plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??o.model,maxTurns:e.config?.maxTurns??o.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??o.maxBudgetUsd,env:{...o.env,...e.config?.env},claudeCodePath:o.claudeCodePath},s={templateId:e.id,executionId:t,stepResults:new Map,config:r,rolePreference:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo},i=this.sortSteps(e.steps);for(let a of i){try{await this.executeStep(a,s)}catch(p){g.error({stepId:a.id,error:p},"Workflow step failed");break}if(s.stepResults.get(a.id)?.status==="failed"){g.warn({stepId:a.id},"Workflow step failed, workflow aborted");break}}g.info({executionId:t,completedSteps:s.stepResults.size,totalSteps:i.length},"Workflow completed")}sortSteps(e){let t=new Set,o=[],r=new Map(e.map(i=>[i.id,i])),s=i=>{if(!t.has(i.id)){if(t.add(i.id),i.dependsOn)for(let a of i.dependsOn){let d=r.get(a);d&&s(d)}o.push(i)}};for(let i of e)s(i);return o}async executeStep(e,t){let o=this.resolveVariables(e.prompt,t.stepResults),r=M();k({id:r,status:"pending",prompt:o,config:t.config,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId,roleId:t.rolePreference,deliverTo:t.deliverTo,reportTo:t.reportTo}),g.debug({stepId:e.id,taskId:r},"Created workflow step as task"),u.emit({type:"task_created",taskId:r});let s=await this.executeWithRetry(r,e.id),i=m(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:s==="completed"?"completed":"failed",result:i?.result,error:i?.error})}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(o,r)=>t.get(r)?.result??`[no result from ${r}]`)}async executeWithRetry(e,t){let o=0;for(;o<this.maxRetries;){if(o++,await this.waitForTaskCompletion(e)==="completed")return"completed";if(o<this.maxRetries){let s=this.baseDelayMs*Math.pow(2,o-1);g.info({stepId:t,attempt:o,maxRetries:this.maxRetries,delayMs:s},"Workflow step failed, retrying"),await this.sleep(s)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(o=>{let r=Date.now(),s=()=>{if(Date.now()-r>t){o("failed");return}let i=m(e);if(!i){o("failed");return}if(i.status==="completed"){o("completed");return}if(i.status==="failed"||i.status==="cancelled"){o("failed");return}setTimeout(s,500)};s()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var n=h("scheduler"),w="ai-hourly-digest";function O(){if(c(w)){n.debug({templateId:w},"Built-in template already exists");return}let e={id:w,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
|
|
2
|
+
|
|
3
|
+
\u641C\u7D22\u6765\u6E90:
|
|
4
|
+
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
5
|
+
2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
|
|
6
|
+
3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
|
|
7
|
+
|
|
8
|
+
\u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
|
|
9
|
+
|
|
10
|
+
\u8F93\u51FA\u683C\u5F0F:
|
|
11
|
+
- \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
|
|
12
|
+
- \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
|
|
13
|
+
- \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
|
|
14
|
+
- \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
|
|
15
|
+
|
|
16
|
+
\u6587\u7AE0\u4FE1\u606F:
|
|
17
|
+
{{search_ai_news.result}}
|
|
18
|
+
|
|
19
|
+
\u8BF7:
|
|
20
|
+
1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
|
|
21
|
+
2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
|
|
22
|
+
3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
|
|
23
|
+
|
|
24
|
+
\u603B\u7ED3\u7ED3\u6784:
|
|
25
|
+
## \u6838\u5FC3\u53D1\u73B0
|
|
26
|
+
[\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
|
|
27
|
+
|
|
28
|
+
## \u6280\u672F\u7EC6\u8282
|
|
29
|
+
[\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
|
|
30
|
+
|
|
31
|
+
## \u5F71\u54CD/\u610F\u4E49
|
|
32
|
+
[\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
|
|
33
|
+
|
|
34
|
+
## \u539F\u6587\u94FE\u63A5
|
|
35
|
+
[\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
|
|
36
|
+
|
|
37
|
+
\u603B\u7ED3\u5185\u5BB9:
|
|
38
|
+
{{summarize_article.result}}
|
|
39
|
+
|
|
40
|
+
\u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
|
|
41
|
+
|
|
42
|
+
osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
|
|
43
|
+
|
|
44
|
+
\u6CE8\u610F\uFF1A
|
|
45
|
+
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
46
|
+
- \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
|
|
47
|
+
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
48
|
+
|
|
49
|
+
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};C(e),n.info({templateId:w,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var A=class{cronJobs=new Map;workflowExecutor=new v;started=!1;taskCompletionHandler=null;async start(){if(this.started)return;this.started=!0,O();let e=y(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let o=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),o++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(s=>{n.error({taskId:r.taskId,error:s},"Event trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:o},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=x(void 0,1e3,0),t=0;for(let o of e)t+=I(o.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.started=!1,n.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let o;try{o=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let p=o.next().getTime()-Date.now();return Math.max(p,1e3)},s=()=>{this.executeCronTrigger(e.id).catch(p=>{n.error({templateId:e.id,error:p},"Cron trigger failed")});let d=setTimeout(s,r());this.cronJobs.set(t,d)},i=r(),a=setTimeout(s,i);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+i).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=c(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,l()))}async scheduleJob(e){let t=c(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,o=this.cronJobs.get(t);o&&(clearTimeout(o),this.cronJobs.delete(t))}async runNow(e){let t=c(e);if(!t)throw new Error(`Template ${e} not found`);let o=l();return this.executeWorkflow(t,o).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),o}async checkEventTriggers(e){let t=m(e);if(!t)return;let o=y(!0),r=o.filter(s=>s.trigger.type==="event"&&s.trigger.event==="task_complete");for(let s of r)n.debug({templateName:s.name},"Event trigger matched"),await this.executeWorkflow(s,l());if(t.templateId){let s=o.filter(i=>i.trigger.type!=="event"||!i.trigger.event?!1:i.trigger.event===`template_complete:${t.templateId}`);for(let i of s)n.info({templateName:i.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(i,l())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let o of e.goalIds){let r=P(o);if(!r){n.warn({goalId:o,templateId:e.id},"Goal reference not found, skipping");continue}let s=l();S({id:s,name:r.name,description:r.description,roleId:r.roleId,metricType:r.metricType,targetValue:r.targetValue,currentValue:0,deadline:r.deadline,budgetUsd:r.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,deliverTo:e.deliverTo,reportTo:e.reportTo});let i=l();k({id:i,status:"pending",prompt:`Decompose and execute goal: ${r.name}. ${r.description??""}`,parentId:s,config:T(),createdAt:Date.now(),templateId:e.id,roleId:e.rolePreference,deliverTo:e.deliverTo,reportTo:e.reportTo}),u.emit({type:"task_created",taskId:i}),n.info({templateId:e.id,sourceGoalId:o,newGoalId:s,taskId:i},"Goal reference triggered, dispatched decomposition task")}return}await this.workflowExecutor.execute(e,t)}scheduleOnceJob(e){let t=c(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let s=`template-${e}`;this.cronJobs.has(s)&&clearTimeout(this.cronJobs.get(s));let i=setTimeout(()=>{this.cronJobs.delete(s),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(s,i),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=c(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,l()),R(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},_=null;function Y(){return _}function Z(f){_=f}export{A as a,Y as b,Z as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i}from"./chunk-6KLG4APZ.js";import{d as a}from"./chunk-REKCZ3GY.js";import{f as c,h as C}from"./chunk-WBAPIPST.js";import{c as l,h as A}from"./chunk-INNDBLZE.js";C();import{readFileSync as R,existsSync as P}from"fs";import{resolve as y}from"path";import{homedir as _}from"os";import{parse as O}from"yaml";A();var w=l("config");function E(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function d(e){return e.startsWith("~/")?y(_(),e.slice(2)):e}function f(e){if(typeof e=="string")return E(e);if(Array.isArray(e))return e.map(f);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=f(n);return t}return e}function p(e,t){let r={...e};for(let n of Object.keys(t)){let s=t[n],o=e[n];s!==null&&typeof s=="object"&&!Array.isArray(s)&&o!==null&&typeof o=="object"&&!Array.isArray(o)?r[n]=p(o,s):r[n]=s}return r}function g(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(d)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(w.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(d)),e}function S(){let e={};for(let t of process.argv.slice(2)){let r=t.match(/^--([a-z-]+)=(.+)$/);r&&(e[r[1]]=r[2])}return e}function h(e){let t=process.env.ADAM_PORT;t&&(e.server.port=parseInt(t,10));let r=process.env.ANTHROPIC_MODEL;r&&(e.defaults.model=r);let n=process.env.ADAM_API_KEY;return n&&(e.server.apiKey=n),e}function m(e){let t=S();return t.port&&(e.server.port=parseInt(t.port,10)),t.host&&(e.server.host=t.host),t.timeout&&(e.defaults.timeout=parseInt(t.timeout,10)),t["api-key"]&&(e.server.apiKey=t["api-key"]),e}function T(e){let t=e??c,r={};if(P(t)){let v=R(t,"utf-8"),u=O(v);u&&(r=f(u))}let n=p(i,r),s=h(n),o=m(s);return g(o)}function k(){let e=JSON.parse(JSON.stringify(i)),t=h(e),r=m(t);return g(r)}function x(){let e={},t={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel",ADAM_PORT:"server.port",ADAM_API_KEY:"server.apiKey"};for(let[r,n]of Object.entries(t)){let s=process.env[r];if(s&&s.length>0)if(n==="server.port"){let o=parseInt(s,10);isNaN(o)||(e[n]=o)}else e[n]=s}return e}function Y(){try{return a().defaults}catch{return i.defaults}}function B(){try{return a().chat??i.chat}catch{return i.chat}}export{T as a,k as b,x as c,Y as d,B as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as l}from"./chunk-
|
|
1
|
+
import{b as s,d as l}from"./chunk-CREHL4BN.js";l();function o(e){let n={type:e.trigger_type,cron:e.trigger_type==="once"?void 0:e.trigger_cron??void 0,event:e.trigger_event??void 0,runAt:e.trigger_type==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:n,steps:JSON.parse(e.steps),rolePreference:e.role_preference??void 0,config:e.config?JSON.parse(e.config):void 0,tags:e.tags?JSON.parse(e.tags):void 0,enabled:e.enabled===1,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,goalIds:e.goal_ids?JSON.parse(e.goal_ids):void 0}}function u(e){s().prepare(`
|
|
2
2
|
INSERT INTO task_templates (id, name, description, trigger_type, trigger_cron,
|
|
3
3
|
trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
|
|
4
4
|
source_session_id, deliver_to, report_to, goal_ids)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as n,d as o}from"./chunk-
|
|
1
|
+
import{b as n,d as o}from"./chunk-CREHL4BN.js";o();function a(e){return{id:e.id,sessionId:e.session_id,role:e.role,content:e.content,source:{type:e.source_type},taskId:e.task_id??void 0,channelMessageId:e.channel_message_id??void 0,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.created_at}}function c(e){n().prepare(`
|
|
2
2
|
INSERT INTO chat_messages (id, session_id, role, content, source_type, task_id,
|
|
3
3
|
channel_message_id, metadata, created_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as n,h as g}from"./chunk-INNDBLZE.js";g();import{query as l}from"@anthropic-ai/claude-agent-sdk";import*as i from"fs/promises";import*as a from"path";import*as m from"os";var v=n("manager"),e=a.join(m.homedir(),".adam","llm-eval");async function w(u,t){await i.mkdir(e,{recursive:!0});let o={cwd:e,maxTurns:3,maxBudgetUsd:.05};t&&(o.systemPrompt=t);let c=l({prompt:u,options:o}),s="";for await(let f of c){let r=f;r.type==="result"&&typeof r.result=="string"&&(s=r.result)}return s}export{w as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as i}from"./chunk-
|
|
1
|
+
import{b as s,d as i}from"./chunk-CREHL4BN.js";i();function l(e){return{id:e.id,name:e.name,platform:e.platform,enabled:e.enabled===1,status:e.status,config:JSON.parse(e.config),linkedRoleId:e.linked_role_id??void 0,allowedChatIds:e.allowed_chat_ids?JSON.parse(e.allowed_chat_ids):void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0,lastMessageAt:e.last_message_at??void 0,messageCount:e.message_count}}function o(e){s().prepare(`
|
|
2
2
|
INSERT INTO channels (id, name, platform, enabled, status, config, linked_role_id,
|
|
3
3
|
allowed_chat_ids, created_at, updated_at, last_message_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as e,d as t,h as a}from"./chunk-WBAPIPST.js";a();var r={defaults:{timeout:600,maxTurns:100,maxBudgetUsd:5,effort:"high",model:"",settingSources:["user","project"],allowedTools:[],disallowedTools:[],approvalRequired:["rm -rf *","git push*","git reset*","curl * -X POST*","curl * --request POST*"],approvalTimeout:600,env:{},plugins:[],workspacePath:t,workspaceRetention:"immediate",deniedReadPaths:[...e]},externalApis:[],server:{port:7100,host:"0.0.0.0",timezone:"system"},logging:{level:"info"},roles:{presets:[],evolution:{triggerEvery:5,reflectionThreshold:150,retirementThreshold:.4,probationTasks:5}},chat:{sessionTimeoutMinutes:30,maxSessionTurns:20,autoTitle:!0,archiveExtractMemory:!0},watchdog:{enabled:!0,intervalMinutes:5,rules:{managerHealthCheck:{enabled:!0,action:"notify",staleDurationMinutes:15},staleTasks:{enabled:!0,action:"notify",maxPendingMinutes:30},staleRunningTasks:{enabled:!0,action:"notify",maxRunningMinutes:15},dbMaintenance:{enabled:!0,action:"ignore",walCheckpointThresholdMB:100},sandboxViolation:{enabled:!0,action:"alert"}}},execution:{maxConcurrent:5,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4},anthropic:{apiKey:"",baseUrl:"",model:"",defaultOpusModel:"",defaultSonnetModel:"",defaultHaikuModel:"",smallFastModel:""}};export{r as a};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as I,f as G}from"./chunk-U3XVAAXA.js";import{a as J}from"./chunk-2C5U3CNX.js";import{a as j}from"./chunk-2CMR5AG7.js";import{a as E,b as S,c as D,j as T}from"./chunk-I5RUEOSQ.js";import{b as P,d as B}from"./chunk-CREHL4BN.js";import{c as W,e as q}from"./chunk-FCV2DPZQ.js";var Q={};q(Q,{getGlobalEnabledState:()=>w,getInstalledPlugin:()=>z,getPluginManifest:()=>_,listInstalledPlugins:()=>A,listMarketplaceSources:()=>V,resolvePluginPaths:()=>M,scanDirectoryConfig:()=>x});import{existsSync as y,readFileSync as k,readdirSync as C}from"fs";import{join as p}from"path";import L from"os";function h(t){try{if(!y(t))return null;let e=k(t,"utf-8");return JSON.parse(e)}catch{return null}}function w(){return h(Y())?.enabledPlugins??{}}function _(t){let e=t;function s(n,r){let o={};try{if(!y(n))return o;let d=k(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let m of r){let i=new RegExp(`^${m}:\\s*(.+)$`,"m"),a=d.match(i);a&&(o[m]=a[1].trim())}}catch{}return o}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},r=p(e,".claude-plugin","plugin.json");if(y(r))try{let i=JSON.parse(k(r,"utf-8"));n.name=i.name??"",n.version=i.version,n.description=i.description,Array.isArray(i.lspServers)&&(n.lspServers=i.lspServers),Array.isArray(i.mcpServers)&&(n.mcpServers=i.mcpServers),Array.isArray(i.hooks)&&(n.hooks=i.hooks)}catch{}let o=p(e,"skills");if(y(o)){let i=C(o,{withFileTypes:!0});for(let a of i){if(!a.isDirectory()&&!a.isSymbolicLink())continue;let u=p(o,a.name,"SKILL.md"),f=s(u,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let l=p(e,"agents");if(y(l)){let i=C(l,{withFileTypes:!0});for(let a of i){if(!a.isFile()||!a.name.endsWith(".md"))continue;let u=s(p(l,a.name),["name","description"]);u.name&&n.agents.push({name:u.name,description:u.description??""})}}let d=p(e,".mcp.json");if(y(d))try{let i=JSON.parse(k(d,"utf-8"));i.mcpServers&&typeof i.mcpServers=="object"&&(n.mcpServers=Object.keys(i.mcpServers))}catch{}let m=p(e,"hooks","hooks.json");if(y(m))try{let i=JSON.parse(k(m,"utf-8"));Array.isArray(i)&&(n.hooks=i.map(a=>typeof a=="object"&&a!==null&&"event"in a?String(a.event):String(a)))}catch{}return n}catch{return null}}function A(t){let e=h(R());if(!e?.plugins)return[];let s=w(),n=[];for(let[r,o]of Object.entries(e.plugins))if(!(!Array.isArray(o)||o.length===0))for(let l of o){let d=l.scope??"user";t?.scope&&d!==t.scope||t?.projectPath&&l.projectPath!==t.projectPath||n.push({id:r,name:r.split("@")[0],version:l.version??"",scope:d,projectPath:l.projectPath,installPath:l.installPath??p(v(),r),enabled:s[r]??l.enabled??!0,installedAt:l.installedAt??"",lastUpdated:l.lastUpdated??""})}return n}function z(t){let e=h(R());if(!e?.plugins?.[t])return null;let s=e.plugins[t];if(!Array.isArray(s)||s.length===0)return null;let n=s[0],r=w();return{id:t,name:t.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??p(v(),t),enabled:r[t]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function M(t){let e=h(R()),s=new Map;for(let n of t){let r=e?.plugins?.[n];Array.isArray(r)&&r.length>0&&s.set(n,r[0].installPath??p(v(),n))}return s}function V(){return h(H())?.marketplaces??[]}function x(t){let e=p(t,".claude","settings.json"),s=h(e);return{enabledPlugins:s?.enabledPlugins??{},mcpServers:s?.mcpServers??{},allowedTools:s?.allowedTools??[],disallowedTools:s?.disallowedTools??[]}}var v,R,H,Y,O=W(()=>{"use strict";v=()=>p(L.homedir(),".claude","plugins"),R=()=>p(v(),"installed_plugins.json"),H=()=>p(v(),"known_marketplaces.json"),Y=()=>p(L.homedir(),".claude","settings.json")});import{tool as b}from"@anthropic-ai/claude-agent-sdk";import{z as c}from"zod";import{v4 as X}from"uuid";function g(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}var Z={query:c.string().describe("Search query for memory retrieval"),roleId:c.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:c.number().optional().describe("Max results to return (default 5)")},ee={query:c.string().describe("Search query for memory retrieval"),topK:c.number().optional().describe("Max results to return (default 5)")},te={id:c.string().optional().describe("Memory ID to update. Omit to create new."),roleId:c.string().describe("Role ID to save memory under"),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},ne={id:c.string().optional().describe("Memory ID to update. Omit to create new."),content:c.string().describe("Memory content text"),type:c.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:c.array(c.string()).optional().describe("Keywords for BM25 search"),importance:c.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:c.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},N={id:c.string().describe("Memory ID to delete")};async function F(t,e){let s=t??e.roleId,n=e.topK??5,r=await J(s,e.query,{topK:n});return g({results:r.map(o=>({id:o.id,type:o.type,content:o.content,keywords:o.keywords,importance:o.importance,score:o.score}))})}async function $(t,e){let s=t??e.roleId;if(!s)return g({error:"roleId is required"});let n,r=!0;try{n=await j(e.content)}catch{r=!1}if(e.id){if(!S(e.id))return g({error:`Memory ${e.id} not found`});let m=D(e.id,{content:e.content,embedding:n,keywords:e.keywords,importance:e.importance,type:e.type});return g({id:e.id,action:"updated",success:m,embeddingUpdated:r})}let o=`mem-${X().slice(0,8)}`,l=Date.now();return E({id:o,roleId:s,type:e.type??"thought",content:e.content,embedding:n,keywords:e.keywords??[],importance:e.importance??3,sourceType:"manual",createdAt:l,lastAccessed:l,retrievedCount:0,tier:e.tier??"episodic"}),g({id:o,action:"created",success:!0,embeddingUpdated:r})}async function K(t,e){if(t){let s=S(e.id);if(!s)return g({error:`Memory ${e.id} not found`});if(s.roleId!==t)return g({error:`Memory ${e.id} does not belong to this role`})}return T(e.id),g({id:e.id,deleted:!0})}function ye(t){return t?[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",ee,async e=>F(t,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",ne,async e=>$(t,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(t,e))]:[b("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Z,async e=>F(void 0,e)),b("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",te,async e=>$(void 0,e)),b("delete_memory","Delete a memory by ID.",N,async e=>K(void 0,e))]}O();G();var re={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function ve(t,e){let s=t.allowedTools??[];if(s.length===0)return"No tool permissions";let n=new Map,r=[];for(let i of s){let a=re[i];if(a){let u=n.get(a.category)??[];u.push(a.label),n.set(a.category,u)}else r.push(i)}let o=[];for(let[i,a]of n)o.push(`${i} (${a.join(", ")})`);r.length>0&&o.push(r.join(", "));let l=o.join(" \xB7 "),d=Object.keys(t.mcpServers??{});d.length>0&&(l+=` \xB7 MCP: ${d.join(", ")}`);let m=t.additionalDirectories??[];if(m.length>0&&(l+=` \xB7 Dirs: ${m.map(i=>i.path).join(", ")}`),e&&e.plugins.length>0){let i=e.plugins.map(a=>{let u=[];return a.skills.length>0&&u.push(`skills: ${a.skills.map(f=>f.name).join(", ")}`),a.agents.length>0&&u.push(`agents: ${a.agents.map(f=>f.name).join(", ")}`),u.length>0?`${a.name} (${u.join("; ")})`:a.name});l+=` \xB7 Plugins: ${i.join(", ")}`}return l}function oe(t){let e=[],s=t.additionalDirectories??[];for(let n of s){if(!n.inheritPlugins&&!n.inheritMcp)continue;let r=x(n.path),o=Object.entries(r.enabledPlugins).filter(([,d])=>d).map(([d])=>d),l=M(o);for(let[,d]of l)e.includes(d)||e.push(d)}try{let n=I(t.name),r=A({scope:"project",projectPath:n});for(let o of r)o.installPath&&!e.includes(o.installPath)&&e.push(o.installPath)}catch{}return e}function Pe(t){let e=oe(t),s=[];for(let n of e){let r=_(n);r&&s.push({name:r.name||n.split("/").pop()||"unknown",description:r.description,skills:r.skills,agents:r.agents,mcpServers:r.mcpServers,hooks:r.hooks})}return{plugins:s}}B();function se(t){return{id:t.id,roleId:t.role_id??void 0,taskPattern:t.task_pattern,maxRiskLevel:t.max_risk_level,createdAt:t.created_at,createdByTaskId:t.created_by_task_id??void 0}}var U={low:1,medium:2,high:3};function we(t){P().prepare(`
|
|
2
|
+
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
3
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
4
|
+
`).run(t.id,t.roleId??null,t.taskPattern,t.maxRiskLevel,t.createdAt,t.createdByTaskId??null)}function _e(t,e,s){let r=P().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let o of r)if(!(o.role_id&&o.role_id!==t)&&!(U[s]>U[o.max_risk_level]))try{if(new RegExp(o.task_pattern,"i").test(e))return se(o)}catch{}}export{we as a,_e as b,w as c,_ as d,A as e,z as f,V as g,x as h,Q as i,O as j,ye as k,ve as l,oe as m,Pe as n};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as I}from"./chunk-
|
|
1
|
+
import{a as T,b as I}from"./chunk-42RHY3Q3.js";import{b as A,d as L}from"./chunk-CREHL4BN.js";import{g as l,h as b}from"./chunk-WBAPIPST.js";import{c as O,h as D}from"./chunk-INNDBLZE.js";import{readFileSync as v,existsSync as y}from"fs";import{fileURLToPath as k}from"url";import{dirname as F,join as d}from"path";var V=k(import.meta.url),R=F(V),_,h;function E(){let e=d(R,"..","package.json");if(y(e))return e;let r=d(R,"..","..","package.json");return y(r)?r:d(process.cwd(),"package.json")}function J(){if(_===void 0){let e=E();_=JSON.parse(v(e,"utf-8")).version}return _}function q(){if(h===void 0){let e=E();h=JSON.parse(v(e,"utf-8")).name}return h}L();D();import{dirname as w,join as H}from"path";import{fileURLToPath as C}from"url";var M=w(C(import.meta.url)),P=H(M,"..");var $=P,rt=O("cli:register-ai-digest"),p="ai-hourly-digest";function U(){try{if(I(p)){console.log(`[INFO] AI Digest template already exists (${p})`);return}}catch{}let e={id:p,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
|
|
2
2
|
|
|
3
3
|
\u641C\u7D22\u6765\u6E90:
|
|
4
4
|
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
@@ -39,14 +39,14 @@ import{a as T,b as I}from"./chunk-VF6GJGD6.js";import{b as O,d as L}from"./chunk
|
|
|
39
39
|
|
|
40
40
|
\u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
|
|
41
41
|
|
|
42
|
-
osascript ${
|
|
42
|
+
osascript ${$}/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
|
|
43
43
|
|
|
44
44
|
\u6CE8\u610F\uFF1A
|
|
45
45
|
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
46
46
|
- \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
|
|
47
47
|
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
48
48
|
|
|
49
|
-
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300
|
|
50
|
-
`)){let o=s.trim();if(!o||o.startsWith("#"))continue;let c=o.startsWith("export ")?o.slice(7).trim():o,i=c.indexOf("=");if(i===-1)continue;let n=c.slice(0,i).trim();if(!(n in u))continue;let t=c.slice(i+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(
|
|
51
|
-
`),o=0,c=new Set;for(let i=0;i<s.length;i++){let n=s[i].trim();if(!n||n.startsWith("#"))continue;let t=n.startsWith("export ")?n.slice(7).trim():n,
|
|
52
|
-
`)),o}export{
|
|
49
|
+
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};T(e),console.log(`[INFO] Registered AI Hourly Digest task template (${p})`),console.log("[INFO] Cron schedule: 0 * * * * (every hour at minute 0)")}import.meta.url===`file://${process.argv[1]}`&&(console.log("Initializing database..."),A(),console.log("Registering AI Digest template..."),U(),console.log("Done."),process.exit(0));b();import{readFileSync as x,writeFileSync as j,existsSync as N}from"fs";var u={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel"},at=Object.fromEntries(Object.entries(u).map(([e,r])=>[r,e]));function W(){if(!N(l))return null;let e=x(l,"utf-8"),r={};for(let s of e.split(`
|
|
50
|
+
`)){let o=s.trim();if(!o||o.startsWith("#"))continue;let c=o.startsWith("export ")?o.slice(7).trim():o,i=c.indexOf("=");if(i===-1)continue;let n=c.slice(0,i).trim();if(!(n in u))continue;let t=c.slice(i+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(m,f,g)=>{let a=f??g;return r[a]??process.env[a]??""}),!t))&&(r[n]=t)}return r}function lt(e){let r=W();if(!r)return[];let s=[];for(let[o,c]of Object.entries(u)){let i=e[c],n=r[o];if(n===void 0)continue;let t=i?String(i):"";t!==n&&s.push({configPath:c,envKey:o,dbValue:t,envValue:n})}return s}function ft(e){if(!N(l))return 0;let s=x(l,"utf-8").split(`
|
|
51
|
+
`),o=0,c=new Set;for(let i=0;i<s.length;i++){let n=s[i].trim();if(!n||n.startsWith("#"))continue;let t=n.startsWith("export ")?n.slice(7).trim():n,m=t.indexOf("=");if(m===-1)continue;let f=t.slice(0,m).trim(),g=u[f];if(!g)continue;let a=e[g];if(a!=null&&String(a).length>0){let S=n.startsWith("export ")?"export ":"";s[i]=`${S}${f}=${String(a)}`,c.add(f),o++}}for(let[i,n]of Object.entries(u)){if(c.has(i))continue;let t=e[n];t&&String(t).length>0&&(s.push(`${i}=${String(t)}`),o++)}return o>0&&j(l,s.join(`
|
|
52
|
+
`)),o}export{P as a,J as b,q as c,at as d,W as e,lt as f,ft as g,U as h};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{b as C}from"./chunk-64FIXWFL.js";import{b as D,c as f,d as w}from"./chunk-TEMWI6U5.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as M,h as U}from"./chunk-INNDBLZE.js";function O(s,c,n){switch(c){case"wechat":return $(s);case"telegram":return s;case"slack":return P(s);case"webhook":return JSON.stringify({result:s,taskId:n,timestamp:new Date().toISOString()});default:return $(s)}}function $(s){return s.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
|
+
|
|
3
|
+
`).trim()}function P(s){return s.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}U();import{v4 as T}from"uuid";var x=M("adam"),v=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:a,chatId:m,content:y,messageType:d,platform:E,webhookUrl:h,replyMarkup:I,mediaUrl:S,mediaType:b}=c,R=d!=="reply"&&!!n,r;if(R){r=`${n}:${a??"none"}:${m??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return x.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=T();return x.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let L=E??(a?C(a)?.platform:void 0)??"unknown",k=h?y:O(y,L,n),e=T(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:a&&m?{type:"channel",channelId:a,chatId:m}:h?{type:"webhook",webhookUrl:h}:{type:"channel",channelId:a??"",chatId:m??""},content:k,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};D(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(h){let t=await fetch(h,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&m){let{getChannelManager:t}=await import("./channels-PQCV74ZI.js"),i=t();if(!i){let l="ChannelManager not available";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}let o={content:k,...I?{replyMarkup:I}:{},...S?{mediaUrl:S}:{},...b?{mediaType:b}:{}},u=await i.sendMessage(a,m,o);if(u===null){let l="Channel adapter send failed (returned null)";return f(e,"failed",l),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:d}),{success:!1,logEntryId:e,error:l}}return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return f(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function W(){return _||(_=new v),_}function q(s){return W().isRecentlySent(s)}export{v as a,W as b,q as c};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as u}from"./chunk-
|
|
1
|
+
import{b as i,d as u}from"./chunk-CREHL4BN.js";u();function c(t){return{id:t.id,status:t.status,source:{type:t.source_type,channelId:t.source_channel_id??void 0,chatId:t.source_chat_id??void 0},title:t.title??void 0,createdAt:t.created_at,lastActiveAt:t.last_active_at,archivedAt:t.archived_at??void 0,messageCount:t.message_count}}function d(t){i().prepare(`
|
|
2
2
|
INSERT INTO chat_sessions (id, status, source_type, source_channel_id, source_chat_id,
|
|
3
3
|
title, created_at, last_active_at, archived_at, message_count)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|