adam-agent-server 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/App-RIYRYLKD.js +9 -0
- package/dist/adam-tools-YBKSTHVJ.js +1 -0
- package/dist/approval-handler-JYIS2PKQ.js +1 -0
- package/dist/audit-manager-7M2CDMP5.js +1 -0
- package/dist/bree-engine-Y24K4PXN.js +1 -0
- package/dist/channels-WMCY4QC3.js +1 -0
- package/dist/{channels-NAPXRIOX.js → channels-WZOYE4O4.js} +1 -1
- package/dist/chunk-2HN2TSP6.js +5 -0
- package/dist/{chunk-ROSOI75V.js → chunk-3RAFA6QK.js} +1 -1
- package/dist/{chunk-I5RUEOSQ.js → chunk-4TCP2AT7.js} +1 -1
- package/dist/{chunk-42RHY3Q3.js → chunk-6DXNXLYG.js} +1 -1
- package/dist/chunk-6HD6NYIB.js +1 -0
- package/dist/{chunk-GA7GEIXB.js → chunk-6YURWVQG.js} +1 -1
- package/dist/chunk-7IFLU3CY.js +4 -0
- package/dist/{chunk-QMKQBU3R.js → chunk-7LBDLAUQ.js} +1 -1
- package/dist/{chunk-BONI2HUN.js → chunk-AJVN3KPM.js} +1 -1
- package/dist/{chunk-4TBGFHYX.js → chunk-AR2IZMM2.js} +1 -1
- package/dist/chunk-B4WHT7DX.js +8 -0
- package/dist/{chunk-XFTRKHH2.js → chunk-BIIP363C.js} +1 -1
- package/dist/{chunk-KHPXEUSY.js → chunk-CDVIT7L5.js} +1 -1
- package/dist/{chunk-BCELBB5Q.js → chunk-EGS6U3V5.js} +2 -2
- package/dist/{chunk-NFSXJNPD.js → chunk-EJVUUIAV.js} +1 -1
- package/dist/{chunk-X26NKAXY.js → chunk-GMCIKDTC.js} +1 -1
- package/dist/{chunk-2C5U3CNX.js → chunk-GUQAIWCQ.js} +1 -1
- package/dist/chunk-IHP7JV6J.js +1 -0
- package/dist/chunk-JTMFEUDA.js +1 -0
- package/dist/chunk-KLQOILIJ.js +21 -0
- package/dist/{chunk-CREHL4BN.js → chunk-KVSO3KGZ.js} +1 -1
- package/dist/{chunk-YEV5YTS3.js → chunk-MPRAVJUO.js} +1 -1
- package/dist/{chunk-6VPL5CXB.js → chunk-OEKM2W3K.js} +1 -1
- package/dist/{chunk-TEMWI6U5.js → chunk-OFOVSC72.js} +1 -1
- package/dist/chunk-PMHNW5IL.js +49 -0
- package/dist/{chunk-35DBEYMG.js → chunk-Q4YE5BU7.js} +1 -1
- package/dist/{chunk-PT55643Q.js → chunk-QN6BEJF5.js} +1 -1
- package/dist/{chunk-64FIXWFL.js → chunk-SWPXG2CY.js} +1 -1
- package/dist/{chunk-CFTWJZVX.js → chunk-U5NRQNBB.js} +14 -14
- package/dist/{chunk-QC6QVNKP.js → chunk-UW3OJG7U.js} +3 -3
- package/dist/chunk-WVGNP2LQ.js +3 -0
- package/dist/cli.js +4 -4
- package/dist/{config-N2GMLTPU.js → config-EI3SCA4W.js} +1 -1
- package/dist/config-OH6Q2D2Y.js +1 -0
- package/dist/{db-S6HDMJ3B.js → db-4NY7ZOS2.js} +1 -1
- package/dist/{delivery-log-VAI35G5V.js → delivery-log-SC2ULFCK.js} +1 -1
- package/dist/engine-JKSNQQDM.js +1 -0
- package/dist/{evolution-audit-KCFDGNSM.js → evolution-audit-KUBXFUHI.js} +1 -1
- package/dist/index.js +10 -10
- package/dist/{learner-ABYVK33T.js → learner-UYDFNURD.js} +1 -1
- package/dist/{memories-3ZAV55YZ.js → memories-FQCRKMK6.js} +1 -1
- package/dist/{memory-extractor-BHHKD7X7.js → memory-extractor-FUOJ5D77.js} +2 -2
- package/dist/memory-service-ANR67OPY.js +1 -0
- package/dist/outbound-gateway-6FQRWYFF.js +1 -0
- package/dist/role-presets-LRP6P5O2.js +1 -0
- package/dist/{roles-LXRHEVUK.js → roles-3UTFKSHI.js} +1 -1
- package/dist/runtime-B2DP3JNB.js +1 -0
- package/dist/session-manager-VYKNKQ46.js +1 -0
- package/dist/{task-templates-XQNKAA4U.js → task-templates-PSP7GOJJ.js} +1 -1
- package/package.json +2 -1
- package/web/dist/assets/Card-4mOZntHG.js +1 -0
- package/web/dist/assets/ChannelDetail-e6rVX_y8.js +1 -0
- package/web/dist/assets/Channels-DJvZPKer.js +12 -0
- package/web/dist/assets/Chat-hTZdEwyE.js +1 -0
- package/web/dist/assets/Dashboard-B4rL_ePs.js +1 -0
- package/web/dist/assets/{EmptyState-DBFJc4PL.js → EmptyState-BlgMMAr-.js} +1 -1
- package/web/dist/assets/EnvVarEditor-C8kRWejV.js +1 -0
- package/web/dist/assets/Evolution-BGwFCo7X.js +6 -0
- package/web/dist/assets/GoalDetail-BH2ku-0t.js +1 -0
- package/web/dist/assets/Goals-DynDtpMC.js +1 -0
- package/web/dist/assets/Logs-CyJFouE6.js +1 -0
- package/web/dist/assets/Memories-ClcFD7OG.js +1 -0
- package/web/dist/assets/{NotFound-Cidygwnn.js → NotFound-CSjhzSGa.js} +1 -1
- package/web/dist/assets/Plugins-SNOQNNcL.js +1 -0
- package/web/dist/assets/RoleDetail-vlTPiYwY.js +33 -0
- package/web/dist/assets/Roles-CFcuHIvA.js +1 -0
- package/web/dist/assets/Settings-C9Kuz-6D.js +1 -0
- package/web/dist/assets/Strategies-DZWlQCHp.js +1 -0
- package/web/dist/assets/Switch-DOi0EFHj.js +1 -0
- package/web/dist/assets/Table-BxbnOSbq.js +1 -0
- package/web/dist/assets/TaskDetail-DjmmnldI.js +2 -0
- package/web/dist/assets/Work-CvESHC3Y.js +1 -0
- package/web/dist/assets/index-BFmC20R2.js +52 -0
- package/web/dist/assets/index-CaocwyO8.css +2 -0
- package/web/dist/assets/{vendor-icons-ZPvC5PUS.js → vendor-icons-CkI4-NxL.js} +1 -1
- package/web/dist/assets/{vendor-react--nRVf2Ep.js → vendor-react-DLRtONKt.js} +1 -1
- package/web/dist/assets/vendor-state-B_-GdGNJ.js +1 -0
- package/web/dist/index.html +5 -5
- package/dist/App-SCPYTYGQ.js +0 -9
- package/dist/adam-tools-FNJJT7AA.js +0 -1
- package/dist/approval-handler-UDWAC5MF.js +0 -4
- package/dist/audit-manager-SCX53YJT.js +0 -1
- package/dist/bree-engine-2DB2QECM.js +0 -1
- package/dist/channels-PQCV74ZI.js +0 -1
- package/dist/chunk-3TIHZZMK.js +0 -1
- package/dist/chunk-7KCBFM2C.js +0 -52
- package/dist/chunk-FXFHGIY6.js +0 -8
- package/dist/chunk-IZQI6QQ7.js +0 -1
- package/dist/chunk-NQHTOFQP.js +0 -1
- package/dist/chunk-REKCZ3GY.js +0 -1
- package/dist/chunk-U3XVAAXA.js +0 -17
- package/dist/config-L4R273R3.js +0 -1
- package/dist/engine-E67UAI3G.js +0 -1
- package/dist/memory-service-5QHTKIUU.js +0 -1
- package/dist/outbound-gateway-ZFKSN2UT.js +0 -1
- package/dist/role-presets-OTU2M37Y.js +0 -1
- package/dist/runtime-UCOE6LNN.js +0 -1
- package/dist/session-manager-RPXFZKMY.js +0 -1
- package/web/dist/assets/Card-BecEmnPW.js +0 -1
- package/web/dist/assets/ChannelDetail-BajTUEU0.js +0 -1
- package/web/dist/assets/Channels-Bhy6rP_t.js +0 -12
- package/web/dist/assets/Chat-Dvt_Oo7d.js +0 -1
- package/web/dist/assets/Dashboard-DlrAor-C.js +0 -1
- package/web/dist/assets/Evolution-Dlsnnr4G.js +0 -6
- package/web/dist/assets/GoalDetail-BuUxwYdd.js +0 -1
- package/web/dist/assets/Goals-CkPQOev6.js +0 -1
- package/web/dist/assets/Logs-D33PqDAd.js +0 -1
- package/web/dist/assets/Memories-D31dbUM6.js +0 -1
- package/web/dist/assets/Plugins-XlBr07x8.js +0 -1
- package/web/dist/assets/RoleDetail-rZFlgXzh.js +0 -33
- package/web/dist/assets/Roles-d29AC6Kh.js +0 -1
- package/web/dist/assets/Settings-Bjh_RXYf.js +0 -1
- package/web/dist/assets/Strategies-Cf4ghknk.js +0 -1
- package/web/dist/assets/Switch-CxzUYL49.js +0 -1
- package/web/dist/assets/Table-tkJ-cuiE.js +0 -1
- package/web/dist/assets/TaskDetail-jMBJbaRU.js +0 -2
- package/web/dist/assets/Work-CCLTkitf.js +0 -1
- package/web/dist/assets/index-CVubgAlC.css +0 -2
- package/web/dist/assets/index-Ds41VvOC.js +0 -52
- package/web/dist/assets/vendor-state-CH64feAE.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{b as v,d as Ht,e as Ro}from"./chunk-VRP4LTHY.js";import{a as Gt,f as Ao,h as Do}from"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{Box as qt,Text as Pt,useInput as ls}from"ink";import{useState as cs,useEffect as so,useRef as wo}from"react";import{createContext as Dr,useContext as Rr,useReducer as Mr}from"react";import{jsx as _r}from"react/jsx-runtime";var Nr={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 Lr(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 Mo=Dr(null);function No({children:e}){let[t,o]=Mr(Lr,Nr);return _r(Mo.Provider,{value:{state:t,dispatch:o},children:e})}function st(){let e=Rr(Mo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Lo,useRef as _o}from"react";var Vr=15e3;function Vo(){let{state:e,dispatch:t}=st(),o=_o(null),c=_o(null);Lo(()=>{c.current=e.session?.id??null},[e.session?.id]),Lo(()=>{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})},Vr)};return(()=>{try{m=new Ht("/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 b=await v(`/tasks/${a.taskId}`);u&&b.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 v("/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 $r,useRef as Or,useState as $o,useCallback as qr}from"react";function Oo(e){let[t,o]=$o([]),[c,u]=$o(!1),m=Or(null),l=qr(()=>{o([]),u(!1)},[]);return $r(()=>{if(!e)return;let i=!0;o([]),u(!0);try{let n=new Ro(e);return m.current=n,n.on("reasoning",r=>{if(!i)return;let d=r.content??"";o(b=>{let p=b[b.length-1];if(p?.type==="reasoning"){let y=[...b];return y[y.length-1]={...p,content:p.content+d},y}return[...b,{type:"reasoning",content:d,timestamp:Date.now()}]})}),n.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}}])}),n.on("tool_result",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"tool_result",content:a.content??"",timestamp:Date.now()}])}),n.on("error",r=>{if(!i)return;let a=r;o(d=>[...d,{type:"error",content:a.error??"unknown error",timestamp:Date.now()}])}),n.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)}),n.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),u(!1))}),()=>{i=!1,n.close()}}catch{u(!1)}},[e]),{events:t,isStreaming:c,clearEvents:l}}import{useState as io,useEffect as Fr,useCallback as Dt}from"react";function ao(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function qo(){let[e,t]=io(null),[o,c]=io(!0),[u,m]=io(null),l=Dt(async()=>{try{let b=(await v("/chat/sessions?status=active")).sessions.find(p=>p.source.type==="tui");return b?ao(b):null}catch{return null}},[]),i=Dt(async()=>{try{let d=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),b=ao(d.session);return t(b),b}catch{return m("Failed to create session"),null}},[]),n=Dt(async d=>{try{let b=await v("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(p=>p&&{...p,messageCount:p.messageCount+1,lastActiveAt:Date.now()}),b}catch{return null}},[]),r=Dt(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),a=Dt(async()=>{if(e)try{let d=await v(`/chat/sessions/${e.id}`);t(ao(d.session))}catch{t(null)}},[e]);return Fr(()=>{let d=!1;async function b(){c(!0);let p=await l();d||(p?t(p):await i(),d||c(!1))}return b(),()=>{d=!0}},[]),{session:e,loading:o,error:u,sendMessage:n,createNewSession:i,archiveCurrentSession:r,refreshSession:a,setSession:t}}import{useEffect as Fo,useRef as Ur,useState as Wr}from"react";function Uo(e){let[t,o]=Wr(null),c=Ur(new Set);return Fo(()=>{if(!e)return;let u=!0,m=null;try{m=new Ht("/chat/stream"),m.on("chat_message",l=>{if(!u)return;let n=l.message;n&&n.sessionId===e&&n.role==="assistant"&&(c.current.has(n.id)||(c.current.add(n.id),o(n)))}),m.connect().catch(()=>{})}catch{}return()=>{u=!1,m?.close()}},[e]),Fo(()=>{c.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as co,Text as Le}from"ink";import Ne from"chalk";var lo={connected:Ne.green,disconnected:Ne.red,warning:Ne.yellow,reasoning:Ne.gray,toolCall:Ne.blue,toolResult:Ne.green,error:Ne.red,dim:Ne.dim,bold:Ne.bold,statusUp:Ne.green("\u25CF"),statusDown:Ne.red("\u25CF")};import{Fragment as Gr,jsx as ut,jsxs as it}from"react/jsx-runtime";function Wo(){let{state:e}=st(),t=e.connected?`${lo.statusUp} Server: up`:`${lo.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 it(co,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[it(co,{children:[ut(Le,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),ut(Le,{children:" \u2502 "}),ut(Le,{children:t}),ut(Le,{children:" \u2502 "}),it(Le,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&it(Gr,{children:[ut(Le,{children:" \u2502 "}),it(Le,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),m&&ut(Le,{color:"yellow",children:" timeout soon"})]})]}),it(co,{children:[it(Le,{children:["Tasks: ",o]}),ut(Le,{children:" \u2502 "}),it(Le,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Kt,Text as jt,useInput as Kr}from"ink";import{useState as mo,useMemo as jr}from"react";import Qr from"ink-text-input";var Hr=[{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 uo(e){let t=e.toLowerCase();return Hr.filter(o=>o.name.startsWith(t))}function Go(e){let t=uo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Qt,jsxs as Rt}from"react/jsx-runtime";function Ho({onSubmit:e}){let[t,o]=mo(""),[c,u]=mo(0),[m,l]=mo(!1),i=t.startsWith("/")&&t.length>=1,n=t.slice(1),r=jr(()=>i?uo(n):[],[i,n]),a=p=>{o(p),p.startsWith("/")?(l(!0),u(0)):l(!1)},d=()=>{let p=t.trim();if(p){if(p.startsWith("/")){let y=p.slice(1),s=Go(y);e(s?`/${s.name}`:p)}else e(p);o(""),l(!1)}},b=p=>{e(`/${p.name}`),o(""),l(!1)};return Kr((p,y)=>{if(!(!m||!i||r.length===0)){if(y.upArrow){u(s=>s<=0?r.length-1:s-1);return}if(y.downArrow){u(s=>s>=r.length-1?0:s+1);return}if(y.tab){let s=r[c];s&&b(s);return}if(y.escape){l(!1),o("");return}}},{isActive:m&&i&&r.length>0}),Rt(Kt,{flexDirection:"column",children:[m&&i&&r.length>0&&Qt(Kt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((p,y)=>{let s=y===c;return Rt(Kt,{children:[Qt(jt,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),Rt(jt,{color:s?"cyan":"white",bold:s,children:["/",p.name]}),Rt(jt,{dimColor:!0,children:[" \u2014 ",p.description]})]},p.name)})}),Rt(Kt,{borderStyle:"round",borderDimColor:!0,children:[Qt(jt,{bold:!0,children:"\u25B8 "}),Qt(Qr,{value:t,onChange:a,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as ht,Text as Se}from"ink";import{useState as Xr}from"react";import{jsx as Pe,jsxs as Ue}from"react/jsx-runtime";function zr({content:e}){let[t,o]=Xr(!1),c=e.split(`
|
|
2
|
+
`);return c.length<=5?Pe(Se,{color:"green",children:e}):t?Pe(Se,{color:"green",children:e}):Ue(Se,{color:"green",children:[c.slice(0,3).join(`
|
|
3
|
+
`),`
|
|
4
|
+
`,Ue(Se,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function Yr({event:e}){switch(e.type){case"reasoning":return Pe(ht,{children:Pe(Se,{color:"gray",children:e.content})});case"tool_call":return Pe(ht,{children:Ue(Se,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Ue(ht,{flexDirection:"column",children:[Pe(Se,{color:"blue",dimColor:!0,children:"[result]"}),Pe(zr,{content:e.content})]});case"error":return Pe(ht,{children:Ue(Se,{color:"red",children:["[error] ",e.content]})});case"complete":return Ue(ht,{flexDirection:"column",marginTop:1,children:[e.content&&Pe(Se,{children:e.content}),Pe(Se,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Ue(Se,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Ue(Se,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Ue(Se,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function Ko({events:e,isStreaming:t}){return e.length===0&&!t?null:Ue(ht,{flexDirection:"column",children:[t&&e.length===0&&Pe(Se,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>Pe(Yr,{event:o},c))]})}import{Box as jo,Text as Qo}from"ink";import{jsx as go,jsxs as Jr}from"react/jsx-runtime";function Xo({messages:e}){return e.length===0?null:go(jo,{flexDirection:"column",children:e.map((t,o)=>Jr(jo,{flexDirection:"column",marginBottom:1,children:[go(Qo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),go(Qo,{children:t.content})]},o))})}import{Box as Mt,Text as We,useInput as Zr}from"ink";import{jsx as Ge,jsxs as Nt}from"react/jsx-runtime";function zo({approval:e,onResolved:t}){return Zr(o=>{o==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&v(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Nt(Mt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Ge(We,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Nt(Mt,{marginTop:1,children:[Ge(We,{children:"Tool: "}),Ge(We,{bold:!0,children:e.toolName})]}),Nt(Mt,{children:[Ge(We,{children:"Input: "}),Ge(We,{children:JSON.stringify(e.toolInput)})]}),Nt(Mt,{children:[Ge(We,{children:"Pattern: "}),Ge(We,{dimColor:!0,children:e.matchedPattern})]}),Nt(Mt,{marginTop:1,children:[Ge(We,{color:"green",children:"[a] Approve"}),Ge(We,{children:" "}),Ge(We,{color:"red",children:"[r] Reject"})]})]})}import{Box as Lt,Text as he,useInput as en}from"ink";import{useState as tn,useEffect as on}from"react";import{jsx as ze,jsxs as _e}from"react/jsx-runtime";var rn=300;function Yo({approval:e,onResolved:t,onTimeout:o}){let[c,u]=tn(rn);on(()=>{let l=setInterval(()=>{u(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),en(l=>{l==="a"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&v(`/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 _e(Lt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[ze(he,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),_e(he,{dimColor:!0,children:["Plan ID: ",e.planId]}),_e(he,{dimColor:!0,children:["Time remaining: ",c,"s"]}),_e(Lt,{marginTop:1,children:[ze(he,{children:"Overall Risk: "}),ze(he,{bold:!0,color:m,children:e.plan.overallRisk.toUpperCase()})]}),_e(he,{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 _e(Lt,{paddingLeft:2,children:[_e(he,{children:["[",l.index,"] "]}),ze(he,{children:l.description}),_e(he,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),_e(he,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),_e(Lt,{marginTop:1,children:[ze(he,{dimColor:!0,children:"Permissions: "}),ze(he,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),_e(Lt,{marginTop:1,children:[ze(he,{color:"green",children:"[a] Allow once "}),ze(he,{color:"green",children:"[p] Allow permanent "}),ze(he,{color:"red",children:"[r] Deny"})]})]})}import{Box as mt,Text as ie,useInput as an}from"ink";import{useEffect as ln,useState as Ye,useCallback as Zo}from"react";import{Box as te,Text as L,useInput as nn}from"ink";import{useState as fo,useEffect as sn}from"react";import{jsx as U,jsxs as K}from"react/jsx-runtime";function Jo({taskId:e,onBack:t}){let[o,c]=fo(null),[u,m]=fo([]),[l,i]=fo(null);if(sn(()=>{v(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),v(`/tasks/${e}/plan`).then(r=>m(r.plans)).catch(()=>m([]))},[e]),nn((r,a)=>{(r==="b"||a.escape)&&t()}),l)return K(te,{flexDirection:"column",children:[K(L,{color:"red",children:["Error: ",l]}),U(L,{dimColor:!0,children:"[b] Back"})]});if(!o)return K(L,{dimColor:!0,children:["Loading task ",e,"..."]});let n=u[0];return K(te,{flexDirection:"column",children:[U(L,{bold:!0,color:"cyan",children:"Task Detail"}),K(te,{marginTop:1,flexDirection:"column",children:[K(te,{children:[U(L,{children:"ID: "}),U(L,{dimColor:!0,children:String(o.id)})]}),K(te,{children:[U(L,{children:"Status: "}),U(L,{bold:!0,children:String(o.status)})]}),K(te,{children:[U(L,{children:"Prompt: "}),U(L,{children:String(o.prompt)})]}),o.result?K(te,{children:[U(L,{children:"Result: "}),U(L,{children:String(o.result).slice(0,200)})]}):null,o.error?K(te,{children:[U(L,{color:"red",children:"Error: "}),U(L,{children:String(o.error)})]}):null,o.deliverTo?.length?K(te,{children:[U(L,{children:"DeliverTo: "}),U(L,{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?K(te,{children:[U(L,{children:"ReportTo: "}),U(L,{dimColor:!0,children:o.reportTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null]}),n&&K(te,{marginTop:1,flexDirection:"column",children:[U(L,{bold:!0,color:"cyan",children:"Execution Plan"}),K(te,{children:[U(L,{children:"Plan ID: "}),U(L,{dimColor:!0,children:n.id})]}),K(te,{children:[U(L,{children:"Status: "}),U(L,{children:n.status})]}),n.plan.overallRisk&&K(te,{children:[U(L,{children:"Overall Risk: "}),U(L,{bold:!0,color:n.plan.overallRisk==="high"?"red":n.plan.overallRisk==="medium"?"yellow":"green",children:n.plan.overallRisk.toUpperCase()})]}),K(L,{bold:!0,children:["Steps (",n.plan.steps.length,"):"]}),n.plan.steps.map(r=>{let a=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return K(te,{paddingLeft:2,children:[K(L,{children:["[",r.index,"] ",r.description]}),K(L,{color:a,children:[" [",r.riskLevel,"]"]})]},r.index)}),n.deviationReport&&K(te,{marginTop:1,flexDirection:"column",children:[U(L,{bold:!0,color:"yellow",children:"Deviation Report"}),K(L,{children:["Planned: ",n.deviationReport.stepsPlanned," | Executed: ",n.deviationReport.stepsExecuted," | Accuracy: ",(n.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),n.deviationReport.deviations.map((r,a)=>K(te,{paddingLeft:2,children:[K(L,{color:"yellow",children:["[",r.deviationType,"] "]}),K(L,{children:["Step ",r.stepIndex,": ",r.actual]})]},a))]}),n.learnedRules&&n.learnedRules.length>0&&K(te,{marginTop:1,flexDirection:"column",children:[U(L,{bold:!0,color:"blue",children:"Learned Rules"}),n.learnedRules.map((r,a)=>U(te,{paddingLeft:2,children:K(L,{children:["* ",r]})},a))]})]}),!n&&u.length===0&&U(te,{marginTop:1,children:U(L,{dimColor:!0,children:"No execution plan for this task."})}),U(te,{marginTop:1,children:U(L,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as un,jsx as ve,jsxs as Be}from"react/jsx-runtime";var cn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Xt=["all","pending","queued","running","completed","failed","cancelled"],po=15;function zt({onBack:e}){let[t,o]=Ye([]),[c,u]=Ye(!0),[m,l]=Ye("list"),[i,n]=Ye(0),[r,a]=Ye("all"),[d,b]=Ye(0),[p,y]=Ye(0),[s,g]=Ye(null),[_,M]=Ye([]),Y=Zo(async()=>{u(!0);try{let I=new URLSearchParams({limit:"100"});r!=="all"&&I.set("status",r);let P=await v(`/tasks?${I}`);o(P.tasks)}catch{o([])}finally{u(!1)}},[r]);ln(()=>{Y()},[Y]);let H=Math.max(1,Math.ceil(t.length/po)),O=t.slice(p*po,(p+1)*po),X=Zo(async()=>{let I=O[i];if(I)try{await v(`/tasks/${I.id}/cancel`,{method:"POST"}),g(`Cancelled: ${I.id.slice(0,8)}`),l("list"),Y()}catch(P){g(`Failed: ${P instanceof Error?P.message:String(P)}`),l("list")}},[O,i,Y]);return an((I,P)=>{if(m==="detail"){(P.escape||P.return||I==="q")&&l("list");return}if(m==="cancelling"){I==="y"?X():l("list");return}if(m==="filter"){if(P.escape){l("list");return}P.upArrow&&d>0&&b(S=>S-1),P.downArrow&&d<Xt.length-1&&b(S=>S+1),P.return&&(a(Xt[d]),y(0),n(0),l("list"));return}if(P.escape||I==="q"){e();return}if(P.upArrow&&i>0&&n(S=>S-1),P.downArrow&&i<O.length-1&&n(S=>S+1),P.return){let S=O[i];S&&(M([]),l("detail"),v(`/tasks/${S.id}/logs?limit=20`).then(({logs:j})=>M(j)).catch(()=>M([])))}if(I==="x"&&O[i]){let S=O[i];["running","pending","queued","paused"].includes(S.status)?(l("cancelling"),g(null)):g(`Cannot cancel task in status: ${S.status}`)}I==="f"&&(b(Xt.indexOf(r)),l("filter")),I==="r"&&Y(),(P.pageDown||I==="n")&&p<H-1&&(y(S=>S+1),n(0)),(P.pageUp||I==="p")&&p>0&&(y(S=>S-1),n(0))}),c?ve(ie,{dimColor:!0,children:"Loading tasks..."}):m==="filter"?Be(mt,{flexDirection:"column",children:[ve(ie,{bold:!0,children:"Filter by status:"}),Xt.map((I,P)=>ve(mt,{children:Be(ie,{color:P===d?"cyan":"white",children:[P===d?"> ":" ",I,I===r?" (current)":""]})},I)),ve(ie,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):m==="detail"&&O[i]?ve(Jo,{taskId:O[i].id,onBack:()=>l("list")}):m==="cancelling"&&O[i]?Be(mt,{flexDirection:"column",children:[Be(ie,{color:"red",children:['Cancel task "',O[i].id.slice(0,8),'"? (y/n)']}),s&&ve(ie,{color:"red",children:s})]}):Be(mt,{flexDirection:"column",children:[Be(mt,{children:[Be(ie,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&Be(ie,{dimColor:!0,children:[" [filter: ",r,"]"]}),Be(ie,{dimColor:!0,children:[" \u2014 Page ",p+1,"/",H]})]}),s&&ve(ie,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?Be(ie,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):Be(un,{children:[ve(mt,{marginTop:1,children:Be(ie,{bold:!0,children:[" ",at("ID",10),at("STATUS",12),at("PROMPT",40),at("DURATION",10),"COST"]})}),O.map((I,P)=>{let S=P===i,j=I.totalDurationMs?`${(I.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",J=I.costUsd!==void 0?`$${I.costUsd.toFixed(4)}`:"\u2014",Re=cn[I.status]??"white";return Be(mt,{children:[ve(ie,{color:S?"cyan":"white",children:S?"> ":" "}),ve(ie,{dimColor:!0,children:at(I.id.slice(0,8),10)}),ve(ie,{color:Re,children:at(I.status,12)}),ve(ie,{children:at(dn(I.prompt,38),40)}),ve(ie,{dimColor:!0,children:at(j,10)}),ve(ie,{dimColor:!0,children:J})]},I.id)})]}),ve(ie,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function at(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function dn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}Do();import{Box as _t,Text as Ve,useInput as mn}from"ink";import{useEffect as gn,useState as er}from"react";import{readFileSync as fn,existsSync as pn}from"fs";import{parse as xn}from"yaml";import{Fragment as Tn,jsx as $e,jsxs as lt}from"react/jsx-runtime";function or({onBack:e}){let[t,o]=er(null),[c,u]=er(null);return mn((m,l)=>{(l.escape||m==="q")&&e()}),gn(()=>{try{let m=Ao;if(!pn(m)){u(`Config file not found: ${m}`);return}let l=fn(m,"utf-8");o(xn(l))}catch(m){u(m.message)}},[]),c?lt(_t,{flexDirection:"column",children:[$e(Ve,{color:"red",children:c}),$e(Ve,{dimColor:!0,children:"Press Esc to go back"})]}):t?lt(_t,{flexDirection:"column",children:[$e(Ve,{bold:!0,children:"Configuration (Esc to go back)"}),$e(_t,{marginTop:1,flexDirection:"column",children:$e(rr,{obj:t,indent:0})})]}):$e(Ve,{dimColor:!0,children:"Loading config..."})}function rr({obj:e,indent:t}){let o=" ".repeat(t);return $e(Tn,{children:Object.entries(e).map(([c,u])=>u&&typeof u=="object"&&!Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt(Ve,{children:[o,$e(Ve,{color:"cyan",children:c}),":"]}),$e(rr,{obj:u,indent:t+1})]},c):Array.isArray(u)?lt(_t,{flexDirection:"column",children:[lt(Ve,{children:[o,$e(Ve,{color:"cyan",children:c}),":"]}),u.map((m,l)=>lt(Ve,{children:[o," - ",tr(c,String(m))]},l))]},c):lt(Ve,{children:[o,$e(Ve,{color:"cyan",children:c}),": ",tr(c,String(u))]},c))})}function tr(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as Yt,Text as Oe,useInput as hn}from"ink";import{useEffect as vn,useState as xo}from"react";import{jsx as Vt,jsxs as He}from"react/jsx-runtime";function nr({onBack:e}){let[t,o]=xo([]),[c,u]=xo(!0),[m,l]=xo(null);return hn((i,n)=>{(n.escape||i==="q")&&e()}),vn(()=>{v("/evolution-audit?limit=20").then(i=>{o(i),u(!1)}).catch(i=>{l(i.message),u(!1)})},[]),c?Vt(Oe,{dimColor:!0,children:"Loading evolution log..."}):m?He(Yt,{flexDirection:"column",children:[Vt(Oe,{color:"red",children:m}),Vt(Oe,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?He(Yt,{flexDirection:"column",children:[Vt(Oe,{dimColor:!0,children:"No evolution records yet"}),Vt(Oe,{dimColor:!0,children:"Press Esc to go back"})]}):He(Yt,{flexDirection:"column",children:[He(Oe,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>He(Yt,{flexDirection:"column",marginTop:1,children:[He(Oe,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&He(Oe,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
5
|
+
`).map((n,r)=>n.startsWith("+")?He(Oe,{color:"green",children:[" ",n]},r):n.startsWith("-")?He(Oe,{color:"red",children:[" ",n]},r):He(Oe,{dimColor:!0,children:[" ",n]},r))]},i.id))]})}import{Box as Je,Text as oe,useInput as yn}from"ink";import bn from"ink-text-input";import{useEffect as Sn,useState as vt}from"react";import{jsx as Ce,jsxs as me}from"react/jsx-runtime";var Cn={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function wn(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function Bn(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function Jt({onBack:e}){let[t,o]=vt([]),[c,u]=vt(null),[m,l]=vt("list"),[i,n]=vt(""),[r,a]=vt(!1),[d,b]=vt(null);yn((s,g)=>{if(m==="create"){g.escape&&(l("list"),n(""),b(null));return}(g.escape||s==="q")&&e(),s==="c"&&(l("create"),b(null)),s==="r"&&p()});let p=()=>{v("/goals?limit=20").then(({goals:s})=>o(s)).catch(s=>u(s.message))};Sn(()=>{p()},[]);let y=async s=>{if(s.trim()){a(!0),b(null);try{let g=await v("/goals",{method:"POST",body:{input:s.trim()}});b(`Goal created: ${g.goal.name}`),n(""),l("list"),p()}catch(g){b(`Failed: ${g instanceof Error?g.message:String(g)}`)}finally{a(!1)}}};return c?me(Je,{flexDirection:"column",children:[me(oe,{color:"red",children:["Failed to load goals: ",c]}),Ce(oe,{dimColor:!0,children:"Press Esc or q to return"})]}):m==="create"?me(Je,{flexDirection:"column",children:[Ce(oe,{bold:!0,children:"Create Goal"}),Ce(oe,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),me(Je,{marginTop:1,children:[Ce(oe,{color:"cyan",children:"> "}),Ce(bn,{value:i,onChange:n,onSubmit:y})]}),r&&Ce(oe,{color:"yellow",children:"Creating goal..."}),d&&Ce(oe,{color:d.startsWith("Failed")?"red":"green",children:d}),Ce(oe,{dimColor:!0,children:"Press Esc to cancel"})]}):me(Je,{flexDirection:"column",children:[me(oe,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?Ce(oe,{dimColor:!0,children:"No goals found. Press c to create one."}):Ce(Je,{marginTop:1,flexDirection:"column",children:t.map(s=>{let g=s.targetValue>0?s.currentValue/s.targetValue:0,_=Cn[s.status]??"white";return me(Je,{marginBottom:1,flexDirection:"column",children:[me(Je,{children:[Ce(oe,{bold:!0,color:_,children:s.name}),me(oe,{dimColor:!0,children:[" (",s.role,")"]}),Ce(oe,{dimColor:!0,children:" \u2014 "}),Ce(oe,{color:_,children:s.status})]}),me(Je,{children:[me(oe,{dimColor:!0,children:[" ",wn(g)," "]}),me(oe,{color:g>=1?"green":"white",children:[Math.round(g*100),"%"]}),me(oe,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),me(Je,{children:[me(oe,{dimColor:!0,children:[" \u23F0 ",Bn(s.deadline)," left"]}),me(oe,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),me(oe,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),Ce(oe,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as yt,Text as Ae,useInput as En}from"ink";import{useEffect as In,useState as sr}from"react";import{jsx as et,jsxs as Ze}from"react/jsx-runtime";function kn(e,t,o=15){let c=e/(e+t),u=Math.round(c*o);return"\u2593".repeat(u)+"\u2591".repeat(o-u)}function ir({onBack:e}){let[t,o]=sr([]),[c,u]=sr(null);if(En((l,i)=>{(i.escape||l==="q")&&e()}),In(()=>{v("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>u(l.message))},[]),c)return Ze(yt,{flexDirection:"column",children:[Ze(Ae,{color:"red",children:["Failed to load strategies: ",c]}),et(Ae,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return Ze(yt,{flexDirection:"column",children:[et(Ae,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),et(Ae,{dimColor:!0,children:"Press Esc or q to return"})]});let m=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,n=m.get(i)??[];n.push(l),m.set(i,n)}return Ze(yt,{flexDirection:"column",children:[et(Ae,{bold:!0,children:"Strategy Lab"}),et(Ae,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),et(yt,{marginTop:1,flexDirection:"column",children:Array.from(m.entries()).map(([l,i])=>Ze(yt,{marginBottom:1,flexDirection:"column",children:[et(Ae,{bold:!0,color:"cyan",children:l}),i.sort((n,r)=>{let a=n.alpha/(n.alpha+n.beta);return r.alpha/(r.alpha+r.beta)-a}).map(n=>{let r=n.alpha/(n.alpha+n.beta);return Ze(yt,{children:[et(Ae,{dimColor:!0,children:" "}),Ze(Ae,{children:[kn(n.alpha,n.beta)," "]}),Ze(Ae,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),Ze(Ae,{dimColor:!0,children:[" ",n.name," (\u03B1=",n.alpha.toFixed(1)," \u03B2=",n.beta.toFixed(1)," trials=",n.totalTrials,")"]})]},n.id)})]},l))}),et(Ae,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as Ee,Text as Z,useInput as Mn}from"ink";import To from"ink-text-input";import{useEffect as Nn,useState as tt,useCallback as bt}from"react";import{CronExpressionParser as Ln}from"cron-parser";import{useState as Pn,useEffect as An,useCallback as ar,useRef as Dn}from"react";var Rn=3e3;function ct(){let[e,t]=Pn(null),o=Dn(null),c=ar(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),u=ar((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},Rn))},[]);return An(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:u,clearMessage:c}}import{jsx as ee,jsxs as xe}from"react/jsx-runtime";var ho=["manual","cron","event"],Zt={name:"",triggerType:"manual",cron:"",stepPrompt:""};function _n(e){try{return Ln.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function to({onBack:e}){let[t,o]=tt([]),[c,u]=tt(!0),[m,l]=tt(0),[i,n]=tt("list"),[r,a]=tt({...Zt}),[d,b]=tt("name"),[p,y]=tt(null),{message:s,setMessage:g,clearMessage:_}=ct(),[M,Y]=tt(!1),[H,O]=tt(!1),X=bt(()=>{u(!0),v("/task-templates").then(({templates:C})=>{o(C),u(!1)}).catch(()=>u(!1))},[]);Nn(()=>{X()},[X]);let I=i==="create"||i==="edit",P=bt(async()=>{let C=t[m];if(!(!C||M)){Y(!0),g(`Triggering ${C.name}...`,"loading");try{let E=await v(`/task-templates/${C.id}/run`,{method:"POST"});g(`Triggered: ${C.name} (${E.executionId})`,"success")}catch(E){g(`Trigger failed: ${E instanceof Error?E.message:String(E)}`,"error")}finally{Y(!1)}}},[t,m,M,g]),S=bt(async()=>{let C=t[m];if(!C||H)return;if(C.trigger?.type!=="cron"&&C.trigger?.type!=="event"){g("Toggle not applicable for manual triggers","error");return}let E=!C.enabled;O(!0),g(`${C.name} \u2192 ${E?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${C.id}`,{method:"PATCH",body:{enabled:E}}),o(R=>R.map(pe=>pe.id===C.id?{...pe,enabled:E}:pe)),g(`${C.name} ${E?"enabled":"disabled"}`,"success")}catch(R){g(`Toggle failed: ${R instanceof Error?R.message:String(R)}`,"error")}finally{O(!1)}},[t,m,H,g]),j=bt(async()=>{let C=t[m];if(C)try{await v(`/task-templates/${C.id}`,{method:"DELETE"}),g(`Deleted: ${C.name}`,"success"),X(),l(E=>Math.max(0,Math.min(E,t.length-2)))}catch(E){g(`Delete failed: ${E instanceof Error?E.message:String(E)}`,"error")}},[t,m,X]),J=bt(()=>{let C=t[m];C&&(y(C.id),a({name:C.name,triggerType:C.trigger?.type??"manual",cron:C.trigger?.cron??"",stepPrompt:C.steps?.[0]?.prompt??""}),b("name"),n("edit"))},[t,m]),Re=bt(async()=>{let C={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 v("/task-templates",{method:"POST",body:C}),g(`Created: ${r.name}`,"success")):i==="edit"&&p&&(await v(`/task-templates/${p}`,{method:"PATCH",body:C}),g(`Updated: ${r.name}`,"success"))}catch(E){g(`Save failed: ${E instanceof Error?E.message:String(E)}`,"error")}n("list"),a({...Zt}),y(null),X()},[r,i,p,X]);return Mn((C,E)=>{if(I){if(E.escape){n("list"),a({...Zt}),y(null);return}if(E.return){let R=["name","triggerType","cron","stepPrompt"],pe=R.indexOf(d);if(pe<R.length-1){let ce=pe+1;if(R[ce]==="cron"&&r.triggerType!=="cron"&&ce++,ce<R.length){b(R[ce]);return}}Re();return}if(E.tab&&d==="triggerType"){a(R=>{let pe=ho.indexOf(R.triggerType);return{...R,triggerType:ho[(pe+1)%ho.length]}});return}return}if(E.escape||C==="q"){e();return}if(E.upArrow){l(R=>Math.max(0,R-1));return}if(E.downArrow){l(R=>Math.min(t.length-1,R+1));return}if(C==="t"){P();return}if(C==="d"){j();return}if(C==="e"){J();return}if(C==="c"){a({...Zt}),b("name"),n("create");return}if(C==="s"||C===" "){S();return}C==="r"&&(X(),_())}),c?ee(Z,{dimColor:!0,children:"Loading templates..."}):I?xe(Ee,{flexDirection:"column",children:[xe(Z,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),xe(Ee,{marginTop:1,flexDirection:"column",children:[xe(Ee,{children:[xe(Z,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?ee(To,{value:r.name,onChange:C=>a(E=>({...E,name:C})),placeholder:"template name"}):ee(Z,{children:r.name||"(empty)"})]}),xe(Ee,{children:[xe(Z,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),ee(Z,{children:r.triggerType}),d==="triggerType"&&ee(Z,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&xe(Ee,{children:[xe(Z,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?ee(To,{value:r.cron,onChange:C=>a(E=>({...E,cron:C})),placeholder:"*/5 * * * *"}):ee(Z,{children:r.cron||"(empty)"})]}),xe(Ee,{children:[xe(Z,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?ee(To,{value:r.stepPrompt,onChange:C=>a(E=>({...E,stepPrompt:C})),placeholder:"What should this template do?"}):ee(Z,{children:r.stepPrompt||"(empty)"})]})]}),ee(Ee,{marginTop:1,children:ee(Z,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):xe(Ee,{flexDirection:"column",children:[xe(Z,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&ee(Ee,{marginTop:1,children:xe(Z,{color:s.type==="success"?"green":s.type==="error"?"red":"gray",children:[s.type==="success"?"\u2713 ":s.type==="error"?"\u2717 ":"\u2192 ",s.text]})}),t.length===0?ee(Ee,{marginTop:1,children:ee(Z,{dimColor:!0,children:"No templates found. Press c to create one."})}):ee(Ee,{marginTop:1,flexDirection:"column",children:t.map((C,E)=>{let R=E===m,pe=C.trigger?.type==="cron"&&C.trigger?.cron?_n(C.trigger.cron):"";return xe(Ee,{children:[ee(Z,{color:R?"cyan":void 0,bold:R,children:R?"> ":" "}),ee(Z,{color:R?"cyan":void 0,bold:R,children:eo(C.name,24)}),ee(Z,{dimColor:!0,children:eo(C.trigger?.type,10)}),C.trigger?.type!=="cron"&&C.trigger?.type!=="event"?ee(Z,{dimColor:!0,children:eo("\u2014",6)}):ee(Z,{color:C.enabled?"green":"gray",children:eo(C.enabled?"on":"off",6)}),pe&&xe(Z,{dimColor:!0,children:["next: ",pe]})]},C.id)})}),ee(Ee,{marginTop:1,children:ee(Z,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function eo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as dt,Text as Ie,useInput as Vn}from"ink";import $n from"ink-text-input";import{useEffect as On,useState as St,useCallback as lr}from"react";import{jsx as ye,jsxs as gt}from"react/jsx-runtime";function cr({onBack:e}){let[t,o]=St([]),[c,u]=St(""),[m,l]=St(!0),[i,n]=St(!1),[r,a]=St(""),[d,b]=St(null),p=lr(()=>{l(!0),v("/webhooks").then(({webhooks:s,auth:g})=>{o(s),u(g),l(!1)}).catch(()=>l(!1))},[]);On(()=>{p()},[p]);let y=lr(async s=>{if(s.trim())try{let g=await v(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});b(`Triggered: ${g.executionId}`)}catch(g){b(`Trigger failed: ${g instanceof Error?g.message:String(g)}`)}},[]);return Vn((s,g)=>{if(i){if(g.escape){n(!1),a("");return}if(g.return){y(r),n(!1),a("");return}return}if(g.escape||s==="q"){e();return}if(s==="t"){n(!0),a(""),b(null);return}s==="r"&&(p(),b(null))}),m?ye(Ie,{dimColor:!0,children:"Loading webhooks..."}):gt(dt,{flexDirection:"column",children:[gt(Ie,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),gt(Ie,{dimColor:!0,children:["Auth: ",c]}),d&&ye(dt,{marginTop:1,children:ye(Ie,{color:"yellow",children:d})}),i&>(dt,{marginTop:1,children:[ye(Ie,{bold:!0,color:"cyan",children:"Trigger webhook: "}),ye($n,{value:r,onChange:a,placeholder:"webhook name or ID"}),ye(Ie,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?ye(dt,{marginTop:1,children:ye(Ie,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):gt(dt,{marginTop:1,flexDirection:"column",children:[ye(dt,{children:gt(Ie,{bold:!0,children:[Ct("NAME",24),Ct("DESCRIPTION",36),Ct("TRIGGER",28),"TAGS"]})}),t.map(s=>gt(dt,{children:[ye(Ie,{children:Ct(s.displayName,24)}),ye(Ie,{dimColor:!0,children:Ct(qn(s.description??"",34),36)}),ye(Ie,{dimColor:!0,children:Ct(s.trigger,28)}),ye(Ie,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),ye(dt,{marginTop:1,children:ye(Ie,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function Ct(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function qn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Ke,Text as ae,useInput as Fn}from"ink";import Un from"ink-text-input";import{useEffect as dr,useState as ot,useCallback as vo}from"react";import{jsx as le,jsxs as qe}from"react/jsx-runtime";function Wn(e){return e>=4?"red":e===3?"yellow":"gray"}function Gn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function Hn(e){return new Date(e).toLocaleDateString()}function mr({onBack:e}){let[t,o]=ot([]),[c,u]=ot(0),[m,l]=ot([]),[i,n]=ot(!0),[r,a]=ot(!1),[d,b]=ot(""),[p,y]=ot("all"),[s,g]=ot(null),[_,M]=ot(!1),Y=vo(()=>{v("/agents").then(({agents:S})=>{o(S),n(!1)}).catch(()=>n(!1))},[]);dr(()=>{Y()},[Y]);let H=t[c],O=vo(()=>{H&&(M(!1),v(`/memories/${H.id}`).then(({memories:S})=>{l(S),g(null)}).catch(S=>g(`Failed: ${S instanceof Error?S.message:String(S)}`)))},[H]);dr(()=>{H&&O()},[H,O]);let X=vo(async S=>{if(!(!H||!S.trim()))try{let j=await v("/memories/query",{method:"POST",body:{agentId:H.id,prompt:S.trim()}});l(j.memories),M(!0),g(`Search: ${j.count} results`)}catch(j){g(`Search failed: ${j instanceof Error?j.message:String(j)}`)}},[H]),I=r,P=m.filter(S=>p==="all"?!0:p==="high"?S.importance>3:p==="medium"?S.importance===3:S.importance<3);return Fn((S,j)=>{if(I){if(j.escape){a(!1),b("");return}if(j.return){X(d),a(!1),b("");return}return}if(j.escape||S==="q"){e();return}if(S==="a"){u(J=>(J+1)%Math.max(1,t.length));return}if(j.leftArrow){u(J=>(J-1+t.length)%Math.max(1,t.length));return}if(j.rightArrow){u(J=>(J+1)%Math.max(1,t.length));return}if(S==="s"){a(!0),b(""),g(null);return}if(S==="h"){y(J=>J==="high"?"all":"high");return}if(S==="m"){y(J=>J==="medium"?"all":"medium");return}if(S==="l"){y(J=>J==="low"?"all":"low");return}S==="r"&&O()}),i?le(ae,{dimColor:!0,children:"Loading agents..."}):t.length===0?qe(Ke,{flexDirection:"column",children:[le(ae,{dimColor:!0,children:"No agents found"}),le(ae,{dimColor:!0,children:"Press Esc to go back"})]}):qe(Ke,{flexDirection:"column",children:[le(ae,{bold:!0,children:"Memories (Esc to go back)"}),qe(Ke,{marginTop:1,children:[le(ae,{children:"Agent: "}),le(ae,{bold:!0,color:"cyan",children:H?.name??"?"}),qe(ae,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),le(Ke,{children:qe(ae,{dimColor:!0,children:["Filter: ",p==="all"?"all":p," | ",_?"search results":"all memories"," (",P.length,")"]})}),s&&le(Ke,{children:le(ae,{color:"yellow",children:s})}),r&&qe(Ke,{marginTop:1,children:[le(ae,{bold:!0,color:"cyan",children:"Search: "}),le(Un,{value:d,onChange:b,placeholder:"search query..."}),le(ae,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),P.length===0?le(Ke,{marginTop:1,children:qe(ae,{dimColor:!0,children:["No memories",p!=="all"?` matching filter '${p}'`:""]})}):le(Ke,{marginTop:1,flexDirection:"column",children:P.map(S=>qe(Ke,{marginBottom:0,children:[qe(ae,{color:Wn(S.importance),bold:!0,children:[Gn(S.importance)," "]}),le(ae,{dimColor:!0,children:ur(S.type??"?",12)}),le(ae,{dimColor:!0,children:ur(`\xD7${S.retrievedCount??0}`,5)}),qe(ae,{children:[Kn(S.content,55)," "]}),le(ae,{dimColor:!0,children:Hn(S.createdAt)}),S.score!==void 0&&qe(ae,{dimColor:!0,children:[" (",S.score.toFixed(2),")"]})]},S.id))}),le(Ke,{marginTop:1,children:le(ae,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function ur(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Kn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Fe,Text as re,useInput as jn}from"ink";import oo from"ink-text-input";import{useState as we,useEffect as gr,useCallback as yo}from"react";import{jsx as ge,jsxs as ue}from"react/jsx-runtime";var fr={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"]},Qn={"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 pr({onBack:e}){let{state:t}=st(),[o,c]=we({}),[u,m]=we([]),[l,i]=we(null),[n,r]=we("view"),[a,d]=we(0),[b,p]=we(""),[y,s]=we(null),[g,_]=we(!1),[M,Y]=we([]),[H,O]=we({}),[X,I]=we(0),[P,S]=we(""),[j,J]=we(""),[Re,C]=we(""),E=Object.values(fr).flat(),R=yo(()=>{v("/config").then(D=>{c(D.config),m(D.mutable)}).catch(D=>i(D.message)),v("/config/env-diff").then(D=>{Y(D.diffs)}).catch(()=>{}),v("/config/env").then(D=>O(D.env??{})).catch(()=>{})},[]);gr(()=>{R()},[R]),gr(()=>{t.configVersion>0&&R()},[t.configVersion,R]);let pe=yo(async()=>{let D=E[a];if(D){_(!0),s(null);try{let $=b,q=o[D];if(q&&typeof q.value=="number"&&($=Number(b),isNaN($))){s("Invalid number"),_(!1);return}let ne=await v("/config",{method:"PATCH",body:{[D]:$}});ne.updated.length>0&&(s(`Updated: ${D}`),R()),ne.errors.length>0&&s(ne.errors[0]),r("view")}catch($){s(`Failed: ${$ instanceof Error?$.message:String($)}`)}finally{_(!1)}}},[E,a,b,o,R]),ce=Object.keys(H),je=yo(async D=>{try{await v("/config/env",{method:"PUT",body:D}),s("Env vars saved"),R()}catch($){s(`Failed: ${$ instanceof Error?$.message:String($)}`)}},[R]);if(jn((D,$)=>{if(n==="edit"){if($.escape){r("view");return}return}if(n==="env-list"){if($.escape){r("view");return}if($.upArrow&&X>0&&I(q=>q-1),$.downArrow&&X<ce.length-1&&I(q=>q+1),D==="a"){S(""),r("env-add-key");return}if(D==="d"&&ce.length>0){let q=ce[X],ne={...H};delete ne[q],je(ne),X>=ce.length-1&&X>0&&I(Qe=>Qe-1);return}if($.return&&ce.length>0){C(H[ce[X]]??""),r("env-edit-value");return}return}if(n==="env-add-key"){if($.escape){r("env-list");return}return}if(n==="env-add-value"){if($.escape){r("env-list");return}return}if(n==="env-edit-value"){if($.escape){r("env-list");return}return}if($.escape||D==="q"){e();return}if($.upArrow&&a>0&&d(q=>q-1),$.downArrow&&a<E.length-1&&d(q=>q+1),$.return||D==="e"){let q=E[a],ne=o[q];ne&&ne.mutable?(p(String(ne.value??"")),r("edit"),s(null)):ne&&!ne.mutable&&s("This setting requires a restart to change")}D==="v"&&(I(0),r("env-list"),s(null)),D==="r"&&(R(),s("Refreshed")),D==="s"&&M.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),Y([]),R()}),D==="l"&&M.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),R()})}),l)return ue(Fe,{flexDirection:"column",children:[ue(re,{color:"red",children:["Failed to load config: ",l]}),ge(re,{dimColor:!0,children:"Press Esc or q to return"})]});let pt=0;return ue(Fe,{flexDirection:"column",children:[ge(re,{bold:!0,children:"Settings"}),y&&ge(re,{color:y.startsWith("Failed")||y.startsWith("This setting")?"yellow":"green",children:y}),M&&M.length>0&&ue(Fe,{flexDirection:"column",marginBottom:1,children:[ue(re,{color:"yellow",children:[".env differs from DB (",M.length," key(s)): ",M.map(D=>D.envKey).join(", ")]}),ge(re,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ge(Fe,{marginTop:1,flexDirection:"column",children:Object.entries(fr).map(([D,$])=>ue(Fe,{marginBottom:1,flexDirection:"column",children:[ge(re,{bold:!0,color:"cyan",children:D}),$.map(q=>{let ne=o[q],xt=pt++===a,Tt=u.includes(q),Ft=Qn[q]??q,Xe=ne?String(ne.value??""):"...";return n==="edit"&&xt?ue(Fe,{children:[ue(re,{color:"cyan",children:["> ",Ft,": "]}),ge(oo,{value:b,onChange:p,onSubmit:()=>{pe()}}),g&&ge(re,{color:"yellow",children:" saving..."})]},q):ue(Fe,{children:[ue(re,{color:xt?"cyan":"white",children:[xt?"> ":" ",Tt?" ":"\u{1F512} ",Ft,": "," "]}),ge(re,{color:Tt?"white":"gray",children:Xe}),!Tt&&ge(re,{dimColor:!0,children:" (restart required)"})]},q)})]},D))}),ge(re,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),n.startsWith("env")&&ue(Fe,{flexDirection:"column",marginTop:1,children:[ue(re,{bold:!0,color:"cyan",children:["Environment Variables (",ce.length,")"]}),ce.length===0&&n==="env-list"&&ge(re,{dimColor:!0,children:" No env vars. Press a to add."}),ce.map((D,$)=>{let q=$===X;return n==="env-edit-value"&&q?ue(Fe,{children:[ue(re,{color:"cyan",children:["> ",D," = "]}),ge(oo,{value:Re,onChange:C,onSubmit:()=>{je({...H,[D]:Re}),r("env-list")}})]},D):ue(re,{color:q&&n==="env-list"?"cyan":"white",children:[q&&n==="env-list"?"> ":" ",D," = ",H[D]]},D)}),n==="env-add-key"&&ue(Fe,{children:[ge(re,{color:"green",children:" New key: "}),ge(oo,{value:P,onChange:S,onSubmit:()=>{P.trim()&&(J(""),r("env-add-value"))}})]}),n==="env-add-value"&&ue(Fe,{children:[ue(re,{color:"green",children:[" ",P," = "]}),ge(oo,{value:j,onChange:J,onSubmit:()=>{je({...H,[P.trim()]:j}),r("env-list")}})]}),ge(re,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as ft,Text as be,useInput as Xn}from"ink";import{useEffect as zn,useState as bo,useCallback as Yn}from"react";import{jsx as Te,jsxs as Bt}from"react/jsx-runtime";function xr({onBack:e}){let[t,o]=bo([]),[c,u]=bo(!0),[m,l]=bo(0),{message:i,setMessage:n,clearMessage:r}=ct(),a=Yn(()=>{u(!0),v("/plugins").then(({plugins:d})=>{o(d),u(!1)}).catch(()=>u(!1))},[]);return zn(()=>{a()},[a]),Xn((d,b)=>{if(b.escape||d==="q"){e();return}if(b.upArrow){l(p=>Math.max(0,p-1));return}if(b.downArrow){l(p=>Math.min(t.length-1,p+1));return}d==="r"&&(a(),r())}),c?Te(be,{dimColor:!0,children:"Loading plugins..."}):Bt(ft,{flexDirection:"column",children:[Bt(be,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Te(ft,{marginTop:1,children:Bt(be,{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?Te(ft,{marginTop:1,children:Te(be,{dimColor:!0,children:"No plugins installed."})}):Bt(ft,{marginTop:1,flexDirection:"column",children:[Bt(ft,{children:[Te(be,{dimColor:!0,children:" "}),Te(be,{dimColor:!0,children:wt("Name",24)}),Te(be,{dimColor:!0,children:wt("Scope",8)}),Te(be,{dimColor:!0,children:wt("User",6)}),Te(be,{dimColor:!0,children:"Path"})]}),t.map((d,b)=>{let p=b===m,y=d.id.split("@")[0];return Bt(ft,{children:[Te(be,{color:p?"cyan":void 0,bold:p,children:p?"> ":" "}),Te(be,{color:p?"cyan":void 0,bold:p,children:wt(y,24)}),Te(be,{color:p?"cyan":void 0,bold:p,children:wt(d.scope,8)}),Te(be,{color:d.globalEnabled?"green":"gray",children:wt(d.globalEnabled?"on":"off",6)}),Te(be,{dimColor:!0,children:d.installPath})]},d.id)})]}),Te(ft,{marginTop:1,children:Te(be,{dimColor:!0,children:"r:refresh"})})]})}function wt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ro,Text as Tr,useInput as Jn}from"ink";import{useState as Zn}from"react";import{jsx as Et,jsxs as So}from"react/jsx-runtime";var es=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function hr({onBack:e}){let[t,o]=Zn("tasks");return Jn((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}}),So(ro,{flexDirection:"column",children:[So(ro,{gap:1,marginBottom:1,children:[es.map(c=>{let u=t===c.id;return Et(ro,{children:So(Tr,{color:u?"cyan":"gray",bold:u,underline:u,children:["[",c.key,":",c.label,"]"]})},c.id)}),Et(ro,{flexGrow:1}),Et(Tr,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&Et(zt,{onBack:e}),t==="automations"&&Et(to,{onBack:e}),t==="goals"&&Et(Jt,{onBack:e})]})}import{Box as z,Text as W,useInput as ts}from"ink";import{useEffect as os,useState as $t}from"react";import{jsx as N,jsxs as fe}from"react/jsx-runtime";var vr={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function yr({onBack:e}){let[t,o]=$t([]),[c,u]=$t(!0),[m,l]=$t(0),[i,n]=$t(null),[r,a]=$t("");os(()=>{d()},[]);async function d(){try{let y=await v("/channels");o(y.channels)}catch{}u(!1)}async function b(y){if(t.find(g=>g.id===y)?.platform==="wechat")try{a("Starting WeChat QR login...");let g=await v(`/channels/${y}/wechat/qr-start`,{method:"POST"});if(g.qrcodeUrl){a(`Scan QR: ${g.qrcodeUrl}
|
|
6
|
+
Waiting for scan...`);let _=await v(`/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 v(`/channels/${y}/connect`,{method:"POST"}),a("Connecting..."),d()}catch{a("Connect failed")}}async function p(y){try{await v(`/channels/${y}/disconnect`,{method:"POST"}),a("Disconnected"),d()}catch{a("Disconnect failed")}}return ts((y,s)=>{if(i){if(s.escape||y==="q"){n(null);return}if(y==="c"){b(i.id);return}if(y==="d"){p(i.id);return}return}if(s.escape){e();return}if(s.upArrow){l(g=>Math.max(0,g-1));return}if(s.downArrow){l(g=>Math.min(t.length-1,g+1));return}if(s.return&&t[m]){n(t[m]),a("");return}}),c?N(z,{flexDirection:"column",children:N(W,{dimColor:!0,children:"Loading channels..."})}):i?fe(z,{flexDirection:"column",children:[fe(z,{marginBottom:1,children:[fe(W,{bold:!0,children:["Channel: ",i.name]}),N(W,{dimColor:!0,children:" (Esc to go back)"})]}),fe(z,{flexDirection:"column",gap:0,children:[fe(W,{children:["ID: ",i.id]}),fe(W,{children:["Platform: ",i.platform]}),fe(W,{children:["Status: ",N(W,{color:vr[i.status]??"white",children:i.status})]}),fe(W,{children:["Enabled: ",i.enabled?"yes":"no"]}),fe(W,{children:["Messages: ",i.messageCount]}),fe(W,{children:["Config: ",JSON.stringify(i.config)]})]}),N(z,{marginTop:1,children:N(W,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&N(W,{color:"yellow",children:r})]}):fe(z,{flexDirection:"column",children:[fe(z,{marginBottom:1,children:[N(W,{bold:!0,children:"Channels"}),fe(W,{dimColor:!0,children:[" (",t.length," total) "]}),N(W,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?N(W,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):fe(z,{flexDirection:"column",children:[fe(z,{children:[N(z,{width:3,children:N(W,{dimColor:!0,children:" "})}),N(z,{width:12,children:N(W,{bold:!0,dimColor:!0,children:"ID"})}),N(z,{width:16,children:N(W,{bold:!0,dimColor:!0,children:"Name"})}),N(z,{width:12,children:N(W,{bold:!0,dimColor:!0,children:"Platform"})}),N(z,{width:14,children:N(W,{bold:!0,dimColor:!0,children:"Status"})}),N(z,{width:10,children:N(W,{bold:!0,dimColor:!0,children:"Enabled"})}),N(z,{width:10,children:N(W,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((y,s)=>fe(z,{children:[N(z,{width:3,children:N(W,{children:s===m?">":" "})}),N(z,{width:12,children:N(W,{inverse:s===m,children:y.id.slice(0,8)})}),N(z,{width:16,children:N(W,{children:y.name})}),N(z,{width:12,children:N(W,{children:y.platform})}),N(z,{width:14,children:fe(W,{color:vr[y.status]??"white",children:[y.status==="connected"?"\u25CF":y.status==="error"?"\u2717":"\u25CB"," ",y.status]})}),N(z,{width:10,children:N(W,{color:y.enabled?"green":"gray",children:y.enabled?"yes":"no"})}),N(z,{width:10,children:N(W,{children:y.messageCount})})]},y.id))]})]})}import{Box as kt,Text as nt,useInput as ns}from"ink";import{useEffect as ss,useState as Ot,useCallback as is}from"react";import{Box as A,Text as T,useInput as rs}from"ink";import rt from"ink-text-input";import{useEffect as br,useState as Q,useCallback as It}from"react";Do();import{Fragment as Sr,jsx as h,jsxs as B}from"react/jsx-runtime";function Cr({roleId:e,onBack:t}){let[o,c]=Q(null),[u,m]=Q([]),[l,i]=Q(!0),[n,r]=Q("view"),[a,d]=Q(""),[b,p]=Q(0),[y,s]=Q(""),[g,_]=Q([]),[M,Y]=Q(0),[H,O]=Q(new Set),[X,I]=Q("inline"),[P,S]=Q(""),[j,J]=Q(""),[Re,C]=Q([]),[E,R]=Q(new Set),[pe,ce]=Q(0),[je,pt]=Q("default"),[D,$]=Q(""),[q,ne]=Q(""),[Qe,xt]=Q("mode"),[Tt,Ft]=Q([]),[Xe,Ut]=Q(0),[Wt,Bo]=Q(""),[Eo,Io]=Q(""),[ko,Po]=Q(""),{message:V,setMessage:F}=ct(),se=It(()=>{i(!0),v(`/roles/${e}`).then(({role:f,boundPlugins:w})=>{c(f),m(w??[]),d(f.cagPrompt??""),O(new Set(f.allowedTools??[])),I(f.executionMode??"inline"),S(f.model??""),J(f.maxBudgetUsd!=null?String(f.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);br(()=>{se(),v("/config").then(f=>{let w=f["defaults.deniedReadPaths"]?.value;Array.isArray(w)&&Ft(w)}).catch(()=>{})},[se]),br(()=>{I(o?.executionMode??"inline"),S(o?.model??""),J(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),pt(o?.permissionMode??"default"),$((o?.allowedBashPatterns??[]).join(", ")),ne((o?.deniedBashPatterns??[]).join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns]);let Br=It(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:a}}),F("CAG prompt saved","success"),r("view"),se()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,a,se,F]),Er=It(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Me}}),F("Directories saved","success"),r("view"),se()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,se,F]),Ir=It(async()=>{if(o)try{await v(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),F("Tool permissions saved","success"),r("view"),se()}catch(f){F(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[o,H,se,F]),kr=It(async()=>{if(!o)return;let f={executionMode:X};P!==void 0&&(f.model=P);let w=parseFloat(j);isNaN(w)||(f.maxBudgetUsd=w);try{await v(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Execution config saved","success"),r("view"),se()}catch(x){F(`Save failed: ${x instanceof Error?x.message:String(x)}`,"error")}},[o,X,P,j,se,F]),Pr=It(async()=>{if(!o)return;let f={permissionMode:je},w=D.split(",").map(k=>k.trim()).filter(Boolean),x=q.split(",").map(k=>k.trim()).filter(Boolean);f.allowedBashPatterns=w.length>0?w:[],f.deniedBashPatterns=x.length>0?x:[];try{await v(`/roles/${o.id}`,{method:"PATCH",body:f}),F("Permission config saved","success"),r("view"),se()}catch(k){F(`Save failed: ${k instanceof Error?k.message:String(k)}`,"error")}},[o,je,D,q,se,F]),Me=o?.additionalDirectories??[];if(rs((f,w)=>{if(w.escape){r("view");return}if(f==="r"){se();return}switch(n){case"view":{if(f==="c"){r("edit-cag");return}if(f==="d"){r("edit-dirs"),p(0),s("");return}if(f==="t"){r("edit-tools");return}if(f==="x"){r("edit-exec");return}if(f==="h"){v("/channels?enabled=true").then(({channels:x})=>{C(x.map(k=>({name:k.name,id:k.id}))),R(new Set(o?.allowedChannels??[])),ce(0),r("edit-channels")}).catch(()=>F("Failed to load channels","error"));return}if(f==="p"){pt(o?.permissionMode??"default"),$((o?.allowedBashPatterns??[]).join(", ")),ne((o?.deniedBashPatterns??[]).join(", ")),xt("mode"),r("edit-permissions");return}if(f==="v"){Ut(0),r("edit-env");return}if(f==="i"){if(!o)return;let x=!o.inheritUserSettings;v(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:x}}).then(()=>{F(`Inherit user settings: ${x?"ON":"OFF"}`,"success"),se()}).catch(()=>F("Failed to toggle","error"));return}break}case"edit-cag":{if(w.ctrl&&f==="s"){Br();return}break}case"edit-dirs":{if(f==="s"){Er();return}if(f==="a"){r("edit-dirs-add");return}if(f==="m"&&Me.length>0){let x=Me[b];if(x){c(de=>de&&{...de,additionalDirectories:de.additionalDirectories?.map((ke,Ar)=>Ar===b?{...typeof ke=="string"?{path:ke}:ke,mode:ke.mode==="ro"?"rw":"ro"}:ke)});let k=x.mode==="ro"?"rw":"ro";F(`Mode set to ${k.toUpperCase()}`,"success")}return}if(f==="x"&&Me.length>0){c(x=>x&&{...x,additionalDirectories:Me.filter((k,de)=>de!==b)}),p(x=>Math.max(0,Math.min(x,Me.length-2)));return}if(w.upArrow){p(x=>Math.max(0,x-1));return}if(w.downArrow){p(x=>Math.min(Me.length-1,x+1));return}break}case"edit-dirs-add":{if(w.escape){r("edit-dirs"),s(""),_([]);return}if(w.return&&g.length>0){let x=g[M];x&&(s(x.endsWith("/")?x:x+"/"),_([]));return}if(w.return){let x=y.trim();x&&x.startsWith("/")?(c(k=>k&&{...k,additionalDirectories:[...k.additionalDirectories??[],{path:x,mode:"rw"}]}),s(""),_([]),r("edit-dirs")):F("Path must be absolute (must start with /)","error");return}if(w.tab){let x=y.trim();if(!x||!x.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(x)}`).then(({suggestions:k})=>{k.length===1?(s(k[0]+"/"),_([])):k.length>1&&(_(k),Y(0))}).catch(()=>{_([])});return}if(w.upArrow&&g.length>0){Y(x=>Math.max(0,x-1));return}if(w.downArrow&&g.length>0){Y(x=>Math.min(g.length-1,x+1));return}break}case"edit-tools":{if(f==="s"){Ir();return}let x=parseInt(f,10)-1;if(!isNaN(x)&&x>=0&&x<Gt.length){let k=Gt[x];O(de=>{let ke=new Set(de);return ke.has(k)?ke.delete(k):ke.add(k),ke});return}break}case"edit-exec":{if(f==="s"){kr();return}if(w.tab){I(x=>x==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(f==="s"){Pr();return}if(w.tab){xt(x=>x==="mode"?"allowed":x==="allowed"?"denied":"mode");return}if(Qe==="mode"&&(w.upArrow||w.downArrow)){let x=["default","acceptEdits","dontAsk","bypassPermissions"],k=x.indexOf(je);w.upArrow&&pt(x[Math.max(0,k-1)]),w.downArrow&&pt(x[Math.min(x.length-1,k+1)]);return}break}case"edit-channels":{if(f==="s"){if(!o)return;let x=E.size>0?Array.from(E):[];v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:x}}).then(()=>{F("Channels saved","success"),r("view"),se()}).catch(()=>F("Save failed","error"));return}if(f==="u"){if(!o)return;v(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{F("Channels: unrestricted","success"),r("view"),se()}).catch(()=>F("Save failed","error"));return}if(f===" "){let x=Re[pe];x&&R(k=>{let de=new Set(k);return de.has(x.name)?de.delete(x.name):de.add(x.name),de});return}if(w.upArrow){ce(x=>Math.max(0,x-1));return}if(w.downArrow){ce(x=>Math.min(Re.length-1,x+1));return}break}case"edit-env":{let x=Object.keys(o?.envVars??{});if(f==="a"){Bo(""),r("edit-env-add-key");return}if(f==="d"&&x.length>0){let k=x[Xe],de={...o?.envVars??{}};delete de[k],v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:de}}).then(()=>{F("Deleted","success"),se()}).catch(()=>F("Delete failed","error")),Xe>=x.length-1&&Xe>0&&Ut(ke=>ke-1);return}if(w.return&&x.length>0){Po((o?.envVars??{})[x[Xe]]??""),r("edit-env-edit-value");return}w.upArrow&&Xe>0&&Ut(k=>k-1),w.downArrow&&Xe<x.length-1&&Ut(k=>k+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),l)return h(T,{dimColor:!0,children:"Loading role..."});if(!o)return h(T,{dimColor:!0,children:"Role not found."});if(n==="edit-cag")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),h(rt,{value:a,onChange:d,placeholder:"Character And Guidance prompt..."}),V&&h(A,{marginTop:1,children:h(T,{color:V.type==="error"?"red":"green",children:V.text})})]});if(n==="edit-dirs-add")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),h(rt,{value:y,onChange:f=>{s(f),_([])},placeholder:"/absolute/path/to/directory"}),g.length>0&&B(A,{flexDirection:"column",marginTop:1,children:[g.map((f,w)=>B(T,{color:w===M?"cyan":void 0,dimColor:w!==M,children:[w===M?"> ":" ",f,"/"]},f)),h(T,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),V&&h(A,{marginTop:1,children:h(T,{color:V.type==="error"?"red":"green",children:V.text})})]});if(n==="edit-dirs")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),Me.length===0?h(T,{dimColor:!0,children:"No directories. Press a to add one."}):Me.map((f,w)=>{let x=typeof f=="string"?{path:f,mode:"rw"}:f,k=x.mode!=="ro";return B(A,{children:[h(T,{color:w===b?"cyan":void 0,bold:w===b,children:w===b?"> ":" "}),B(T,{color:k?"green":"yellow",children:["[",k?"RW":"RO","]"," "]}),h(T,{color:w===b?"cyan":void 0,children:x.path})]},x.path)})]});if(n==="edit-tools")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),Gt.map((f,w)=>{let x=H.has(f);return B(A,{children:[B(T,{dimColor:!0,children:[w+1,". "]}),h(T,{color:x?"green":"red",children:x?"[ON] ":"[OFF] "}),h(T,{children:f})]},f)})]});if(n==="edit-exec")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(A,{children:[h(T,{bold:!0,children:" Mode: "}),h(T,{color:"cyan",children:X}),h(T,{dimColor:!0,children:" (Tab to toggle)"})]}),B(A,{children:[h(T,{bold:!0,children:" Model: "}),h(rt,{value:P,onChange:S,placeholder:"sonnet, opus, haiku, or blank"})]}),B(A,{children:[h(T,{bold:!0,children:" Max Budget (USD): "}),h(rt,{value:j,onChange:J,placeholder:"0 = unlimited"})]}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]});if(n==="edit-permissions")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(A,{children:[h(T,{bold:!0,color:Qe==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(w=>B(T,{color:w===je?"green":"gray",children:[w===je?`[${w}]`:` ${w} `," "]},w))]}),B(A,{children:[h(T,{bold:!0,color:Qe==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),Qe==="allowed"?h(rt,{value:D,onChange:$,placeholder:"git add *, pnpm test*"}):h(T,{children:D||"(none)"})]}),B(A,{children:[h(T,{bold:!0,color:Qe==="denied"?"cyan":void 0,children:" Denied Bash: "}),Qe==="denied"?h(rt,{value:q,onChange:ne,placeholder:"rm -rf *, ssh *"}):h(T,{children:q||"(none)"})]}),h(T,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]});if(n==="edit-channels")return B(A,{flexDirection:"column",children:[h(T,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),Re.length===0?h(T,{dimColor:!0,children:"No channels available"}):Re.map((f,w)=>B(A,{children:[B(T,{children:[w===pe?">":" "," "]}),B(T,{color:E.has(f.name)?"green":"gray",children:["[",E.has(f.name)?"x":" ","] ",f.name]})]},f.id)),B(T,{dimColor:!0,children:["Selected: ",E.size>0?Array.from(E).join(", "):"none (= block all)"]}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})})]});if(n.startsWith("edit-env")){let f=Object.keys(o.envVars??{});return B(A,{flexDirection:"column",children:[B(T,{bold:!0,children:["Environment Variables (",f.length,")"]}),f.length===0&&n==="edit-env"&&h(T,{dimColor:!0,children:" No env vars. Press a to add."}),f.map((w,x)=>{let k=x===Xe;return n==="edit-env-edit-value"&&k?B(A,{children:[B(T,{color:"cyan",children:["> ",w," = "]}),h(rt,{value:ko,onChange:Po,onSubmit:()=>{let de={...o.envVars??{},[w]:ko};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:de}}).then(()=>{F("Saved","success"),se(),r("edit-env")}).catch(()=>F("Save failed","error"))}})]},w):B(T,{color:k&&n==="edit-env"?"cyan":"white",children:[k&&n==="edit-env"?"> ":" ",w," = ",(o.envVars??{})[w]]},w)}),n==="edit-env-add-key"&&B(A,{children:[h(T,{color:"green",children:" New key: "}),h(rt,{value:Wt,onChange:Bo,onSubmit:()=>{Wt.trim()&&(Io(""),r("edit-env-add-value"))}})]}),n==="edit-env-add-value"&&B(A,{children:[B(T,{color:"green",children:[" ",Wt," = "]}),h(rt,{value:Eo,onChange:Io,onSubmit:()=>{let w={...o.envVars??{},[Wt.trim()]:Eo};v(`/roles/${o.id}`,{method:"PATCH",body:{envVars:w}}).then(()=>{F("Added","success"),se(),r("edit-env")}).catch(()=>F("Add failed","error"))}})]}),h(T,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),V&&h(T,{color:V.type==="error"?"red":"green",children:V.text})]})}return B(A,{flexDirection:"column",children:[B(T,{bold:!0,children:["Role: ",o.name]}),B(A,{children:[h(T,{dimColor:!0,children:"ID: "}),h(T,{children:o.id})]}),B(A,{children:[h(T,{dimColor:!0,children:"Status: "}),h(T,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&B(A,{children:[h(T,{dimColor:!0,children:"Score: "}),B(T,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),B(A,{children:[h(T,{dimColor:!0,children:"Created: "}),h(T,{children:new Date(o.createdAt).toLocaleString()})]}),B(A,{children:[h(T,{dimColor:!0,children:"Execution: "}),B(T,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),Me.length>0&&B(Sr,{children:[h(T,{bold:!0,children:"Additional Directories:"}),Me.map(f=>B(T,{dimColor:!0,children:[" ",f.path]},f.path))]}),B(A,{children:[h(T,{dimColor:!0,children:"Permission: "}),h(T,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&B(A,{children:[h(T,{dimColor:!0,children:" Bash Allow: "}),h(T,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&B(A,{children:[h(T,{dimColor:!0,children:" Bash Deny: "}),h(T,{children:o.deniedBashPatterns.join(", ")})]}),Tt.length>0&&B(A,{flexDirection:"column",children:[h(T,{dimColor:!0,children:"Denied Read Paths (global):"}),Tt.map(f=>B(T,{dimColor:!0,children:[" ",f]},f)),B(T,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(A,{children:[h(T,{dimColor:!0,children:"Channels: "}),h(T,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),B(A,{children:[h(T,{dimColor:!0,children:"Inherit User Settings: "}),h(T,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&B(Sr,{children:[h(T,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(f=>B(T,{dimColor:!0,children:[" - ",f]},f))]}),V&&h(A,{children:h(T,{color:V.type==="error"?"red":V.type==="success"?"green":"gray",children:V.text})}),h(A,{marginTop:1,children:h(T,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec p:perms h:channels v:env i:inherit r:refresh Esc:back"})})]})}import{jsx as De,jsxs as no}from"react/jsx-runtime";function wr({onBack:e}){let[t,o]=Ot([]),[c,u]=Ot(!0),[m,l]=Ot(0),[i,n]=Ot("list"),[r,a]=Ot(null),{message:d,setMessage:b,clearMessage:p}=ct(),y=is(()=>{u(!0),v("/roles").then(({roles:s})=>{o(s.map(g=>({id:g.id,name:g.name,status:g.status,performanceScore:g.performanceScore,createdAt:g.createdAt}))),u(!1)}).catch(()=>u(!1))},[]);return ss(()=>{y()},[y]),ns((s,g)=>{if(g.escape||s==="q"){e();return}if(g.upArrow){l(_=>Math.max(0,_-1));return}if(g.downArrow){l(_=>Math.min(t.length-1,_+1));return}if(s==="r"&&(y(),p()),s===`
|
|
7
|
+
`||s==="o"||s==="e"){t.length>0&&(a(t[m].id),n("detail"));return}}),c?De(nt,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?De(Cr,{roleId:r,onBack:()=>n("list")}):no(kt,{flexDirection:"column",children:[no(nt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&De(kt,{marginTop:1,children:no(nt,{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?De(kt,{marginTop:1,children:De(nt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):De(kt,{marginTop:1,flexDirection:"column",children:t.map((s,g)=>{let _=g===m,M=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014";return no(kt,{children:[De(nt,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),De(nt,{color:_?"cyan":void 0,bold:_,children:Co(s.name,24)}),De(nt,{color:as(s.status),children:Co(s.status,12)}),De(nt,{dimColor:!0,children:Co(M,8)})]},s.id)})}),De(kt,{marginTop:1,children:De(nt,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function as(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Co(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as gs,jsx as G,jsxs as At}from"react/jsx-runtime";function ds(){let{state:e,dispatch:t}=st(),{session:o,sendMessage:c,createNewSession:u,archiveCurrentSession:m}=qo(),[l,i]=cs([]);so(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Vo();let{latestMessage:n}=Uo(o?.id??null),r=wo(null);so(()=>{n&&n.id!==r.current&&(r.current=n.id,i(M=>[...M,{role:"assistant",content:n.content}]))},[n]);let{events:a,isStreaming:d,clearEvents:b}=Oo(e.activeTaskId),p=a[a.length-1],y=p?.type==="complete"&&!d,s=wo(null),g=wo("");so(()=>{g.current=a.filter(M=>M.type==="reasoning").map(M=>M.content).join("")},[a]),so(()=>{if(y&&e.activeTaskId!==s.current){s.current=e.activeTaskId;let M=p?.content||g.current;M&&i(Y=>[...Y,{role:"assistant",content:M}])}},[y,p,e.activeTaskId]);let _=async M=>{let Y=M.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(Y)&&process.exit(0),M.startsWith("/")){let O=M.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"}[O];if(I){t({type:"SET_VIEW",view:I});return}if(O==="new"){if(await m()){let S=await u();i([]),b(),S&&i([{role:"assistant",content:`Session archived. New session started: ${S.id.slice(0,8)}`}])}return}if(O==="session"){let P=o?`Session: ${o.id}
|
|
8
|
+
Turns: ${o.messageCount}
|
|
9
|
+
Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(S=>[...S,{role:"assistant",content:P}]);return}}if(i(O=>[...O,{role:"user",content:M}]),b(),!await c(M)){i(O=>[...O,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}};return At(qt,{flexDirection:"column",paddingX:1,children:[G(Wo,{}),At(qt,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&At(gs,{children:[G(Xo,{messages:l}),G(Ko,{events:a,isStreaming:d}),!e.connected&&!e.serverUnreachable&&G(qt,{children:G(Pt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&At(qt,{flexDirection:"column",children:[G(Pt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),G(Pt,{dimColor:!0,children:"Check: adam server logs"}),G(Pt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&G(hr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&G(zt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&G(or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&G(nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&G(Jt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&G(ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&G(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&G(cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&G(mr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&G(xr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&G(wr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&G(pr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&G(yr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?G(Yo,{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?G(zo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):G(Ho,{onSubmit:_}),e.planTimeoutNotice&&G(us,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function us({planId:e,onDismiss:t}){return ls(o=>{o==="d"&&t()}),At(qt,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[At(Pt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),G(Pt,{dimColor:!0,children:" [d] Dismiss"})]})}function ms(){return G(No,{children:G(ds,{})})}export{ms as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as a,o as b}from"./chunk-UW3OJG7U.js";import"./chunk-5V36ACKZ.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-6YURWVQG.js";import"./chunk-CDVIT7L5.js";import"./chunk-3RAFA6QK.js";import"./chunk-MPRAVJUO.js";import"./chunk-AJVN3KPM.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-KLQOILIJ.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-JTMFEUDA.js";import"./chunk-6KLG4APZ.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-2HN2TSP6.js";import"./chunk-EGS6U3V5.js";import"./chunk-SWPXG2CY.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a 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-U5NRQNBB.js";import"./chunk-QN6BEJF5.js";import"./chunk-OEKM2W3K.js";import"./chunk-EJVUUIAV.js";import"./chunk-GMCIKDTC.js";import"./chunk-3RAFA6QK.js";import"./chunk-BIIP363C.js";import"./chunk-KLQOILIJ.js";import"./chunk-OFOVSC72.js";import"./chunk-L7JP7DUO.js";import"./chunk-GUQAIWCQ.js";import"./chunk-2CMR5AG7.js";import"./chunk-4TCP2AT7.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.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-Q4YE5BU7.js";import"./chunk-CDVIT7L5.js";import"./chunk-3RAFA6QK.js";import"./chunk-L7JP7DUO.js";import"./chunk-4TCP2AT7.js";import"./chunk-6DXNXLYG.js";import"./chunk-JTMFEUDA.js";import"./chunk-6KLG4APZ.js";import"./chunk-7IFLU3CY.js";import"./chunk-6HD6NYIB.js";import"./chunk-B4WHT7DX.js";import"./chunk-7LBDLAUQ.js";import"./chunk-KVSO3KGZ.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{c as a,d as b,e as c}from"./chunk-IHP7JV6J.js";import"./chunk-AR2IZMM2.js";import"./chunk-SWPXG2CY.js";import"./chunk-KVSO3KGZ.js";import"./chunk-WBAPIPST.js";import"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f}from"./chunk-SWPXG2CY.js";import"./chunk-KVSO3KGZ.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,5 @@
|
|
|
1
|
+
import{b as f}from"./chunk-EGS6U3V5.js";import{b as m}from"./chunk-SWPXG2CY.js";import{c as h,h as v}from"./chunk-INNDBLZE.js";v();var p=h("channels"),u=new Map,I=3e5,A=new Set(["telegram"]);function w(i){let e=i.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!e)return null;let[,c,l]=e,o=["yes","y","\u662F","\u5141\u8BB8"].includes(c);return{requestId:l,decision:o?"allow":"deny"}}function $(i){let n=m(i);return n?A.has(n.platform):!1}var T={low:"\u{1F7E2}",medium:"\u{1F7E1}",high:"\u{1F534}"},P={low:"\u4F4E",medium:"\u4E2D",high:"\u9AD8"};function k(i){let n=["\u{1F512} \u9700\u8981\u5BA1\u6279",""];for(let e of i.steps){if(e.description.startsWith("Execute task without OS sandbox"))n.push("\u26A0\uFE0F \u65E0\u6C99\u7BB1\u6267\u884C \u2014 \u6587\u4EF6\u7CFB\u7EDF\u9694\u79BB\u672A\u542F\u7528");else{let o=e.description.indexOf(": "),r=o>0?e.description.slice(0,o):"Operation";if(n.push(`\u64CD\u4F5C: ${r}`),r==="Bash"&&o>0)try{let t=JSON.parse(e.description.slice(o+2));if(t.command){let s=String(t.command).trim();n.push(`\u547D\u4EE4: ${s.length>120?s.slice(0,117)+"...":s}`)}}catch{let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}else if(o>0){let t=e.description.slice(o+2,o+122);n.push(`\u8BE6\u60C5: ${t}${e.description.length>o+122?"...":""}`)}}let c=T[e.riskLevel]??"\u{1F7E1}",l=P[e.riskLevel]??e.riskLevel;n.push(`\u98CE\u9669: ${c} ${l}`),n.push("")}return n.join(`
|
|
2
|
+
`).trimEnd()}async function C(i,n,e,c,l,o=I){let r=e,t=r.slice(0,8);u.set(t,{planId:e,taskId:c,channelId:i,chatId:n,requestId:r,timestamp:Date.now(),timeoutMs:o});let s=f(),d=$(i);if(d){let a=`${l}
|
|
3
|
+
|
|
4
|
+
`;await s.send({channelId:i,chatId:n,content:a,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${t}`},{text:"\u274C Deny",callbackData:`no ${t}`}]]}})}else{let a=[l,"",`Reply 'yes ${t}' or 'no ${t}'`].join(`
|
|
5
|
+
`);await s.send({channelId:i,chatId:n,content:a,messageType:"approval"})}setTimeout(()=>{let a=u.get(t);if(a&&Date.now()-a.timestamp>=a.timeoutMs){u.delete(t),p.warn({requestId:r,shortId:t,taskId:c},"Approval timed out, auto-denying"),s.send({channelId:a.channelId,chatId:a.chatId,content:`\u23F0 Approval ${t} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(g=>p.error({requestId:r,error:g},"Failed to notify timeout"));let y=process.env.ADAM_PORT??"7100";fetch(`http://localhost:${y}/tasks/${a.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:a.planId,decision:"deny"})}).catch(g=>p.error({requestId:r,error:g},"Failed to auto-deny"))}},o+1e3),p.info({channelId:i,chatId:n,planId:e,shortId:t,interactive:d},"Interactive approval sent to channel")}async function S(i,n,e,c){let o=w(c??e);if(!o)return!1;let{requestId:r,decision:t}=o,s=u.get(r);if(!s)return!1;if(s.channelId!==i||s.chatId!==n)return p.debug({shortId:r,expectedChannel:s.channelId,gotChannel:i},"Approval reply from different channel"),!1;u.delete(r),p.info({shortId:r,requestId:s.requestId,decision:t},"Channel approval reply received");try{let d=process.env.ADAM_PORT??"7100",a=await fetch(`http://localhost:${d}/tasks/${s.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:s.planId,decision:t}),signal:AbortSignal.timeout(1e4)});a.ok||p.error({shortId:r,status:a.status},"Failed to forward approval to API")}catch(d){p.error({shortId:r,error:d},"Error forwarding approval to API")}return!0}function E(){return[...u.keys()]}export{w as a,k as b,C as c,S as d,E as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as u,d as a}from"./chunk-
|
|
1
|
+
import{b as u,d as a}from"./chunk-KVSO3KGZ.js";a();function d(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0}}function c(e){u().prepare(`
|
|
2
2
|
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
3
|
sdk_session_id, template_id, role_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
4
|
created_at, started_at, completed_at,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as f,k as h}from"./chunk-
|
|
1
|
+
import{e as f,k as h}from"./chunk-B4WHT7DX.js";import{b as u,d as E}from"./chunk-KVSO3KGZ.js";E();h();function l(e){return{id:e.id,roleId:e.role_id,type:e.type,content:e.content,embedding:e.embedding?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength/4):void 0,keywords:e.keywords?JSON.parse(e.keywords):[],importance:e.importance,sourceType:e.source_type,sourceTaskId:e.source_task_id??void 0,evidence:e.evidence?JSON.parse(e.evidence):void 0,createdAt:e.created_at,lastAccessed:e.last_accessed,retrievedCount:e.retrieved_count,tier:e.tier,supersededBy:e.superseded_by??void 0}}function b(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function v(e){u().prepare(`
|
|
2
2
|
INSERT INTO memories (id, role_id, type, content, embedding, keywords,
|
|
3
3
|
importance, source_type, source_task_id, evidence,
|
|
4
4
|
created_at, last_accessed, retrieved_count, tier, superseded_by)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as s,d as l}from"./chunk-
|
|
1
|
+
import{b as s,d as l}from"./chunk-KVSO3KGZ.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)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var f=["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","logging.level","roles.evolution.triggerEvery","roles.evolution.reflectionThreshold","chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory","server.timezone","anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel","defaults.approvalTimeout","defaults.deniedReadPaths","defaults.approvalRequired"],g=["server.port","server.host","server.apiKey"],p={"anthropic.apiKey":"ANTHROPIC_API_KEY","anthropic.baseUrl":"ANTHROPIC_BASE_URL","anthropic.model":"ANTHROPIC_MODEL","anthropic.defaultOpusModel":"ANTHROPIC_DEFAULT_OPUS_MODEL","anthropic.defaultSonnetModel":"ANTHROPIC_DEFAULT_SONNET_MODEL","anthropic.defaultHaikuModel":"ANTHROPIC_DEFAULT_HAIKU_MODEL","anthropic.smallFastModel":"ANTHROPIC_SMALL_FAST_MODEL"},a=null;function A(t){a=JSON.parse(JSON.stringify(t))}function i(){if(!a)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return a}function _(t){let r=i(),o=t();for(let[n,e]of Object.entries(o))d(r,n,e)}function R(){let t=i(),r={};for(let[o,n]of Object.entries(p)){let e=E(t,o);e&&typeof e=="string"&&e.length>0?r[n]=e:process.env[n]&&(r[n]=process.env[n])}return r}function c(t){let r={};for(let[o,n]of Object.entries(t))o.startsWith("ANTHROPIC_")||(r[o]=n);return r}var l=/key|token|secret|password|credential/i;function k(t){let r={};for(let[o,n]of Object.entries(t))r[o]=l.test(o)&&n.length>4?n.slice(0,4)+"****":l.test(o)&&n.length>0?"****":n;return r}function O(t){let o=i().defaults?.env??{};return{...process.env,...o,...R(),...c(t?.roleEnvVars??{}),...c(t?.taskEnv??{}),DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1"}}function S(t,r){let o=i(),n=[],e=[];for(let[s,u]of Object.entries(t)){if(!h(s)){v(s)?e.push(`"${s}" requires restart. Cannot modify at runtime.`):e.push(`"${s}" is not a recognized config path.`);continue}d(o,s,u)&&(n.push(s),r?.(s,u))}return{success:e.length===0,updated:n,errors:e}}function d(t,r,o){let n=r.split("."),e=t;for(let s=0;s<n.length-1;s++)if(e&&typeof e=="object")e=e[n[s]];else return!1;return e&&typeof e=="object"?(e[n[n.length-1]]=o,!0):!1}function E(t,r){let o=r.split("."),n=t;for(let e of o)if(n&&typeof n=="object")n=n[e];else return;return n}function h(t){return f.includes(t)}function v(t){return g.includes(t)}export{f as a,g as b,A as c,i as d,_ as e,R as f,c as g,k as h,O as i,S as j,E as k,h as l,v as m};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as a,d as u}from"./chunk-
|
|
1
|
+
import{b as a,d as u}from"./chunk-KVSO3KGZ.js";u();function l(e){return{id:e.id,eventType:e.event_type,matchCriteria:JSON.parse(e.match_criteria),target:JSON.parse(e.target),formatTemplate:e.format_template??void 0,maxPerMinute:e.max_per_minute,skipOriginChannel:e.skip_origin_channel===1,enabled:e.enabled===1,createdAt:e.created_at,createdBy:e.created_by??void 0}}function d(e){a().prepare(`
|
|
2
2
|
INSERT INTO delivery_rules (id, event_type, match_criteria, target, format_template,
|
|
3
3
|
max_per_minute, skip_origin_channel, enabled, created_at, created_by)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{g as a,h as E}from"./chunk-WBAPIPST.js";E();import{readFileSync as h,writeFileSync as _,existsSync as v}from"fs";var f={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"},R=Object.fromEntries(Object.entries(f).map(([c,o])=>[o,c]));function m(c){let o={};for(let i of c.split(`
|
|
2
|
+
`)){let r=i.trim();if(!r||r.startsWith("#"))continue;let n=r.startsWith("export ")?r.slice(7).trim():r,s=n.indexOf("=");if(s===-1)continue;let e=n.slice(0,s).trim(),t=n.slice(s+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(l,g,u)=>{let d=g??u;return o[d]??process.env[d]??""}),!t))&&(o[e]=t)}return o}function y(){if(!v(a))return null;let c=m(h(a,"utf-8")),o={};for(let[i,r]of Object.entries(c))i in f&&(o[i]=r);return o}function V(){return v(a)?m(h(a,"utf-8")):null}function P(c){let o=V();if(!o)return[];let i=[];for(let[n,s]of Object.entries(f)){let e=c[s],t=o[n];if(t===void 0)continue;let l=e?String(e):"";l!==t&&i.push({configPath:s,envKey:n,dbValue:l,envValue:t})}let r=c["defaults.env"]??{};for(let[n,s]of Object.entries(o)){if(n in f)continue;let e=r[n]??"";e!==s&&i.push({configPath:`defaults.env.${n}`,envKey:n,dbValue:e,envValue:s})}for(let[n,s]of Object.entries(r))n in o||i.push({configPath:`defaults.env.${n}`,envKey:n,dbValue:s,envValue:""});return i}function S(c){if(!v(a))return 0;let i=h(a,"utf-8").split(`
|
|
3
|
+
`),r=0,n=new Set,s=c["defaults.env"]??{};for(let e=0;e<i.length;e++){let t=i[e].trim();if(!t||t.startsWith("#"))continue;let l=t.startsWith("export ")?t.slice(7).trim():t,g=l.indexOf("=");if(g===-1)continue;let u=l.slice(0,g).trim(),d=t.startsWith("export ")?"export ":"",O=f[u];if(O){let p=c[O];p!=null&&String(p).length>0&&(i[e]=`${d}${u}=${String(p)}`,n.add(u),r++);continue}u in s&&(i[e]=`${d}${u}=${s[u]}`,n.add(u),r++)}for(let[e,t]of Object.entries(f)){if(n.has(e))continue;let l=c[t];l&&String(l).length>0&&(i.push(`${e}=${String(l)}`),r++)}for(let[e,t]of Object.entries(s))n.has(e)||t&&t.length>0&&(i.push(`${e}=${t}`),r++);return r>0&&_(a,i.join(`
|
|
4
|
+
`)),r}export{R as a,y as b,V as c,P as d,S as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{b as r,d as s}from"./chunk-
|
|
1
|
+
import{b as r,d as s}from"./chunk-KVSO3KGZ.js";import{c as i}from"./chunk-FCV2DPZQ.js";function p(e){let n=r().prepare("SELECT value FROM config WHERE key = ?").get(e);if(n)try{return JSON.parse(n.value)}catch{return n.value}}function E(e,t){let n=r(),o=JSON.stringify(t),u=Date.now();n.prepare(`INSERT INTO config (key, value, updated_at) VALUES (?, ?, ?)
|
|
2
2
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(e,o,u)}function k(){let t=r().prepare("SELECT key, value FROM config").all(),n={};for(let o of t)try{n[o.key]=JSON.parse(o.value)}catch{n[o.key]=o.value}return n}function b(e){let t=r(),n=t.prepare("INSERT OR IGNORE INTO config (key, value, updated_at) VALUES (?, ?, ?)"),o=Date.now(),u=0;return t.transaction(()=>{for(let[c,a]of Object.entries(e)){if(a==null||a==="")continue;n.run(c,JSON.stringify(a),o).changes>0&&u++}})(),u}function w(){return r().prepare("SELECT COUNT(*) as count FROM config").get().count===0}function O(e){return r().prepare("DELETE FROM config WHERE key = ?").run(e).changes>0}var d=i(()=>{s()});export{p as a,E as b,k as c,b as d,w as e,O as f,d as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as u}from"./chunk-
|
|
1
|
+
import{b as i,d as u}from"./chunk-KVSO3KGZ.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as n,d as o}from"./chunk-
|
|
1
|
+
import{b as n,d as o}from"./chunk-KVSO3KGZ.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,8 @@
|
|
|
1
|
+
import{a as u,g as O}from"./chunk-7LBDLAUQ.js";import{b as l,d as R}from"./chunk-KVSO3KGZ.js";import{b as a,h}from"./chunk-WBAPIPST.js";import{c as m,e as v}from"./chunk-FCV2DPZQ.js";import*as _ from"os";import*as g from"path";function d(e){return e.startsWith("~/")||e==="~"?g.join(_.homedir(),e.slice(1)):e}var S=m(()=>{"use strict";h()});var x={};v(x,{createRole:()=>E,deleteRole:()=>T,getRole:()=>N,getRoleByName:()=>b,listRoles:()=>J,updateRole:()=>w,validateAdditionalDirectories:()=>p});import{existsSync as y}from"fs";import{resolve as c}from"path";function p(e,n){for(let s of e){let i=typeof s=="string"?s:s.path;if(!i.startsWith("/")&&!i.startsWith("~/")&&i!=="~")throw new Error(`additionalDirectories must be absolute paths: '${i}' is not absolute`);let r=c(d(i));if(!r.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${i}' is not absolute`);for(let t of a){let o=c(d(t));if(r.startsWith(o))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${i}' matches '${t}'`)}if(n?.length)for(let t of n){let o=c(d(t));if(r.startsWith(o)||o.startsWith(r))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${i}' conflicts with '${t}'`)}if(!y(r))throw new Error(`additionalDirectories path does not exist: '${i}'`)}}function f(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:e.learned_rules?JSON.parse(e.learned_rules):[],memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let n=JSON.parse(e.additional_directories);return Array.isArray(n)?n.map(s=>typeof s=="string"?{path:s}:s):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0}}function E(e){let n=u("defaults.deniedReadPaths")??[...a];e.additionalDirectories&&p(e.additionalDirectories,n),l().prepare(`
|
|
2
|
+
INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
|
|
3
|
+
performance_score, preferences, created_at, updated_at,
|
|
4
|
+
allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
|
|
5
|
+
max_budget_usd, approval_required, source, additional_directories, allowed_channels, mcp_servers, inherit_user_settings,
|
|
6
|
+
permission_mode, allowed_bash_patterns, denied_bash_patterns, env_vars)
|
|
7
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
8
|
+
`).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0,e.permissionMode??null,e.allowedBashPatterns?JSON.stringify(e.allowedBashPatterns):null,e.deniedBashPatterns?JSON.stringify(e.deniedBashPatterns):null,e.envVars?JSON.stringify(e.envVars):null)}function N(e){let s=l().prepare("SELECT * FROM roles WHERE id = ?").get(e);return s?f(s):void 0}function b(e){let s=l().prepare("SELECT * FROM roles WHERE name = ?").get(e);return s?f(s):void 0}function w(e,n){let s=l(),i=[],r=[];if("name"in n&&(i.push("name = ?"),r.push(n.name)),"cagPrompt"in n&&(i.push("cag_prompt = ?"),r.push(n.cagPrompt)),"learnedRules"in n&&(i.push("learned_rules = ?"),r.push(JSON.stringify(n.learnedRules))),"memoryStreamId"in n&&(i.push("memory_stream_id = ?"),r.push(n.memoryStreamId)),"status"in n&&(i.push("status = ?"),r.push(n.status)),"performanceScore"in n&&(i.push("performance_score = ?"),r.push(n.performanceScore??null)),"preferences"in n&&(i.push("preferences = ?"),r.push(n.preferences?JSON.stringify(n.preferences):null)),"updatedAt"in n&&(i.push("updated_at = ?"),r.push(n.updatedAt??null)),"allowedTools"in n&&(i.push("allowed_tools = ?"),r.push(n.allowedTools?JSON.stringify(n.allowedTools):null)),"disallowedTools"in n&&(i.push("disallowed_tools = ?"),r.push(n.disallowedTools?JSON.stringify(n.disallowedTools):null)),"evaluationCriteria"in n&&(i.push("evaluation_criteria = ?"),r.push(n.evaluationCriteria?JSON.stringify(n.evaluationCriteria):null)),"executionMode"in n&&(i.push("execution_mode = ?"),r.push(n.executionMode??null)),"model"in n&&(i.push("model = ?"),r.push(n.model??null)),"maxBudgetUsd"in n&&(i.push("max_budget_usd = ?"),r.push(n.maxBudgetUsd??null)),"approvalRequired"in n&&(i.push("approval_required = ?"),r.push(n.approvalRequired?JSON.stringify(n.approvalRequired):null)),"source"in n&&(i.push("source = ?"),r.push(n.source??null)),"additionalDirectories"in n){let t=u("defaults.deniedReadPaths")??[...a];n.additionalDirectories&&p(n.additionalDirectories,t),i.push("additional_directories = ?"),r.push(n.additionalDirectories?JSON.stringify(n.additionalDirectories):null)}"allowedChannels"in n&&(i.push("allowed_channels = ?"),r.push(n.allowedChannels?JSON.stringify(n.allowedChannels):null)),"mcpServers"in n&&(i.push("mcp_servers = ?"),r.push(n.mcpServers?JSON.stringify(n.mcpServers):null)),"inheritUserSettings"in n&&(i.push("inherit_user_settings = ?"),r.push(n.inheritUserSettings?1:0)),"permissionMode"in n&&(i.push("permission_mode = ?"),r.push(n.permissionMode??null)),"allowedBashPatterns"in n&&(i.push("allowed_bash_patterns = ?"),r.push(n.allowedBashPatterns?JSON.stringify(n.allowedBashPatterns):null)),"deniedBashPatterns"in n&&(i.push("denied_bash_patterns = ?"),r.push(n.deniedBashPatterns?JSON.stringify(n.deniedBashPatterns):null)),"envVars"in n&&(i.push("env_vars = ?"),r.push(n.envVars?JSON.stringify(n.envVars):null)),i.length!==0&&(r.push(e),s.prepare(`UPDATE roles SET ${i.join(", ")} WHERE id = ?`).run(...r))}function J(e,n=100,s=0){let i=l(),r="SELECT * FROM roles",t=[];return e&&(r+=" WHERE status = ?",t.push(e)),r+=" ORDER BY created_at ASC LIMIT ? OFFSET ?",t.push(n,s),i.prepare(r).all(...t).map(f)}function T(e){l().prepare("DELETE FROM roles WHERE id = ?").run(e)}var D=m(()=>{R();h();S();O()});export{d as a,S as b,p as c,E as d,N as e,b as f,w as g,J as h,T as i,x as j,D as k};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{f as s,j as w}from"./chunk-KLQOILIJ.js";import{d as i,e as f,h as g,k as y}from"./chunk-B4WHT7DX.js";import{c as p,h}from"./chunk-INNDBLZE.js";y();w();h();import{v4 as c}from"uuid";var t=p("store"),a="role-chat-manager",l=[{name:"Engineer",cagPrompt:`Role: General-purpose software engineer.
|
|
2
2
|
Capabilities: Read, write, and edit code; run shell commands; search codebases.
|
|
3
3
|
Approach: Analyze requirements \u2192 implement \u2192 test \u2192 verify. Write tests for new code. Follow existing code patterns.
|
|
4
4
|
Best for: Feature implementation, bug fixes, refactoring, build/deploy scripts.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as i,d as l}from"./chunk-
|
|
1
|
+
import{b as i,d as l}from"./chunk-KVSO3KGZ.js";l();function o(e){return{id:e.id,name:e.name,description:e.description??void 0,roleId:e.role,metricType:e.metric_type,targetValue:e.target_value,currentValue:e.current_value,deadline:e.deadline,budgetUsd:e.budget_usd,status:e.status,createdAt:e.created_at,updatedAt:e.updated_at??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0}}function c(e){i().prepare(`
|
|
2
2
|
INSERT INTO goals (id, name, description, role, metric_type, target_value,
|
|
3
3
|
current_value, deadline, budget_usd, status, created_at, updated_at,
|
|
4
4
|
source_session_id, deliver_to, report_to)
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{b as C}from"./chunk-
|
|
1
|
+
import{b as C}from"./chunk-SWPXG2CY.js";import{b as D,c as f,d as w}from"./chunk-OFOVSC72.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
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-
|
|
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-WMCY4QC3.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 t,d}from"./chunk-
|
|
1
|
+
import{b as t,d}from"./chunk-KVSO3KGZ.js";d();function s(e){return{id:e.id,taskId:e.task_id,roleId:void 0,plan:JSON.parse(e.plan_json),status:e.status,approvalType:e.approval_type??void 0,deviationReport:e.deviation_report_json?JSON.parse(e.deviation_report_json):void 0,learnedRules:e.learned_rules_json?JSON.parse(e.learned_rules_json):void 0,createdAt:e.created_at,approvedAt:e.approved_at??void 0,reviewedAt:e.reviewed_at??void 0}}function p(e){t().prepare(`
|
|
2
2
|
INSERT INTO task_plans (id, task_id, plan_json, status, approval_type,
|
|
3
3
|
deviation_report_json, learned_rules_json, created_at, approved_at, reviewed_at)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as e,d as p}from"./chunk-
|
|
1
|
+
import{b as e,d as p}from"./chunk-KVSO3KGZ.js";p();function i(t){return{id:t.id,taskId:t.task_id,index:t.index,type:t.type,content:t.content,toolName:t.tool_name??void 0,toolInput:t.tool_input?JSON.parse(t.tool_input):void 0,toolOutput:t.tool_output??void 0,truncated:t.truncated===1,timestamp:t.timestamp,tokenUsage:t.token_usage?JSON.parse(t.token_usage):void 0,planStepIndex:t.plan_step_index??void 0}}function a(t){e().prepare(`
|
|
2
2
|
INSERT INTO step_logs (id, task_id, "index", type, content, tool_name,
|
|
3
3
|
tool_input, tool_output, truncated, timestamp, token_usage, plan_step_index)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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-4TCP2AT7.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{f as ce}from"./chunk-AR2IZMM2.js";import{a as ue,b as x,c as X,d as le,e as ge}from"./chunk-SWPXG2CY.js";import{c as _,h as R}from"./chunk-INNDBLZE.js";import{z as g}from"zod/v4";import{v4 as Dt}from"uuid";import{randomUUID as _e}from"crypto";import Ye from"crypto";var me="2.1.7",F="bot";function Ze(t){let e=t.split(".").map(r=>parseInt(r,10)),s=e[0]??0,i=e[1]??0,n=e[2]??0;return(s&255)<<16|(i&255)<<8|n&255}var J=Ze(me),et=35e3,pe=15e3,tt=1e4;function L(){return{channel_version:me}}function nt(t){return t.endsWith("/")?t:`${t}/`}function st(){let t=Ye.randomBytes(4).readUInt32BE(0);return Buffer.from(String(t),"utf-8").toString("base64")}function it(t){let e={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(t.body,"utf-8")),"X-WECHAT-UIN":st(),"iLink-App-Id":F,"iLink-App-ClientVersion":String(J)};return t.token?.trim()&&(e.Authorization=`Bearer ${t.token.trim()}`),t.routeTag&&(e.SKRouteTag=t.routeTag),e}async function D(t){let e=nt(t.baseUrl),s=new URL(t.endpoint,e),i=it({token:t.token,routeTag:t.routeTag,body:t.body}),n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs);try{let o=await fetch(s.toString(),{method:"POST",headers:i,body:t.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${t.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function fe(t){let e=t.timeoutMs??et;try{let s=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:t.get_updates_buf??"",base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:e,label:"getUpdates"});return JSON.parse(s)}catch(s){if(s instanceof Error&&s.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:t.get_updates_buf};throw s}}var rt={[-2]:2,[-3]:3},ot=1e3;async function C(t){let e=(await import("./logger-QCJUU7GV.js")).getLogger("channels"),s=new Map;for(;;){let i=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??pe,label:"sendMessage"});e.info({status:200,responseBody:i.slice(0,300)},"apiFetch sendMessage response");try{let n=JSON.parse(i);if(n.ret&&n.ret!==0){let r=rt[n.ret],o=(s.get(n.ret)??0)+1;if(s.set(n.ret,o),r!==void 0&&o<r){e.warn({ret:n.ret,attempt:o,maxRetries:r},"sendMessage: retriable iLink error, retrying"),await new Promise(a=>setTimeout(a,ot*o));continue}throw e.error({ret:n.ret,errmsg:n.errmsg,attempt:o},"sendMessage: iLink API error, no more retries"),new Error(`sendMessage failed: iLink ret=${n.ret}${n.errmsg?` errmsg=${n.errmsg}`:""}`)}}catch(n){if(n instanceof SyntaxError)e.warn({rawText:i.slice(0,200)},"sendMessage: non-JSON response, treating as success");else throw n}return}}async function he(t){await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...t.body,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??tt,label:"sendTyping"})}async function ye(t){let e=await D({baseUrl:t.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:t.filekey,media_type:t.media_type,to_user_id:t.to_user_id,rawsize:t.rawsize,rawfilemd5:t.rawfilemd5,filesize:t.filesize,thumb_rawsize:t.thumb_rawsize,thumb_rawfilemd5:t.thumb_rawfilemd5,thumb_filesize:t.thumb_filesize,no_need_thumb:t.no_need_thumb,aeskey:t.aeskey,base_info:L()}),token:t.token,routeTag:t.routeTag,timeoutMs:t.timeoutMs??pe,label:"getUploadUrl"});return JSON.parse(e)}var at=5*6e4,dt=35e3,be="3",w=new Map;function Y(t){return Date.now()-t.startedAt<at}function ct(){for(let[t,e]of w)Y(e)||w.delete(t)}async function we(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F};s&&(r.SKRouteTag=s);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function ut(t,e,s){let i=t.endsWith("/")?t:`${t}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(e)}`,i),r={"iLink-App-Id":F,"iLink-App-ClientVersion":String(J)};s&&(r.SKRouteTag=s);let o=new AbortController,a=setTimeout(()=>o.abort(),dt);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);let c=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(c)}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function xe(t){let e=t.accountId||_e();ct();let s=w.get(e);if(!t.force&&s&&Y(s)&&s.qrcodeUrl)return{qrcodeUrl:s.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:e};if(!t.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:e};try{let i=t.botType||be,n=await we(t.apiBaseUrl,i,t.routeTag),r={sessionKey:e,id:_e(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return w.set(e,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:e}}catch(i){return{message:`Failed to start login: ${String(i)}`,sessionKey:e}}}var lt=3;async function Ie(t){let e=w.get(t.sessionKey);if(!e)return{connected:!1,message:"No active login session. Start QR login first."};if(!Y(e))return w.delete(t.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let s=Math.max(t.timeoutMs??48e4,1e3),i=Date.now()+s,n=1;for(;Date.now()<i;){try{let r=await ut(t.apiBaseUrl,e.qrcode,t.routeTag);switch(e.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>lt)return w.delete(t.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=t.botType||be,a=await we(t.apiBaseUrl,o,t.routeTag);e.qrcode=a.qrcode,e.qrcodeUrl=a.qrcode_img_content,e.startedAt=Date.now()}catch(o){return w.delete(t.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(w.delete(t.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(w.delete(t.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return w.delete(t.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return w.delete(t.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import T,{promises as q}from"fs";import I from"path";import{homedir as K}from"os";var W={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},E={NONE:0,USER:1,BOT:2},y={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},A={NEW:0,GENERATING:1,FINISH:2},Te={TYPING:1,CANCEL:2};R();var gt=_("channels"),Z=-14,B=3600*1e3,S=new Map;function Re(t){let e=Date.now()+B;S.set(t,e),gt.info({channelId:t},`Session paused until ${new Date(e).toISOString()} (${B/1e3}s)`)}function j(t){let e=S.get(t);return e===void 0?!1:Date.now()>=e?(S.delete(t),!1):!0}function Me(t){let e=S.get(t);if(e===void 0)return 0;let s=e-Date.now();return s<=0?(S.delete(t),0):s}function Ue(t){S.delete(t)}R();import Ne from"fs";import $e from"path";import{homedir as wt}from"os";import{createCipheriv as mt,createDecipheriv as pt}from"crypto";function ke(t,e){let s=mt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Se(t,e){let s=pt("aes-128-ecb",e,null);return Buffer.concat([s.update(t),s.final()])}function Ce(t){return Math.ceil((t+1)/16)*16}function ee(t,e){return`${e}/download?encrypted_query_param=${encodeURIComponent(t)}`}function Ee(t){return`${t.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(t.uploadParam)}&filekey=${encodeURIComponent(t.filekey)}`}R();var sn=_("channels");function ft(t){let e=Buffer.from(t,"base64");if(e.length===16)return e;if(e.length===32&&/^[0-9a-fA-F]{32}$/.test(e.toString("ascii")))return Buffer.from(e.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${e.length} bytes`)}async function Ae(t){let e=await fetch(t);if(!e.ok)throw new Error(`CDN download ${e.status} ${e.statusText}`);return Buffer.from(await e.arrayBuffer())}async function P(t){let{encryptQueryParam:e,aesKeyBase64:s,cdnBaseUrl:i,fullUrl:n}=t,r=ft(s),o=n?.trim()||(e?ee(e,i):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Ae(o);return Se(a,r)}async function Pe(t){let{encryptQueryParam:e,cdnBaseUrl:s,fullUrl:i}=t,n=i?.trim()||(e?ee(e,s):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Ae(n)}R();var Q=_("channels"),ve=24e3;function ht(t,e){let s=t.byteLength,i=44+s,n=Buffer.allocUnsafe(i),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(i-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(e,r),r+=4,n.writeUInt32LE(e*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(s,r),r+=4,Buffer.from(t.buffer,t.byteOffset,t.byteLength).copy(n,r),n}async function Oe(t){try{let{decode:e}=await import("silk-wasm");Q.debug(`silkToWav: decoding ${t.length} bytes of SILK`);let s=await e(t,ve);Q.debug(`silkToWav: decoded duration=${s.duration}ms pcmBytes=${s.data.byteLength}`);let i=ht(s.data,ve);return Q.debug(`silkToWav: WAV size=${i.length}`),i}catch(e){return Q.warn(`silkToWav: transcode failed, will use raw silk err=${String(e)}`),null}}import yt from"path";var _t={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".amr":"audio/amr",".silk":"audio/x-silk",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},bt={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","audio/amr":".amr","audio/x-silk":".silk","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function V(t){let e=yt.extname(t).toLowerCase();return _t[e]??"application/octet-stream"}function qe(t){let e=t.split(";")[0].trim().toLowerCase();return bt[e]??".bin"}var k=_("channels"),Fe=100*1024*1024;function xt(t){return qe(t)??".bin"}async function v(t,e,s,i,n=Fe,r){if(t.length>n)throw new Error(`Media too large: ${t.length} bytes exceeds ${n} bytes`);let o=$e.join(wt(),".adam","wechat","media",i,s);await Ne.promises.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let c=e?xt(e):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${c}`}let d=$e.join(o,a);return await Ne.promises.writeFile(d,t),k.debug(`saveMedia: saved ${t.length} bytes to ${d}`),d}async function Le(t,e){let{cdnBaseUrl:s,channelId:i}=e;if(t.type===y.IMAGE){let n=t.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await P({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:s,fullUrl:n.media?.full_url}):await Pe({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:s,fullUrl:n.media?.full_url});return{path:await v(o,"image/png","inbound",i),mimeType:"image/png",type:"image"}}catch(o){return k.error({channelId:i},`Image download/decrypt failed: ${String(o)}`),null}}if(t.type===y.VOICE){let n=t.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await P({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=await Oe(r);if(o){let a=await v(o,"audio/wav","inbound",i);return k.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await v(r,"audio/silk","inbound",i);return k.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return k.error({channelId:i},`Voice download/transcode failed: ${String(r)}`),null}}if(t.type===y.FILE){let n=t.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await P({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url}),o=V(n.file_name??"file.bin");return{path:await v(r,o,"inbound",i,Fe,n.file_name),mimeType:o,type:"file"}}catch(r){return k.error({channelId:i},`File download failed: ${String(r)}`),null}}if(t.type===y.VIDEO){let n=t.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await P({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:s,fullUrl:n.media.full_url});return{path:await v(r,"video/mp4","inbound",i),mimeType:"video/mp4",type:"video"}}catch(r){return k.error({channelId:i},`Video download failed: ${String(r)}`),null}}return null}import Be from"path";import te from"crypto";import It from"fs/promises";R();var M=_("channels"),z=3;async function Tt(t){let{buf:e,uploadFullUrl:s,uploadParam:i,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=t,d=ke(e,a),c=s?.trim(),u;if(c)u=c;else if(i)u=Ee({cdnBaseUrl:r,uploadParam:i,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);M.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,l;for(let h=1;h<=z;h++)try{let m=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(m.status>=400&&m.status<500){let b=m.headers.get("x-error-message")??await m.text();throw M.error(`${o}: CDN client error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload client error ${m.status}: ${b}`)}if(m.status!==200){let b=m.headers.get("x-error-message")??`status ${m.status}`;throw M.error(`${o}: CDN server error attempt=${h} status=${m.status} errMsg=${b}`),new Error(`CDN upload server error: ${b}`)}if(p=m.headers.get("x-encrypted-param")??void 0,!p)throw M.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");M.debug(`${o}: CDN upload success attempt=${h}`);break}catch(m){if(l=m,m instanceof Error&&m.message.includes("client error"))throw m;h<z?M.warn(`${o}: attempt ${h} failed, retrying... err=${String(m)}`):M.error(`${o}: all ${z} attempts failed err=${String(m)}`)}if(!p)throw l instanceof Error?l:new Error(`CDN upload failed after ${z} attempts`);return{downloadParam:p}}async function ne(t){let{filePath:e,toUserId:s,opts:i,cdnBaseUrl:n,mediaType:r,label:o}=t,a=await It.readFile(e),d=a.length,c=te.createHash("md5").update(a).digest("hex"),u=Ce(d),p=te.randomBytes(16).toString("hex"),l=te.randomBytes(16);M.debug(`${o}: file=${e} rawsize=${d} filesize=${u} md5=${c} filekey=${p}`);let h=await ye({...i,filekey:p,media_type:r,to_user_id:s,rawsize:d,rawfilemd5:c,filesize:u,no_need_thumb:!0,aeskey:l.toString("hex")}),m=h.upload_full_url?.trim(),b=h.upload_param;if(!m&&!b)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:Je}=await Tt({buf:a,uploadFullUrl:m||void 0,uploadParam:b??void 0,filekey:p,cdnBaseUrl:n,aeskey:l,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:Je,aeskey:l.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function De(t){return ne({...t,mediaType:W.IMAGE,label:"uploadImageToWeixin"})}async function We(t){return ne({...t,mediaType:W.VIDEO,label:"uploadVideoToWeixin"})}async function se(t){return ne({...t,mediaType:W.FILE,label:"uploadFileAttachmentToWeixin"})}R();var O=_("channels");function Rt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Mt(t){let e=t;return e=e.replace(/```[^\n]*\n?([\s\S]*?)```/g,(s,i)=>i.trim()),e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,""),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/^\|[\s:|-]+\|$/gm,""),e=e.replace(/^\|(.+)\|$/gm,(s,i)=>i.split("|").map(n=>n.trim()).join(" ")),e}async function ie(t){let{to:e,text:s,mediaItem:i,opts:n,label:r}=t,o=[],a=Mt(s);a&&o.push({type:y.TEXT,text_item:{text:a}}),o.push(i);let d="";for(let c of o){d=Rt();let u={msg:{from_user_id:"",to_user_id:e,client_id:d,message_type:E.BOT,message_state:A.FINISH,item_list:[c],context_token:n.contextToken}};await C({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return O.debug(`${r}: sent to=${e} messageId=${d}`),{messageId:d}}async function Ut(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.IMAGE,image_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},mid_size:i.fileSizeCiphertext}};return ie({to:e,text:s,mediaItem:r,opts:n,label:"sendImageMessage"})}async function kt(t){let{to:e,text:s,uploaded:i,opts:n}=t,r={type:y.VIDEO,video_item:{media:{encrypt_query_param:i.downloadEncryptedQueryParam,aes_key:Buffer.from(i.aeskey).toString("base64"),encrypt_type:1},video_size:i.fileSizeCiphertext}};return ie({to:e,text:s,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function je(t){let{to:e,text:s,fileName:i,uploaded:n,opts:r}=t,o={type:y.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:i,len:String(n.fileSize)}};return ie({to:e,text:s,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Qe(t){let{filePath:e,to:s,text:i,opts:n,cdnBaseUrl:r}=t,o=V(e),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){O.debug(`sendWeixinMediaFile: uploading video filePath=${e} to=${s}`);let u=await We({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return kt({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("image/")){O.debug(`sendWeixinMediaFile: uploading image filePath=${e} to=${s}`);let u=await De({filePath:e,toUserId:s,opts:a,cdnBaseUrl:r});return Ut({to:s,text:i,uploaded:u,opts:n})}if(o.startsWith("audio/")){let u=Be.basename(e);O.debug(`sendWeixinMediaFile: uploading audio as file filePath=${e} name=${u} to=${s}`);let p=await se({filePath:e,fileName:u,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:u,uploaded:p,opts:n})}let d=Be.basename(e);O.debug(`sendWeixinMediaFile: uploading file attachment filePath=${e} name=${d} to=${s}`);let c=await se({filePath:e,fileName:d,toUserId:s,opts:a,cdnBaseUrl:r});return je({to:s,text:i,fileName:d,uploaded:c,opts:n})}R();var f=_("channels"),Ve="https://novac2c.cdn.weixin.qq.com/c2c",ae=new Map;function Ke(t){return I.join(K(),".adam","wechat",`${t}.context-tokens.json`)}function St(t){let e=Ke(t);try{let s=T.readFileSync(e,"utf-8"),i=JSON.parse(s);for(let[n,r]of Object.entries(i))typeof r=="string"&&r&&ae.set(`${t}:${n}`,r);f.debug({channelId:t,count:Object.keys(i).length},"Restored context tokens from disk")}catch{}}function Ct(t,e,s){let i=Ke(t);try{let n={};try{let o=T.readFileSync(i,"utf-8");n=JSON.parse(o)}catch{}n[e]=s;let r=I.dirname(i);T.mkdirSync(r,{recursive:!0}),T.writeFileSync(i,JSON.stringify(n),"utf-8")}catch(n){f.warn({channelId:t,userId:e},`Failed to persist context token: ${String(n)}`)}}function Et(t,e,s){ae.set(`${t}:${e}`,s),Ct(t,e,s)}function re(t,e){return ae.get(`${t}:${e}`)}function He(t){return I.join(K(),".adam","wechat",`${t}.sync`)}function At(t){try{return T.readFileSync(He(t),"utf-8")}catch{return""}}function Pt(t,e){let s=He(t);T.mkdirSync(I.dirname(s),{recursive:!0}),T.writeFileSync(s,e,"utf-8")}var oe=1440*60*1e3,ze=10,vt=20,Ge=1440*60*1e3,Ot=1320*60*1e3,qt=1,Nt=7200*1e3;function Xe(t){return I.join(K(),".adam","wechat",`${t}.session.json`)}function $t(t){let e=new Map,s=Xe(t);try{let i=T.readFileSync(s,"utf-8"),n=JSON.parse(i);for(let[r,o]of Object.entries(n))o&&typeof o.lastUserMessageAt=="number"&&e.set(r,o);f.debug({channelId:t,count:e.size},"Restored sessions from disk")}catch{}return e}function N(t,e){let s=Xe(t);try{let i={};for(let[r,o]of e)i[r]=o;let n=I.dirname(s);T.mkdirSync(n,{recursive:!0}),T.writeFileSync(s,JSON.stringify(i),"utf-8")}catch(i){f.warn({channelId:t},`Failed to persist sessions: ${String(i)}`)}}var Ft=0;function $(){return`adam-wechat-${Date.now()}-${++Ft}`}var G=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";sessions=new Map;pendingQueue=new Map;lastReminderAt=new Map;constructor(e,s){if(this.id=e,!s.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=s}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=At(this.id),St(this.id),this.sessions=$t(this.id),this.pollAbort=new AbortController,this.status="connected",f.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",f.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){if(this.status==="connected"&&j(this.id))return"error";if(this.status==="connected"){for(let[,e]of this.sessions)if(this.isSessionActive(e)&&e.quotaRemaining<=0)return"degraded"}return this.status}async sendMessage(e,s){if(j(this.id)){let c=Math.ceil(Me(this.id)/6e4);throw new Error(`WeChat session paused, ${c} min remaining. Re-scan QR to reconnect.`)}let i=this.getOrCreateSession(e),r=this.getSessionRemainingMs(i)/36e5;if(!this.isSessionActive(i))return f.warn({channelId:this.id,chatId:e.slice(0,12),lastUserMessageAt:i.lastUserMessageAt,sessionExpired:!0},"iLink session expired (>24h), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;if(i.quotaRemaining<=0)return f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0,remainingHours:r.toFixed(1)},"iLink quota exhausted, message queued"),this.enqueueMessage(e,s),`queued-${$()}`;let o=$(),a=re(this.id,e),d=this.config.cdnBaseUrl??Ve;try{if(s.mediaUrl){let c=!s.mediaUrl.includes("://")||s.mediaUrl.startsWith("file://"),u=I.join(K(),".adam","wechat","media","outbound-tmp");await q.mkdir(u,{recursive:!0});let p=this.getExtensionFromMediaType(s.mediaType),l;if(c){let m=s.mediaUrl.startsWith("file://")?new URL(s.mediaUrl).pathname:I.isAbsolute(s.mediaUrl)?s.mediaUrl:I.resolve(s.mediaUrl),b=await q.readFile(m);l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await q.writeFile(l,b)}else{let m=await fetch(s.mediaUrl);if(!m.ok)throw new Error(`Failed to fetch media: ${m.status}`);let b=Buffer.from(await m.arrayBuffer());l=I.join(u,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${p}`),await q.writeFile(l,b)}let h=await Qe({filePath:l,to:e,text:s.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:a},cdnBaseUrl:d});return await q.unlink(l).catch(()=>{}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(m=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(m)}`)}),h.messageId}return await C({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:o,message_type:E.BOT,message_state:A.FINISH,item_list:s.content?[{type:y.TEXT,text_item:{text:s.content}}]:void 0,context_token:a}}}),i.quotaRemaining--,N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining,sessionRemainingHours:(this.getSessionRemainingMs(i)/36e5).toFixed(1)},"iLink send success: quota decremented"),this.checkAndSendReminder(e,i).catch(c=>{f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(c)}`)}),o}catch(c){if(c instanceof Error&&c.message.includes("ret=-2"))return i.quotaRemaining=0,N(this.id,this.sessions),f.warn({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:0},"iLink quota exhausted (ret=-2 confirmed), message queued"),this.enqueueMessage(e,s),`queued-${$()}`;throw c}}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(j(this.id))return;let s=re(this.id,e);try{await he({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:e,status:Te.TYPING}})}catch{}}updateConfig(e){Object.assign(this.config,e)}getOrCreateSession(e){let s=this.sessions.get(e);return s||(s={lastUserMessageAt:0,quotaRemaining:0},this.sessions.set(e,s)),s}isSessionActive(e){return e.lastUserMessageAt>0&&Date.now()-e.lastUserMessageAt<=oe}getSessionRemainingMs(e){return e.lastUserMessageAt===0?0:Math.max(0,oe-(Date.now()-e.lastUserMessageAt))}enqueueMessage(e,s){let i=this.pendingQueue.get(e);i||(i=[],this.pendingQueue.set(e,i));let n=Date.now();i=i.filter(r=>n-r.queuedAt<Ge),i.length>=vt&&(i.shift(),f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue full, dropping oldest message")),i.push({message:s,queuedAt:n}),this.pendingQueue.set(e,i),f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:i.length},"Message enqueued")}async flushQueue(e){let s=this.pendingQueue.get(e);if(!s||s.length===0)return;let i=this.getOrCreateSession(e),n=Math.min(s.length,Math.max(0,i.quotaRemaining-2));if(n<=0){f.info({channelId:this.id,chatId:e.slice(0,12),quotaRemaining:i.quotaRemaining},"Queue flush skipped: insufficient quota (reserving 2 for conversation)");return}f.info({channelId:this.id,chatId:e.slice(0,12),queueDepth:s.length,sending:n,quotaRemaining:i.quotaRemaining},"Flushing queued messages");let r=0;for(;r<n&&s.length>0;){let o=s[0];if(Date.now()-o.queuedAt>Ge){s.shift();continue}try{if(await this.sendMessage(e,o.message),s.shift(),r++,i.quotaRemaining<=0)break}catch{f.warn({channelId:this.id,chatId:e.slice(0,12)},"Queue flush: send failed, stopping");break}}s.length===0&&this.pendingQueue.delete(e),f.info({channelId:this.id,chatId:e.slice(0,12),sent:r,remaining:s.length},"Queue flush complete")}async checkAndSendReminder(e,s){let i=Date.now(),n=this.lastReminderAt.get(e)??0;if(i-n<Nt)return;let r=this.getSessionRemainingMs(s),a=i-s.lastUserMessageAt>=Ot,d=s.quotaRemaining<=qt;if(!a&&!d)return;let c=(r/36e5).toFixed(1),u;a&&d?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6/${s.quotaRemaining}\u6761\u914D\u989D\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:a?u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u7A97\u53E3\u5373\u5C06\u5173\u95ED\uFF08\u5269\u4F59${c}\u5C0F\u65F6\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u4FDD\u6301\u8FDE\u63A5\u3002`:u=`[\u7CFB\u7EDF\u63D0\u9192] \u6D88\u606F\u914D\u989D\u5373\u5C06\u7528\u5B8C\uFF08\u5269\u4F59${s.quotaRemaining}\u6761\uFF09\u3002\u8BF7\u56DE\u590D\u4EFB\u610F\u6D88\u606F\u4EE5\u91CD\u7F6E\u914D\u989D\u3002`;let p=re(this.id,e);try{await C({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:e,client_id:$(),message_type:E.BOT,message_state:A.FINISH,item_list:[{type:y.TEXT,text_item:{text:u}}],context_token:p}}}),s.quotaRemaining--,this.lastReminderAt.set(e,i),N(this.id,this.sessions),f.info({channelId:this.id,chatId:e.slice(0,12),remainingHours:c,quotaRemaining:s.quotaRemaining,trigger:a?"time":"quota"},"iLink session reminder sent")}catch(l){f.warn({channelId:this.id,chatId:e.slice(0,12)},`Reminder send failed: ${String(l)}`)}}async startLongPoll(){let e=this.pollAbort?.signal,s=0,i=3,n=3e4,r=2e3;for(;!e?.aborted;)try{let o=await fe({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===Z||o.errcode===Z){Re(this.id),this.status="error",f.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep(B,e),Ue(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){s++,f.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e);continue}s=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,Pt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(e?.aborted)return;s++,f.error({channelId:this.id,error:o},"getUpdates error"),s>=i?(s=0,await this.sleep(n,e)):await this.sleep(r,e)}}async processInbound(e){if(!this.messageHandler)return;let s=!!e.group_id,i=s?e.group_id:e.from_user_id??"",n=e.from_user_id??"";e.context_token&&i&&Et(this.id,i,e.context_token);let r=this.getOrCreateSession(i),o=r.quotaRemaining;r.lastUserMessageAt=Date.now(),r.quotaRemaining=ze,N(this.id,this.sessions),f.info({channelId:this.id,chatId:i.slice(0,12),quotaReset:!0,prevQuota:o,newQuota:ze,sessionWindowMs:oe},"iLink session reset: user message received, quota restored"),this.flushQueue(i);let a="",d,c=[];for(let l of e.item_list??[])l.type===y.TEXT&&l.text_item?.text&&(a+=l.text_item.text),l.type===y.IMAGE&&(d="image",c.push(l)),l.type===y.VOICE&&(d="audio",c.push(l),l.voice_item?.text&&!a&&(a=l.voice_item.text)),l.type===y.FILE&&(d="file",c.push(l)),l.type===y.VIDEO&&(d="video",c.push(l));if(!a&&!d)return;let u;if(c.length>0){let l=this.config.cdnBaseUrl??Ve;try{let h=await Le(c[0],{cdnBaseUrl:l,channelId:this.id});h&&(u=h.path,d=h.type)}catch(h){f.error({channelId:this.id},`Media download failed: ${String(h)}`)}}let p={channelId:this.id,platform:"wechat",chatId:i,senderId:n,content:a,mediaType:d,mediaPath:u,isGroup:s,timestamp:e.create_time_ms??Date.now(),raw:e};this.messageHandler(p)}getExtensionFromMediaType(e){switch(e){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(e,s){return new Promise((i,n)=>{let r=setTimeout(i,e);s?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};R();var Lt=_("channels"),H=class{platform="discord";id;config;status="disconnected";messageHandler=null;client=null;constructor(e,s){if(this.id=e,!s.botToken)throw new Error("Discord adapter requires botToken");this.config=s}async connect(){this.status="connecting";try{let{Client:e,GatewayIntentBits:s}=await import("discord.js");this.client=new e({intents:[s.Guilds,s.GuildMessages,s.MessageContent,s.DirectMessages]});let i=this.client;i.on("messageCreate",n=>{if(!this.messageHandler||n.author.bot||this.config.allowedGuildIds?.length&&n.guildId&&!this.config.allowedGuildIds.includes(n.guildId))return;let r={channelId:this.id,platform:"discord",chatId:n.channelId,senderId:n.author.id,senderName:n.author.displayName??n.author.username,content:n.content,isGroup:!!n.guildId,timestamp:n.createdTimestamp,raw:n};this.messageHandler(r)}),await i.login(this.config.botToken),this.status="connected",Lt.info({channelId:this.id},"Discord bot connected")}catch(e){throw this.status="error",e}}async disconnect(){this.client&&await this.client.destroy(),this.client=null,this.status="disconnected"}getStatus(){return this.status}async sendMessage(e,s){if(!this.client)throw new Error("Discord client not connected");let n=await this.client.channels.fetch(e);if(!n||!("send"in n))throw new Error(`Channel ${e} not found or not text channel`);return(await n.send({content:s.content,reply:s.replyToMessageId?{messageReference:s.replyToMessageId}:void 0})).id}onMessage(e){this.messageHandler=e}async sendTypingIndicator(e){if(!this.client)return;let i=await this.client.channels.fetch(e);i&&"sendTyping"in i&&await i.sendTyping()}};var U=g.object({id:g.string().uuid()}),Wt=g.object({name:g.string().min(1,"name is required"),platform:g.string().min(1,"platform is required"),config:g.record(g.string(),g.unknown()),enabled:g.boolean().optional().default(!0),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),Bt=g.object({name:g.string().min(1).optional(),enabled:g.boolean().optional(),config:g.record(g.string(),g.unknown()).optional(),linkedRoleId:g.string().optional(),allowedChatIds:g.array(g.string()).optional()}),de;function es(t){de=t}function ts(){return de}async function ns(t){let e=de;t.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(s,i)=>({channels:le(s.query.enabled)})),t.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(s,i)=>{let n=Wt.safeParse(s.body);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:c,allowedChatIds:u}=n.data,p={id:Dt(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:c,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return ue(p),i.status(201).send({channel:p})}),t.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?{channel:r}:i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Bt.safeParse(s.body);return o.success?(X(r.id,o.data),{channel:x(r.id)}):i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(o.error)})}),t.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);return r?(ge(r.id),i.status(204).send()):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!e.hasAdapter(r.id)&&r.platform==="discord"){let o=r.config;if(!o.botToken)return i.status(400).send({code:"MISSING_CONFIG",message:"Discord channel requires botToken in config"});let a=new H(r.id,{botToken:o.botToken});await e.addChannel(r,a)}if(!e.hasAdapter(r.id))return i.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await e.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return i.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),t.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});if(!e)return i.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=x(n.data.id);return r?(await e.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):i.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),t.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=s.query;return{messages:ce(r.id,o,a)}}),t.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await xe({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),t.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(s,i)=>{let n=U.safeParse(s.params);if(!n.success)return i.status(400).send({code:"VALIDATION_ERROR",message:g.prettifyError(n.error)});let r=x(n.data.id);if(!r)return i.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return i.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=s.body??{},c=await Ie({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(c.connected&&c.botToken){let u={...o,botToken:c.botToken,accountId:c.accountId,baseUrl:c.baseUrl??o.baseUrl,userId:c.userId};if(X(r.id,{config:u}),e){let p=new G(r.id,u),l=x(r.id);l&&await e.addChannel(l,p)}}return{connected:c.connected,accountId:c.accountId,message:c.message}})}export{G as a,H as b,es as c,ts as d,ns as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i}from"./chunk-6KLG4APZ.js";import{c as p}from"./chunk-7IFLU3CY.js";import{d as c}from"./chunk-6HD6NYIB.js";import{f as d,h as R}from"./chunk-WBAPIPST.js";import{c as g,h as y}from"./chunk-INNDBLZE.js";R();import{readFileSync as P,existsSync as _}from"fs";import{resolve as O}from"path";import{homedir as E}from"os";import{parse as w}from"yaml";y();var T=g("config");function S(e){return e.replace(/\$\{(\w+)}/g,(t,r)=>process.env[r]??"")}function h(e){return e.startsWith("~/")?O(E(),e.slice(2)):e}function u(e){if(typeof e=="string")return S(e);if(Array.isArray(e))return e.map(u);if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=u(n);return t}return e}function m(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]=m(o,s):r[n]=s}return r}function v(e){return e.defaults.deniedReadPaths&&(e.defaults.deniedReadPaths=e.defaults.deniedReadPaths.map(h)),e.defaults.sensitivePaths&&!e.defaults.deniedReadPaths&&(T.warn("config.defaults.sensitivePaths is deprecated \u2014 use config.defaults.deniedReadPaths instead. Values have been migrated automatically."),e.defaults.deniedReadPaths=e.defaults.sensitivePaths.map(h)),e}function k(){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 A(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 C(e){let t=k();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 D(e){let t=e??d,r={};if(_(t)){let f=P(t,"utf-8"),l=w(f);l&&(r=u(l))}let n=m(i,r),s=A(n),o=C(s);return v(o)}function I(){let e=JSON.parse(JSON.stringify(i)),t=A(e),r=C(t);return v(r)}function V(){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"},r={};for(let[s,o]of Object.entries(t)){let a=process.env[s];if(a&&a.length>0)if(o==="server.port"){let f=parseInt(a,10);isNaN(f)||(e[o]=f)}else e[o]=a}let n=p();if(n)for(let[s,o]of Object.entries(n))s in t||s.startsWith("ANTHROPIC_")||s.startsWith("ADAM_")||(r[s]=o);return Object.keys(r).length>0&&(e["defaults.env"]=r),e}function j(){try{return c().defaults}catch{return i.defaults}}function W(){try{return c().chat??i.chat}catch{return i.chat}}export{D as a,I as b,V as c,j as d,W as e};
|