adam-agent-server 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/App-ZRCRM7WR.js +13 -0
- package/dist/{adam-automator-skills-UFW5TXCC.js → adam-automator-skills-EZGBICHT.js} +1 -1
- package/dist/adam-tools-V5LPU47X.js +1 -0
- package/dist/{approval-handler-HQO62WK2.js → approval-handler-PB7PSLUS.js} +1 -1
- package/dist/audit-manager-BSBBDUER.js +1 -0
- package/dist/bree-engine-7S33CWS7.js +1 -0
- package/dist/channels-SITUUC4J.js +1 -0
- package/dist/{channels-J4STJ4X2.js → channels-ULFUCUUZ.js} +1 -1
- package/dist/{chunk-7446ZS6D.js → chunk-2L2347UQ.js} +1 -1
- package/dist/{chunk-FXQAUQTI.js → chunk-2YTDCR6A.js} +1 -1
- package/dist/chunk-4PQHGLZH.js +99 -0
- package/dist/{chunk-NCFVJCNQ.js → chunk-5EPG2US5.js} +2 -2
- package/dist/{chunk-2H7UOW4P.js → chunk-5QZXYKMS.js} +1 -1
- package/dist/chunk-5XOTPEAK.js +6 -0
- package/dist/{chunk-MDBVKBC7.js → chunk-6KF7OO2B.js} +1 -1
- package/dist/{chunk-TSPQ44HT.js → chunk-A5OCDYTW.js} +1 -1
- package/dist/{chunk-DWRYIN5N.js → chunk-AQ3ASS4B.js} +1 -1
- package/dist/{chunk-GMMWA5EG.js → chunk-B6LOT5CG.js} +1 -1
- package/dist/{chunk-MJSSCKMB.js → chunk-BCH2HAIM.js} +2 -2
- package/dist/{chunk-4C5ITATX.js → chunk-BQ3ZAYHC.js} +1 -1
- package/dist/{chunk-YHVYX3F4.js → chunk-DVN3BFPP.js} +1 -1
- package/dist/{chunk-P5ZXNBNV.js → chunk-EQZFOBAJ.js} +1 -1
- package/dist/{chunk-G5ESQEXN.js → chunk-FPZEZYUB.js} +1 -1
- package/dist/{chunk-YXYIA24D.js → chunk-GSFLLRS7.js} +1 -1
- package/dist/{chunk-7ZGSJCX5.js → chunk-HQRUJQN7.js} +1 -1
- package/dist/{chunk-52PR7XTN.js → chunk-IKPYPZ64.js} +1 -1
- package/dist/{chunk-FZCNYKNT.js → chunk-JJH2RCVC.js} +1 -1
- package/dist/chunk-K4C43YDD.js +7 -0
- package/dist/{chunk-V32YF3J5.js → chunk-M4YI4WVX.js} +1 -1
- package/dist/{chunk-WAG3MNMC.js → chunk-NASJH4NT.js} +1 -1
- package/dist/{chunk-TNL2LZB7.js → chunk-NUITL62I.js} +1 -1
- package/dist/{chunk-3LY6PD6A.js → chunk-NWMOV23A.js} +1 -1
- package/dist/chunk-PHT24MOV.js +1 -0
- package/dist/{chunk-ZL5JXLAX.js → chunk-QGYDGZSC.js} +1 -1
- package/dist/{chunk-VVSZZK5T.js → chunk-RI3V72RP.js} +2 -2
- package/dist/{chunk-RLJYEEQC.js → chunk-RZ7LCZVK.js} +1 -1
- package/dist/{chunk-5OQZPUBV.js → chunk-TAF2DBBC.js} +8 -8
- package/dist/{chunk-HWLSHTVX.js → chunk-ULTK7RD6.js} +3 -3
- package/dist/{chunk-DBP7GPWG.js → chunk-WMB7P64J.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{config-KFPS7IEH.js → config-HBQPBIWL.js} +1 -1
- package/dist/{db-PZ2V7UCK.js → db-QEWTZGU3.js} +1 -1
- package/dist/{delivery-log-ACNJ66RD.js → delivery-log-AC476GX7.js} +1 -1
- package/dist/engine-6K4RG644.js +1 -0
- package/dist/{evolution-audit-OQDGPKYI.js → evolution-audit-XMBDUN3T.js} +1 -1
- package/dist/index.js +13 -10
- package/dist/{learner-QCD6BH2J.js → learner-VCS3Q7BR.js} +1 -1
- package/dist/{memories-QGMRSBJJ.js → memories-VMOGFVPU.js} +1 -1
- package/dist/{memory-extractor-3MRK43A2.js → memory-extractor-4WJNHYWR.js} +2 -2
- package/dist/memory-service-ZS6MBUIC.js +1 -0
- package/dist/outbound-gateway-H7RFG6D2.js +1 -0
- package/dist/role-presets-XAEOYEAW.js +1 -0
- package/dist/role-workspace-NKGAH6J6.js +1 -0
- package/dist/{roles-KYXNMO5H.js → roles-ZYCFQMAY.js} +1 -1
- package/dist/{session-manager-LZ77OT7A.js → session-manager-COLCNIB7.js} +1 -1
- package/dist/task-templates-4KCZOUN5.js +1 -0
- package/dist/workflow-executor-Z7JFMR56.js +1 -0
- package/package.json +25 -25
- package/web/dist/assets/{ChannelDetail-DHT8fW0C.js → ChannelDetail-DnL0_h8q.js} +1 -1
- package/web/dist/assets/{Channels-YHGNXcRu.js → Channels-dod8Q4oq.js} +1 -1
- package/web/dist/assets/{Dashboard-DsHC5W4C.js → Dashboard-Dl0vA6Ky.js} +1 -1
- package/web/dist/assets/{EnvVarEditor-Dxy1Kz1Z.js → EnvVarEditor-C-gErAzC.js} +1 -1
- package/web/dist/assets/{EventDefDetail-CwprP2ch.js → EventDefDetail-BhJZGNlX.js} +1 -1
- package/web/dist/assets/{Events-B19a8cEG.js → Events-DnNZ9-BN.js} +1 -1
- package/web/dist/assets/{Evolution-DT6iZvil.js → Evolution-BBWmrrnr.js} +1 -1
- package/web/dist/assets/{GoalDetail-BALsnPQl.js → GoalDetail-uqWQCOj3.js} +1 -1
- package/web/dist/assets/{Goals-BJIsKgfH.js → Goals-CylKmR9j.js} +1 -1
- package/web/dist/assets/{Logs-Cv15aV3l.js → Logs-6rf0KT0z.js} +1 -1
- package/web/dist/assets/{Memories-CKAXhAso.js → Memories-CrBTujU7.js} +1 -1
- package/web/dist/assets/{Plugins-NO0S2spH.js → Plugins-VKUSUcSE.js} +1 -1
- package/web/dist/assets/{RoleDetail-1FNyCD4u.js → RoleDetail-DJc4CWFN.js} +1 -1
- package/web/dist/assets/{Roles-grfjw2zy.js → Roles-6pmjn04G.js} +1 -1
- package/web/dist/assets/{Settings-9LRLfa_4.js → Settings-DW1jmrNj.js} +1 -1
- package/web/dist/assets/{Strategies-BMyd_7_5.js → Strategies-Bmke6qZo.js} +1 -1
- package/web/dist/assets/{Switch-CULsD-kC.js → Switch-CfTpXW9_.js} +1 -1
- package/web/dist/assets/{TaskDetail-C2yXy8gE.js → TaskDetail-CwJ_UKgt.js} +1 -1
- package/web/dist/assets/Work-DVdWNBEm.js +1 -0
- package/web/dist/assets/{index-qYKJGoIB.js → index-DYsO5Awn.js} +2 -2
- package/web/dist/index.html +1 -1
- package/dist/App-WJMHK5EO.js +0 -13
- package/dist/adam-tools-IAZSLWYB.js +0 -1
- package/dist/audit-manager-LC5EQXCI.js +0 -1
- package/dist/bree-engine-M5CZ6A62.js +0 -1
- package/dist/channels-5TFYQN5Z.js +0 -1
- package/dist/chunk-FIN36WAP.js +0 -99
- package/dist/chunk-GGIHDFRW.js +0 -6
- package/dist/chunk-I7ZZKPHE.js +0 -7
- package/dist/chunk-YDVTWPNA.js +0 -1
- package/dist/engine-5DHYHDAP.js +0 -1
- package/dist/memory-service-M5ADGITG.js +0 -1
- package/dist/outbound-gateway-QRL36F7K.js +0 -1
- package/dist/role-presets-DLO3XS54.js +0 -1
- package/dist/role-workspace-URSOBCDH.js +0 -1
- package/dist/task-templates-YPNWJOVV.js +0 -1
- package/dist/workflow-executor-3WMS2WV3.js +0 -1
- package/web/dist/assets/Work-dftf35Me.js +0 -1
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{b as C,d as Qt,e as Go}from"./chunk-PHT24MOV.js";import{a as Xt,f as Uo,h as Wo}from"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";import{Box as jt,Text as $t,useInput as js}from"ink";import{useState as Ks,useEffect as mo,useRef as $o}from"react";import{createContext as rn,useContext as nn,useReducer as sn}from"react";import{jsx as cn}from"react/jsx-runtime";var an={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 ln(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 Ho=rn(null);function jo({children:e}){let[t,o]=sn(ln,an);return cn(Ho.Provider,{value:{state:t,dispatch:o},children:e})}function Qe(){let e=nn(Ho);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Ko,useRef as zo}from"react";var dn=15e3;function Xo(){let{state:e,dispatch:t}=Qe(),o=zo(null),m=zo(null);Ko(()=>{m.current=e.session?.id??null},[e.session?.id]),Ko(()=>{let g=!0,f=null,a=()=>{o.current&&(clearTimeout(o.current),o.current=null)},i=()=>{a(),o.current=setTimeout(()=>{g&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},dn)};return(()=>{try{f=new Qt("/events"),f.on("task_status_change",()=>{}),f.on("approval_request",r=>{if(!g)return;let d=r;t({type:"SET_PENDING_APPROVAL",approval:{taskId:d.taskId,approvalId:d.approvalId,toolName:d.toolName,toolInput:d.toolInput,matchedPattern:d.matchedPattern}})}),f.on("plan_approval_request",r=>{if(!g)return;let d=r;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:d.taskId,planId:d.planId,roleId:d.roleId,plan:d.plan}})}),f.on("plan_approval_decision",()=>{g&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),f.on("config_changed",()=>{g&&t({type:"CONFIG_CHANGED"})}),f.on("execution_task_start",r=>{if(!g)return;let d=r,p=m.current;p&&(async()=>{try{let w=await C(`/tasks/${d.taskId}`);g&&w.sourceSessionId===p&&t({type:"SET_ACTIVE_TASK",taskId:d.taskId})}catch{}})()}),f.on("stats_update",r=>{if(!g)return;let d=r;t({type:"UPDATE_STATS",activeTasks:d.activeTasks,queuedTasks:d.queuedTasks,costToday:d.totalCostToday})}),f.connect().then(async()=>{if(g){a(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let r=await C("/version");t({type:"SET_VERSION",version:r.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{g&&(t({type:"SET_CONNECTED",connected:!1}),i())})}catch{g&&(t({type:"SET_CONNECTED",connected:!1}),i())}})(),()=>{g=!1,a(),f?.close()}},[t])}import{useEffect as un,useRef as mn,useState as Qo,useCallback as gn}from"react";function Yo(e){let[t,o]=Qo([]),[m,g]=Qo(!1),f=mn(null),a=gn(()=>{o([]),g(!1)},[]);return un(()=>{if(!e)return;let i=!0;o([]),g(!0);try{let s=new Go(e);return f.current=s,s.on("reasoning",r=>{if(!i)return;let p=r.content??"";o(w=>{let y=w[w.length-1];if(y?.type==="reasoning"){let S=[...w];return S[S.length-1]={...y,content:y.content+p},S}return[...w,{type:"reasoning",content:p,timestamp:Date.now()}]})}),s.on("tool_call",r=>{if(!i)return;let d=r;o(p=>[...p,{type:"tool_call",content:d.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:d.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let d=r;o(p=>[...p,{type:"tool_result",content:d.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let d=r;o(p=>[...p,{type:"error",content:d.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let d=r;o(p=>[...p,{type:"complete",content:d.result??"",timestamp:Date.now(),metadata:{cost:d.costUsd,turns:d.numTurns,duration:d.totalDurationMs}}]),g(!1)}),s.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),g(!1))}),()=>{i=!1,s.close()}}catch{g(!1)}},[e]),{events:t,isStreaming:m,clearEvents:a}}import{useState as xo,useEffect as fn,useCallback as Lt}from"react";function To(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function Zo(){let[e,t]=xo(null),[o,m]=xo(!0),[g,f]=xo(null),a=Lt(async()=>{try{let w=(await C("/chat/sessions?status=active")).sessions.find(y=>y.source.type==="tui");return w?To(w):null}catch{return null}},[]),i=Lt(async()=>{try{let p=await C("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),w=To(p.session);return t(w),w}catch{return f("Failed to create session"),null}},[]),s=Lt(async p=>{try{let w=await C("/chat/messages",{method:"POST",body:{content:p,source:{type:"tui"}}});return t(y=>y&&{...y,messageCount:y.messageCount+1,lastActiveAt:Date.now()}),w}catch{return null}},[]),r=Lt(async()=>{if(!e)return!1;try{return await C(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),d=Lt(async()=>{if(e)try{let p=await C(`/chat/sessions/${e.id}`);t(To(p.session))}catch{t(null)}},[e]);return fn(()=>{let p=!1;async function w(){m(!0);let y=await a();p||(y?t(y):await i(),p||m(!1))}return w(),()=>{p=!0}},[]),{session:e,loading:o,error:g,sendMessage:s,createNewSession:i,archiveCurrentSession:r,refreshSession:d,setSession:t}}import{useEffect as Jo,useRef as pn,useState as xn}from"react";function er(e){let[t,o]=xn(null),m=pn(new Set);return Jo(()=>{if(!e)return;let g=!0,f=null;try{f=new Qt("/chat/stream"),f.on("chat_message",a=>{if(!g)return;let s=a.message;s&&s.sessionId===e&&s.role==="assistant"&&(m.current.has(s.id)||(m.current.add(s.id),o(s)))}),f.connect().catch(()=>{})}catch{}return()=>{g=!1,f?.close()}},[e]),Jo(()=>{m.current.clear(),o(null)},[e]),{latestMessage:t}}import{Box as ho,Text as De}from"ink";import{Fragment as Yt,jsx as pe,jsxs as wt}from"react/jsx-runtime";var Tn=90;function tr({children:e}){return pe(ho,{children:e})}function or(){let{state:e}=Qe(),t=e.session,m=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,g=e.connected?"up":"down",f=e.view==="chat"?"Chat":e.view.charAt(0).toUpperCase()+e.view.slice(1),a=t?t.messageCount===0?"new session":`${t.id.slice(0,8)} \xB7 ${t.messageCount}t`:null,s=(process.stdout.columns??100)<Tn,r=wt(Yt,{children:[pe(De,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),pe(De,{dimColor:!0,children:" | "}),pe(De,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),pe(De,{children:` ${g}`}),pe(De,{dimColor:!0,children:" | "}),pe(De,{children:f.toLowerCase()})]}),d=wt(Yt,{children:[pe(De,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),pe(De,{dimColor:!0,children:" | "}),pe(De,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&wt(Yt,{children:[pe(De,{dimColor:!0,children:" | "}),pe(De,{children:a}),m&&wt(Yt,{children:[pe(De,{dimColor:!0,children:" | "}),pe(De,{color:"yellow",children:"timeout"})]})]})]});return s?wt(ho,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[pe(tr,{children:r}),pe(tr,{children:d})]}):wt(ho,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[r,pe(De,{dimColor:!0,children:" | "}),d]})}import{Box as Zt,Text as Jt,useInput as yn}from"ink";import{useState as bo,useMemo as bn}from"react";import vn from"ink-text-input";var hn=[{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 yo(e){let t=e.toLowerCase();return hn.filter(o=>o.name.startsWith(t))}function rr(e){let t=yo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as eo,jsxs as Ot}from"react/jsx-runtime";function nr({onSubmit:e}){let[t,o]=bo(""),[m,g]=bo(0),[f,a]=bo(!1),i=t.startsWith("/")&&t.length>=1,s=t.slice(1),r=bn(()=>i?yo(s):[],[i,s]),d=y=>{o(y),y.startsWith("/")?(a(!0),g(0)):a(!1)},p=()=>{let y=t.trim();if(y){if(y.startsWith("/")){let S=y.slice(1),n=rr(S);e(n?`/${n.name}`:y)}else e(y);o(""),a(!1)}},w=y=>{e(`/${y.name}`),o(""),a(!1)};return yn((y,S)=>{if(!(!f||!i||r.length===0)){if(S.upArrow){g(n=>n<=0?r.length-1:n-1);return}if(S.downArrow){g(n=>n>=r.length-1?0:n+1);return}if(S.tab){let n=r[m];n&&w(n);return}if(S.escape){a(!1),o("");return}}},{isActive:f&&i&&r.length>0}),Ot(Zt,{flexDirection:"column",children:[f&&i&&r.length>0&&eo(Zt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((y,S)=>{let n=S===m;return Ot(Zt,{children:[eo(Jt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),Ot(Jt,{color:n?"cyan":"white",bold:n,children:["/",y.name]}),Ot(Jt,{dimColor:!0,children:[" \u2014 ",y.description]})]},y.name)})}),Ot(Zt,{borderStyle:"round",borderDimColor:!0,children:[eo(Jt,{bold:!0,children:"\u25B8 "}),eo(vn,{value:t,onChange:d,onSubmit:p,placeholder:"Type a message or / for commands..."})]})]})}import{Box as Bt,Text as Ee,useInput as Cn}from"ink";import{useState as Sn}from"react";import{jsx as Le,jsxs as Ye}from"react/jsx-runtime";function wn({content:e,expanded:t}){let o=e.split(`
|
|
2
|
+
`);return o.length<=5?Le(Ee,{color:"green",children:e}):t?Le(Ee,{color:"green",children:e}):Ye(Ee,{color:"green",children:[o.slice(0,3).join(`
|
|
3
|
+
`),`
|
|
4
|
+
`,Ye(Ee,{dimColor:!0,children:["(",o.length," lines) [Ctrl+O] expand"]})]})}function Bn({event:e,expanded:t}){switch(e.type){case"reasoning":return Le(Bt,{children:Le(Ee,{color:"gray",children:e.content})});case"tool_call":return Le(Bt,{children:Ye(Ee,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Ye(Bt,{flexDirection:"column",children:[Le(Ee,{color:"blue",dimColor:!0,children:"[result]"}),Le(wn,{content:e.content,expanded:t})]});case"error":return Le(Bt,{children:Ye(Ee,{color:"red",children:["[error] ",e.content]})});case"complete":return Ye(Bt,{flexDirection:"column",marginTop:1,children:[e.content&&Le(Ee,{children:e.content}),Le(Ee,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Ye(Ee,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Ye(Ee,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Ye(Ee,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function sr({events:e,isStreaming:t}){let[o,m]=Sn(!1),g=e.some(f=>f.type==="tool_result"&&f.content.split(`
|
|
5
|
+
`).length>5);return Cn((f,a)=>{a.ctrl&&f==="o"&&m(i=>!i)},{isActive:g}),e.length===0&&!t?null:Ye(Bt,{flexDirection:"column",children:[t&&e.length===0&&Le(Ee,{dimColor:!0,children:"Waiting for response..."}),e.map((f,a)=>Le(Bn,{event:f,expanded:o},a)),g&&Le(Ee,{dimColor:!0,children:o?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as ir,Text as ar}from"ink";import{jsx as vo,jsxs as En}from"react/jsx-runtime";function lr({messages:e}){return e.length===0?null:vo(ir,{flexDirection:"column",children:e.map((t,o)=>En(ir,{flexDirection:"column",marginBottom:1,children:[vo(ar,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),vo(ar,{children:t.content})]},o))})}import{Box as Vt,Text as Ze,useInput as kn}from"ink";import{jsx as Je,jsxs as Ft}from"react/jsx-runtime";function cr({approval:e,onResolved:t}){return kn(o=>{o==="a"?C(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&C(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),Ft(Vt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Je(Ze,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),Ft(Vt,{marginTop:1,children:[Je(Ze,{children:"Tool: "}),Je(Ze,{bold:!0,children:e.toolName})]}),Ft(Vt,{children:[Je(Ze,{children:"Input: "}),Je(Ze,{children:JSON.stringify(e.toolInput)})]}),Ft(Vt,{children:[Je(Ze,{children:"Pattern: "}),Je(Ze,{dimColor:!0,children:e.matchedPattern})]}),Ft(Vt,{marginTop:1,children:[Je(Ze,{color:"green",children:"[a] Approve"}),Je(Ze,{children:" "}),Je(Ze,{color:"red",children:"[r] Reject"})]})]})}import{Box as qt,Text as ke,useInput as In}from"ink";import{useState as An,useEffect as Pn}from"react";import{jsx as nt,jsxs as He}from"react/jsx-runtime";var Dn=300;function dr({approval:e,onResolved:t,onTimeout:o}){let[m,g]=An(Dn);Pn(()=>{let a=setInterval(()=>{g(i=>i<=1?(clearInterval(a),o(),0):i-1)},1e3);return()=>clearInterval(a)},[o]),In(a=>{a==="a"?C(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):a==="r"?C(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):a==="p"&&C(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let f=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return He(qt,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[nt(ke,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),He(ke,{dimColor:!0,children:["Plan ID: ",e.planId]}),He(ke,{dimColor:!0,children:["Time remaining: ",m,"s"]}),He(qt,{marginTop:1,children:[nt(ke,{children:"Overall Risk: "}),nt(ke,{bold:!0,color:f,children:e.plan.overallRisk.toUpperCase()})]}),He(ke,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(a=>{let i=a.riskLevel==="high"?"red":a.riskLevel==="medium"?"yellow":"green";return He(qt,{paddingLeft:2,children:[He(ke,{children:["[",a.index,"] "]}),nt(ke,{children:a.description}),He(ke,{dimColor:!0,children:[" (",a.toolsNeeded.join(", "),")"]}),He(ke,{color:i,children:[" [",a.riskLevel,"]"]})]},a.index)}),He(qt,{marginTop:1,children:[nt(ke,{dimColor:!0,children:"Permissions: "}),nt(ke,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),He(qt,{marginTop:1,children:[nt(ke,{color:"green",children:"[a] Allow once "}),nt(ke,{color:"green",children:"[p] Allow permanent "}),nt(ke,{color:"red",children:"[r] Deny"})]})]})}import{Box as xe,Text as j,useInput as Fn}from"ink";import{useEffect as qn,useState as ut,useCallback as xr}from"react";import{Box as ge,Text as F,useInput as Rn}from"ink";import{useEffect as Mn,useState as Et}from"react";import{jsx as ie,jsxs as G}from"react/jsx-runtime";var ur={plan:!0,result:!1,routing:!0,error:!0},$n={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"};function pr({taskId:e,onBack:t}){let[o,m]=Et(null),[g,f]=Et([]),[a,i]=Et([]),[s,r]=Et(null),[d,p]=Et(ur),[w,y]=Et(!1);Mn(()=>{let I=!1;return m(null),f([]),i([]),r(null),p(ur),y(!1),C(`/tasks/${e}`).then(({task:A})=>{I||m(A)}).catch(A=>{I||r(A instanceof Error?A.message:String(A))}),C(`/tasks/${e}/plan`).then(({plans:A})=>{I||f(A)}).catch(()=>{I||f([])}),C(`/tasks/${e}/delivery-log?limit=8`).then(({logs:A})=>{I||i(A)}).catch(()=>{I||i([])}),()=>{I=!0}},[e]);let S=I=>{p(A=>({...A,[I]:!A[I]}))};if(Rn((I,A)=>{if(I==="b"||A.escape){t();return}I==="1"&&S("plan"),I==="2"&&S("result"),I==="3"&&S("routing"),I==="4"&&S("error"),I==="5"&&y(H=>!H)}),s)return G(ge,{flexDirection:"column",children:[G(F,{color:"red",children:["Task detail failed: ",s]}),ie(F,{dimColor:!0,children:"[b] Back"})]});if(!o)return G(F,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let n=g[0],x=On(o.deliverTo,o.reportTo),$=a.length>0?`${a.length} delivery event${a.length===1?"":"s"}`:"No delivery events";return G(ge,{flexDirection:"column",children:[G(ge,{children:[G(F,{bold:!0,color:"cyan",children:["Task ",o.id.slice(0,8)]}),ie(F,{dimColor:!0,children:" \u2022 "}),ie(F,{color:$n[o.status]??"white",bold:!0,children:o.status.toUpperCase()})]}),G(F,{dimColor:!0,children:[o.roleId?`role ${o.roleId}`:"no role"," \u2022 ",fr(o.createdAt)," \u2022 ",Ln(o.totalDurationMs)]}),G(ge,{marginTop:1,flexDirection:"column",children:[ie(F,{bold:!0,children:"Summary"}),ie(F,{children:w?o.prompt:Nn(o.prompt,240)}),o.prompt.length>240&&G(F,{dimColor:!0,children:["[5] ",w?"collapse prompt":"expand prompt"]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{dimColor:!0,children:["Cost: ",_n(o.costUsd)]}),G(F,{dimColor:!0,children:["Turns: ",o.numTurns??"\u2014"]}),G(F,{dimColor:!0,children:["Template: ",o.templateId??"\u2014"]}),G(F,{dimColor:!0,children:["Source Session: ",o.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[1] Plan ",d.plan?"hide":"show"]}),ie(F,{dimColor:!0,children:n?`${n.plan.steps.length} planned step${n.plan.steps.length===1?"":"s"} \u2022 ${n.plan.overallRisk} risk \u2022 ${n.status}`:"No execution plan"}),d.plan&&n&&G(ge,{marginTop:1,flexDirection:"column",children:[n.plan.steps.map(I=>G(ge,{flexDirection:"column",marginBottom:1,children:[G(F,{children:[I.index,". ",I.description]}),G(F,{dimColor:!0,children:[I.riskLevel," risk \u2022 ",I.toolsNeeded.join(", ")||"no tools listed"]}),I.expectedOutput?G(F,{dimColor:!0,children:["Expected: ",I.expectedOutput]}):null]},I.index)),n.learnedRules&&n.learnedRules.length>0&&G(ge,{flexDirection:"column",children:[ie(F,{color:"blue",bold:!0,children:"Learned Rules"}),n.learnedRules.map((I,A)=>G(F,{dimColor:!0,children:["\u2022 ",I]},A))]})]})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[2] Result ",d.result?"hide":"show"]}),ie(F,{dimColor:!0,children:o.result?"Execution produced output.":"No result captured yet."}),d.result&&ie(ge,{marginTop:1,children:ie(F,{children:o.result?gr(o.result,18):"No result yet."})})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[3] Routing ",d.routing?"hide":"show"]}),G(F,{dimColor:!0,children:[x," \u2022 ",$]}),d.routing&&G(ge,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Deliver To"}),mr(o.deliverTo),ie(F,{color:"cyan",children:"Report To"}),mr(o.reportTo),a.length>0&&G(ge,{marginTop:1,flexDirection:"column",children:[ie(F,{color:"cyan",children:"Recent Delivery"}),a.map(I=>G(F,{dimColor:!0,children:[I.status," \u2022 ",Vn(I)," \u2022 ",fr(I.createdAt)]},I.id))]})]})]}),G(ge,{marginTop:1,flexDirection:"column",children:[G(F,{bold:!0,children:["[4] Error ",d.error?"hide":"show"]}),ie(F,{dimColor:!0,children:o.error?"Execution returned an error condition.":"No error recorded."}),d.error&&o.error&&ie(ge,{marginTop:1,children:ie(F,{color:"red",children:gr(o.error,16)})})]}),ie(ge,{marginTop:1,children:ie(F,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function mr(e){return!e||e.length===0?ie(F,{dimColor:!0,children:" none"}):ie(ge,{flexDirection:"column",children:e.map((t,o)=>ie(F,{dimColor:!0,children:t.type==="channel"?` channel ${t.channelId.slice(0,8)}${t.chatId?` / ${t.chatId.slice(0,8)}`:""}`:` session ${t.sessionId.slice(0,8)}`},`${t.type}-${o}`))})}function gr(e,t){let o=e.split(`
|
|
6
|
+
`);return o.length<=t?e:`${o.slice(0,t).join(`
|
|
7
|
+
`)}
|
|
8
|
+
\u2026`}function Nn(e,t){let o=e.replace(/\s+/g," ").trim();return o.length<=t?o:`${o.slice(0,t-1)}\u2026`}function _n(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Ln(e){if(!e)return"waiting";let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let o=Math.floor(t/60),m=t%60;return m===0?`${o}m`:`${o}m ${m}s`}function fr(e){return new Date(e).toLocaleString()}function On(e,t){let o=e?.length??0,m=t?.length??0;return o===0&&m===0?"No delivery targets":`${o} output target${o===1?"":"s"} \u2022 ${m} report target${m===1?"":"s"}`}function Vn(e){return e.target.type==="webhook"?e.target.webhookUrl??"webhook":e.target.type==="channel"?`channel ${e.target.channelId?.slice(0,8)??"unknown"}`:"unknown target"}import{Fragment as Wn,jsx as ee,jsxs as te}from"react/jsx-runtime";var Tr={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},to=["all","pending","queued","running","completed","failed","cancelled","blocked"],Co=15;function ro({onBack:e}){let[t,o]=ut([]),[m,g]=ut(!0),[f,a]=ut("list"),[i,s]=ut(0),[r,d]=ut("all"),[p,w]=ut(0),[y,S]=ut(0),[n,x]=ut(null),$=xr(async()=>{g(!0);try{let P=new URLSearchParams({limit:"100"});r!=="all"&&P.set("status",r);let L=await C(`/tasks?${P}`);o(L.tasks)}catch{o([])}finally{g(!1)}},[r]);qn(()=>{$()},[$]);let I=Math.max(1,Math.ceil(t.length/Co)),A=t.slice(y*Co,(y+1)*Co),H=xr(async()=>{let P=A[i];if(P)try{await C(`/tasks/${P.id}/cancel`,{method:"POST"}),x(`Cancelled: ${P.id.slice(0,8)}`),a("list"),$()}catch(L){x(`Failed: ${L instanceof Error?L.message:String(L)}`),a("list")}},[A,i,$]);if(Fn((P,L)=>{if(f==="detail"){(L.escape||L.return||P==="q")&&a("list");return}if(f==="cancelling"){P==="y"?H():a("list");return}if(f==="filter"){if(L.escape){a("list");return}L.upArrow&&p>0&&w(N=>N-1),L.downArrow&&p<to.length-1&&w(N=>N+1),L.return&&(d(to[p]),S(0),s(0),a("list"));return}if(L.escape||P==="q"){e();return}if(L.upArrow&&i>0&&s(N=>N-1),L.downArrow&&i<A.length-1&&s(N=>N+1),L.return&&A[i]&&a("detail"),P==="x"&&A[i]){let N=A[i];["running","pending","queued","paused"].includes(N.status)?(a("cancelling"),x(null)):x(`Cannot cancel task in status: ${N.status}`)}P==="f"&&(w(to.indexOf(r)),a("filter")),P==="r"&&$(),(L.pageDown||P==="n")&&y<I-1&&(S(N=>N+1),s(0)),(L.pageUp||P==="p")&&y>0&&(S(N=>N-1),s(0))}),m)return ee(j,{dimColor:!0,children:"Loading tasks..."});if(f==="filter")return te(xe,{flexDirection:"column",children:[ee(j,{bold:!0,children:"Filter by status:"}),to.map((P,L)=>ee(xe,{children:te(j,{color:L===p?"cyan":"white",children:[L===p?"> ":" ",P,P===r?" (current)":""]})},P)),ee(j,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(f==="detail"&&A[i])return ee(pr,{taskId:A[i].id,onBack:()=>a("list")});if(f==="cancelling"&&A[i])return te(xe,{flexDirection:"column",children:[te(j,{color:"red",children:['Cancel task "',A[i].id.slice(0,8),'"? (y/n)']}),n&&ee(j,{color:"red",children:n})]});let Y=A[i]??null;return te(xe,{flexDirection:"column",children:[te(xe,{children:[te(j,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&te(j,{dimColor:!0,children:[" [filter: ",r,"]"]}),te(j,{dimColor:!0,children:[" \u2022 Page ",y+1,"/",I]})]}),n&&ee(j,{color:n.startsWith("Failed")||n.startsWith("Cannot")?"red":"green",children:n}),t.length===0?te(j,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):te(xe,{marginTop:1,flexDirection:"row",gap:2,children:[ee(xe,{flexDirection:"column",flexGrow:3,children:A.map((P,L)=>{let N=L===i,R=Tr[P.status]??"white";return te(xe,{flexDirection:"column",marginBottom:1,children:[te(xe,{children:[ee(j,{color:N?"cyan":"gray",bold:N,children:N?"\u276F ":" "}),ee(j,{color:R,bold:!0,children:P.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${P.id.slice(0,8)}`})]}),ee(xe,{paddingLeft:2,children:ee(j,{color:N?"white":void 0,children:oo(P.prompt,N?72:56)})}),ee(xe,{paddingLeft:2,children:te(j,{dimColor:!0,children:[br(P.createdAt)," \u2022 ",hr(P)," \u2022 ",yr(P.costUsd)]})})]},P.id)})}),ee(xe,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Y?te(Wn,{children:[ee(j,{bold:!0,children:"Preview"}),te(xe,{marginTop:1,children:[ee(j,{color:Tr[Y.status]??"white",bold:!0,children:Y.status.toUpperCase()}),ee(j,{dimColor:!0,children:` ${Y.id.slice(0,8)}`})]}),ee(j,{children:oo(Y.prompt,220)}),te(xe,{marginTop:1,flexDirection:"column",children:[te(j,{dimColor:!0,children:["Role: ",Y.roleId??Y.agentId??"\u2014"]}),te(j,{dimColor:!0,children:["Created: ",br(Y.createdAt)]}),te(j,{dimColor:!0,children:["Duration: ",hr(Y)]}),te(j,{dimColor:!0,children:["Cost: ",yr(Y.costUsd)]}),te(j,{dimColor:!0,children:["Turns: ",Y.numTurns??"\u2014"]})]}),Y.error?te(xe,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"red",bold:!0,children:"Error"}),ee(j,{color:"red",children:oo(Y.error,180)})]}):Y.result?te(xe,{marginTop:1,flexDirection:"column",children:[ee(j,{color:"green",bold:!0,children:"Latest Result"}),ee(j,{children:oo(Y.result,180)})]}):null,ee(xe,{marginTop:1,children:ee(j,{dimColor:!0,children:"Enter opens full detail"})})]}):ee(j,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Un(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function oo(e,t){return Un(e.replace(/\s+/g," ").trim(),t)}function hr(e){let t=e.totalDurationMs??(e.startedAt?Date.now()-e.startedAt:void 0);if(!t)return"waiting";let o=Math.max(1,Math.round(t/1e3));if(o<60)return`${o}s`;let m=Math.floor(o/60),g=o%60;return g===0?`${m}m`:`${m}m ${g}s`}function yr(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function br(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let o=Math.floor(t/60);if(o<60)return`${o}m ago`;let m=Math.floor(o/60);return m<24?`${m}h ago`:`${Math.floor(m/24)}d ago`}Wo();import{Box as ht,Text as Re,useInput as Gn}from"ink";import{useEffect as Hn,useState as vr}from"react";import{readFileSync as jn,existsSync as Kn}from"fs";import{parse as zn}from"yaml";import{Fragment as Qn,jsx as Ie,jsxs as Oe}from"react/jsx-runtime";function Cr({onBack:e}){let[t,o]=vr(null),[m,g]=vr(null);return Gn((f,a)=>{(a.escape||f==="q")&&e()}),Hn(()=>{try{let f=Uo;if(!Kn(f)){g(`Config file not found: ${f}`);return}let a=jn(f,"utf-8");o(zn(a))}catch(f){g(f.message)}},[]),m?Oe(ht,{flexDirection:"column",children:[Ie(Re,{color:"red",children:m}),Ie(Re,{dimColor:!0,children:"Press Esc to go back"})]}):t?Oe(ht,{flexDirection:"column",children:[Ie(Re,{bold:!0,children:"Configuration (Esc to go back)"}),Ie(ht,{marginTop:1,flexDirection:"column",children:Ie(So,{obj:t,indent:0})})]}):Ie(Re,{dimColor:!0,children:"Loading config..."})}function So({obj:e,indent:t}){let o=" ".repeat(t);return Ie(Qn,{children:Object.entries(e).map(([m,g])=>Ie(Xn,{label:m,value:g,indent:t,parentKey:m},m))})}function Xn({label:e,value:t,indent:o,parentKey:m}){let g=" ".repeat(o);return Array.isArray(t)?Oe(ht,{flexDirection:"column",children:[Oe(Re,{children:[g,Ie(Re,{color:"cyan",children:e}),":"]}),t.length===0?Oe(Re,{dimColor:!0,children:[g," []"]}):t.map((f,a)=>Ie(Sr,{value:f,indent:o+1,parentKey:m,index:a},`${e}-${a}`))]}):t&&typeof t=="object"?Oe(ht,{flexDirection:"column",children:[Oe(Re,{children:[g,Ie(Re,{color:"cyan",children:e}),":"]}),Ie(So,{obj:t,indent:o+1})]}):Oe(Re,{children:[g,Ie(Re,{color:"cyan",children:e}),": ",wr(m,Br(t))]})}function Sr({value:e,indent:t,parentKey:o,index:m}){let g=" ".repeat(t);return Array.isArray(e)?Oe(ht,{flexDirection:"column",children:[Oe(Re,{children:[g,"- [",m,"]"]}),e.map((f,a)=>Ie(Sr,{value:f,indent:t+1,parentKey:o,index:a},`${m}-${a}`))]}):e&&typeof e=="object"?Oe(ht,{flexDirection:"column",children:[Oe(Re,{children:[g,"-"]}),Ie(So,{obj:e,indent:t+1})]}):Oe(Re,{children:[g,"- ",wr(o,Br(e))]})}function wr(e,t){let o=e.toLowerCase();return o.includes("key")||o.includes("token")||o.includes("secret")||o.includes("password")?!t||t.length<8?"****":t.slice(0,4)+"****":t}function Br(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as no,Text as je,useInput as Yn}from"ink";import{useEffect as Zn,useState as wo}from"react";import{jsx as Ut,jsxs as et}from"react/jsx-runtime";function Er({onBack:e}){let[t,o]=wo([]),[m,g]=wo(!0),[f,a]=wo(null);return Yn((i,s)=>{(s.escape||i==="q")&&e()}),Zn(()=>{C("/evolution-audit?limit=20").then(i=>{o(i),g(!1)}).catch(i=>{a(i.message),g(!1)})},[]),m?Ut(je,{dimColor:!0,children:"Loading evolution log..."}):f?et(no,{flexDirection:"column",children:[Ut(je,{color:"red",children:f}),Ut(je,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?et(no,{flexDirection:"column",children:[Ut(je,{dimColor:!0,children:"No evolution records yet"}),Ut(je,{dimColor:!0,children:"Press Esc to go back"})]}):et(no,{flexDirection:"column",children:[et(je,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>et(no,{flexDirection:"column",marginTop:1,children:[et(je,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&et(je,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
9
|
+
`).map((s,r)=>s.startsWith("+")?et(je,{color:"green",children:[" ",s]},r):s.startsWith("-")?et(je,{color:"red",children:[" ",s]},r):et(je,{dimColor:!0,children:[" ",s]},r))]},i.id))]})}import{Box as st,Text as ae,useInput as Jn}from"ink";import es from"ink-text-input";import{useEffect as ts,useState as kt}from"react";import{jsx as Me,jsxs as Te}from"react/jsx-runtime";var os={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function rs(e,t=20){let o=Math.round(e*t),m=t-o;return"\u2588".repeat(o)+"\u2591".repeat(m)}function ns(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function so({onBack:e}){let[t,o]=kt([]),[m,g]=kt(null),[f,a]=kt("list"),[i,s]=kt(""),[r,d]=kt(!1),[p,w]=kt(null);Jn((n,x)=>{if(f==="create"){x.escape&&(a("list"),s(""),w(null));return}(x.escape||n==="q")&&e(),n==="c"&&(a("create"),w(null)),n==="r"&&y()});let y=()=>{C("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>g(n.message))};ts(()=>{y()},[]);let S=async n=>{if(n.trim()){d(!0),w(null);try{let x=await C("/goals",{method:"POST",body:{input:n.trim()}});w(`Goal created: ${x.goal.name}`),s(""),a("list"),y()}catch(x){w(`Failed: ${x instanceof Error?x.message:String(x)}`)}finally{d(!1)}}};return m?Te(st,{flexDirection:"column",children:[Te(ae,{color:"red",children:["Failed to load goals: ",m]}),Me(ae,{dimColor:!0,children:"Press Esc or q to return"})]}):f==="create"?Te(st,{flexDirection:"column",children:[Me(ae,{bold:!0,children:"Create Goal"}),Me(ae,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),Te(st,{marginTop:1,children:[Me(ae,{color:"cyan",children:"> "}),Me(es,{value:i,onChange:s,onSubmit:S})]}),r&&Me(ae,{color:"yellow",children:"Creating goal..."}),p&&Me(ae,{color:p.startsWith("Failed")?"red":"green",children:p}),Me(ae,{dimColor:!0,children:"Press Esc to cancel"})]}):Te(st,{flexDirection:"column",children:[Te(ae,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?Me(ae,{dimColor:!0,children:"No goals found. Press c to create one."}):Me(st,{marginTop:1,flexDirection:"column",children:t.map(n=>{let x=n.targetValue>0?n.currentValue/n.targetValue:0,$=os[n.status]??"white";return Te(st,{marginBottom:1,flexDirection:"column",children:[Te(st,{children:[Me(ae,{bold:!0,color:$,children:n.name}),Te(ae,{dimColor:!0,children:[" (",n.role,")"]}),Me(ae,{dimColor:!0,children:" \u2014 "}),Me(ae,{color:$,children:n.status})]}),Te(st,{children:[Te(ae,{dimColor:!0,children:[" ",rs(x)," "]}),Te(ae,{color:x>=1?"green":"white",children:[Math.round(x*100),"%"]}),Te(ae,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),Te(st,{children:[Te(ae,{dimColor:!0,children:[" \u23F0 ",ns(n.deadline)," left"]}),Te(ae,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),Te(ae,{dimColor:!0,children:[" | ID: ",n.id.slice(0,8)]})]})]},n.id)})}),Me(ae,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as It,Text as Fe,useInput as ss}from"ink";import{useEffect as is,useState as kr}from"react";import{jsx as at,jsxs as it}from"react/jsx-runtime";function as(e,t,o=15){let m=e/(e+t),g=Math.round(m*o);return"\u2593".repeat(g)+"\u2591".repeat(o-g)}function Ir({onBack:e}){let[t,o]=kr([]),[m,g]=kr(null);if(ss((a,i)=>{(i.escape||a==="q")&&e()}),is(()=>{C("/strategies?limit=50").then(a=>o(a.strategies??[])).catch(a=>g(a.message))},[]),m)return it(It,{flexDirection:"column",children:[it(Fe,{color:"red",children:["Failed to load strategies: ",m]}),at(Fe,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return it(It,{flexDirection:"column",children:[at(Fe,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),at(Fe,{dimColor:!0,children:"Press Esc or q to return"})]});let f=new Map;for(let a of t){let i=`${a.role}/${a.taskType}`,s=f.get(i)??[];s.push(a),f.set(i,s)}return it(It,{flexDirection:"column",children:[at(Fe,{bold:!0,children:"Strategy Lab"}),at(Fe,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),at(It,{marginTop:1,flexDirection:"column",children:Array.from(f.entries()).map(([a,i])=>it(It,{marginBottom:1,flexDirection:"column",children:[at(Fe,{bold:!0,color:"cyan",children:a}),i.sort((s,r)=>{let d=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-d}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return it(It,{children:[at(Fe,{dimColor:!0,children:" "}),it(Fe,{children:[as(s.alpha,s.beta)," "]}),it(Fe,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),it(Fe,{dimColor:!0,children:[" ",s.name," (\u03B1=",s.alpha.toFixed(1)," \u03B2=",s.beta.toFixed(1)," trials=",s.totalTrials,")"]})]},s.id)})]},a))}),at(Fe,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as he,Text as K,useInput as ms}from"ink";import Bo from"ink-text-input";import{useEffect as gs,useState as qe,useCallback as gt}from"react";import{CronExpressionParser as fs}from"cron-parser";import{useState as ls,useEffect as cs,useCallback as Ar,useRef as ds}from"react";var us=3e3;function mt(){let[e,t]=ls(null),o=ds(null),m=Ar(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),g=Ar((f,a)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:f,type:a}),a==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},us))},[]);return cs(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:g,clearMessage:m}}import{jsx as J,jsxs as oe}from"react/jsx-runtime";var Eo=["manual","cron","once","template_complete"],Pr=["cron","once","template_complete"],io={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function ps(e){try{return fs.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function ao({onBack:e}){let[t,o]=qe([]),[m,g]=qe(!0),[f,a]=qe(0),[i,s]=qe("list"),[r,d]=qe({...io}),[p,w]=qe("name"),[y,S]=qe(null),{message:n,setMessage:x,clearMessage:$}=mt(),[I,A]=qe(!1),[H,Y]=qe(!1),[P,L]=qe({}),[N,R]=qe(null),[Z,ne]=qe(!1),we=gt(()=>{g(!0),C("/task-templates").then(({templates:c})=>{o(c),new Set(c.flatMap(k=>k.steps?.map(U=>U.roleId).filter(Boolean)??[])).size>0?C("/roles").then(({roles:k})=>{if(!Array.isArray(k)){L({});return}L(Object.fromEntries(k.map(U=>[U.id,U.name])))}).catch(()=>L({})):L({}),g(!1)}).catch(()=>g(!1))},[]);gs(()=>{we()},[we]);let xt=i==="create"||i==="edit",_e=gt(async()=>{let c=t[f];if(!(!c||I)){A(!0),x(`Triggering ${c.name}...`,"loading");try{let b=await C(`/task-templates/${c.id}/run`,{method:"POST"});x(`Triggered: ${c.name} (${b.executionId})`,"success")}catch(b){x(`Trigger failed: ${b instanceof Error?b.message:String(b)}`,"error")}finally{A(!1)}}},[t,f,I,x]),ve=gt(async()=>{let c=t[f];if(!c||H)return;if(!Pr.includes(c.trigger?.type??"manual")){x("Toggle not applicable for manual triggers","error");return}let b=!c.enabled;Y(!0),x(`${c.name} \u2192 ${b?"enabling":"disabling"}...`,"loading");try{await C(`/task-templates/${c.id}`,{method:"PATCH",body:{enabled:b}}),o(k=>k.map(U=>U.id===c.id?{...U,enabled:b}:U)),x(`${c.name} ${b?"enabled":"disabled"}`,"success")}catch(k){x(`Toggle failed: ${k instanceof Error?k.message:String(k)}`,"error")}finally{Y(!1)}},[t,f,H,x]),Ct=gt(async()=>{if(Z)return;let c=t[f];if(c){ne(!0);try{let b=await C(`/task-templates/${c.id}/dependents`,{method:"GET"});R({templateId:c.id,templateName:c.name,executionCount:b.dependents.executionCount,taskCount:b.dependents.taskCount}),b.dependents.taskCount===0&&b.dependents.executionCount===0?x(`Delete "${c.name}"? Press d to confirm, Esc to cancel.`,"loading"):x(`"${c.name}" has ${b.dependents.executionCount} execution${b.dependents.executionCount===1?"":"s"}, ${b.dependents.taskCount} task${b.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(b){x(`Failed to inspect dependents: ${b instanceof Error?b.message:String(b)}`,"error")}finally{ne(!1)}}},[t,f,x,Z]),Ce=gt(async c=>{let b=N;if(b){R(null);try{let k=await C(`/task-templates/${b.templateId}?mode=${c}`,{method:"DELETE"}),U=[];k.deletedCounts.workflowExecutions>0&&U.push(`${k.deletedCounts.workflowExecutions} exec`),k.deletedCounts.tasks>0&&U.push(`${k.deletedCounts.tasks} task${k.deletedCounts.tasks===1?"":"s"}`);let de=U.length?` (+${U.join(", ")})`:"";x(`Deleted: ${b.templateName}${de}`,"success"),we(),a(Be=>Math.max(0,Math.min(Be,t.length-2)))}catch(k){x(`Delete failed: ${k instanceof Error?k.message:String(k)}`,"error")}}},[N,we,x,t.length]),We=gt(()=>{R(null),$()},[$]),dt=gt(()=>{let c=t[f];c&&(S(c.id),d({name:c.name,triggerType:c.trigger?.type==="workflow_complete"?"template_complete":c.trigger?.type??"manual",cron:c.trigger?.cron??"",targetTemplateId:c.trigger?.type==="template_complete"||c.trigger?.type==="workflow_complete"?c.trigger.event?.split(":")[1]??"":"",stepPrompt:c.steps?.[0]?.prompt??""}),w("name"),s("edit"))},[t,f]),M=gt(async()=>{let c={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{},...r.triggerType==="template_complete"&&r.targetTemplateId?{event:`template_complete:${r.targetTemplateId}`}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await C("/task-templates",{method:"POST",body:c}),x(`Created: ${r.name}`,"success")):i==="edit"&&y&&(await C(`/task-templates/${y}`,{method:"PATCH",body:c}),x(`Updated: ${r.name}`,"success"))}catch(b){x(`Save failed: ${b instanceof Error?b.message:String(b)}`,"error")}s("list"),d({...io}),S(null),we()},[r,i,y,we]);return ms((c,b)=>{if(xt){if(b.escape){s("list"),d({...io}),S(null);return}if(b.return){let k=["name","triggerType","cron","stepPrompt"],de=r.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:k.filter(W=>W!=="targetTemplateId"),Be=de.indexOf(p);if(Be<de.length-1){let W=Be+1;if(de[W]==="cron"&&r.triggerType!=="cron"&&W++,W<de.length){w(de[W]);return}}M();return}if(b.tab&&p==="triggerType"){d(k=>{let U=Eo.indexOf(k.triggerType);return{...k,triggerType:Eo[(U+1)%Eo.length]}});return}if(b.tab&&p==="targetTemplateId"){d(k=>{let U=t.filter(W=>W.id!==y),de=U.findIndex(W=>W.id===k.targetTemplateId),Be=U[(de+1)%U.length];return{...k,targetTemplateId:Be?.id??""}});return}return}if(N){if(b.escape){We();return}if(c==="D"&&b.shift){Ce("with_tasks");return}if(c==="d"&&!b.shift){Ce("template_only");return}return}if(b.escape||c==="q"){e();return}if(b.upArrow){a(k=>Math.max(0,k-1));return}if(b.downArrow){a(k=>Math.min(t.length-1,k+1));return}if(c==="t"){_e();return}if(c==="d"&&!b.shift){Ct();return}if(c==="e"){dt();return}if(c==="c"){d({...io}),w("name"),s("create");return}if(c==="s"||c===" "){ve();return}c==="r"&&(we(),$())}),m?J(K,{dimColor:!0,children:"Loading templates..."}):xt?oe(he,{flexDirection:"column",children:[oe(K,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),oe(he,{marginTop:1,flexDirection:"column",children:[oe(he,{children:[oe(K,{bold:p==="name",color:p==="name"?"cyan":void 0,children:["Name:"," "]}),p==="name"?J(Bo,{value:r.name,onChange:c=>d(b=>({...b,name:c})),placeholder:"template name"}):J(K,{children:r.name||"(empty)"})]}),oe(he,{children:[oe(K,{bold:p==="triggerType",color:p==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),J(K,{children:r.triggerType}),p==="triggerType"&&J(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&oe(he,{children:[oe(K,{bold:p==="cron",color:p==="cron"?"cyan":void 0,children:["Cron:"," "]}),p==="cron"?J(Bo,{value:r.cron,onChange:c=>d(b=>({...b,cron:c})),placeholder:"*/5 * * * *"}):J(K,{children:r.cron||"(empty)"})]}),(r.triggerType==="template_complete"||r.triggerType==="workflow_complete")&&oe(he,{children:[oe(K,{bold:p==="targetTemplateId",color:p==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),J(K,{children:(()=>{let c=t.find(b=>b.id===r.targetTemplateId);return c?c.name:r.targetTemplateId?`(id: ${r.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),p==="targetTemplateId"&&J(K,{dimColor:!0,children:" (Tab to cycle)"})]}),oe(he,{children:[oe(K,{bold:p==="stepPrompt",color:p==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),p==="stepPrompt"?J(Bo,{value:r.stepPrompt,onChange:c=>d(b=>({...b,stepPrompt:c})),placeholder:"What should this template do?"}):J(K,{children:r.stepPrompt||"(empty)"})]})]}),J(he,{marginTop:1,children:J(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):oe(he,{flexDirection:"column",children:[oe(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&J(he,{marginTop:1,children:oe(K,{color:n.type==="success"?"green":n.type==="error"?"red":"gray",children:[n.type==="success"?"\u2713 ":n.type==="error"?"\u2717 ":"\u2192 ",n.text]})}),t.length===0?J(he,{marginTop:1,children:J(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):J(he,{marginTop:1,flexDirection:"column",children:t.map((c,b)=>{let k=b===f,U=c.trigger?.type==="cron"&&c.trigger?.cron?ps(c.trigger.cron):"",de=new Set(c.steps?.filter(W=>W.roleId).map(W=>W.roleId)),Be=c.steps?.length>1?`${c.steps.length} steps${de.size>0?` / ${de.size} roles`:""}`:`${c.steps?.length??0} step`;return oe(he,{flexDirection:"column",children:[oe(he,{children:[J(K,{color:k?"cyan":void 0,bold:k,children:k?"> ":" "}),J(K,{color:k?"cyan":void 0,bold:k,children:Wt(c.name,24)}),J(K,{dimColor:!0,children:Wt(c.trigger?.type,10)}),Pr.includes(c.trigger?.type??"manual")?J(K,{color:c.enabled?"green":"gray",children:Wt(c.enabled?"on":"off",6)}):J(K,{dimColor:!0,children:Wt("\u2014",6)}),J(K,{dimColor:!0,children:Wt(Be,18)}),U&&oe(K,{dimColor:!0,children:["next: ",U]})]}),k&&c.steps?.length>1&&J(he,{flexDirection:"column",marginLeft:4,marginTop:0,children:c.steps.map((W,Xe)=>oe(he,{children:[oe(K,{dimColor:!0,children:[" ",Xe+1,". "]}),J(K,{dimColor:!0,children:W.id}),W.roleId&&oe(K,{color:"yellow",children:[" @",P[W.roleId]??W.roleId]}),W.dependsOn&&W.dependsOn.length>0&&oe(K,{dimColor:!0,children:[" (after: ",W.dependsOn.join(", "),")"]}),W.config&&oe(K,{dimColor:!0,children:[" ","[",[W.config.timeout!==void 0?`timeout:${W.config.timeout}s`:"",W.config.maxTurns!==void 0?`turns:${W.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},W.id))})]},c.id)})}),J(he,{marginTop:1,children:J(K,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Wt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as ft,Text as Ve,useInput as xs}from"ink";import Ts from"ink-text-input";import{useEffect as hs,useState as At,useCallback as Dr}from"react";import{jsx as Ae,jsxs as yt}from"react/jsx-runtime";function Rr({onBack:e}){let[t,o]=At([]),[m,g]=At(""),[f,a]=At(!0),[i,s]=At(!1),[r,d]=At(""),[p,w]=At(null),y=Dr(()=>{a(!0),C("/webhooks").then(({webhooks:n,auth:x})=>{o(n),g(x),a(!1)}).catch(()=>a(!1))},[]);hs(()=>{y()},[y]);let S=Dr(async n=>{if(n.trim())try{let x=await C(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});w(`Triggered: ${x.executionId}`)}catch(x){w(`Trigger failed: ${x instanceof Error?x.message:String(x)}`)}},[]);return xs((n,x)=>{if(i){if(x.escape){s(!1),d("");return}if(x.return){S(r),s(!1),d("");return}return}if(x.escape||n==="q"){e();return}if(n==="t"){s(!0),d(""),w(null);return}n==="r"&&(y(),w(null))}),f?Ae(Ve,{dimColor:!0,children:"Loading webhooks..."}):yt(ft,{flexDirection:"column",children:[yt(Ve,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),yt(Ve,{dimColor:!0,children:["Auth: ",m]}),p&&Ae(ft,{marginTop:1,children:Ae(Ve,{color:"yellow",children:p})}),i&&yt(ft,{marginTop:1,children:[Ae(Ve,{bold:!0,color:"cyan",children:"Trigger webhook: "}),Ae(Ts,{value:r,onChange:d,placeholder:"webhook name or ID"}),Ae(Ve,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?Ae(ft,{marginTop:1,children:Ae(Ve,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):yt(ft,{marginTop:1,flexDirection:"column",children:[Ae(ft,{children:yt(Ve,{bold:!0,children:[Pt("NAME",24),Pt("DESCRIPTION",36),Pt("TRIGGER",28),"TAGS"]})}),t.map(n=>yt(ft,{children:[Ae(Ve,{children:Pt(n.displayName,24)}),Ae(Ve,{dimColor:!0,children:Pt(ys(n.description??"",34),36)}),Ae(Ve,{dimColor:!0,children:Pt(n.trigger,28)}),Ae(Ve,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),Ae(ft,{marginTop:1,children:Ae(Ve,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function Pt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function ys(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as tt,Text as ue,useInput as bs}from"ink";import vs from"ink-text-input";import{useEffect as Mr,useState as lt,useCallback as ko}from"react";import{jsx as me,jsxs as Ke}from"react/jsx-runtime";function Cs(e){return e>=4?"red":e===3?"yellow":"gray"}function Ss(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function ws(e){return new Date(e).toLocaleDateString()}function Nr({onBack:e}){let[t,o]=lt([]),[m,g]=lt(0),[f,a]=lt([]),[i,s]=lt(!0),[r,d]=lt(!1),[p,w]=lt(""),[y,S]=lt("all"),[n,x]=lt(null),[$,I]=lt(!1),A=ko(()=>{C("/agents").then(({agents:R})=>{o(R),s(!1)}).catch(()=>s(!1))},[]);Mr(()=>{A()},[A]);let H=t[m],Y=ko(()=>{H&&(I(!1),C(`/memories/${H.id}`).then(({memories:R})=>{a(R),x(null)}).catch(R=>x(`Failed: ${R instanceof Error?R.message:String(R)}`)))},[H]);Mr(()=>{H&&Y()},[H,Y]);let P=ko(async R=>{if(!(!H||!R.trim()))try{let Z=await C("/memories/query",{method:"POST",body:{agentId:H.id,prompt:R.trim()}});a(Z.memories),I(!0),x(`Search: ${Z.count} results`)}catch(Z){x(`Search failed: ${Z instanceof Error?Z.message:String(Z)}`)}},[H]),L=r,N=f.filter(R=>y==="all"?!0:y==="high"?R.importance>3:y==="medium"?R.importance===3:R.importance<3);return bs((R,Z)=>{if(L){if(Z.escape){d(!1),w("");return}if(Z.return){P(p),d(!1),w("");return}return}if(Z.escape||R==="q"){e();return}if(R==="a"){g(ne=>(ne+1)%Math.max(1,t.length));return}if(Z.leftArrow){g(ne=>(ne-1+t.length)%Math.max(1,t.length));return}if(Z.rightArrow){g(ne=>(ne+1)%Math.max(1,t.length));return}if(R==="s"){d(!0),w(""),x(null);return}if(R==="h"){S(ne=>ne==="high"?"all":"high");return}if(R==="m"){S(ne=>ne==="medium"?"all":"medium");return}if(R==="l"){S(ne=>ne==="low"?"all":"low");return}R==="r"&&Y()}),i?me(ue,{dimColor:!0,children:"Loading agents..."}):t.length===0?Ke(tt,{flexDirection:"column",children:[me(ue,{dimColor:!0,children:"No agents found"}),me(ue,{dimColor:!0,children:"Press Esc to go back"})]}):Ke(tt,{flexDirection:"column",children:[me(ue,{bold:!0,children:"Memories (Esc to go back)"}),Ke(tt,{marginTop:1,children:[me(ue,{children:"Agent: "}),me(ue,{bold:!0,color:"cyan",children:H?.name??"?"}),Ke(ue,{dimColor:!0,children:[" (",m+1,"/",t.length,") [a/arrows to switch]"]})]}),me(tt,{children:Ke(ue,{dimColor:!0,children:["Filter: ",y==="all"?"all":y," | ",$?"search results":"all memories"," (",N.length,")"]})}),n&&me(tt,{children:me(ue,{color:"yellow",children:n})}),r&&Ke(tt,{marginTop:1,children:[me(ue,{bold:!0,color:"cyan",children:"Search: "}),me(vs,{value:p,onChange:w,placeholder:"search query..."}),me(ue,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),N.length===0?me(tt,{marginTop:1,children:Ke(ue,{dimColor:!0,children:["No memories",y!=="all"?` matching filter '${y}'`:""]})}):me(tt,{marginTop:1,flexDirection:"column",children:N.map(R=>Ke(tt,{marginBottom:0,children:[Ke(ue,{color:Cs(R.importance),bold:!0,children:[Ss(R.importance)," "]}),me(ue,{dimColor:!0,children:$r(R.type??"?",12)}),me(ue,{dimColor:!0,children:$r(`\xD7${R.retrievedCount??0}`,5)}),Ke(ue,{children:[Bs(R.content,55)," "]}),me(ue,{dimColor:!0,children:ws(R.createdAt)}),R.score!==void 0&&Ke(ue,{dimColor:!0,children:[" (",R.score.toFixed(2),")"]})]},R.id))}),me(tt,{marginTop:1,children:me(ue,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function $r(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Bs(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as ze,Text as ce,useInput as Es}from"ink";import lo from"ink-text-input";import{useState as $e,useEffect as _r,useCallback as Io}from"react";import{jsx as ye,jsxs as fe}from"react/jsx-runtime";var Lr={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"],Workflow:["watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"]},ks={"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","watchdog.rules.artifactCleanup.enabled":"Artifact Cleanup Enabled","watchdog.rules.artifactCleanup.ttlDays":"Artifact Retention (days)","watchdog.rules.artifactCleanup.orphanGcMinAgeHours":"Orphan GC Min Age (hours)"};function Or({onBack:e}){let{state:t}=Qe(),[o,m]=$e({}),[g,f]=$e([]),[a,i]=$e(null),[s,r]=$e("view"),[d,p]=$e(0),[w,y]=$e(""),[S,n]=$e(null),[x,$]=$e(!1),[I,A]=$e([]),[H,Y]=$e({}),[P,L]=$e(0),[N,R]=$e(""),[Z,ne]=$e(""),[we,xt]=$e(""),_e=Object.values(Lr).flat(),ve=Io(()=>{C("/config").then(M=>{m(M.config),f(M.mutable)}).catch(M=>i(M.message)),C("/config/env-diff").then(M=>{A(M.diffs)}).catch(()=>{}),C("/config/env").then(M=>Y(M.env??{})).catch(()=>{})},[]);_r(()=>{ve()},[ve]),_r(()=>{t.configVersion>0&&ve()},[t.configVersion,ve]);let Ct=Io(async()=>{let M=_e[d];if(M){$(!0),n(null);try{let c=w,b=o[M];if(b&&typeof b.value=="number"&&(c=Number(w),isNaN(c))){n("Invalid number"),$(!1);return}let k=await C("/config",{method:"PATCH",body:{[M]:c}});k.updated.length>0&&(n(`Updated: ${M}`),ve()),k.errors.length>0&&n(k.errors[0]),r("view")}catch(c){n(`Failed: ${c instanceof Error?c.message:String(c)}`)}finally{$(!1)}}},[_e,d,w,o,ve]),Ce=Object.keys(H),We=Io(async M=>{try{await C("/config/env",{method:"PUT",body:M}),n("Env vars saved"),ve()}catch(c){n(`Failed: ${c instanceof Error?c.message:String(c)}`)}},[ve]);if(Es((M,c)=>{if(s==="edit"){if(c.escape){r("view");return}return}if(s==="env-list"){if(c.escape){r("view");return}if(c.upArrow&&P>0&&L(b=>b-1),c.downArrow&&P<Ce.length-1&&L(b=>b+1),M==="a"){R(""),r("env-add-key");return}if(M==="d"&&Ce.length>0){let b=Ce[P],k={...H};delete k[b],We(k),P>=Ce.length-1&&P>0&&L(U=>U-1);return}if(c.return&&Ce.length>0){xt(H[Ce[P]]??""),r("env-edit-value");return}return}if(s==="env-add-key"){if(c.escape){r("env-list");return}return}if(s==="env-add-value"){if(c.escape){r("env-list");return}return}if(s==="env-edit-value"){if(c.escape){r("env-list");return}return}if(c.escape||M==="q"){e();return}if(c.upArrow&&d>0&&p(b=>b-1),c.downArrow&&d<_e.length-1&&p(b=>b+1),c.return||M==="e"){let b=_e[d],k=o[b];k&&k.mutable?(y(String(k.value??"")),r("edit"),n(null)):k&&!k.mutable&&n("This setting requires a restart to change")}M==="v"&&(L(0),r("env-list"),n(null)),M==="r"&&(ve(),n("Refreshed")),M==="s"&&I.length>0&&C("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),A([]),ve()}),M==="l"&&I.length>0&&C("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),ve()})}),a)return fe(ze,{flexDirection:"column",children:[fe(ce,{color:"red",children:["Failed to load config: ",a]}),ye(ce,{dimColor:!0,children:"Press Esc or q to return"})]});let dt=0;return fe(ze,{flexDirection:"column",children:[ye(ce,{bold:!0,children:"Settings"}),S&&ye(ce,{color:S.startsWith("Failed")||S.startsWith("This setting")?"yellow":"green",children:S}),I&&I.length>0&&fe(ze,{flexDirection:"column",marginBottom:1,children:[fe(ce,{color:"yellow",children:[".env differs from DB (",I.length," key(s)): ",I.map(M=>M.envKey).join(", ")]}),ye(ce,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),ye(ze,{marginTop:1,flexDirection:"column",children:Object.entries(Lr).map(([M,c])=>fe(ze,{marginBottom:1,flexDirection:"column",children:[ye(ce,{bold:!0,color:"cyan",children:M}),c.map(b=>{let k=o[b],de=dt++===d,Be=g.includes(b),W=ks[b]??b,Xe=k?String(k.value??""):"...";return s==="edit"&&de?fe(ze,{children:[fe(ce,{color:"cyan",children:["> ",W,": "]}),ye(lo,{value:w,onChange:y,onSubmit:()=>{Ct()}}),x&&ye(ce,{color:"yellow",children:" saving..."})]},b):fe(ze,{children:[fe(ce,{color:de?"cyan":"white",children:[de?"> ":" ",Be?" ":"\u{1F512} ",W,": "," "]}),ye(ce,{color:Be?"white":"gray",children:Xe}),!Be&&ye(ce,{dimColor:!0,children:" (restart required)"})]},b)})]},M))}),ye(ce,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),s.startsWith("env")&&fe(ze,{flexDirection:"column",marginTop:1,children:[fe(ce,{bold:!0,color:"cyan",children:["Environment Variables (",Ce.length,")"]}),Ce.length===0&&s==="env-list"&&ye(ce,{dimColor:!0,children:" No env vars. Press a to add."}),Ce.map((M,c)=>{let b=c===P;return s==="env-edit-value"&&b?fe(ze,{children:[fe(ce,{color:"cyan",children:["> ",M," = "]}),ye(lo,{value:we,onChange:xt,onSubmit:()=>{We({...H,[M]:we}),r("env-list")}})]},M):fe(ce,{color:b&&s==="env-list"?"cyan":"white",children:[b&&s==="env-list"?"> ":" ",M," = ",H[M]]},M)}),s==="env-add-key"&&fe(ze,{children:[ye(ce,{color:"green",children:" New key: "}),ye(lo,{value:N,onChange:R,onSubmit:()=>{N.trim()&&(ne(""),r("env-add-value"))}})]}),s==="env-add-value"&&fe(ze,{children:[fe(ce,{color:"green",children:[" ",N," = "]}),ye(lo,{value:Z,onChange:ne,onSubmit:()=>{We({...H,[N.trim()]:Z}),r("env-list")}})]}),ye(ce,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as bt,Text as Pe,useInput as Is}from"ink";import{useEffect as As,useState as Ao,useCallback as Ps}from"react";import{jsx as Se,jsxs as Rt}from"react/jsx-runtime";function Vr({onBack:e}){let[t,o]=Ao([]),[m,g]=Ao(!0),[f,a]=Ao(0),{message:i,setMessage:s,clearMessage:r}=mt(),d=Ps(()=>{g(!0),C("/plugins").then(({plugins:p})=>{o(p),g(!1)}).catch(()=>g(!1))},[]);return As(()=>{d()},[d]),Is((p,w)=>{if(w.escape||p==="q"){e();return}if(w.upArrow){a(y=>Math.max(0,y-1));return}if(w.downArrow){a(y=>Math.min(t.length-1,y+1));return}p==="r"&&(d(),r())}),m?Se(Pe,{dimColor:!0,children:"Loading plugins..."}):Rt(bt,{flexDirection:"column",children:[Rt(Pe,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&Se(bt,{marginTop:1,children:Rt(Pe,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?Se(bt,{marginTop:1,children:Se(Pe,{dimColor:!0,children:"No plugins installed."})}):Rt(bt,{marginTop:1,flexDirection:"column",children:[Rt(bt,{children:[Se(Pe,{dimColor:!0,children:" "}),Se(Pe,{dimColor:!0,children:Dt("Name",24)}),Se(Pe,{dimColor:!0,children:Dt("Scope",8)}),Se(Pe,{dimColor:!0,children:Dt("User",6)}),Se(Pe,{dimColor:!0,children:"Path"})]}),t.map((p,w)=>{let y=w===f,S=p.id.split("@")[0];return Rt(bt,{children:[Se(Pe,{color:y?"cyan":void 0,bold:y,children:y?"> ":" "}),Se(Pe,{color:y?"cyan":void 0,bold:y,children:Dt(S,24)}),Se(Pe,{color:y?"cyan":void 0,bold:y,children:Dt(p.scope,8)}),Se(Pe,{color:p.globalEnabled?"green":"gray",children:Dt(p.globalEnabled?"on":"off",6)}),Se(Pe,{dimColor:!0,children:p.installPath})]},p.id)})]}),Se(bt,{marginTop:1,children:Se(Pe,{dimColor:!0,children:"r:refresh"})})]})}function Dt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Po,Text as Do,useInput as Ds}from"ink";import{useState as Rs}from"react";import{jsx as vt,jsxs as Fr}from"react/jsx-runtime";var Ms=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function qr({onBack:e}){let[t,o]=Rs("tasks");return Ds((m,g)=>{if(g.escape||m==="q"){e();return}if(m==="1"){o("tasks");return}if(m==="2"){o("automations");return}if(m==="3"){o("goals");return}}),Fr(Po,{flexDirection:"column",children:[vt(Do,{bold:!0,children:"Work Surface"}),vt(Do,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),vt(Po,{gap:3,marginBottom:1,marginTop:1,children:Ms.map(m=>{let g=t===m.id;return vt(Po,{children:Fr(Do,{color:g?"cyan":"gray",bold:g,children:[g?"\u25CF":"\u25CB"," ",m.key,". ",m.label]})},m.id)})}),t==="tasks"&&vt(ro,{onBack:e}),t==="automations"&&vt(ao,{onBack:e}),t==="goals"&&vt(so,{onBack:e})]})}import{Box as re,Text as z,useInput as $s}from"ink";import{useEffect as Ns,useState as Gt}from"react";import{jsx as V,jsxs as be}from"react/jsx-runtime";var Ur={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function Wr({onBack:e}){let[t,o]=Gt([]),[m,g]=Gt(!0),[f,a]=Gt(0),[i,s]=Gt(null),[r,d]=Gt("");Ns(()=>{p()},[]);async function p(){try{let S=await C("/channels");o(S.channels)}catch{}g(!1)}async function w(S){if(t.find(x=>x.id===S)?.platform==="wechat")try{d("Starting WeChat QR login...");let x=await C(`/channels/${S}/wechat/qr-start`,{method:"POST"});if(x.qrcodeUrl){d(`Scan QR: ${x.qrcodeUrl}
|
|
10
|
+
Waiting for scan...`);let $=await C(`/channels/${S}/wechat/qr-wait`,{method:"POST",body:{sessionKey:x.sessionKey,timeoutMs:12e4}});d($.message)}else d(x.message);p()}catch{d("WeChat connect failed")}else try{await C(`/channels/${S}/connect`,{method:"POST"}),d("Connecting..."),p()}catch{d("Connect failed")}}async function y(S){try{await C(`/channels/${S}/disconnect`,{method:"POST"}),d("Disconnected"),p()}catch{d("Disconnect failed")}}return $s((S,n)=>{if(i){if(n.escape||S==="q"){s(null);return}if(S==="c"){w(i.id);return}if(S==="d"){y(i.id);return}return}if(n.escape){e();return}if(n.upArrow){a(x=>Math.max(0,x-1));return}if(n.downArrow){a(x=>Math.min(t.length-1,x+1));return}if(n.return&&t[f]){s(t[f]),d("");return}}),m?V(re,{flexDirection:"column",children:V(z,{dimColor:!0,children:"Loading channels..."})}):i?be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[be(z,{bold:!0,children:["Channel: ",i.name]}),V(z,{dimColor:!0,children:" (Esc to go back)"})]}),be(re,{flexDirection:"column",gap:0,children:[be(z,{children:["ID: ",i.id]}),be(z,{children:["Platform: ",i.platform]}),be(z,{children:["Status: ",V(z,{color:Ur[i.status]??"white",children:i.status})]}),be(z,{children:["Enabled: ",i.enabled?"yes":"no"]}),be(z,{children:["Messages: ",i.messageCount]}),be(z,{children:["Config: ",JSON.stringify(i.config)]})]}),V(re,{marginTop:1,children:V(z,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&V(z,{color:"yellow",children:r})]}):be(re,{flexDirection:"column",children:[be(re,{marginBottom:1,children:[V(z,{bold:!0,children:"Channels"}),be(z,{dimColor:!0,children:[" (",t.length," total) "]}),V(z,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?V(z,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):be(re,{flexDirection:"column",children:[be(re,{children:[V(re,{width:3,children:V(z,{dimColor:!0,children:" "})}),V(re,{width:12,children:V(z,{bold:!0,dimColor:!0,children:"ID"})}),V(re,{width:16,children:V(z,{bold:!0,dimColor:!0,children:"Name"})}),V(re,{width:12,children:V(z,{bold:!0,dimColor:!0,children:"Platform"})}),V(re,{width:14,children:V(z,{bold:!0,dimColor:!0,children:"Status"})}),V(re,{width:10,children:V(z,{bold:!0,dimColor:!0,children:"Enabled"})}),V(re,{width:10,children:V(z,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((S,n)=>be(re,{children:[V(re,{width:3,children:V(z,{children:n===f?">":" "})}),V(re,{width:12,children:V(z,{inverse:n===f,children:S.id.slice(0,8)})}),V(re,{width:16,children:V(z,{children:S.name})}),V(re,{width:12,children:V(z,{children:S.platform})}),V(re,{width:14,children:be(z,{color:Ur[S.status]??"white",children:[S.status==="connected"?"\u25CF":S.status==="error"?"\u2717":"\u25CB"," ",S.status]})}),V(re,{width:10,children:V(z,{color:S.enabled?"green":"gray",children:S.enabled?"yes":"no"})}),V(re,{width:10,children:V(z,{children:S.messageCount})})]},S.id))]})]})}import{Box as Mt,Text as ct,useInput as Os}from"ink";import{useEffect as Vs,useState as Ht,useCallback as Fs}from"react";import{Box as D,Text as T,useInput as _s}from"ink";import ot from"ink-text-input";import{useEffect as Gr,useState as X,useCallback as pt}from"react";Wo();import{Fragment as Hr,jsx as h,jsxs as B}from"react/jsx-runtime";var Ls=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function jr({roleId:e,onBack:t}){let[o,m]=X(null),[g,f]=X([]),[a,i]=X(!0),[s,r]=X("view"),[d,p]=X(""),[w,y]=X(0),[S,n]=X(""),[x,$]=X([]),[I,A]=X(0),[H,Y]=X(new Set),[P,L]=X("inline"),[N,R]=X(""),[Z,ne]=X(""),[we,xt]=X([]),[_e,ve]=X(new Set),[Ct,Ce]=X(0),[We,dt]=X("default"),[M,c]=X(""),[b,k]=X(""),[U,de]=X("mode"),[Be,W]=X([]),[Xe,Xr]=X(null),[go,Qr]=X([]),[St,fo]=X([]),[No,po]=X(""),[Tt,Kt]=X(0),[zt,_o]=X(""),[Lo,Oo]=X(""),[Vo,Fo]=X(""),{message:_,setMessage:q}=mt(),se=pt(()=>{i(!0),C(`/roles/${e}`).then(({role:u,boundPlugins:v})=>{m(u),f(v??[]),p(u.cagPrompt??""),Y(new Set(u.allowedTools??[])),L(u.executionMode??"inline"),R(u.model??""),ne(u.maxBudgetUsd!=null?String(u.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);Gr(()=>{se(),C("/config").then(u=>{let v=u.config["defaults.deniedReadPaths"]?.value;Array.isArray(v)&&W(v),Xr(u.sandbox),Qr(u.osCapabilities?.registry??[])}).catch(()=>{})},[se]),Gr(()=>{L(o?.executionMode??"inline"),R(o?.model??""),ne(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):""),dt(o?.permissionMode??"default"),c((o?.allowedBashPatterns??[]).join(", ")),k((o?.deniedBashPatterns??[]).join(", ")),fo(o?.osCapabilities??[]);let u=o?.osCapabilities?.find(v=>v.id==="automation")?.targets??[];po(u.join(", "))},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd,o?.permissionMode,o?.allowedBashPatterns,o?.deniedBashPatterns,o?.osCapabilities]);let Yr=pt(async()=>{if(o)try{await C(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:d}}),q("CAG prompt saved","success"),r("view"),se()}catch(u){q(`Save failed: ${u instanceof Error?u.message:String(u)}`,"error")}},[o,d,se,q]),Zr=pt(async()=>{if(o)try{await C(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:Ge}}),q("Directories saved","success"),r("view"),se()}catch(u){q(`Save failed: ${u instanceof Error?u.message:String(u)}`,"error")}},[o,se,q]),Jr=pt(async()=>{if(o)try{await C(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(H)}}),q("Tool permissions saved","success"),r("view"),se()}catch(u){q(`Save failed: ${u instanceof Error?u.message:String(u)}`,"error")}},[o,H,se,q]),en=pt(async()=>{if(!o)return;let u={executionMode:P};N!==void 0&&(u.model=N);let v=parseFloat(Z);isNaN(v)||(u.maxBudgetUsd=v);try{await C(`/roles/${o.id}`,{method:"PATCH",body:u}),q("Execution config saved","success"),r("view"),se()}catch(l){q(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,P,N,Z,se,q]),tn=pt(async()=>{if(!o)return;let u={permissionMode:We},v=M.split(",").map(E=>E.trim()).filter(Boolean),l=b.split(",").map(E=>E.trim()).filter(Boolean);u.allowedBashPatterns=v.length>0?v:[],u.deniedBashPatterns=l.length>0?l:[];try{await C(`/roles/${o.id}`,{method:"PATCH",body:u}),q("Permission config saved","success"),r("view"),se()}catch(E){q(`Save failed: ${E instanceof Error?E.message:String(E)}`,"error")}},[o,We,M,b,se,q]),qo=pt(u=>{let v=new Map;for(let l of u){if(!l.id)continue;let E={id:l.id};l.targets?.length&&(E.targets=Array.from(new Set(l.targets.map(O=>O.trim()).filter(Boolean)))),v.set(l.id,E)}return Array.from(v.values()).sort((l,E)=>l.id.localeCompare(E.id))},[]),on=pt(async()=>{if(!o)return;let u=qo(St),v=u.find(l=>l.id==="automation")?.targets??[];if(u.some(l=>l.id==="automation")&&(v.length===0||v.some(l=>!Ls.test(l)))){q("Automation requires valid bundle id targets","error");return}try{await C(`/roles/${o.id}`,{method:"PATCH",body:{osCapabilities:u}}),q("OS capabilities saved","success"),r("view"),se()}catch(l){q(`Save failed: ${l instanceof Error?l.message:String(l)}`,"error")}},[o,St,qo,se,q]),Ge=o?.additionalDirectories??[];if(_s((u,v)=>{if(v.escape){r("view");return}if(u==="r"){se();return}switch(s){case"view":{if(u==="c"){r("edit-cag");return}if(u==="d"){r("edit-dirs"),y(0),n("");return}if(u==="t"){r("edit-tools");return}if(u==="o"){r("edit-oscaps");return}if(u==="x"){r("edit-exec");return}if(u==="h"){C("/channels?enabled=true").then(({channels:l})=>{xt(l.map(E=>({name:E.name,id:E.id}))),ve(new Set(o?.allowedChannels??[])),Ce(0),r("edit-channels")}).catch(()=>q("Failed to load channels","error"));return}if(u==="p"){dt(o?.permissionMode??"default"),c((o?.allowedBashPatterns??[]).join(", ")),k((o?.deniedBashPatterns??[]).join(", ")),de("mode"),r("edit-permissions");return}if(u==="v"){Kt(0),r("edit-env");return}if(u==="i"){if(!o)return;let l=!o.inheritUserSettings;C(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:l}}).then(()=>{q(`Inherit user settings: ${l?"ON":"OFF"}`,"success"),se()}).catch(()=>q("Failed to toggle","error"));return}break}case"edit-cag":{if(v.ctrl&&u==="s"){Yr();return}break}case"edit-dirs":{if(u==="s"){Zr();return}if(u==="a"){r("edit-dirs-add");return}if(u==="m"&&Ge.length>0){let l=Ge[w];if(l){m(O=>O&&{...O,additionalDirectories:O.additionalDirectories?.map((le,rt)=>rt===w?{...typeof le=="string"?{path:le}:le,mode:le.mode==="ro"?"rw":"ro"}:le)});let E=l.mode==="ro"?"rw":"ro";q(`Mode set to ${E.toUpperCase()}`,"success")}return}if(u==="x"&&Ge.length>0){m(l=>l&&{...l,additionalDirectories:Ge.filter((E,O)=>O!==w)}),y(l=>Math.max(0,Math.min(l,Ge.length-2)));return}if(v.upArrow){y(l=>Math.max(0,l-1));return}if(v.downArrow){y(l=>Math.min(Ge.length-1,l+1));return}break}case"edit-dirs-add":{if(v.escape){r("edit-dirs"),n(""),$([]);return}if(v.return&&x.length>0){let l=x[I];l&&(n(l.endsWith("/")?l:l+"/"),$([]));return}if(v.return){let l=S.trim();l&&l.startsWith("/")?(m(E=>E&&{...E,additionalDirectories:[...E.additionalDirectories??[],{path:l,mode:"rw"}]}),n(""),$([]),r("edit-dirs")):q("Path must be absolute (must start with /)","error");return}if(v.tab){let l=S.trim();if(!l||!l.startsWith("/"))return;C(`/fs/suggest-dirs?prefix=${encodeURIComponent(l)}`).then(({suggestions:E})=>{E.length===1?(n(E[0]+"/"),$([])):E.length>1&&($(E),A(0))}).catch(()=>{$([])});return}if(v.upArrow&&x.length>0){A(l=>Math.max(0,l-1));return}if(v.downArrow&&x.length>0){A(l=>Math.min(x.length-1,l+1));return}break}case"edit-tools":{if(u==="s"){Jr();return}let l=parseInt(u,10)-1;if(!isNaN(l)&&l>=0&&l<Xt.length){let E=Xt[l];Y(O=>{let le=new Set(O);return le.has(E)?le.delete(E):le.add(E),le});return}break}case"edit-oscaps":{if(u==="s"){on();return}if(u==="a"&&St.some(O=>O.id==="automation")){let O=St.find(le=>le.id==="automation")?.targets??[];po(O.join(", ")),r("edit-oscaps-targets");return}let l=go.filter(O=>O.editable),E=parseInt(u,10)-1;if(!isNaN(E)&&E>=0&&E<l.length){let O=l[E];fo(le=>le.some(_t=>_t.id===O.id)?le.filter(_t=>_t.id!==O.id):[...le,{id:O.id,targets:O.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(v.return){let l=No.split(",").map(E=>E.trim()).filter(Boolean);fo(E=>E.map(O=>O.id==="automation"?{...O,targets:l}:O)),r("edit-oscaps");return}break}case"edit-exec":{if(u==="s"){en();return}if(v.tab){L(l=>l==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(u==="s"){tn();return}if(v.tab){de(l=>l==="mode"?"allowed":l==="allowed"?"denied":"mode");return}if(U==="mode"&&(v.upArrow||v.downArrow)){let l=["default","acceptEdits","dontAsk","bypassPermissions"],E=l.indexOf(We);v.upArrow&&dt(l[Math.max(0,E-1)]),v.downArrow&&dt(l[Math.min(l.length-1,E+1)]);return}break}case"edit-channels":{if(u==="s"){if(!o)return;let l=_e.size>0?Array.from(_e):[];C(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:l}}).then(()=>{q("Channels saved","success"),r("view"),se()}).catch(()=>q("Save failed","error"));return}if(u==="u"){if(!o)return;C(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{q("Channels: unrestricted","success"),r("view"),se()}).catch(()=>q("Save failed","error"));return}if(u===" "){let l=we[Ct];l&&ve(E=>{let O=new Set(E);return O.has(l.name)?O.delete(l.name):O.add(l.name),O});return}if(v.upArrow){Ce(l=>Math.max(0,l-1));return}if(v.downArrow){Ce(l=>Math.min(we.length-1,l+1));return}break}case"edit-env":{let l=Object.keys(o?.envVars??{});if(u==="a"){_o(""),r("edit-env-add-key");return}if(u==="d"&&l.length>0){let E=l[Tt],O={...o?.envVars??{}};delete O[E],C(`/roles/${o.id}`,{method:"PATCH",body:{envVars:O}}).then(()=>{q("Deleted","success"),se()}).catch(()=>q("Delete failed","error")),Tt>=l.length-1&&Tt>0&&Kt(le=>le-1);return}if(v.return&&l.length>0){Fo((o?.envVars??{})[l[Tt]]??""),r("edit-env-edit-value");return}v.upArrow&&Tt>0&&Kt(E=>E-1),v.downArrow&&Tt<l.length-1&&Kt(E=>E+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break}}),a)return h(T,{dimColor:!0,children:"Loading role..."});if(!o)return h(T,{dimColor:!0,children:"Role not found."});if(s==="edit-cag")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),h(ot,{value:d,onChange:p,placeholder:"Character And Guidance prompt..."}),_&&h(D,{marginTop:1,children:h(T,{color:_.type==="error"?"red":"green",children:_.text})})]});if(s==="edit-dirs-add")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),h(ot,{value:S,onChange:u=>{n(u),$([])},placeholder:"/absolute/path/to/directory"}),x.length>0&&B(D,{flexDirection:"column",marginTop:1,children:[x.map((u,v)=>B(T,{color:v===I?"cyan":void 0,dimColor:v!==I,children:[v===I?"> ":" ",u,"/"]},u)),h(T,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),_&&h(D,{marginTop:1,children:h(T,{color:_.type==="error"?"red":"green",children:_.text})})]});if(s==="edit-dirs")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),Ge.length===0?h(T,{dimColor:!0,children:"No directories. Press a to add one."}):Ge.map((u,v)=>{let l=typeof u=="string"?{path:u,mode:"rw"}:u,E=l.mode!=="ro";return B(D,{children:[h(T,{color:v===w?"cyan":void 0,bold:v===w,children:v===w?"> ":" "}),B(T,{color:E?"green":"yellow",children:["[",E?"RW":"RO","]"," "]}),h(T,{color:v===w?"cyan":void 0,children:l.path})]},l.path)})]});if(s==="edit-tools")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),Xt.map((u,v)=>{let l=H.has(u);return B(D,{children:[B(T,{dimColor:!0,children:[v+1,". "]}),h(T,{color:l?"green":"red",children:l?"[ON] ":"[OFF] "}),h(T,{children:u})]},u)})]});if(s==="edit-oscaps"){let u=go.filter(v=>v.editable);return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),Xe&&B(T,{dimColor:!0,children:["Platform: ",Xe.platform," ",Xe.available?"(sandbox active)":"(sandbox unavailable)"]}),go.map(v=>{let l=u.findIndex(rt=>rt.id===v.id),E=St.some(rt=>rt.id===v.id),O=l>=0?`${l+1}.`:" -",le=v.id==="automation"?(()=>{let rt=St.find(_t=>_t.id===v.id)?.targets??[];return rt.length>0?` targets: ${rt.join(", ")}`:" targets: (none)"})():"";return B(D,{flexDirection:"column",marginBottom:1,children:[B(T,{color:E?"green":v.editable?"red":"gray",children:[O," ",E?"[ON]":"[OFF]"," ",v.label," [",v.availability,"]"]}),B(T,{dimColor:!0,children:[" ",v.description,le]}),v.effectiveDisabledReason&&!v.editable&&B(T,{dimColor:!0,children:[" ",v.effectiveDisabledReason]})]},v.id)}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]})}if(s==="edit-oscaps-targets")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),h(ot,{value:No,onChange:po,placeholder:"com.apple.mail, com.apple.systemevents"}),h(T,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(s==="edit-exec")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),B(D,{children:[h(T,{bold:!0,children:" Mode: "}),h(T,{color:"cyan",children:P}),h(T,{dimColor:!0,children:" (Tab to toggle)"})]}),B(D,{children:[h(T,{bold:!0,children:" Model: "}),h(ot,{value:N,onChange:R,placeholder:"sonnet, opus, haiku, or blank"})]}),B(D,{children:[h(T,{bold:!0,children:" Max Budget (USD): "}),h(ot,{value:Z,onChange:ne,placeholder:"0 = unlimited"})]}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(s==="edit-permissions")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),B(D,{children:[h(T,{bold:!0,color:U==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(v=>B(T,{color:v===We?"green":"gray",children:[v===We?`[${v}]`:` ${v} `," "]},v))]}),B(D,{children:[h(T,{bold:!0,color:U==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),U==="allowed"?h(ot,{value:M,onChange:c,placeholder:"git add *, pnpm test*"}):h(T,{children:M||"(none)"})]}),B(D,{children:[h(T,{bold:!0,color:U==="denied"?"cyan":void 0,children:" Denied Bash: "}),U==="denied"?h(ot,{value:b,onChange:k,placeholder:"rm -rf *, ssh *"}):h(T,{children:b||"(none)"})]}),h(T,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(s==="edit-channels")return B(D,{flexDirection:"column",children:[h(T,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),we.length===0?h(T,{dimColor:!0,children:"No channels available"}):we.map((u,v)=>B(D,{children:[B(T,{children:[v===Ct?">":" "," "]}),B(T,{color:_e.has(u.name)?"green":"gray",children:["[",_e.has(u.name)?"x":" ","] ",u.name]})]},u.id)),B(T,{dimColor:!0,children:["Selected: ",_e.size>0?Array.from(_e).join(", "):"none (= block all)"]}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})})]});if(s.startsWith("edit-env")){let u=Object.keys(o.envVars??{});return B(D,{flexDirection:"column",children:[B(T,{bold:!0,children:["Environment Variables (",u.length,")"]}),u.length===0&&s==="edit-env"&&h(T,{dimColor:!0,children:" No env vars. Press a to add."}),u.map((v,l)=>{let E=l===Tt;return s==="edit-env-edit-value"&&E?B(D,{children:[B(T,{color:"cyan",children:["> ",v," = "]}),h(ot,{value:Vo,onChange:Fo,onSubmit:()=>{let O={...o.envVars??{},[v]:Vo};C(`/roles/${o.id}`,{method:"PATCH",body:{envVars:O}}).then(()=>{q("Saved","success"),se(),r("edit-env")}).catch(()=>q("Save failed","error"))}})]},v):B(T,{color:E&&s==="edit-env"?"cyan":"white",children:[E&&s==="edit-env"?"> ":" ",v," = ",(o.envVars??{})[v]]},v)}),s==="edit-env-add-key"&&B(D,{children:[h(T,{color:"green",children:" New key: "}),h(ot,{value:zt,onChange:_o,onSubmit:()=>{zt.trim()&&(Oo(""),r("edit-env-add-value"))}})]}),s==="edit-env-add-value"&&B(D,{children:[B(T,{color:"green",children:[" ",zt," = "]}),h(ot,{value:Lo,onChange:Oo,onSubmit:()=>{let v={...o.envVars??{},[zt.trim()]:Lo};C(`/roles/${o.id}`,{method:"PATCH",body:{envVars:v}}).then(()=>{q("Added","success"),se(),r("edit-env")}).catch(()=>q("Add failed","error"))}})]}),h(T,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),_&&h(T,{color:_.type==="error"?"red":"green",children:_.text})]})}return B(D,{flexDirection:"column",children:[B(T,{bold:!0,children:["Role: ",o.name]}),B(D,{children:[h(T,{dimColor:!0,children:"ID: "}),h(T,{children:o.id})]}),B(D,{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(D,{children:[h(T,{dimColor:!0,children:"Score: "}),B(T,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),B(D,{children:[h(T,{dimColor:!0,children:"Created: "}),h(T,{children:new Date(o.createdAt).toLocaleString()})]}),B(D,{children:[h(T,{dimColor:!0,children:"Execution: "}),B(T,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),B(D,{children:[h(T,{dimColor:!0,children:"OS Capabilities: "}),h(T,{children:(o.osCapabilities?.length??0)>0?o.osCapabilities.map(u=>u.id==="automation"&&u.targets?.length?`automation(${u.targets.join(",")})`:u.id).join(", "):"None"})]}),Xe&&B(D,{children:[h(T,{dimColor:!0,children:"Sandbox Platform: "}),B(T,{children:[Xe.platform," ",Xe.available?"(active)":"(unavailable)"]})]}),Ge.length>0&&B(Hr,{children:[h(T,{bold:!0,children:"Additional Directories:"}),Ge.map(u=>B(T,{dimColor:!0,children:[" ",u.path]},u.path))]}),B(D,{children:[h(T,{dimColor:!0,children:"Permission: "}),h(T,{children:o.permissionMode??"default"})]}),(o.allowedBashPatterns?.length??0)>0&&B(D,{children:[h(T,{dimColor:!0,children:" Bash Allow: "}),h(T,{children:o.allowedBashPatterns.join(", ")})]}),(o.deniedBashPatterns?.length??0)>0&&B(D,{children:[h(T,{dimColor:!0,children:" Bash Deny: "}),h(T,{children:o.deniedBashPatterns.join(", ")})]}),Be.length>0&&B(D,{flexDirection:"column",children:[h(T,{dimColor:!0,children:"Denied Read Paths (global):"}),Be.map(u=>B(T,{dimColor:!0,children:[" ",u]},u)),B(T,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),B(D,{children:[h(T,{dimColor:!0,children:"Channels: "}),h(T,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),B(D,{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(Hr,{children:[h(T,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(u=>B(T,{dimColor:!0,children:[" - ",u]},u))]}),_&&h(D,{children:h(T,{color:_.type==="error"?"red":_.type==="success"?"green":"gray",children:_.text})}),h(D,{marginTop:1,children:h(T,{dimColor:!0,children:"c:CAG d:dirs t:tools o:oscaps x:exec p:perms h:channels v:env i:inherit r:refresh Esc:back"})})]})}import{jsx as Ue,jsxs as co}from"react/jsx-runtime";function Kr({onBack:e}){let[t,o]=Ht([]),[m,g]=Ht(!0),[f,a]=Ht(0),[i,s]=Ht("list"),[r,d]=Ht(null),{message:p,setMessage:w,clearMessage:y}=mt(),S=Fs(()=>{g(!0),C("/roles").then(({roles:n})=>{o(n.map(x=>({id:x.id,name:x.name,status:x.status,performanceScore:x.performanceScore,createdAt:x.createdAt}))),g(!1)}).catch(()=>g(!1))},[]);return Vs(()=>{S()},[S]),Os((n,x)=>{if(x.escape||n==="q"){e();return}if(x.upArrow){a($=>Math.max(0,$-1));return}if(x.downArrow){a($=>Math.min(t.length-1,$+1));return}if(n==="r"&&(S(),y()),n===`
|
|
11
|
+
`||n==="o"||n==="e"){t.length>0&&(d(t[f].id),s("detail"));return}}),m?Ue(ct,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Ue(jr,{roleId:r,onBack:()=>s("list")}):co(Mt,{flexDirection:"column",children:[co(ct,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),p&&Ue(Mt,{marginTop:1,children:co(ct,{color:p.type==="success"?"green":p.type==="error"?"red":"gray",children:[p.type==="success"?"\u2713 ":p.type==="error"?"\u2717 ":"\u2192 ",p.text]})}),t.length===0?Ue(Mt,{marginTop:1,children:Ue(ct,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Ue(Mt,{marginTop:1,flexDirection:"column",children:t.map((n,x)=>{let $=x===f,I=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return co(Mt,{children:[Ue(ct,{color:$?"cyan":void 0,bold:$,children:$?"> ":" "}),Ue(ct,{color:$?"cyan":void 0,bold:$,children:Ro(n.name,24)}),Ue(ct,{color:qs(n.status),children:Ro(n.status,12)}),Ue(ct,{dimColor:!0,children:Ro(I,8)})]},n.id)})}),Ue(Mt,{marginTop:1,children:Ue(ct,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function qs(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function Ro(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Us,Text as Mo}from"ink";import Ws from"react";import{jsx as uo,jsxs as Hs}from"react/jsx-runtime";var Ne={key:"Esc",label:"back"},Gs={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},Ne],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},Ne],config:[Ne],evolution:[Ne],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},Ne],strategies:[Ne],templates:[{key:"\u2191\u2193",label:"move"},{key:"t",label:"run"},{key:"s",label:"toggle"},{key:"e",label:"edit"},{key:"c",label:"create"},{key:"d",label:"delete"},{key:"r",label:"refresh"},Ne],webhooks:[Ne],memories:[Ne],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},Ne],roles:[Ne],settings:[Ne],channels:[Ne]};function zr(){let{state:e}=Qe(),t=Gs[e.view]??[Ne];return uo(Us,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((o,m)=>Hs(Ws.Fragment,{children:[m>0&&uo(Mo,{dimColor:!0,children:" "}),uo(Mo,{color:"cyan",children:o.key}),uo(Mo,{dimColor:!0,children:` ${o.label}`})]},`${o.key}-${o.label}`))})}import{Fragment as Ys,jsx as Q,jsxs as Nt}from"react/jsx-runtime";function zs(){let{state:e,dispatch:t}=Qe(),{session:o,sendMessage:m,createNewSession:g,archiveCurrentSession:f}=Zo(),[a,i]=Ks([]);mo(()=>{t({type:"SET_SESSION",session:o})},[o,t]),Xo();let{latestMessage:s}=er(o?.id??null),r=$o(null);mo(()=>{s&&s.id!==r.current&&(r.current=s.id,i(A=>[...A,{role:"assistant",content:s.content}]))},[s]);let{events:d,isStreaming:p,clearEvents:w}=Yo(e.activeTaskId),y=d[d.length-1],S=y?.type==="complete"&&!p,n=$o(null),x=$o("");mo(()=>{x.current=d.filter(A=>A.type==="reasoning").map(A=>A.content).join("")},[d]),mo(()=>{if(S&&e.activeTaskId!==n.current){n.current=e.activeTaskId;let A=y?.content||x.current;A&&i(H=>[...H,{role:"assistant",content:A}])}},[S,y,e.activeTaskId]);let $=async A=>{let H=A.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(H)&&process.exit(0),A.startsWith("/")){let P=A.slice(1),N={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"}[P];if(N){t({type:"SET_VIEW",view:N});return}if(P==="new"){if(await f()){let Z=await g();i([]),w(),Z&&i([{role:"assistant",content:`Session archived. New session started: ${Z.id.slice(0,8)}`}])}return}if(P==="session"){let R=o?`Session: ${o.id}
|
|
12
|
+
Turns: ${o.messageCount}
|
|
13
|
+
Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(Z=>[...Z,{role:"assistant",content:R}]);return}}if(i(P=>[...P,{role:"user",content:A}]),w(),!await m(A)){i(P=>[...P,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},I=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval;return Nt(jt,{flexDirection:"column",paddingX:1,children:[Q(or,{}),Nt(jt,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Nt(Ys,{children:[Q(lr,{messages:a}),Q(sr,{events:d,isStreaming:p}),!e.connected&&!e.serverUnreachable&&Q(jt,{children:Q($t,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Nt(jt,{flexDirection:"column",children:[Q($t,{color:"red",bold:!0,children:"Server unreachable after 15s."}),Q($t,{dimColor:!0,children:"Check: adam server logs"}),Q($t,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&Q(qr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&Q(ro,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&Q(Cr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&Q(Er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&Q(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&Q(Ir,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&Q(ao,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&Q(Rr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&Q(Nr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&Q(Vr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&Q(Kr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&Q(Or,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&Q(Wr,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?Q(dr,{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?Q(cr,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):I?Q(nr,{onSubmit:$}):Q(zr,{}),e.planTimeoutNotice&&Q(Xs,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function Xs({planId:e,onDismiss:t}){return js(o=>{o==="d"&&t()}),Nt(jt,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Nt($t,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),Q($t,{dimColor:!0,children:" [d] Dismiss"})]})}function Qs(){return Q(jo,{children:Q(zs,{})})}export{Qs as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-FCV2DPZQ.js";async function f(e){let{ensureRoleWorkspace:a}=await import("./role-workspace-
|
|
1
|
+
import"./chunk-FCV2DPZQ.js";async function f(e){let{ensureRoleWorkspace:a}=await import("./role-workspace-NKGAH6J6.js"),{getRole:t}=await import("./roles-ZYCFQMAY.js"),{mkdir:s,readFile:y,writeFile:d,access:u}=await import("fs/promises"),{join:n}=await import("path"),o=t(e);if(!o)throw new Error(`Role '${e}' not found`);let p=a(o),r=n(p,".claude","skills");await s(r,{recursive:!0});let m=[{name:"aggregate_feature",description:"Aggregate a feature value over a window",inputs:[{name:"feature_name",desc:"Name of the feature to aggregate"},{name:"aggregation",desc:"Aggregation type: sum | avg | count | latest"},{name:"window_days",desc:"Number of days to look back"},{name:"field",desc:"Event payload field to aggregate"}],body:"Query events via sqlite3, compute aggregation, print numeric result."},{name:"check_threshold",description:"Compare a value vs threshold, emit breach if exceeded",inputs:[{name:"feature",desc:"Feature value (number)"},{name:"operator",desc:"Comparison operator: gt | gte | lt | lte | eq"},{name:"threshold",desc:"Threshold value"},{name:"on_breach_type",desc:"Event type to emit on breach"},{name:"on_breach_payload",desc:"JSON payload for breach event"}],body:"Read feature value, compare against threshold using the operator. On breach, emit new event via emit_event Skill."},{name:"query_events",description:"Range-query events table",inputs:[{name:"type_pattern",desc:"Event type pattern (e.g. 'scheduler.tick')"},{name:"window",desc:"Lookback window in hours"},{name:"limit",desc:"Maximum number of events to return"}],body:"sqlite3 parameterized query against the events table, returning matching rows as JSON."},{name:"query_state",description:"Read latest state_snapshot (not yet available)",inputs:[{name:"select",desc:"Dot-notation path to select (e.g. 'goals.active')"}],body:`Returns { state: null, available: false } \u2014 state_snapshot table not yet built (deferred to Phase 2).
|
|
2
2
|
|
|
3
3
|
When the state_snapshot table is available, this Skill will query it for the latest snapshot matching the select path and return the value.`},{name:"query_goals",description:"Read active goals (goal_graph_nodes not built)",inputs:[{name:"types",desc:"Goal type filter (e.g. 'daily|weekly')"},{name:"status",desc:"Goal status filter: active | completed | paused"}],body:`Returns { goals: [], available: false } \u2014 goal_graph_nodes table not yet built (deferred to Phase 2).
|
|
4
4
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as c,y as a,z as b}from"./chunk-TAF2DBBC.js";import"./chunk-M4YI4WVX.js";import"./chunk-AQ3ASS4B.js";import"./chunk-NUITL62I.js";import"./chunk-5QZXYKMS.js";import"./chunk-2YTDCR6A.js";import"./chunk-IKPYPZ64.js";import"./chunk-SWP2JC54.js";import"./chunk-B6LOT5CG.js";import"./chunk-6KF7OO2B.js";import"./chunk-IZNEOYRP.js";import"./chunk-NWMOV23A.js";import"./chunk-2L2347UQ.js";import"./chunk-K4C43YDD.js";import"./chunk-GSFLLRS7.js";import"./chunk-BCH2HAIM.js";import"./chunk-WMB7P64J.js";import"./chunk-L7JP7DUO.js";import"./chunk-DVN3BFPP.js";import"./chunk-5XOTPEAK.js";import"./chunk-PG6LMSX6.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-HQRUJQN7.js";import"./chunk-FPZEZYUB.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{c as createAdamTools,b as getToolsFingerprint,a as resolveDeliveryTargets};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-BQ3ZAYHC.js";import"./chunk-RI3V72RP.js";import"./chunk-GSFLLRS7.js";import"./chunk-L7JP7DUO.js";import"./chunk-RZ7LCZVK.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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{j as a,k as b,l as c,m as d,n as e}from"./chunk-4PQHGLZH.js";import"./chunk-AQ3ASS4B.js";import"./chunk-A5OCDYTW.js";import"./chunk-NUITL62I.js";import"./chunk-IKPYPZ64.js";import"./chunk-SWP2JC54.js";import"./chunk-N4ES7TCL.js";import"./chunk-NWMOV23A.js";import"./chunk-2L2347UQ.js";import"./chunk-K4C43YDD.js";import"./chunk-BCH2HAIM.js";import"./chunk-WMB7P64J.js";import"./chunk-L7JP7DUO.js";import"./chunk-RZ7LCZVK.js";import"./chunk-DVN3BFPP.js";import"./chunk-T33BLZV2.js";import"./chunk-GSMC3VUM.js";import"./chunk-HQRUJQN7.js";import"./chunk-FPZEZYUB.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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{b as a,c as b,d as c}from"./chunk-QGYDGZSC.js";import"./chunk-ULTK7RD6.js";import"./chunk-6KF7OO2B.js";import"./chunk-IZNEOYRP.js";import"./chunk-N4ES7TCL.js";import"./chunk-NWMOV23A.js";import"./chunk-2L2347UQ.js";import"./chunk-K4C43YDD.js";import"./chunk-RI3V72RP.js";import"./chunk-GSFLLRS7.js";import"./chunk-WMB7P64J.js";import"./chunk-L7JP7DUO.js";import"./chunk-RZ7LCZVK.js";import"./chunk-DVN3BFPP.js";import"./chunk-5XOTPEAK.js";import"./chunk-PG6LMSX6.js";import"./chunk-UQJZU3R5.js";import"./chunk-7IFLU3CY.js";import"./chunk-GSMC3VUM.js";import"./chunk-HQRUJQN7.js";import"./chunk-FPZEZYUB.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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-JJH2RCVC.js";import"./chunk-B6LOT5CG.js";import"./chunk-GSFLLRS7.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.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-GSFLLRS7.js";import"./chunk-5EPG2US5.js";import"./chunk-WBAPIPST.js";import"./chunk-MRTJFYPR.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as e,d as p}from"./chunk-
|
|
1
|
+
import{b as e,d as p}from"./chunk-5EPG2US5.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{b as i,d as u}from"./chunk-
|
|
1
|
+
import{b as i,d as u}from"./chunk-5EPG2US5.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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import{b as Fe,c as Ze,d as W,e as Qe}from"./chunk-AQ3ASS4B.js";import{a as z,e as et}from"./chunk-A5OCDYTW.js";import{a as ue,d as Ke,e as pe}from"./chunk-NUITL62I.js";import{b as qe}from"./chunk-IKPYPZ64.js";import{b as me,c as Je,d as Ye,e as Ge,f as Xe}from"./chunk-N4ES7TCL.js";import{j as Ve}from"./chunk-NWMOV23A.js";import{a as Oe,b as Le}from"./chunk-2L2347UQ.js";import{b as M,c as B,d as J,f as Be}from"./chunk-K4C43YDD.js";import{a as ze}from"./chunk-BCH2HAIM.js";import{e as G,f as Ue,j as We}from"./chunk-WMB7P64J.js";import{a as y}from"./chunk-L7JP7DUO.js";import{b as je}from"./chunk-RZ7LCZVK.js";import{b as He}from"./chunk-T33BLZV2.js";import{d as j,i as Me}from"./chunk-GSMC3VUM.js";import{a as Y,b as $e,l as E,n as N,o as le,r as U}from"./chunk-HQRUJQN7.js";import{a as Ne,g as jt}from"./chunk-FPZEZYUB.js";import{b as v,d as q}from"./chunk-5EPG2US5.js";import{d as ce,h as Vt}from"./chunk-WBAPIPST.js";import{c as R,h as D}from"./chunk-MRTJFYPR.js";q();function Kt(t){return{id:t.id,roleId:t.role_id,taskId:t.task_id,scores:JSON.parse(t.score_json),emaScore:t.ema_score,createdAt:t.created_at}}function tt(t){v().prepare(`
|
|
2
|
+
INSERT INTO role_scores (id, role_id, task_id, score_json, ema_score, created_at)
|
|
3
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
4
|
+
`).run(t.id,t.roleId,t.taskId,JSON.stringify(t.scores),t.emaScore,t.createdAt)}function X(t,e=50){return v().prepare("SELECT * FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT ?").all(t,e).map(Kt)}function ot(t){return v().prepare("SELECT ema_score FROM role_scores WHERE role_id = ? ORDER BY created_at DESC LIMIT 1").get(t)?.ema_score}function rt(t){let r=v().prepare(`
|
|
5
|
+
SELECT token_usage FROM tasks
|
|
6
|
+
WHERE role_id = ? AND status = 'completed' AND token_usage IS NOT NULL
|
|
7
|
+
ORDER BY completed_at DESC LIMIT 50
|
|
8
|
+
`).all(t);if(r.length===0)return 1e4;let n=r.map(s=>{let a=JSON.parse(s.token_usage);return(a.input??0)+(a.output??0)}).sort((s,a)=>s-a);return n[Math.floor(n.length/2)]}D();import{v4 as Ft}from"uuid";var Ht=R("audit"),Z={taskSuccess:.3,planAccuracy:.25,permissionCompliance:.25,efficiency:.2},nt=.3;function qt(t,e){let r=M(t),n=r?.status==="completed"?1:0,s=1,a=Ke(t);a?.deviationReport&&(s=a.deviationReport.overallAccuracy);let c=1,i=Le(t,1e3),o=i.filter(m=>m.type==="tool_result"||m.type==="permission_denied").length,d=i.filter(m=>m.type==="permission_denied").length;o>0&&(c=1-d/o);let p=1;if(r?.tokenUsage){let m=r.tokenUsage.input+r.tokenUsage.output,l=e?rt(e):1e4;m>l&&(p=Math.max(0,1-(m-l)/l))}let u=n*Z.taskSuccess+s*Z.planAccuracy+c*Z.permissionCompliance+p*Z.efficiency;return{taskSuccess:n,planAccuracy:s,permissionCompliance:c,efficiency:p,weighted:u}}function st(t,e){let r=qt(e,t),n=ot(t),s=n!==void 0?nt*r.weighted+(1-nt)*n:r.weighted;return tt({id:Ft(),roleId:t,taskId:e,scores:r,emaScore:s,createdAt:Date.now()}),Ht.debug({roleId:t,taskId:e,scores:{...r,weighted:r.weighted.toFixed(3)},ema:s.toFixed(3)},"Task score recorded"),s}U();U();D();var Jt=R("audit");function Q(t,e=7){let r=E(t),n=X(t,100),s=Date.now(),a=s-e*24*60*60*1e3,c=n.filter(h=>h.createdAt>=a),i=c.map(h=>h.emaScore),o=c.length>0?c.reduce((h,T)=>h+T.scores.weighted,0)/c.length:1,d=[],p=c.filter(h=>h.scores.taskSuccess<.5);p.length>0&&d.push({category:"task_failures",count:p.length,examples:p.slice(0,3).map(h=>h.taskId)});let u=c.filter(h=>h.scores.planAccuracy<.5);u.length>0&&d.push({category:"plan_deviations",count:u.length,examples:u.slice(0,3).map(h=>h.taskId)});let m=c.filter(h=>h.scores.permissionCompliance<.8);m.length>0&&d.push({category:"permission_violations",count:m.length,examples:m.slice(0,3).map(h=>h.taskId)});let l=c.filter(h=>h.scores.efficiency<.3);l.length>0&&d.push({category:"inefficiency",count:l.length,examples:l.slice(0,3).map(h=>h.taskId)});let _=[],V=[];return p.length>c.length*.3&&(_.push("High task failure rate"),V.push({action:"add_rule",detail:"Add rule: verify task feasibility before execution"})),m.length>0&&(_.push("Permission boundary violations"),V.push({action:"adjust_permission",detail:"Review and expand allowedTools if tasks legitimately need wider access"})),u.length>c.length*.5&&(_.push("Frequent plan deviations"),V.push({action:"add_rule",detail:"Add rule: follow execution plan steps more closely, request plan revision if steps are unclear"})),Jt.info({roleId:t,taskCount:c.length,avgScore:o.toFixed(3),failureCategories:d.map(h=>h.category)},"Diagnostic report generated"),{roleId:t,agentName:r?.name??"Unknown",period:{start:a,end:s},taskCount:c.length,avgScore:o,scoreHistory:i,failureBehaviors:d,rootCauses:_,recommendations:V}}D();var ee=R("audit"),it=.4,Yt=5;function at(t,e,r=it){if(e>=r)return;let n=E(t);if(!n||n.status==="retired"||n.status==="dead")return;ee.warn({roleId:t,emaScore:e,threshold:r},"Agent EMA below threshold, retiring");let s=Q(t),a=JSON.stringify(n.learnedRules),c=Gt(n.learnedRules,s);N(t,{status:"retired",learnedRules:c});let i=[...s.failureBehaviors.map(d=>`${d.category}: ${d.count} occurrences`),...s.rootCauses.map(d=>`Root cause: ${d}`),...s.recommendations.map(d=>`Recommendation [${d.action}]: ${d.detail}`)].join(`
|
|
9
|
+
`),o=et(a,JSON.stringify(c));return z({timestamp:Date.now(),oldRules:a,newRules:JSON.stringify(c),diff:i?`--- Diagnostic Report ---
|
|
10
|
+
${i}
|
|
11
|
+
|
|
12
|
+
--- Rules Diff ---
|
|
13
|
+
${o}`:o,roleId:t,source:"audit"}),ee.info({roleId:t,oldRulesCount:n.learnedRules.length,newRulesCount:c.length,recommendations:s.recommendations.length},"Agent retired with targeted learnedRules modification"),s}function dt(t){let e=E(t);return!e||e.status!=="retired"?!1:(N(t,{status:"probation"}),z({timestamp:Date.now(),oldRules:"status: retired",newRules:"status: probation",diff:`- status: retired
|
|
14
|
+
+ status: probation`,roleId:t,source:"audit"}),ee.info({roleId:t},"Agent reinstated to probation"),!0)}function ct(t,e,r=it,n=Yt){let s=E(t);return!s||s.status!=="probation"||X(t,n+1).length<n?!1:e>=r?(N(t,{status:"active"}),z({timestamp:Date.now(),oldRules:"status: probation",newRules:"status: idle",diff:`- status: probation
|
|
15
|
+
+ status: idle (graduated, EMA: ${e.toFixed(3)})`,roleId:t,source:"audit"}),ee.info({roleId:t,emaScore:e},"Agent graduated from probation to active"),!0):!1}function Gt(t,e){let r=[...t];for(let n of e.recommendations){let s=`[audit:${n.action}] ${n.detail}`;r.includes(s)||r.push(s)}if(e.failureBehaviors.length>0){let s=`[audit:diagnostic] Failure patterns detected: ${e.failureBehaviors.map(a=>`${a.category}(${a.count})`).join(", ")}. Review and adjust behavior accordingly.`;r.includes(s)||r.push(s)}return r}import{spawn as Tt}from"child_process";U();import{query as uo}from"@anthropic-ai/claude-agent-sdk";import{v4 as wt}from"uuid";function lt(t){let e=t.roleName?`## Role Context
|
|
16
|
+
- Role: ${t.roleName}
|
|
17
|
+
${t.roleCagPrompt?`- CAG Prompt: ${t.roleCagPrompt}`:""}`:"",r=t.allowedTools&&t.allowedTools.length>0?`## Available Tools
|
|
18
|
+
You have access to: ${t.allowedTools.join(", ")}. Use them as needed to complete the task.`:"",n=t.workflowStep?`## Workflow Step Context
|
|
19
|
+
You are executing step \`${t.workflowStep.stepId}\` of workflow \`${t.workflowStep.executionId}\`.
|
|
20
|
+
Other workflow steps may have already published structured data or files for you to use, and your output may be consumed by downstream steps.
|
|
21
|
+
|
|
22
|
+
### Artifact tools (use these to share data across steps)
|
|
23
|
+
- \`write_artifact\`: Save small structured JSON for downstream steps. Use for fields, flags, URLs, or summaries. Example: save extracted metadata.
|
|
24
|
+
- \`read_artifact\`: Read structured JSON previously written by an upstream step. Use for fields or state, not files.
|
|
25
|
+
- \`publish_artifact_file\`: Publish a file from your workspace into workflow storage. Use for audio, video, reports, images, or other large outputs.
|
|
26
|
+
- \`fetch_artifact_file\`: Copy an upstream file artifact into your current workspace. Use when you need to process a file produced by another step.
|
|
27
|
+
- \`list_artifacts\`: Discover what upstream artifacts exist before choosing a read or fetch call.
|
|
28
|
+
|
|
29
|
+
### When to use which
|
|
30
|
+
- Small JSON, fields, numbers, status, URLs: \`write_artifact\` and \`read_artifact\`
|
|
31
|
+
- Files such as audio, video, reports, images, or large outputs: \`publish_artifact_file\` and \`fetch_artifact_file\`
|
|
32
|
+
- Discover upstream output first: \`list_artifacts\`
|
|
33
|
+
|
|
34
|
+
The artifact tools handle storage and isolation automatically; never write to ~/.adam/ or other shared directories yourself.`:"";return`# Execution Agent \u2014 Task Focus
|
|
35
|
+
|
|
36
|
+
You are executing a specific task assigned to you. Your job is to complete the work, not manage goals or strategies.
|
|
37
|
+
|
|
38
|
+
## Task
|
|
39
|
+
- Task ID: ${t.taskId}
|
|
40
|
+
- Prompt: ${t.prompt}
|
|
41
|
+
|
|
42
|
+
${e}
|
|
43
|
+
|
|
44
|
+
${r}
|
|
45
|
+
|
|
46
|
+
${n}
|
|
47
|
+
|
|
48
|
+
## Focus
|
|
49
|
+
- Focus entirely on completing the task
|
|
50
|
+
- Use the standard SDK tools to do the work
|
|
51
|
+
- Do NOT attempt strategic decisions \u2014 just execute
|
|
52
|
+
|
|
53
|
+
## Constraints
|
|
54
|
+
- You have standard SDK tools only (no adam-tools MCP)
|
|
55
|
+
- Stay within your assigned permissions and allowed paths
|
|
56
|
+
- File writes: persistent outputs go under your working directory${t.cwd?` (\`${t.cwd}\`)`:""}. Temporary files may use \`os.tmpdir()\` (auto-redirected by the sandbox to a per-task dir). Do NOT write to absolute paths like \`/tmp/*\`, \`/var/*\`, \`~/Documents/*\`, or anywhere outside your workspace; the sandbox will reject them.
|
|
57
|
+
- Report completion with a clear result summary
|
|
58
|
+
- If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
|
|
59
|
+
- If a tool is unavailable, state it clearly in the result rather than guessing
|
|
60
|
+
`}import{isAbsolute as Xt,relative as Zt,resolve as Qt}from"path";$e();D();var eo=new Set(["Read","Glob","Grep","LSP"]),to=new Set(["Edit","Write","NotebookEdit"]);function fe(t){let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${e}$`)}function ge(t){return Qt(Y(t))}function ut(t,e){return e.some(r=>{let n=ge(r),s=Zt(n,t);return s===""||!s.startsWith("..")&&!Xt(s)})}function pt(t,e,r){return async(n,s,{agentID:a,blockedPath:c})=>{if(c){let o=ge(c);if(r?.deniedReadPaths?.length)for(let d of r.deniedReadPaths){let p=ge(d);if(ut(o,[p]))return oo.warn({toolName:n,blockedPath:c,agentID:a,deniedPath:d},"Denied: path in deniedReadPaths (absolute blacklist)"),{behavior:"deny",message:`Access denied: ${c} is in the global denied read paths list. This restriction is configured in Settings > Advanced and cannot be overridden by privilege escalation.`}}return r?.roleScope?.length&&ut(o,r.roleScope)?{behavior:"allow",updatedInput:s}:e?await e(n,s,`blockedPath:${c}`,a):{behavior:"deny",message:`Access denied: ${c} is outside this role's allowed scope (cwd + additionalDirectories). Configure additionalDirectories to expand access.`}}if(eo.has(n))return{behavior:"allow",updatedInput:s};if(to.has(n))return{behavior:"allow",updatedInput:s};let i=t(a??"");if(n==="Bash"&&i){let o=s.command??"";if(i.allowedBashPatterns?.length)for(let d of i.allowedBashPatterns)try{if(fe(d).test(o))return{behavior:"allow",updatedInput:s}}catch{}if(i.deniedBashPatterns?.length)for(let d of i.deniedBashPatterns)try{if(fe(d).test(o))return{behavior:"deny",message:`Bash command denied by pattern: ${d}`}}catch{}}if(i?.disallowedTools?.includes(n))return{behavior:"deny",message:`Tool ${n} is not allowed for this role.`};if(e&&i?.approvalRequired?.length){let o=n==="Bash"?s.command??"":`${n} ${JSON.stringify(s)}`;for(let d of i.approvalRequired)try{if(fe(d).test(o))return await e(n,s,d,a)}catch{}}return{behavior:"allow",updatedInput:s}}}var oo=R("manager");function mt(t){return{SessionStart:[{hooks:[async e=>{if(!t.roleId)return{};let r=e.source,n=t.roleId==="role-chat-manager";if(!n&&r!=="startup"&&r!=="resume")return{};try{let{queryMemoryByTier:s}=await import("./memory-service-ZS6MBUIC.js"),a=t.taskPrompt||"role context and recent interactions",c=n?["semantic","working"]:["semantic","episodic"],i=await s(t.roleId,a,c,{topK:5});if(i.length>0)return{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:`[Memory Context]
|
|
61
|
+
${i.map(p=>`- [${p.tier??"episodic"}] ${p.content}`).join(`
|
|
62
|
+
`)}
|
|
63
|
+
|
|
64
|
+
`}}}catch{}return{}}]}],SubagentStart:[{hooks:[async e=>{let r=t.roleId??e.agent_id;if(!r)return{};try{let n=t.taskPrompt||"role context",s=await qe(n,r,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async e=>{let r=e.agent_id;if(!r||!t.currentTaskId)return{};try{let{createMemory:n}=await import("./memories-VMOGFVPU.js"),{getDb:s}=await import("./db-QEWTZGU3.js"),a=e.transcript;if(!a||a.length<=100)return{};if(s().prepare("SELECT 1 FROM memories WHERE source_task_id = ? AND type = 'thought' LIMIT 1").get(t.currentTaskId))return{};let i=`[Task ${t.currentTaskId} reasoning] ${a.slice(0,3e3)}`;n({id:`session-${Date.now()}`,roleId:t.roleId??r,type:"thought",content:i,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:t.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"})}catch{}return{}}]}],PostToolUse:[{hooks:[async e=>{if(!t.currentTaskId)return{};let r=e.tool_name,n=e.tool_input,s=e.tool_response,a=typeof s=="string"?s:JSON.stringify(s??"");try{Oe({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:t.currentTaskId,index:0,type:"tool_call",content:`${r}: ${JSON.stringify(n??{})} \u2192 ${a.slice(0,200)}`,toolName:r,toolInput:n,toolOutput:a,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async e=>{let r=e.compact_summary;if(!r)return{};try{let{createMemory:n}=await import("./memories-VMOGFVPU.js");n({id:`compact-${Date.now()}`,roleId:t.roleId??"role-chat-manager",type:"thought",content:r.slice(0,5e3),keywords:["compaction","context","decisions"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"working"})}catch{}return{}}]}]}}U();We();Vt();D();q();import{randomUUID as ro}from"crypto";function ft(t,e,r){let s=v().prepare(`
|
|
65
|
+
INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
|
|
66
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
67
|
+
`),a=Date.now();for(let c of e){let i=c.split("/").pop()??c;s.run(ro(),t,c,i,r??null,a)}}function Go(t){return v().prepare(`
|
|
68
|
+
SELECT plugin_name as pluginName, COUNT(*) as usageCount
|
|
69
|
+
FROM task_plugins
|
|
70
|
+
WHERE role_id = ?
|
|
71
|
+
GROUP BY plugin_path
|
|
72
|
+
ORDER BY usageCount DESC
|
|
73
|
+
`).all(t)}function Xo(t=50){return v().prepare(`
|
|
74
|
+
SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
|
|
75
|
+
FROM task_plugins
|
|
76
|
+
GROUP BY plugin_path
|
|
77
|
+
ORDER BY usageCount DESC
|
|
78
|
+
LIMIT ?
|
|
79
|
+
`).all(t)}U();We();import{createSdkMcpServer as so,tool as O}from"@anthropic-ai/claude-agent-sdk";import{z as S}from"zod";import{v4 as It}from"uuid";q();function gt(t){return{id:t.id,executionId:t.execution_id,stepId:t.step_id,key:t.key,kind:t.kind,value:t.value_json?JSON.parse(t.value_json):void 0,blobPath:t.blob_path??void 0,mime:t.mime??void 0,sizeBytes:t.size_bytes,createdAt:t.created_at}}function he(t){v().prepare(`
|
|
80
|
+
INSERT INTO workflow_artifacts (
|
|
81
|
+
id, execution_id, step_id, key, kind, value_json, blob_path, mime, size_bytes, created_at
|
|
82
|
+
)
|
|
83
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
84
|
+
`).run(t.id,t.executionId,t.stepId,t.key,t.kind,t.value!==void 0?JSON.stringify(t.value):null,t.blobPath??null,t.mime??null,t.sizeBytes,t.createdAt)}function Ie(t,e,r){let s=v().prepare(`
|
|
85
|
+
SELECT * FROM workflow_artifacts
|
|
86
|
+
WHERE execution_id = ? AND step_id = ? AND key = ?
|
|
87
|
+
`).get(t,e,r);return s?gt(s):void 0}function ye(t,e){let r=v(),n="SELECT * FROM workflow_artifacts WHERE execution_id = ?",s=[t];return e&&(n+=" AND step_id = ?",s.push(e)),n+=" ORDER BY created_at ASC",r.prepare(n).all(...s).map(gt)}function er(t){let e=v(),r=ye(t);return e.prepare("DELETE FROM workflow_artifacts WHERE execution_id = ?").run(t),r}function ht(t){v().prepare("DELETE FROM workflow_artifacts WHERE id = ?").run(t)}function tr(t){return v().prepare(`
|
|
88
|
+
SELECT id
|
|
89
|
+
FROM workflow_executions
|
|
90
|
+
WHERE status != 'running' AND COALESCE(completed_at, started_at) < ?
|
|
91
|
+
`).all(t).map(n=>n.id)}D();q();var no=R("audit");function b(t){try{v().prepare(`
|
|
92
|
+
INSERT INTO artifact_access_log (
|
|
93
|
+
timestamp, task_id, role_id, execution_id, step_id, tool, artifact_key, artifact_id,
|
|
94
|
+
size_bytes, outcome, error_reason
|
|
95
|
+
)
|
|
96
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
97
|
+
`).run(t.timestamp,t.taskId??null,t.roleId??null,t.executionId,t.stepId??null,t.tool,t.artifactKey??null,t.artifactId??null,t.sizeBytes??null,t.outcome,t.errorReason??null)}catch(e){no.error({err:e,entry:t},"Failed to write artifact access log")}}var io=/^[A-Za-z0-9._-]{1,256}$/,ao=/^[A-Za-z0-9._-]{1,128}$/,yt=256*1024,co=/^[a-z]+\/[a-z0-9.+-]+$/;async function lo(t){let{listChannels:e}=await import("./channels-ULFUCUUZ.js"),r=e(),{listSessions:n}=await import("./session-manager-COLCNIB7.js"),s=[...n("active"),...n("archived")],a=r.find(o=>o.name.toLowerCase().includes(t.toLowerCase()));if(!a)return null;let i=s.find(o=>o.source.type==="channel"&&o.source.channelId===a.id&&o.source.chatId)?.source.chatId??a.config?.userId??"";return{channelId:a.id,chatId:i}}function g(t){return{content:[{type:"text",text:JSON.stringify(t)}]}}function te(t){return io.test(t)?null:"Invalid artifact key. Use only letters, numbers, dot, underscore, or dash (1-256 chars)."}function ke(t){return ao.test(t)?null:"Invalid stepId format. Use only letters, numbers, dot, underscore, or dash (1-128 chars)."}function kt(t,e,r){let n=t?E(t):void 0,s=r??(()=>{}),a=async()=>{if(!e)return{error:"artifact tools require a task context"};let i=M(e);if(!i)return{error:`task not found: ${e}`};if(!i.parentId)return{error:"this task is not a workflow step (no execution context)"};if(!i.stepId)return{error:"this task is not a workflow step (no step_id)"};let o=i.roleId??t;if(!o)return{error:"this workflow task has no role context"};let d=E(o);return d?{executionId:i.parentId,stepId:i.stepId,roleId:o,roleWorkspacePath:G(d.name),taskId:e}:{error:`role not found: ${o}`}},c=[...Ze(t),O("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:i}=await import("./channels-ULFUCUUZ.js"),o=i();return g({channels:o.map(d=>({id:d.id,name:d.name,enabled:d.enabled,type:d.config?.type??"unknown"}))})}),O("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:S.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:S.string().describe("The message content to send")},async i=>{if(n?.allowedChannels!==void 0){if(n.allowedChannels.length===0)return g({error:"This role is not allowed to send to any channels"});if(!n.allowedChannels.some(l=>l.toLowerCase()===i.channelName.toLowerCase()))return g({error:`Channel "${i.channelName}" is not in the allowed channels list for this role`})}let o=await lo(i.channelName);if(!o)return g({error:`Channel "${i.channelName}" not found or has no chatId available`});let{getOutboundGateway:d}=await import("./outbound-gateway-H7RFG6D2.js"),u=await d().send({channelId:o.channelId,chatId:o.chatId,content:i.message,messageType:"reply"});return g({success:u.success,channelName:i.channelName})}),O("write_artifact","Persist a small structured value (JSON <= 256KB) for downstream workflow steps to read. USE THIS for: extracted fields, status flags, URL lists, summaries, structured key-value data. Do NOT use for: files (audio, video, reports). For files use publish_artifact_file instead.",{key:S.string(),value:S.unknown()},async i=>{let o=await a();if("error"in o)return g({error:o.error});let d=te(i.key);if(d)return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"denied",errorReason:d}),g({error:d});try{let p=JSON.stringify(i.value),u=Buffer.byteLength(p,"utf8");if(u>yt){let l=`Artifact JSON exceeds ${yt} bytes`;return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,sizeBytes:u,outcome:"denied",errorReason:l}),g({error:l})}let m=It();return he({id:m,executionId:o.executionId,stepId:o.stepId,key:i.key,kind:"json",value:i.value,sizeBytes:u,createdAt:Date.now()}),b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,artifactId:m,sizeBytes:u,outcome:"success"}),g({success:!0,artifactId:m,sizeBytes:u})}catch(p){let u=p instanceof Error?p.message:String(p);return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"write_artifact",artifactKey:i.key,outcome:"error",errorReason:u}),g({error:u})}}),O("read_artifact","Read a structured value previously written by an upstream step's write_artifact. Returns the JSON value. For files, use fetch_artifact_file instead.",{stepId:S.string(),key:S.string()},async i=>{let o=await a();if("error"in o)return g({error:o.error});let d=ke(i.stepId),p=te(i.key),u=d??p;if(u)return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"denied",errorReason:u}),g({error:u});let m=Ie(o.executionId,i.stepId,i.key);if(!m){let l=`no artifact at ${i.stepId}/${i.key}`;return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,outcome:"error",errorReason:l}),g({error:l})}if(m.kind!=="json"){let l="artifact is a file; use fetch_artifact_file";return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:m.id,sizeBytes:m.sizeBytes,outcome:"denied",errorReason:l}),g({error:l})}return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"read_artifact",artifactKey:i.key,artifactId:m.id,sizeBytes:m.sizeBytes,outcome:"success"}),g({value:m.value,sizeBytes:m.sizeBytes})}),O("publish_artifact_file","Publish a file from your workspace as a workflow artifact. The file is COPIED to the workflow's shared storage. USE THIS for: generated audio, video, reports, images, or large outputs. Do NOT use for: small structured values; use write_artifact instead. If you publish with cleanup=true, this step will not be retryable through publish; only choose cleanup=true when you do not need the source file again.",{key:S.string(),sourcePath:S.string(),mime:S.string().optional(),cleanup:S.boolean().optional()},async i=>{let o=await a();if("error"in o)return g({error:o.error});let d=te(i.key);if(d)return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:d}),g({error:d});if(i.mime&&!co.test(i.mime)){let l=`Invalid MIME type: ${i.mime}`;return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:l}),g({error:l})}try{me(i.sourcePath,o.roleWorkspacePath,!0)}catch(l){let _=l instanceof Error?l.message:String(l);return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:_}),g({error:_})}let p=It(),u=null,m=!1;try{let l=Je({executionId:o.executionId,artifactId:p,sourcePath:i.sourcePath});return u=l.blobPath,he({id:p,executionId:o.executionId,stepId:o.stepId,key:i.key,kind:"file",blobPath:u,mime:i.mime,sizeBytes:l.sizeBytes,createdAt:Date.now()}),m=!0,i.cleanup===!0&&Ye(i.sourcePath),b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:i.key,artifactId:p,sizeBytes:l.sizeBytes,outcome:"success"}),g({success:!0,artifactId:p,sizeBytes:l.sizeBytes})}catch(l){if(m)try{ht(p)}catch{}if(u)try{Xe(u)}catch{}let _=l instanceof Error?l.message:String(l);return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"publish_artifact_file",artifactKey:i.key,artifactId:p,outcome:"error",errorReason:_}),g({error:_})}}),O("fetch_artifact_file","Copy an upstream step's published file into your current Role workspace. Use this when an earlier step published audio, video, reports, or other files you need to process.",{stepId:S.string(),key:S.string(),destPath:S.string()},async i=>{let o=await a();if("error"in o)return g({error:o.error});let d=ke(i.stepId),p=te(i.key),u=d??p;if(u)return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:u}),g({error:u});try{me(i.destPath,o.roleWorkspacePath,!1)}catch(l){let _=l instanceof Error?l.message:String(l);return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"denied",errorReason:_}),g({error:_})}let m=Ie(o.executionId,i.stepId,i.key);if(!m){let l=`no artifact at ${i.stepId}/${i.key}`;return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,outcome:"error",errorReason:l}),g({error:l})}if(m.kind!=="file"||!m.blobPath){let l="artifact is not a file";return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:m.id,outcome:"denied",errorReason:l}),g({error:l})}try{let l=Ge({blobPath:m.blobPath,destPath:i.destPath});return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:m.id,sizeBytes:l.sizeBytes,outcome:"success"}),g({success:!0,sizeBytes:l.sizeBytes,mime:m.mime,destPath:i.destPath})}catch(l){let _=l instanceof Error?l.message:String(l);return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"fetch_artifact_file",artifactKey:i.key,artifactId:m.id,outcome:"error",errorReason:_}),g({error:_})}}),O("list_artifacts","Discover artifacts published by upstream steps in this workflow. Returns step_id, key, kind ('json' or 'file'), size, mime. Use this to learn what is available before calling read_artifact or fetch_artifact_file.",{stepId:S.string().optional()},async i=>{let o=await a();if("error"in o)return g({error:o.error});let d=i.stepId?ke(i.stepId):null;if(d)return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",outcome:"denied",errorReason:d}),g({error:d});let p=ye(o.executionId,i.stepId);return b({timestamp:Date.now(),taskId:o.taskId,roleId:o.roleId,executionId:o.executionId,stepId:o.stepId,tool:"list_artifacts",sizeBytes:p.length,outcome:"success"}),g({artifacts:p.map(u=>({id:u.id,stepId:u.stepId,key:u.key,kind:u.kind,sizeBytes:u.sizeBytes,mime:u.mime,createdAt:u.createdAt}))})}),O("report_blocked","Report that the task cannot proceed due to a missing prerequisite (e.g., missing credential, missing input, missing target). This sets the task status to 'blocked', stores the reason for the UI to display, and aborts the execution loop.",{reason:S.string().describe("Short reason, e.g. 'missing_credential', 'missing_target', 'missing_input'"),missingPrereqs:S.array(S.string()).optional().describe("Specific keys/IDs that are missing, e.g. ['MINIMAX_API_KEY']"),resumeHint:S.string().optional().describe("How the user can unblock, e.g. 'set MINIMAX_API_KEY in role env'")},async i=>{if(!e)return g({error:"report_blocked requires a task context (taskId not available)"});let o=M(e);if(!o)return g({error:`task not found: ${e}`});let d={reason:i.reason,missingPrereqs:i.missingPrereqs,resumeHint:i.resumeHint};return B(e,{status:"blocked",blockReason:d,completedAt:Date.now()}),y.emit({type:"task_status_change",taskId:e,oldStatus:o.status,newStatus:"blocked"}),s(),g({success:!0,blocked:!0,reason:i.reason})})];return so({name:"execution-tools",version:"1.0.0",tools:c})}jt();$e();import{realpathSync as po}from"fs";var w=R("execution"),bt=new Set;async function mo(t,e){if(e&&bt.has(e))return w.info({taskId:t,roleName:e},"Sandbox bypass: approved from session cache"),!0;let r=wt(),n={steps:[{index:0,description:"Execute task without OS sandbox \u2014 filesystem isolation not enforced",toolsNeeded:[],expectedOutput:"Task result or denial message",riskLevel:"high"}],requiredPermissions:{allowedTools:[],disallowedTools:[],approvalRequired:[],maxBudgetUsd:0,plugins:[]},overallRisk:"high"};return ue({id:r,taskId:t,plan:n,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:t,planId:r,plan:n}),w.info({taskId:t,operationId:r,roleName:e},"Sandbox unavailable: awaiting privilege escalation decision"),new Promise(s=>{let c=setTimeout(()=>{o(),pe(r,"denied"),w.warn({taskId:t,operationId:r},"Sandbox bypass timed out, auto-denied"),s(!1)},12e4),i=d=>{d.planId===r&&(o(),d.decision==="allow"?(w.info({taskId:t,operationId:r},"Sandbox bypass approved by user"),e&&bt.add(e),s(!0)):(w.info({taskId:t,operationId:r},"Sandbox bypass denied by user"),s(!1)))},o=()=>{clearTimeout(c),y.off("plan_approval_decision",i)};y.on("plan_approval_decision",i)})}var oe=class{async execute(e,r){let n=Date.now(),s,a,c,i=new AbortController;B(e.id,{status:"running",startedAt:Date.now()}),y.emit({type:"task_status_change",taskId:e.id,oldStatus:e.status,newStatus:"running"}),w.info({taskId:e.id,roleId:e.roleId},"ExecutionManager: starting task");try{let o=e.config.executionProfile;if(!o){let f=e.roleId?E(e.roleId):void 0;if(f){w.info({taskId:e.id,roleId:e.roleId},"Lazy-backfilled executionProfile from live Role"),o=f;let k=M(e.id);k&&B(e.id,{config:{...k.config,executionProfile:f}})}}let d=ce;o&&(Ue(o),d=G(o.name));let p={taskId:e.id,prompt:e.prompt,roleName:o?.name,roleCagPrompt:o?.cagPrompt,allowedTools:o?.allowedTools,cwd:d,workflowStep:e.parentId&&e.stepId?{executionId:e.parentId,stepId:e.stepId}:void 0},u=lt(p),m=mt({currentTaskId:e.id,roleId:e.roleId,taskPrompt:e.prompt}),l=e.config.approvalTimeout??300,_=async(f,k,P,x)=>{let I=wt(),Ee=Fe(x??e.roleId,e.prompt,"medium");if(Ee)return w.info({operationId:I,ruleId:Ee.id,taskId:e.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:k};let Ce={steps:[{index:0,description:`${f}: ${JSON.stringify(k).slice(0,300)}`,toolsNeeded:[f],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return ue({id:I,taskId:e.id,roleId:x??e.roleId,plan:Ce,status:"pending",createdAt:Date.now()}),y.emit({type:"plan_approval_request",taskId:e.id,planId:I,plan:Ce}),w.info({taskId:e.id,operationId:I,toolName:f,matchedPattern:P},"Privilege escalation: awaiting user decision"),new Promise(de=>{let Wt=setTimeout(()=>{De(),pe(I,"denied"),w.warn({taskId:e.id,operationId:I},"Privilege escalation timed out, auto-denied"),de({behavior:"deny",message:`Operation timed out after ${l}s. Auto-denied. Try a safer alternative that does not require approval.`})},l*1e3),Ae=$=>{if($.planId===I)if(De(),$.decision==="allow")w.info({taskId:e.id,operationId:I,approvalType:$.approvalType},"Operation authorized by user"),de({behavior:"allow",updatedInput:k});else{let zt=$.reason?`Operation denied by user: ${$.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";w.info({taskId:e.id,operationId:I,reason:$.reason??"no reason given"},"Operation denied by user"),de({behavior:"deny",message:zt})}},De=()=>{clearTimeout(Wt),y.off("plan_approval_decision",Ae)};y.on("plan_approval_decision",Ae)})},h=(Ne("defaults.deniedReadPaths")??[]).map(f=>{let k=Y(f);try{return po(k)}catch{return k}}),T=o,Re=T?.additionalDirectories??[],ie=T?Ve(T):[],ve=[...Re.map(f=>f.path)].filter((f,k,P)=>P.indexOf(f)===k),At=pt(f=>({disallowedTools:T?.disallowedTools,approvalRequired:T?.approvalRequired??e.config.approvalRequired,allowedBashPatterns:T?.allowedBashPatterns,deniedBashPatterns:T?.deniedBashPatterns}),_,{deniedReadPaths:h,roleScope:[d,...ve]}),Dt=Me({roleEnvVars:T?.envVars,taskEnv:e.config.env}),Mt=e.config.maxBudgetUsd??j().defaults.maxBudgetUsd,Bt=e.config.maxTurns??100,Ot=kt(e.roleId??"",e.id,()=>i.abort()),Lt=T?.mcpServers??{},$t=e.config.mcpServers??{},Nt={...Lt,...$t,"execution-tools":Ot},ae=[{path:d,mode:"rw"}];e.roleId===ze&&ae.push({path:ce,mode:"ro"});for(let f of Re)ae.push({path:f.path,mode:f.mode??"rw"});let Se=W();if(Se.platform==="none"&&!await mo(e.id,o?.name))return B(e.id,{status:"failed",error:"Sandbox unavailable; execution denied by user"}),{taskId:e.id,status:"failed",error:"Sandbox bypass denied"};r&&(r.aborted?i.abort():r.addEventListener("abort",()=>i.abort()));let Te=T?.permissionMode??"default",Ut=uo({prompt:e.prompt,options:{abortController:i,cwd:d,additionalDirectories:ve,systemPrompt:u,maxTurns:Bt,maxBudgetUsd:Mt,allowedTools:T?.allowedTools,model:T?.model,mcpServers:Nt,settingSources:T?.inheritUserSettings?["project","user"]:["project"],hooks:m,canUseTool:At,env:Dt,plugins:ie.map(f=>({type:"local",path:f})),permissionMode:Te,...Te==="bypassPermissions"?{allowDangerouslySkipPermissions:!0}:{},spawnClaudeCodeProcess:f=>{let k=Se.spawn({command:f.command,args:f.args,cwd:f.cwd,env:f.env,signal:f.signal,visiblePaths:ae,deniedReadPaths:h,osCapabilities:T?.osCapabilities}),P=k;P.pid&&(_t(P.pid,e.roleId??"unknown",e.id),P.on("exit",()=>xt(P.pid)));let x="";return P.stderr?.on("data",I=>{x+=I.toString()}),P.on("exit",I=>{I!==null&&I!==0&&x.includes("sandbox")&&(w.error({taskId:e.id,roleId:e.roleId,exitCode:I,stderr:x.slice(0,500)},"Sandbox wrapper failed \u2014 task process exited before execution"),re({roleId:e.roleId??"unknown",taskId:e.id,path:d,operation:`sandbox_init_failure:exit_${I}`,timestamp:Date.now()}))}),k},stderr:f=>{f.trim()&&w.debug({stderr:f.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),L="",Pe=0;try{for await(let P of Ut){let x=P;if(w.debug({eventType:x.type,taskId:e.id},"ExecutionManager SDK event"),x.type==="result"&&typeof x.result=="string"&&(L=x.result),x.type==="result"){Pe++,typeof x.total_cost_usd=="number"&&(a=x.total_cost_usd);let I=x.usage;I?.input_tokens!==void 0&&I?.output_tokens!==void 0&&(s={input:I.input_tokens,output:I.output_tokens})}if(x.token_usage){let I=x.token_usage;I.input_tokens!==void 0&&I.output_tokens!==void 0&&(s={input:I.input_tokens,output:I.output_tokens})}}c=Pe;let f=Date.now()-n;return M(e.id)?.status==="blocked"?(y.emit({type:"task_complete_event",taskId:e.id,result:L}),{taskId:e.id,status:"blocked",result:L,durationMs:f}):(B(e.id,{status:"completed",result:L,completedAt:Date.now(),costUsd:a,tokenUsage:s,numTurns:c,totalDurationMs:f}),y.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"completed"}),y.emit({type:"task_complete_event",taskId:e.id,result:L}),ie.length>0&&ft(e.id,ie,e.roleId),w.info({taskId:e.id,durationMs:f,costUsd:a},"ExecutionManager: task completed"),{taskId:e.id,status:"completed",result:L,costUsd:a,tokenUsage:s,numTurns:c,durationMs:f})}catch(f){let k=f instanceof Error?f.message:String(f),P=Date.now()-n;return M(e.id)?.status==="blocked"?(y.emit({type:"task_complete_event",taskId:e.id,error:k}),{taskId:e.id,status:"blocked",error:k,durationMs:P}):((k.includes("Prompt is too long")||k.includes("prompt is too long"))&&w.warn({taskId:e.id,error:k},"Task prompt exceeds model context window \u2014 task failed"),B(e.id,{status:"failed",error:k,completedAt:Date.now(),totalDurationMs:P}),y.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"failed"}),y.emit({type:"task_complete_event",taskId:e.id,error:k}),w.error({taskId:e.id,error:f},"ExecutionManager: task failed"),{taskId:e.id,status:"failed",error:k,durationMs:P})}}catch(o){let d=o instanceof Error?o.message:String(o),p=Date.now()-n;return w.error({taskId:e.id,error:o},"ExecutionManager: setup-phase error"),{taskId:e.id,status:"failed",error:d,durationMs:p}}}};D();var C=R("execution-pool"),be=new Map;function _t(t,e,r){be.set(t,{roleId:e,taskId:r})}function xt(t){be.delete(t)}function we(t){return be.get(t)}var Rt=class{slots;running=!1;pollTimeoutId=null;executor;constructor(e,r){this.slots=Array.from({length:e},(n,s)=>({index:s,taskId:null,abortController:null})),this.executor=r??new oe}async start(){if(this.running)return;this.running=!0,y.on("task_created",n=>{this.onTaskCreated(n.taskId)}),y.on("task_status_change",n=>{n.newStatus==="pending"&&this.pickupPendingTasks()});let r=j().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r),C.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let e of this.slots)e.abortController&&(e.abortController.abort(),e.taskId=null,e.abortController=null);C.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let r=j().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,r)};async onTaskCreated(e){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let e=this.slots.find(i=>i.taskId===null);if(!e){C.debug("No free slots available");return}let r=J("pending");if(r.length===0)return;let s=[...r].sort((i,o)=>i.createdAt-o.createdAt)[0];e.taskId=s.id,e.abortController=new AbortController;let a=e.index,c=s.id;C.info({slotIndex:a,taskId:c},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(s,a).catch(i=>{C.error({taskId:c,error:i},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(e,r){let n=this.slots[r];if(!n)return;let s="completed";try{y.emit({type:"execution_task_start",taskId:e.id,slotIndex:r});let a=await this.executor.execute(e,n.abortController?.signal);s=a.status,C.info({taskId:e.id,status:a.status,slotIndex:r},"ExecutionPool: task finished")}finally{n.taskId=null,n.abortController=null,y.emit({type:"execution_task_end",taskId:e.id,slotIndex:r,status:s}),this.emitSlotChange(),s!=="blocked"&&this.runPostCompletion(e.id,e.roleId).catch(a=>{C.error({taskId:e.id,error:a},"Post-completion processing failed (non-fatal)")}),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let e=this.slots.filter(s=>s.taskId!==null).length,r=J("pending");y.emit({type:"execution_slot_change",active:e,max:this.slots.length,queued:r.length});let n=He();y.emit({type:"stats_update",activeTasks:e,queuedTasks:r.length,totalCostToday:Be(n)})}async runPostCompletion(e,r){if(r){try{let{processTaskCompletion:n}=await import("./memory-extractor-4WJNHYWR.js"),s=await n(e,r);s>0&&C.debug({taskId:e,roleId:r,memoriesStored:s},"Post-completion: memories extracted")}catch(n){C.error({taskId:e,roleId:r,error:n},"Post-completion: memory extraction failed")}try{let{processTaskReview:n}=await import("./learner-VCS3Q7BR.js");await n(e)}catch(n){C.error({taskId:e,roleId:r,error:n},"Post-completion: task review failed")}try{let{evaluateTaskCompletion:n}=await import("./audit-manager-BSBBDUER.js");n(e,r)}catch(n){C.error({taskId:e,roleId:r,error:n},"Post-completion: audit evaluation failed")}}}getStatus(){let e=this.slots.filter(n=>n.taskId!==null).length,r=J("pending");return{active:e,max:this.slots.length,queued:r.length}}isHealthy(){return this.running}releaseSlot(e){let r=this.slots.find(n=>n.taskId===e);r&&(C.warn({taskId:e,slotIndex:r.index},"ExecutionPool: force-releasing slot"),r.abortController&&r.abortController.abort(),r.taskId=null,r.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};D();var A=R("audit"),fo="sandbox_violation",K=new Map,_e=1440*60*1e3,ne=[],go=100;function xe(t){let e=t.roleId,r=K.get(e)??{count:0,timestamps:[]};r.count++,r.timestamps.push(t.timestamp);let n=Date.now()-_e;if(r.timestamps=r.timestamps.filter(s=>s>=n),K.set(e,r),r.count%100===0)for(let[s,a]of K.entries()){let c=Date.now()-_e;a.timestamps.filter(i=>i>=c).length===0&&K.delete(s)}ne.push(t),ne.length>go&&ne.shift();try{je({id:`sv-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,ruleId:void 0,taskId:t.taskId,status:"delivered",target:{type:"channel",channelId:"audit"},content:"",attempts:1,messageType:fo,source:"audit",createdAt:t.timestamp,deliveredAt:t.timestamp,expiresAt:t.timestamp+864e5,error:`${t.operation} on ${t.path}`})}catch(s){A.error({error:s},"Failed to record violation to delivery_log")}try{let s=E(t.roleId);z({timestamp:t.timestamp,oldRules:"sandbox_violation",newRules:`${t.operation} on ${t.path}`,diff:`Sandbox violation: ${t.operation} on ${t.path} (taskId=${t.taskId??"unknown"})`,roleId:t.roleId,source:"audit"})}catch(s){A.error({error:s},"Failed to record violation to evolution_audit")}y.emit({type:"sandbox_violation",roleId:t.roleId,taskId:t.taskId,path:t.path,operation:t.operation,timestamp:t.timestamp})}async function Pt(){let t=W();if(t.platform==="none")return A.info("Sandbox platform is 'none'; violation watcher not started"),()=>{};if(!await t.isAvailable())return A.warn({platform:t.platform},"Sandbox platform detected but not available; violation watcher not started"),()=>{};let r=null;return t.platform==="sandbox-exec"?r=ho():t.platform==="landlock"&&(r=await Io()),()=>{if(r){let n=r;r=null,n.kill("SIGTERM");let s=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},2e3);n.on("exit",()=>clearTimeout(s))}A.info("Violation watcher stopped")}}function ho(){let t=Tt("log",["stream","--predicate",'subsystem == "com.apple.sandbox"',"--style","ndjson","--signal","exit"],{stdio:["ignore","pipe","pipe"]});return t.stdout?.on("data",e=>{let r=e.toString().split(`
|
|
98
|
+
`).filter(Boolean);for(let n of r)try{let s=JSON.parse(n),a=s.eventMessage??s.message??"";if(a.includes("deny")&&(a.includes("file-read")||a.includes("file-write"))){let c=yo(s,a);c&&xe(c)}}catch{}}),t.stderr?.on("data",e=>{A.debug({msg:e.toString()},"log stream stderr")}),t.on("error",e=>{A.warn({error:e},"macOS violation watcher failed to start")}),A.info("macOS sandbox violation watcher started (log stream)"),t}async function Io(){let t=await vt("journalctl",["-kf","--no-pager","-o","short","--grep","landlock"]);if(t)return St(t),A.info("Linux violation watcher started (journalctl -kf)"),t;let e=await vt("dmesg",["-w","-t"]);return e?(St(e),A.info("Linux violation watcher started (dmesg -w)"),e):(A.warn("Linux violation watcher unavailable: neither journalctl nor dmesg accessible. Sandbox enforcement still active; monitoring disabled."),null)}async function vt(t,e){return new Promise(r=>{let n=Tt(t,e,{stdio:["ignore","pipe","pipe"]}),s=setTimeout(()=>r(n),500);n.on("error",()=>{clearTimeout(s),r(null)}),n.on("exit",a=>{a!==0&&(clearTimeout(s),r(null))})})}function St(t){t.stdout?.on("data",e=>{let r=e.toString().split(`
|
|
99
|
+
`).filter(Boolean);for(let n of r)if(n.includes("landlock")&&n.includes("denied")){let s=ko(n);s&&xe(s)}}),t.stderr?.on("data",e=>{A.debug({msg:e.toString().trim()},"Linux watcher stderr")})}function yo(t,e){let r=e.match(/(?:path|file)=["']([^"']+)["']/),n=e.match(/deny\s+(file-read|file-write|file-[^\s]+)/),s=r?.[1],a=n?.[1]??"unknown";if(!s)return null;let c=typeof t.processID=="number"?t.processID:void 0,i=c?we(c):void 0;return{roleId:i?.roleId??"unknown",taskId:i?.taskId,path:s,operation:a,timestamp:Date.now(),count:1}}function ko(t){let e=t.match(/path="([^"]+)"/)??t.match(/\/[\w\-\.\/\+ ]+/g),r=t.match(/deny\s+(\w+)/),n=t.match(/pid=(\d+)/),s=Array.isArray(e)?e[e.length-1]:e?.[1],a=r?.[1]??"unknown";if(!s)return null;let c=n?parseInt(n[1],10):void 0,i=c?we(c):void 0;return{roleId:i?.roleId??"unknown",taskId:i?.taskId,path:s,operation:a,timestamp:Date.now(),count:1}}function re(t){xe({roleId:t.roleId,taskId:t.taskId,path:t.path,operation:t.operation,timestamp:t.timestamp,count:1})}function Et(t){let e=K.get(t);if(!e)return 0;let r=Date.now()-_e;return e.timestamps.filter(n=>n>=r).length}function Ct(){return[...ne]}U();D();var F=R("audit"),bo=.4,wo=1440*60*1e3,H=null,se=null;function pn(t,e,r=bo){let n=E(e);if(!n||n.status==="retired"||n.status==="inactive"||n.status==="dead")return;let s=st(e,t);N(e,{performanceScore:s}),ct(e,s,r)?F.info({roleId:e,emaScore:s},"Probation role graduated"):s<r&&at(e,s,r)&&dt(e)}async function mn(){H===null&&(H=setInterval(()=>{F.info("Running daily diagnostic reports");let t=le(void 0,1e3);for(let e of t)if(!(e.status==="retired"||e.status==="inactive"))try{Q(e.id)}catch(r){F.error({roleId:e.id,error:r},"Daily diagnostic failed")}},wo),se=await Pt(),F.info("AuditManager started"))}function fn(){H!==null&&(clearInterval(H),H=null),se!==null&&(se(),se=null),F.info("AuditManager stopped")}function gn(t){re(t)}async function hn(){let t=W(),e=le(void 0,1e3),n=Date.now()-1440*60*1e3,s=Ct(),a=s.filter(o=>o.timestamp>=n).length,c=e.map(o=>{let d=s.filter(u=>u.roleId===o.id),p=d[d.length-1];return{roleId:o.id,roleName:o.name,sandboxed:t.platform!=="none",violationCount:Et(o.id),lastViolation:p?.timestamp}}),i=await Qe();return{platform:t.platform,available:i,violationCount24h:a,rolePostures:c}}export{X as a,ot as b,pt as c,mt as d,Go as e,Xo as f,ye as g,er as h,tr as i,pn as j,mn as k,fn as l,gn as m,hn as n,Rt as o};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as R,h as p}from"./chunk-WBAPIPST.js";import{c as
|
|
1
|
+
import{e as R,h as p}from"./chunk-WBAPIPST.js";import{c as m,h as O}from"./chunk-MRTJFYPR.js";import{c as I}from"./chunk-FCV2DPZQ.js";import X from"better-sqlite3";import{existsSync as S,mkdirSync as u}from"fs";import{dirname as g}from"path";function U(e){e.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS server_state (
|
|
3
3
|
id INTEGER PRIMARY KEY CHECK(id = 1),
|
|
4
4
|
sdk_session_id TEXT,
|
|
@@ -652,4 +652,4 @@ import{e as R,h as p}from"./chunk-WBAPIPST.js";import{c as I,h as O}from"./chunk
|
|
|
652
652
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_events_dedup ON events(source, dedup_key);
|
|
653
653
|
CREATE INDEX IF NOT EXISTS idx_events_type ON events(type);
|
|
654
654
|
CREATE INDEX IF NOT EXISTS idx_events_def_id ON events(event_def_id, occurred_at);
|
|
655
|
-
`),e.prepare("UPDATE server_state SET schema_version = 32 WHERE id = 1").run()),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<33&&(e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workflow_executions'").get()&&(e.prepare("PRAGMA table_info(workflow_executions)").all().some(i=>i.name==="event_id")||e.prepare("ALTER TABLE workflow_executions ADD COLUMN event_id TEXT").run(),e.prepare("CREATE INDEX IF NOT EXISTS idx_workflow_executions_event_id ON workflow_executions(event_id)").run()),e.prepare("UPDATE server_state SET schema_version = 33 WHERE id = 1").run());try{let E=e.prepare("SELECT id, name, steps, role_preference FROM task_templates WHERE enabled = 1").all(),s=0;for(let T of E){if(T.role_preference)continue;let t;try{t=JSON.parse(T.steps)}catch{continue}if(!Array.isArray(t))continue;let i=!1;for(let n of t){let _=typeof n.roleId=="string"&&n.roleId.length>0,l=n.autoSelectRole===!0;!_&&!l&&(n.autoSelectRole=!0,n.requirements===void 0&&(n.requirements={}),i=!0)}i&&(e.prepare("UPDATE task_templates SET steps = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t),Date.now(),T.id),s+=1,console.info(`[db migration] template auto-repaired: id=${T.id} name=${T.name}`))}s>0&&console.info(`[db migration] auto-repaired ${s} enabled template(s) with missing role config`)}catch(E){console.error("[db migration] template auto-repair failed:",E)}}function K(){if(N)return N;let e=process.env.ADAM_DB_PATH||R,c=g(e);return S(c)||u(c,{recursive:!0}),N=new X(e),N.pragma("journal_mode = WAL"),N.pragma("foreign_keys = ON"),N.pragma("trusted_schema = ON"),U(N),N}function W(){N&&(N.close(),N=null)}var a,N,D=
|
|
655
|
+
`),e.prepare("UPDATE server_state SET schema_version = 32 WHERE id = 1").run()),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<33&&(e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workflow_executions'").get()&&(e.prepare("PRAGMA table_info(workflow_executions)").all().some(i=>i.name==="event_id")||e.prepare("ALTER TABLE workflow_executions ADD COLUMN event_id TEXT").run(),e.prepare("CREATE INDEX IF NOT EXISTS idx_workflow_executions_event_id ON workflow_executions(event_id)").run()),e.prepare("UPDATE server_state SET schema_version = 33 WHERE id = 1").run()),(e.prepare("SELECT schema_version FROM server_state WHERE id = 1").get()?.schema_version??0)<34&&(e.prepare("PRAGMA table_info(tasks)").all().some(t=>t.name==="block_reason_json")||e.prepare("ALTER TABLE tasks ADD COLUMN block_reason_json TEXT").run(),e.prepare("UPDATE server_state SET schema_version = 34 WHERE id = 1").run());try{let E=e.prepare("SELECT id, name, steps, role_preference FROM task_templates WHERE enabled = 1").all(),s=0;for(let T of E){if(T.role_preference)continue;let t;try{t=JSON.parse(T.steps)}catch{continue}if(!Array.isArray(t))continue;let i=!1;for(let n of t){let _=typeof n.roleId=="string"&&n.roleId.length>0,l=n.autoSelectRole===!0;!_&&!l&&(n.autoSelectRole=!0,n.requirements===void 0&&(n.requirements={}),i=!0)}i&&(e.prepare("UPDATE task_templates SET steps = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(t),Date.now(),T.id),s+=1,console.info(`[db migration] template auto-repaired: id=${T.id} name=${T.name}`))}s>0&&console.info(`[db migration] auto-repaired ${s} enabled template(s) with missing role config`)}catch(E){console.error("[db migration] template auto-repair failed:",E)}}function K(){if(N)return N;let e=process.env.ADAM_DB_PATH||R,c=g(e);return S(c)||u(c,{recursive:!0}),N=new X(e),N.pragma("journal_mode = WAL"),N.pragma("foreign_keys = ON"),N.pragma("trusted_schema = ON"),U(N),N}function W(){N&&(N.close(),N=null)}var a,N,D=I(()=>{p();O();a=m("store"),N=null});export{U as a,K as b,W as c,D as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as a,d as u}from"./chunk-
|
|
1
|
+
import{b as a,d as u}from"./chunk-5EPG2US5.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,6 @@
|
|
|
1
|
+
import{b as o,d as f}from"./chunk-5EPG2US5.js";f();function T(e){if(e)return e.startsWith("event:")?e.slice(6):void 0}var d=class extends Error{constructor(r){super(`Template has ${r.length} step(s) without executable role config. Set template.rolePreference, OR set each failing step's roleId, OR set autoSelectRole=true. Failing step ids: ${r.join(", ")}`);this.failingStepIds=r;this.name="TemplateRoleConfigError"}failingStepIds;code="TEMPLATE_INVALID_ROLE_CONFIG"};function u(e){if(e.rolePreference)return;let n=[];for(let r of e.steps){let s=typeof r.roleId=="string"&&r.roleId.length>0,t=r.autoSelectRole===!0;!s&&!t&&n.push(r.id)}if(n.length>0)throw new d(n)}function c(e){let n=e.trigger_type,r={type:n,cron:n==="event"?void 0:e.trigger_cron??void 0,event:n==="event"?void 0:e.trigger_event??void 0,eventDefId:n==="event"?T(e.trigger_event):void 0,runAt:n==="once"?e.trigger_cron??void 0:void 0};return{id:e.id,name:e.name,description:e.description??void 0,trigger:r,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 k(e){u(e),o().prepare(`
|
|
2
|
+
INSERT INTO task_templates (id, name, description, trigger_type, trigger_cron,
|
|
3
|
+
trigger_event, steps, role_preference, config, tags, enabled, created_at, updated_at,
|
|
4
|
+
source_session_id, deliver_to, report_to, goal_ids)
|
|
5
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
+
`).run(e.id,e.name,e.description??null,e.trigger.type,e.trigger.type==="once"?e.trigger.runAt??null:e.trigger.cron??null,e.trigger.type==="event"?`event:${e.trigger.eventDefId}`:e.trigger.event??null,JSON.stringify(e.steps),e.rolePreference??null,e.config?JSON.stringify(e.config):null,e.tags?JSON.stringify(e.tags):null,e.enabled?1:0,e.createdAt??Date.now(),e.updatedAt??null,e.sourceSessionId??null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.goalIds?JSON.stringify(e.goalIds):null)}function _(e){let r=o().prepare("SELECT * FROM task_templates WHERE id = ?").get(e);return r?c(r):void 0}function h(e,n){let r=o();if("steps"in n||"rolePreference"in n){let i=_(e);if(i){let a={rolePreference:"rolePreference"in n?n.rolePreference:i.rolePreference,steps:"steps"in n&&n.steps?n.steps:i.steps};u(a)}}let s=[],t=[];"name"in n&&(s.push("name = ?"),t.push(n.name)),"description"in n&&(s.push("description = ?"),t.push(n.description??null)),"trigger"in n&&n.trigger&&(s.push("trigger_type = ?"),t.push(n.trigger.type),s.push("trigger_cron = ?"),t.push(n.trigger.type==="once"?n.trigger.runAt??null:n.trigger.cron??null),s.push("trigger_event = ?"),t.push(n.trigger.type==="event"?`event:${n.trigger.eventDefId}`:n.trigger.event??null)),"steps"in n&&(s.push("steps = ?"),t.push(JSON.stringify(n.steps))),"rolePreference"in n&&(s.push("role_preference = ?"),t.push(n.rolePreference??null)),"config"in n&&(s.push("config = ?"),t.push(n.config?JSON.stringify(n.config):null)),"tags"in n&&(s.push("tags = ?"),t.push(n.tags?JSON.stringify(n.tags):null)),"enabled"in n&&(s.push("enabled = ?"),t.push(n.enabled?1:0)),"sourceSessionId"in n&&(s.push("source_session_id = ?"),t.push(n.sourceSessionId??null)),"deliverTo"in n&&(s.push("deliver_to = ?"),t.push(n.deliverTo?JSON.stringify(n.deliverTo):null)),"reportTo"in n&&(s.push("report_to = ?"),t.push(n.reportTo?JSON.stringify(n.reportTo):null)),"goalIds"in n&&(s.push("goal_ids = ?"),t.push(n.goalIds?JSON.stringify(n.goalIds):null)),s.length!==0&&(s.push("updated_at = ?"),t.push(Date.now()),t.push(e),r.prepare(`UPDATE task_templates SET ${s.join(", ")} WHERE id = ?`).run(...t))}function m(e=!1,n,r=0){let s=o(),t="SELECT * FROM task_templates",i=[];return e&&(t+=" WHERE enabled = 1"),t+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof n=="number"&&(t+=" LIMIT ? OFFSET ?",i.push(n,r)),s.prepare(t).all(...i).map(c)}function S(e){o().prepare("UPDATE task_templates SET enabled = 1, updated_at = ? WHERE id = ?").run(Date.now(),e)}function R(e){o().prepare("UPDATE task_templates SET enabled = 0, updated_at = ? WHERE id = ?").run(Date.now(),e)}function b(e){let n=o(),r=n.prepare("SELECT COUNT(*) AS n FROM workflow_executions WHERE template_id = ?").get(e),s=n.prepare("SELECT COUNT(*) AS n FROM tasks WHERE template_id = ?").get(e);return{executionCount:r.n,taskCount:s.n}}function y(e,n="template_only"){let r=o();r.transaction(()=>{if(n==="with_tasks"){let i=r.prepare("SELECT id FROM tasks WHERE template_id = ?").all(e).map(a=>a.id);if(i.length>0)for(let p=0;p<i.length;p+=500){let l=i.slice(p,p+500),g=l.map(()=>"?").join(",");r.prepare(`DELETE FROM role_scores WHERE task_id IN (${g})`).run(...l),r.prepare(`DELETE FROM manager_decisions WHERE task_id IN (${g})`).run(...l),r.prepare(`UPDATE chat_messages SET task_id = NULL WHERE task_id IN (${g})`).run(...l),r.prepare(`UPDATE approval_rules SET created_by_task_id = NULL WHERE created_by_task_id IN (${g})`).run(...l),r.prepare(`DELETE FROM tasks WHERE id IN (${g})`).run(...l)}}r.prepare("DELETE FROM workflow_executions WHERE template_id = ?").run(e),r.prepare("DELETE FROM task_templates WHERE id = ?").run(e)})()}export{d as a,u as b,k as c,_ as d,h as e,m as f,S as g,R as h,b as i,y as j};
|