adam-agent-server 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +129 -81
- package/dist/App-XZABZ2AF.js +9 -0
- package/dist/{adam-tools-Q4BRKX3U.js → adam-tools-RTCTINZI.js} +1 -1
- package/dist/{approval-handler-D3J6NCMM.js → approval-handler-SSKO2IGC.js} +1 -1
- package/dist/{chunk-2VKE7ONM.js → chunk-BQE7XAMQ.js} +1 -1
- package/dist/chunk-KMMC7BEF.js +1 -0
- package/dist/chunk-LBLERTM4.js +3 -0
- package/dist/chunk-T7WVM27S.js +52 -0
- package/dist/cli.js +8 -8
- package/dist/{engine-V5MOGOLN.js → engine-6SFURLSL.js} +1 -1
- package/dist/index.js +14 -14
- package/dist/{outbound-gateway-FIPC4BZO.js → outbound-gateway-UCB57NPJ.js} +1 -1
- package/package.json +1 -1
- package/dist/App-G2WZKRUH.js +0 -9
- package/dist/chunk-EALDBELJ.js +0 -52
- package/dist/chunk-NICRQZ7T.js +0 -1
- package/dist/chunk-UOTDT2KY.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-LBLERTM4.js";import"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
|
package/package.json
CHANGED
package/dist/App-G2WZKRUH.js
DELETED
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{b as T,d as co,e as uo}from"./chunk-NSJAV7IH.js";import{a as At,e as ao,g as lo}from"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{Box as kt,Text as xt,useInput as On}from"ink";import{useState as Vn,useEffect as io,useRef as tr}from"react";import{createContext as ir,useContext as ar,useReducer as lr}from"react";import{jsx as ur}from"react/jsx-runtime";var cr={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",configVersion:0,session:null};function dr(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};default:return e}}var mo=ir(null);function go({children:e}){let[t,o]=lr(dr,cr);return ur(mo.Provider,{value:{state:t,dispatch:o},children:e})}function Xe(){let e=ar(mo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as mr,useRef as gr}from"react";var fr=15e3;function fo(){let{dispatch:e}=Xe(),t=gr(null);mr(()=>{let o=!0,c=null,g=()=>{t.current&&(clearTimeout(t.current),t.current=null)},f=()=>{g(),t.current=setTimeout(()=>{o&&e({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},fr)};return(()=>{try{c=new co("/events"),c.on("task_status_change",()=>{}),c.on("approval_request",i=>{if(!o)return;let s=i;e({type:"SET_PENDING_APPROVAL",approval:{taskId:s.taskId,approvalId:s.approvalId,toolName:s.toolName,toolInput:s.toolInput,matchedPattern:s.matchedPattern}})}),c.on("plan_approval_request",i=>{if(!o)return;let s=i;e({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:s.taskId,planId:s.planId,roleId:s.roleId,plan:s.plan}})}),c.on("plan_approval_decision",()=>{o&&e({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),c.on("config_changed",()=>{o&&e({type:"CONFIG_CHANGED"})}),c.on("stats_update",i=>{if(!o)return;let s=i;e({type:"UPDATE_STATS",activeTasks:s.activeTasks,queuedTasks:s.queuedTasks,costToday:s.totalCostToday})}),c.connect().then(()=>{o&&(g(),e({type:"SET_CONNECTED",connected:!0}),e({type:"SET_SERVER_UNREACHABLE",unreachable:!1}))}).catch(()=>{o&&(e({type:"SET_CONNECTED",connected:!1}),f())})}catch{o&&(e({type:"SET_CONNECTED",connected:!1}),f())}})(),()=>{o=!1,g(),c?.close()}},[e])}import{useEffect as pr,useRef as xr,useState as po,useCallback as Tr}from"react";function xo(e){let[t,o]=po([]),[c,g]=po(!1),f=xr(null),l=Tr(()=>{o([]),g(!1)},[]);return pr(()=>{if(!e)return;let i=!0;o([]),g(!0);try{let s=new uo(e);return f.current=s,s.on("reasoning",r=>{if(!i)return;let d=r.content??"";o(y=>{let u=y[y.length-1];if(u?.type==="reasoning"){let x=[...y];return x[x.length-1]={...u,content:u.content+d},x}return[...y,{type:"reasoning",content:d,timestamp:Date.now()}]})}),s.on("tool_call",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"tool_call",content:m.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:m.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"tool_result",content:m.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"error",content:m.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"complete",content:m.result??"",timestamp:Date.now(),metadata:{cost:m.costUsd,turns:m.numTurns,duration:m.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:c,clearEvents:l}}import{useState as Gt,useEffect as hr,useCallback as ht}from"react";function Ht(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function To(){let[e,t]=Gt(null),[o,c]=Gt(!0),[g,f]=Gt(null),l=ht(async()=>{try{let y=(await T("/chat/sessions?status=active")).sessions.find(u=>u.source.type==="tui");return y?Ht(y):null}catch{return null}},[]),i=ht(async()=>{try{let d=await T("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),y=Ht(d.session);return t(y),y}catch{return f("Failed to create session"),null}},[]),s=ht(async d=>{try{let y=await T("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(u=>u&&{...u,messageCount:u.messageCount+1,lastActiveAt:Date.now()}),y}catch{return null}},[]),r=ht(async()=>{if(!e)return!1;try{return await T(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),m=ht(async()=>{if(e)try{let d=await T(`/chat/sessions/${e.id}`);t(Ht(d.session))}catch{t(null)}},[e]);return hr(()=>{let d=!1;async function y(){c(!0);let u=await l();d||(u?t(u):await i(),d||c(!1))}return y(),()=>{d=!0}},[]),{session:e,loading:o,error:g,sendMessage:s,createNewSession:i,archiveCurrentSession:r,refreshSession:m,setSession:t}}import{Box as jt,Text as ve}from"ink";import Ce from"chalk";var Kt={connected:Ce.green,disconnected:Ce.red,warning:Ce.yellow,reasoning:Ce.gray,toolCall:Ce.blue,toolResult:Ce.green,error:Ce.red,dim:Ce.dim,bold:Ce.bold,statusUp:Ce.green("\u25CF"),statusDown:Ce.red("\u25CF")};import{Fragment as yr,jsx as tt,jsxs as ze}from"react/jsx-runtime";function ho(){let{state:e}=Xe(),t=e.connected?`${Kt.statusUp} Server: up`:`${Kt.statusDown} Disconnected`,o=e.activeTasks>0?`${e.activeTasks} running, ${e.queuedTasks} queued`:"No active tasks",c=e.session,f=(c?Math.floor((Date.now()-c.lastActiveAt)/6e4):1/0)>=25;return ze(jt,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[ze(jt,{children:[tt(ve,{bold:!0,children:"Adam v0.2.0"}),tt(ve,{children:" \u2502 "}),tt(ve,{children:t}),tt(ve,{children:" \u2502 "}),ze(ve,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&ze(yr,{children:[tt(ve,{children:" \u2502 "}),ze(ve,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),f&&tt(ve,{color:"yellow",children:" timeout soon"})]})]}),ze(jt,{children:[ze(ve,{children:["Tasks: ",o]}),tt(ve,{children:" \u2502 "}),ze(ve,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Dt,Text as Rt,useInput as Sr}from"ink";import{useState as Xt,useMemo as Cr}from"react";import vr from"ink-text-input";var br=[{name:"work",description:"Tasks, Automations & Goals"},{name:"config",description:"Configuration"},{name:"evolution",description:"Evolution audit"},{name:"webhooks",description:"Webhook triggers"},{name:"memories",description:"Memory browser"},{name:"strategies",description:"Strategy lab"},{name:"plugins",description:"Plugin management"},{name:"roles",description:"Role management"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function Qt(e){let t=e.toLowerCase();return br.filter(o=>o.name.startsWith(t))}function yo(e){let t=Qt(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Mt,jsxs as yt}from"react/jsx-runtime";function bo({onSubmit:e}){let[t,o]=Xt(""),[c,g]=Xt(0),[f,l]=Xt(!1),i=t.startsWith("/")&&t.length>=1,s=t.slice(1),r=Cr(()=>i?Qt(s):[],[i,s]),m=u=>{o(u),u.startsWith("/")?(l(!0),g(0)):l(!1)},d=()=>{let u=t.trim();if(u){if(u.startsWith("/")){let x=u.slice(1),n=yo(x);e(n?`/${n.name}`:u)}else e(u);o(""),l(!1)}},y=u=>{e(`/${u.name}`),o(""),l(!1)};return Sr((u,x)=>{if(!(!f||!i||r.length===0)){if(x.upArrow){g(n=>n<=0?r.length-1:n-1);return}if(x.downArrow){g(n=>n>=r.length-1?0:n+1);return}if(x.tab){let n=r[c];n&&y(n);return}if(x.escape){l(!1),o("");return}}},{isActive:f&&i&&r.length>0}),yt(Dt,{flexDirection:"column",children:[f&&i&&r.length>0&&Mt(Dt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((u,x)=>{let n=x===c;return yt(Dt,{children:[Mt(Rt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),yt(Rt,{color:n?"cyan":"white",bold:n,children:["/",u.name]}),yt(Rt,{dimColor:!0,children:[" \u2014 ",u.description]})]},u.name)})}),yt(Dt,{borderStyle:"round",borderDimColor:!0,children:[Mt(Rt,{bold:!0,children:"\u25B8 "}),Mt(vr,{value:t,onChange:m,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as it,Text as ge}from"ink";import{useState as Er}from"react";import{jsx as ye,jsxs as Ae}from"react/jsx-runtime";function Br({content:e}){let[t,o]=Er(!1),c=e.split(`
|
|
2
|
-
`);return c.length<=5?ye(ge,{color:"green",children:e}):t?ye(ge,{color:"green",children:e}):Ae(ge,{color:"green",children:[c.slice(0,3).join(`
|
|
3
|
-
`),`
|
|
4
|
-
`,Ae(ge,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function wr({event:e}){switch(e.type){case"reasoning":return ye(it,{children:ye(ge,{color:"gray",children:e.content})});case"tool_call":return ye(it,{children:Ae(ge,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Ae(it,{flexDirection:"column",children:[ye(ge,{color:"blue",dimColor:!0,children:"[result]"}),ye(Br,{content:e.content})]});case"error":return ye(it,{children:Ae(ge,{color:"red",children:["[error] ",e.content]})});case"complete":return Ae(it,{flexDirection:"column",marginTop:1,children:[e.content&&ye(ge,{children:e.content}),ye(ge,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Ae(ge,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Ae(ge,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Ae(ge,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function So({events:e,isStreaming:t}){return e.length===0&&!t?null:Ae(it,{flexDirection:"column",children:[t&&e.length===0&&ye(ge,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>ye(wr,{event:o},c))]})}import{Box as Co,Text as vo}from"ink";import{jsx as zt,jsxs as Ir}from"react/jsx-runtime";function Eo({messages:e}){return e.length===0?null:zt(Co,{flexDirection:"column",children:e.map((t,o)=>Ir(Co,{flexDirection:"column",marginBottom:1,children:[zt(vo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),zt(vo,{children:t.content})]},o))})}import{Box as bt,Text as De,useInput as kr}from"ink";import{jsx as Re,jsxs as St}from"react/jsx-runtime";function Bo({approval:e,onResolved:t}){return kr(o=>{o==="a"?T(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&T(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),St(bt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Re(De,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),St(bt,{marginTop:1,children:[Re(De,{children:"Tool: "}),Re(De,{bold:!0,children:e.toolName})]}),St(bt,{children:[Re(De,{children:"Input: "}),Re(De,{children:JSON.stringify(e.toolInput)})]}),St(bt,{children:[Re(De,{children:"Pattern: "}),Re(De,{dimColor:!0,children:e.matchedPattern})]}),St(bt,{marginTop:1,children:[Re(De,{color:"green",children:"[a] Approve"}),Re(De,{children:" "}),Re(De,{color:"red",children:"[r] Reject"})]})]})}import{Box as Ct,Text as le,useInput as Pr}from"ink";import{useState as Ar,useEffect as Dr}from"react";import{jsx as Oe,jsxs as Ee}from"react/jsx-runtime";var Rr=300;function wo({approval:e,onResolved:t,onTimeout:o}){let[c,g]=Ar(Rr);Dr(()=>{let l=setInterval(()=>{g(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),Pr(l=>{l==="a"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let f=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Ee(Ct,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Oe(le,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Ee(le,{dimColor:!0,children:["Plan ID: ",e.planId]}),Ee(le,{dimColor:!0,children:["Time remaining: ",c,"s"]}),Ee(Ct,{marginTop:1,children:[Oe(le,{children:"Overall Risk: "}),Oe(le,{bold:!0,color:f,children:e.plan.overallRisk.toUpperCase()})]}),Ee(le,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(l=>{let i=l.riskLevel==="high"?"red":l.riskLevel==="medium"?"yellow":"green";return Ee(Ct,{paddingLeft:2,children:[Ee(le,{children:["[",l.index,"] "]}),Oe(le,{children:l.description}),Ee(le,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),Ee(le,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),Ee(Ct,{marginTop:1,children:[Oe(le,{dimColor:!0,children:"Permissions: "}),Oe(le,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Ee(Ct,{marginTop:1,children:[Oe(le,{color:"green",children:"[a] Allow once "}),Oe(le,{color:"green",children:"[p] Allow permanent "}),Oe(le,{color:"red",children:"[r] Deny"})]})]})}import{Box as ot,Text as Z,useInput as Nr}from"ink";import{useEffect as _r,useState as Ve,useCallback as ko}from"react";import{Box as Q,Text as A,useInput as Mr}from"ink";import{useState as Yt,useEffect as Lr}from"react";import{jsx as $,jsxs as F}from"react/jsx-runtime";function Io({taskId:e,onBack:t}){let[o,c]=Yt(null),[g,f]=Yt([]),[l,i]=Yt(null);if(Lr(()=>{T(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),T(`/tasks/${e}/plan`).then(r=>f(r.plans)).catch(()=>f([]))},[e]),Mr((r,m)=>{(r==="b"||m.escape)&&t()}),l)return F(Q,{flexDirection:"column",children:[F(A,{color:"red",children:["Error: ",l]}),$(A,{dimColor:!0,children:"[b] Back"})]});if(!o)return F(A,{dimColor:!0,children:["Loading task ",e,"..."]});let s=g[0];return F(Q,{flexDirection:"column",children:[$(A,{bold:!0,color:"cyan",children:"Task Detail"}),F(Q,{marginTop:1,flexDirection:"column",children:[F(Q,{children:[$(A,{children:"ID: "}),$(A,{dimColor:!0,children:String(o.id)})]}),F(Q,{children:[$(A,{children:"Status: "}),$(A,{bold:!0,children:String(o.status)})]}),F(Q,{children:[$(A,{children:"Prompt: "}),$(A,{children:String(o.prompt)})]}),o.result?F(Q,{children:[$(A,{children:"Result: "}),$(A,{children:String(o.result).slice(0,200)})]}):null,o.error?F(Q,{children:[$(A,{color:"red",children:"Error: "}),$(A,{children:String(o.error)})]}):null,o.deliverTo?.length?F(Q,{children:[$(A,{children:"DeliverTo: "}),$(A,{dimColor:!0,children:o.deliverTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null,o.reportTo?.length?F(Q,{children:[$(A,{children:"ReportTo: "}),$(A,{dimColor:!0,children:o.reportTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null]}),s&&F(Q,{marginTop:1,flexDirection:"column",children:[$(A,{bold:!0,color:"cyan",children:"Execution Plan"}),F(Q,{children:[$(A,{children:"Plan ID: "}),$(A,{dimColor:!0,children:s.id})]}),F(Q,{children:[$(A,{children:"Status: "}),$(A,{children:s.status})]}),s.plan.overallRisk&&F(Q,{children:[$(A,{children:"Overall Risk: "}),$(A,{bold:!0,color:s.plan.overallRisk==="high"?"red":s.plan.overallRisk==="medium"?"yellow":"green",children:s.plan.overallRisk.toUpperCase()})]}),F(A,{bold:!0,children:["Steps (",s.plan.steps.length,"):"]}),s.plan.steps.map(r=>{let m=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return F(Q,{paddingLeft:2,children:[F(A,{children:["[",r.index,"] ",r.description]}),F(A,{color:m,children:[" [",r.riskLevel,"]"]})]},r.index)}),s.deviationReport&&F(Q,{marginTop:1,flexDirection:"column",children:[$(A,{bold:!0,color:"yellow",children:"Deviation Report"}),F(A,{children:["Planned: ",s.deviationReport.stepsPlanned," | Executed: ",s.deviationReport.stepsExecuted," | Accuracy: ",(s.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),s.deviationReport.deviations.map((r,m)=>F(Q,{paddingLeft:2,children:[F(A,{color:"yellow",children:["[",r.deviationType,"] "]}),F(A,{children:["Step ",r.stepIndex,": ",r.actual]})]},m))]}),s.learnedRules&&s.learnedRules.length>0&&F(Q,{marginTop:1,flexDirection:"column",children:[$(A,{bold:!0,color:"blue",children:"Learned Rules"}),s.learnedRules.map((r,m)=>$(Q,{paddingLeft:2,children:F(A,{children:["* ",r]})},m))]})]}),!s&&g.length===0&&$(Q,{marginTop:1,children:$(A,{dimColor:!0,children:"No execution plan for this task."})}),$(Q,{marginTop:1,children:$(A,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as Vr,jsx as ce,jsxs as pe}from"react/jsx-runtime";var $r={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Lt=["all","pending","queued","running","completed","failed","cancelled"],Jt=15;function Nt({onBack:e}){let[t,o]=Ve([]),[c,g]=Ve(!0),[f,l]=Ve("list"),[i,s]=Ve(0),[r,m]=Ve("all"),[d,y]=Ve(0),[u,x]=Ve(0),[n,a]=Ve(null),[P,M]=Ve([]),z=ko(async()=>{g(!0);try{let w=new URLSearchParams({limit:"100"});r!=="all"&&w.set("status",r);let S=await T(`/tasks?${w}`);o(S.tasks)}catch{o([])}finally{g(!1)}},[r]);_r(()=>{z()},[z]);let U=Math.max(1,Math.ceil(t.length/Jt)),D=t.slice(u*Jt,(u+1)*Jt),H=ko(async()=>{let w=D[i];if(w)try{await T(`/tasks/${w.id}/cancel`,{method:"POST"}),a(`Cancelled: ${w.id.slice(0,8)}`),l("list"),z()}catch(S){a(`Failed: ${S instanceof Error?S.message:String(S)}`),l("list")}},[D,i,z]);return Nr((w,S)=>{if(f==="detail"){(S.escape||S.return||w==="q")&&l("list");return}if(f==="cancelling"){w==="y"?H():l("list");return}if(f==="filter"){if(S.escape){l("list");return}S.upArrow&&d>0&&y(p=>p-1),S.downArrow&&d<Lt.length-1&&y(p=>p+1),S.return&&(m(Lt[d]),x(0),s(0),l("list"));return}if(S.escape||w==="q"){e();return}if(S.upArrow&&i>0&&s(p=>p-1),S.downArrow&&i<D.length-1&&s(p=>p+1),S.return){let p=D[i];p&&(M([]),l("detail"),T(`/tasks/${p.id}/logs?limit=20`).then(({logs:I})=>M(I)).catch(()=>M([])))}if(w==="x"&&D[i]){let p=D[i];["running","pending","queued","paused"].includes(p.status)?(l("cancelling"),a(null)):a(`Cannot cancel task in status: ${p.status}`)}w==="f"&&(y(Lt.indexOf(r)),l("filter")),w==="r"&&z(),(S.pageDown||w==="n")&&u<U-1&&(x(p=>p+1),s(0)),(S.pageUp||w==="p")&&u>0&&(x(p=>p-1),s(0))}),c?ce(Z,{dimColor:!0,children:"Loading tasks..."}):f==="filter"?pe(ot,{flexDirection:"column",children:[ce(Z,{bold:!0,children:"Filter by status:"}),Lt.map((w,S)=>ce(ot,{children:pe(Z,{color:S===d?"cyan":"white",children:[S===d?"> ":" ",w,w===r?" (current)":""]})},w)),ce(Z,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):f==="detail"&&D[i]?ce(Io,{taskId:D[i].id,onBack:()=>l("list")}):f==="cancelling"&&D[i]?pe(ot,{flexDirection:"column",children:[pe(Z,{color:"red",children:['Cancel task "',D[i].id.slice(0,8),'"? (y/n)']}),n&&ce(Z,{color:"red",children:n})]}):pe(ot,{flexDirection:"column",children:[pe(ot,{children:[pe(Z,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&pe(Z,{dimColor:!0,children:[" [filter: ",r,"]"]}),pe(Z,{dimColor:!0,children:[" \u2014 Page ",u+1,"/",U]})]}),n&&ce(Z,{color:n.startsWith("Failed")||n.startsWith("Cannot")?"red":"green",children:n}),t.length===0?pe(Z,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):pe(Vr,{children:[ce(ot,{marginTop:1,children:pe(Z,{bold:!0,children:[" ",Ye("ID",10),Ye("STATUS",12),Ye("PROMPT",40),Ye("DURATION",10),"COST"]})}),D.map((w,S)=>{let p=S===i,I=w.totalDurationMs?`${(w.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",L=w.costUsd!==void 0?`$${w.costUsd.toFixed(4)}`:"\u2014",_e=$r[w.status]??"white";return pe(ot,{children:[ce(Z,{color:p?"cyan":"white",children:p?"> ":" "}),ce(Z,{dimColor:!0,children:Ye(w.id.slice(0,8),10)}),ce(Z,{color:_e,children:Ye(w.status,12)}),ce(Z,{children:Ye(Or(w.prompt,38),40)}),ce(Z,{dimColor:!0,children:Ye(I,10)}),ce(Z,{dimColor:!0,children:L})]},w.id)})]}),ce(Z,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function Ye(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Or(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}lo();import{Box as vt,Text as Be,useInput as qr}from"ink";import{useEffect as Ur,useState as Po}from"react";import{readFileSync as Fr,existsSync as Wr}from"fs";import{parse as Gr}from"yaml";import{Fragment as Hr,jsx as we,jsxs as Je}from"react/jsx-runtime";function Do({onBack:e}){let[t,o]=Po(null),[c,g]=Po(null);return qr((f,l)=>{(l.escape||f==="q")&&e()}),Ur(()=>{try{let f=ao;if(!Wr(f)){g(`Config file not found: ${f}`);return}let l=Fr(f,"utf-8");o(Gr(l))}catch(f){g(f.message)}},[]),c?Je(vt,{flexDirection:"column",children:[we(Be,{color:"red",children:c}),we(Be,{dimColor:!0,children:"Press Esc to go back"})]}):t?Je(vt,{flexDirection:"column",children:[we(Be,{bold:!0,children:"Configuration (Esc to go back)"}),we(vt,{marginTop:1,flexDirection:"column",children:we(Ro,{obj:t,indent:0})})]}):we(Be,{dimColor:!0,children:"Loading config..."})}function Ro({obj:e,indent:t}){let o=" ".repeat(t);return we(Hr,{children:Object.entries(e).map(([c,g])=>g&&typeof g=="object"&&!Array.isArray(g)?Je(vt,{flexDirection:"column",children:[Je(Be,{children:[o,we(Be,{color:"cyan",children:c}),":"]}),we(Ro,{obj:g,indent:t+1})]},c):Array.isArray(g)?Je(vt,{flexDirection:"column",children:[Je(Be,{children:[o,we(Be,{color:"cyan",children:c}),":"]}),g.map((f,l)=>Je(Be,{children:[o," - ",Ao(c,String(f))]},l))]},c):Je(Be,{children:[o,we(Be,{color:"cyan",children:c}),": ",Ao(c,String(g))]},c))})}function Ao(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as _t,Text as Ie,useInput as Kr}from"ink";import{useEffect as jr,useState as Zt}from"react";import{jsx as Et,jsxs as Me}from"react/jsx-runtime";function Mo({onBack:e}){let[t,o]=Zt([]),[c,g]=Zt(!0),[f,l]=Zt(null);return Kr((i,s)=>{(s.escape||i==="q")&&e()}),jr(()=>{T("/evolution-audit?limit=20").then(i=>{o(i),g(!1)}).catch(i=>{l(i.message),g(!1)})},[]),c?Et(Ie,{dimColor:!0,children:"Loading evolution log..."}):f?Me(_t,{flexDirection:"column",children:[Et(Ie,{color:"red",children:f}),Et(Ie,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?Me(_t,{flexDirection:"column",children:[Et(Ie,{dimColor:!0,children:"No evolution records yet"}),Et(Ie,{dimColor:!0,children:"Press Esc to go back"})]}):Me(_t,{flexDirection:"column",children:[Me(Ie,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>Me(_t,{flexDirection:"column",marginTop:1,children:[Me(Ie,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&Me(Ie,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
|
|
5
|
-
`).map((s,r)=>s.startsWith("+")?Me(Ie,{color:"green",children:[" ",s]},r):s.startsWith("-")?Me(Ie,{color:"red",children:[" ",s]},r):Me(Ie,{dimColor:!0,children:[" ",s]},r))]},i.id))]})}import{Box as qe,Text as X,useInput as Qr}from"ink";import Xr from"ink-text-input";import{useEffect as zr,useState as at}from"react";import{jsx as fe,jsxs as oe}from"react/jsx-runtime";var Yr={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function Jr(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function Zr(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function $t({onBack:e}){let[t,o]=at([]),[c,g]=at(null),[f,l]=at("list"),[i,s]=at(""),[r,m]=at(!1),[d,y]=at(null);Qr((n,a)=>{if(f==="create"){a.escape&&(l("list"),s(""),y(null));return}(a.escape||n==="q")&&e(),n==="c"&&(l("create"),y(null)),n==="r"&&u()});let u=()=>{T("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>g(n.message))};zr(()=>{u()},[]);let x=async n=>{if(n.trim()){m(!0),y(null);try{let a=await T("/goals",{method:"POST",body:{input:n.trim()}});y(`Goal created: ${a.goal.name}`),s(""),l("list"),u()}catch(a){y(`Failed: ${a instanceof Error?a.message:String(a)}`)}finally{m(!1)}}};return c?oe(qe,{flexDirection:"column",children:[oe(X,{color:"red",children:["Failed to load goals: ",c]}),fe(X,{dimColor:!0,children:"Press Esc or q to return"})]}):f==="create"?oe(qe,{flexDirection:"column",children:[fe(X,{bold:!0,children:"Create Goal"}),fe(X,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),oe(qe,{marginTop:1,children:[fe(X,{color:"cyan",children:"> "}),fe(Xr,{value:i,onChange:s,onSubmit:x})]}),r&&fe(X,{color:"yellow",children:"Creating goal..."}),d&&fe(X,{color:d.startsWith("Failed")?"red":"green",children:d}),fe(X,{dimColor:!0,children:"Press Esc to cancel"})]}):oe(qe,{flexDirection:"column",children:[oe(X,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?fe(X,{dimColor:!0,children:"No goals found. Press c to create one."}):fe(qe,{marginTop:1,flexDirection:"column",children:t.map(n=>{let a=n.targetValue>0?n.currentValue/n.targetValue:0,P=Yr[n.status]??"white";return oe(qe,{marginBottom:1,flexDirection:"column",children:[oe(qe,{children:[fe(X,{bold:!0,color:P,children:n.name}),oe(X,{dimColor:!0,children:[" (",n.role,")"]}),fe(X,{dimColor:!0,children:" \u2014 "}),fe(X,{color:P,children:n.status})]}),oe(qe,{children:[oe(X,{dimColor:!0,children:[" ",Jr(a)," "]}),oe(X,{color:a>=1?"green":"white",children:[Math.round(a*100),"%"]}),oe(X,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),oe(qe,{children:[oe(X,{dimColor:!0,children:[" \u23F0 ",Zr(n.deadline)," left"]}),oe(X,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),oe(X,{dimColor:!0,children:[" | ID: ",n.id.slice(0,8)]})]})]},n.id)})}),fe(X,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as lt,Text as be,useInput as en}from"ink";import{useEffect as tn,useState as Lo}from"react";import{jsx as Fe,jsxs as Ue}from"react/jsx-runtime";function on(e,t,o=15){let c=e/(e+t),g=Math.round(c*o);return"\u2593".repeat(g)+"\u2591".repeat(o-g)}function No({onBack:e}){let[t,o]=Lo([]),[c,g]=Lo(null);if(en((l,i)=>{(i.escape||l==="q")&&e()}),tn(()=>{T("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>g(l.message))},[]),c)return Ue(lt,{flexDirection:"column",children:[Ue(be,{color:"red",children:["Failed to load strategies: ",c]}),Fe(be,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return Ue(lt,{flexDirection:"column",children:[Fe(be,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Fe(be,{dimColor:!0,children:"Press Esc or q to return"})]});let f=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,s=f.get(i)??[];s.push(l),f.set(i,s)}return Ue(lt,{flexDirection:"column",children:[Fe(be,{bold:!0,children:"Strategy Lab"}),Fe(be,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Fe(lt,{marginTop:1,flexDirection:"column",children:Array.from(f.entries()).map(([l,i])=>Ue(lt,{marginBottom:1,flexDirection:"column",children:[Fe(be,{bold:!0,color:"cyan",children:l}),i.sort((s,r)=>{let m=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-m}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return Ue(lt,{children:[Fe(be,{dimColor:!0,children:" "}),Ue(be,{children:[on(s.alpha,s.beta)," "]}),Ue(be,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),Ue(be,{dimColor:!0,children:[" ",s.name," (\u03B1=",s.alpha.toFixed(1)," \u03B2=",s.beta.toFixed(1)," trials=",s.totalTrials,")"]})]},s.id)})]},l))}),Fe(be,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as xe,Text as K,useInput as ln}from"ink";import eo from"ink-text-input";import{useEffect as cn,useState as We,useCallback as ct}from"react";import{CronExpressionParser as dn}from"cron-parser";import{useState as rn,useEffect as nn,useCallback as _o,useRef as sn}from"react";var an=3e3;function Ze(){let[e,t]=rn(null),o=sn(null),c=_o(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),g=_o((f,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:f,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},an))},[]);return nn(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:g,clearMessage:c}}import{jsx as j,jsxs as se}from"react/jsx-runtime";var to=["manual","cron","event"],Ot={name:"",triggerType:"manual",cron:"",stepPrompt:""};function un(e){try{return dn.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function qt({onBack:e}){let[t,o]=We([]),[c,g]=We(!0),[f,l]=We(0),[i,s]=We("list"),[r,m]=We({...Ot}),[d,y]=We("name"),[u,x]=We(null),{message:n,setMessage:a,clearMessage:P}=Ze(),[M,z]=We(!1),[U,D]=We(!1),H=ct(()=>{g(!0),T("/task-templates").then(({templates:b})=>{o(b),g(!1)}).catch(()=>g(!1))},[]);cn(()=>{H()},[H]);let w=i==="create"||i==="edit",S=ct(async()=>{let b=t[f];if(!(!b||M)){z(!0),a(`Triggering ${b.name}...`,"loading");try{let B=await T(`/task-templates/${b.id}/run`,{method:"POST"});a(`Triggered: ${b.name} (${B.executionId})`,"success")}catch(B){a(`Trigger failed: ${B instanceof Error?B.message:String(B)}`,"error")}finally{z(!1)}}},[t,f,M,a]),p=ct(async()=>{let b=t[f];if(!b||U)return;if(b.trigger?.type!=="cron"&&b.trigger?.type!=="event"){a("Toggle not applicable for manual triggers","error");return}let B=!b.enabled;D(!0),a(`${b.name} \u2192 ${B?"enabling":"disabling"}...`,"loading");try{await T(`/task-templates/${b.id}`,{method:"PATCH",body:{enabled:B}}),o(_=>_.map(ne=>ne.id===b.id?{...ne,enabled:B}:ne)),a(`${b.name} ${B?"enabled":"disabled"}`,"success")}catch(_){a(`Toggle failed: ${_ instanceof Error?_.message:String(_)}`,"error")}finally{D(!1)}},[t,f,U,a]),I=ct(async()=>{let b=t[f];if(b)try{await T(`/task-templates/${b.id}`,{method:"DELETE"}),a(`Deleted: ${b.name}`,"success"),H(),l(B=>Math.max(0,Math.min(B,t.length-2)))}catch(B){a(`Delete failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[t,f,H]),L=ct(()=>{let b=t[f];b&&(x(b.id),m({name:b.name,triggerType:b.trigger?.type??"manual",cron:b.trigger?.cron??"",stepPrompt:b.steps?.[0]?.prompt??""}),y("name"),s("edit"))},[t,f]),_e=ct(async()=>{let b={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await T("/task-templates",{method:"POST",body:b}),a(`Created: ${r.name}`,"success")):i==="edit"&&u&&(await T(`/task-templates/${u}`,{method:"PATCH",body:b}),a(`Updated: ${r.name}`,"success"))}catch(B){a(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}s("list"),m({...Ot}),x(null),H()},[r,i,u,H]);return ln((b,B)=>{if(w){if(B.escape){s("list"),m({...Ot}),x(null);return}if(B.return){let _=["name","triggerType","cron","stepPrompt"],ne=_.indexOf(d);if(ne<_.length-1){let je=ne+1;if(_[je]==="cron"&&r.triggerType!=="cron"&&je++,je<_.length){y(_[je]);return}}_e();return}if(B.tab&&d==="triggerType"){m(_=>{let ne=to.indexOf(_.triggerType);return{..._,triggerType:to[(ne+1)%to.length]}});return}return}if(B.escape||b==="q"){e();return}if(B.upArrow){l(_=>Math.max(0,_-1));return}if(B.downArrow){l(_=>Math.min(t.length-1,_+1));return}if(b==="t"){S();return}if(b==="d"){I();return}if(b==="e"){L();return}if(b==="c"){m({...Ot}),y("name"),s("create");return}if(b==="s"||b===" "){p();return}b==="r"&&(H(),P())}),c?j(K,{dimColor:!0,children:"Loading templates..."}):w?se(xe,{flexDirection:"column",children:[se(K,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),se(xe,{marginTop:1,flexDirection:"column",children:[se(xe,{children:[se(K,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?j(eo,{value:r.name,onChange:b=>m(B=>({...B,name:b})),placeholder:"template name"}):j(K,{children:r.name||"(empty)"})]}),se(xe,{children:[se(K,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),j(K,{children:r.triggerType}),d==="triggerType"&&j(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&se(xe,{children:[se(K,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?j(eo,{value:r.cron,onChange:b=>m(B=>({...B,cron:b})),placeholder:"*/5 * * * *"}):j(K,{children:r.cron||"(empty)"})]}),se(xe,{children:[se(K,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?j(eo,{value:r.stepPrompt,onChange:b=>m(B=>({...B,stepPrompt:b})),placeholder:"What should this template do?"}):j(K,{children:r.stepPrompt||"(empty)"})]})]}),j(xe,{marginTop:1,children:j(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):se(xe,{flexDirection:"column",children:[se(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&j(xe,{marginTop:1,children:se(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(xe,{marginTop:1,children:j(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):j(xe,{marginTop:1,flexDirection:"column",children:t.map((b,B)=>{let _=B===f,ne=b.trigger?.type==="cron"&&b.trigger?.cron?un(b.trigger.cron):"";return se(xe,{children:[j(K,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),j(K,{color:_?"cyan":void 0,bold:_,children:Vt(b.name,24)}),j(K,{dimColor:!0,children:Vt(b.trigger?.type,10)}),b.trigger?.type!=="cron"&&b.trigger?.type!=="event"?j(K,{dimColor:!0,children:Vt("\u2014",6)}):j(K,{color:b.enabled?"green":"gray",children:Vt(b.enabled?"on":"off",6)}),ne&&se(K,{dimColor:!0,children:["next: ",ne]})]},b.id)})}),j(xe,{marginTop:1,children:j(K,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Vt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as et,Text as Te,useInput as mn}from"ink";import gn from"ink-text-input";import{useEffect as fn,useState as dt,useCallback as $o}from"react";import{jsx as de,jsxs as rt}from"react/jsx-runtime";function Oo({onBack:e}){let[t,o]=dt([]),[c,g]=dt(""),[f,l]=dt(!0),[i,s]=dt(!1),[r,m]=dt(""),[d,y]=dt(null),u=$o(()=>{l(!0),T("/webhooks").then(({webhooks:n,auth:a})=>{o(n),g(a),l(!1)}).catch(()=>l(!1))},[]);fn(()=>{u()},[u]);let x=$o(async n=>{if(n.trim())try{let a=await T(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});y(`Triggered: ${a.executionId}`)}catch(a){y(`Trigger failed: ${a instanceof Error?a.message:String(a)}`)}},[]);return mn((n,a)=>{if(i){if(a.escape){s(!1),m("");return}if(a.return){x(r),s(!1),m("");return}return}if(a.escape||n==="q"){e();return}if(n==="t"){s(!0),m(""),y(null);return}n==="r"&&(u(),y(null))}),f?de(Te,{dimColor:!0,children:"Loading webhooks..."}):rt(et,{flexDirection:"column",children:[rt(Te,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),rt(Te,{dimColor:!0,children:["Auth: ",c]}),d&&de(et,{marginTop:1,children:de(Te,{color:"yellow",children:d})}),i&&rt(et,{marginTop:1,children:[de(Te,{bold:!0,color:"cyan",children:"Trigger webhook: "}),de(gn,{value:r,onChange:m,placeholder:"webhook name or ID"}),de(Te,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?de(et,{marginTop:1,children:de(Te,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):rt(et,{marginTop:1,flexDirection:"column",children:[de(et,{children:rt(Te,{bold:!0,children:[ut("NAME",24),ut("DESCRIPTION",36),ut("TRIGGER",28),"TAGS"]})}),t.map(n=>rt(et,{children:[de(Te,{children:ut(n.displayName,24)}),de(Te,{dimColor:!0,children:ut(pn(n.description??"",34),36)}),de(Te,{dimColor:!0,children:ut(n.trigger,28)}),de(Te,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),de(et,{marginTop:1,children:de(Te,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function ut(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function pn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Le,Text as ee,useInput as xn}from"ink";import Tn from"ink-text-input";import{useEffect as Vo,useState as Ge,useCallback as oo}from"react";import{jsx as te,jsxs as ke}from"react/jsx-runtime";function hn(e){return e>=4?"red":e===3?"yellow":"gray"}function yn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function bn(e){return new Date(e).toLocaleDateString()}function Uo({onBack:e}){let[t,o]=Ge([]),[c,g]=Ge(0),[f,l]=Ge([]),[i,s]=Ge(!0),[r,m]=Ge(!1),[d,y]=Ge(""),[u,x]=Ge("all"),[n,a]=Ge(null),[P,M]=Ge(!1),z=oo(()=>{T("/agents").then(({agents:p})=>{o(p),s(!1)}).catch(()=>s(!1))},[]);Vo(()=>{z()},[z]);let U=t[c],D=oo(()=>{U&&(M(!1),T(`/memories/${U.id}`).then(({memories:p})=>{l(p),a(null)}).catch(p=>a(`Failed: ${p instanceof Error?p.message:String(p)}`)))},[U]);Vo(()=>{U&&D()},[U,D]);let H=oo(async p=>{if(!(!U||!p.trim()))try{let I=await T("/memories/query",{method:"POST",body:{agentId:U.id,prompt:p.trim()}});l(I.memories),M(!0),a(`Search: ${I.count} results`)}catch(I){a(`Search failed: ${I instanceof Error?I.message:String(I)}`)}},[U]),w=r,S=f.filter(p=>u==="all"?!0:u==="high"?p.importance>3:u==="medium"?p.importance===3:p.importance<3);return xn((p,I)=>{if(w){if(I.escape){m(!1),y("");return}if(I.return){H(d),m(!1),y("");return}return}if(I.escape||p==="q"){e();return}if(p==="a"){g(L=>(L+1)%Math.max(1,t.length));return}if(I.leftArrow){g(L=>(L-1+t.length)%Math.max(1,t.length));return}if(I.rightArrow){g(L=>(L+1)%Math.max(1,t.length));return}if(p==="s"){m(!0),y(""),a(null);return}if(p==="h"){x(L=>L==="high"?"all":"high");return}if(p==="m"){x(L=>L==="medium"?"all":"medium");return}if(p==="l"){x(L=>L==="low"?"all":"low");return}p==="r"&&D()}),i?te(ee,{dimColor:!0,children:"Loading agents..."}):t.length===0?ke(Le,{flexDirection:"column",children:[te(ee,{dimColor:!0,children:"No agents found"}),te(ee,{dimColor:!0,children:"Press Esc to go back"})]}):ke(Le,{flexDirection:"column",children:[te(ee,{bold:!0,children:"Memories (Esc to go back)"}),ke(Le,{marginTop:1,children:[te(ee,{children:"Agent: "}),te(ee,{bold:!0,color:"cyan",children:U?.name??"?"}),ke(ee,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),te(Le,{children:ke(ee,{dimColor:!0,children:["Filter: ",u==="all"?"all":u," | ",P?"search results":"all memories"," (",S.length,")"]})}),n&&te(Le,{children:te(ee,{color:"yellow",children:n})}),r&&ke(Le,{marginTop:1,children:[te(ee,{bold:!0,color:"cyan",children:"Search: "}),te(Tn,{value:d,onChange:y,placeholder:"search query..."}),te(ee,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),S.length===0?te(Le,{marginTop:1,children:ke(ee,{dimColor:!0,children:["No memories",u!=="all"?` matching filter '${u}'`:""]})}):te(Le,{marginTop:1,flexDirection:"column",children:S.map(p=>ke(Le,{marginBottom:0,children:[ke(ee,{color:hn(p.importance),bold:!0,children:[yn(p.importance)," "]}),te(ee,{dimColor:!0,children:qo(p.type??"?",12)}),te(ee,{dimColor:!0,children:qo(`\xD7${p.retrievedCount??0}`,5)}),ke(ee,{children:[Sn(p.content,55)," "]}),te(ee,{dimColor:!0,children:bn(p.createdAt)}),p.score!==void 0&&ke(ee,{dimColor:!0,children:[" (",p.score.toFixed(2),")"]})]},p.id))}),te(Le,{marginTop:1,children:te(ee,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function qo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Sn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as nt,Text as he,useInput as Cn}from"ink";import vn from"ink-text-input";import{useState as He,useEffect as Fo,useCallback as Wo}from"react";import{jsx as Pe,jsxs as Ne}from"react/jsx-runtime";var Go={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"],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"]},En={"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)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold"};function Ho({onBack:e}){let{state:t}=Xe(),[o,c]=He({}),[g,f]=He([]),[l,i]=He(null),[s,r]=He("view"),[m,d]=He(0),[y,u]=He(""),[x,n]=He(null),[a,P]=He(!1),[M,z]=He([]),U=Object.values(Go).flat(),D=Wo(()=>{T("/config").then(S=>{c(S.config),f(S.mutable)}).catch(S=>i(S.message)),T("/config/env-diff").then(S=>{z(S.diffs)}).catch(()=>{})},[]);Fo(()=>{D()},[D]),Fo(()=>{t.configVersion>0&&D()},[t.configVersion,D]);let H=Wo(async()=>{let S=U[m];if(S){P(!0),n(null);try{let p=y,I=o[S];if(I&&typeof I.value=="number"&&(p=Number(y),isNaN(p))){n("Invalid number"),P(!1);return}let L=await T("/config",{method:"PATCH",body:{[S]:p}});L.updated.length>0&&(n(`Updated: ${S}`),D()),L.errors.length>0&&n(L.errors[0]),r("view")}catch(p){n(`Failed: ${p instanceof Error?p.message:String(p)}`)}finally{P(!1)}}},[U,m,y,o,D]);if(Cn((S,p)=>{if(s==="edit"){if(p.escape){r("view");return}return}if(p.escape||S==="q"){e();return}if(p.upArrow&&m>0&&d(I=>I-1),p.downArrow&&m<U.length-1&&d(I=>I+1),p.return||S==="e"){let I=U[m],L=o[I];L&&L.mutable?(u(String(L.value??"")),r("edit"),n(null)):L&&!L.mutable&&n("This setting requires a restart to change")}S==="r"&&(D(),n("Refreshed")),S==="s"&&M.length>0&&T("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),z([]),D()}),S==="l"&&M.length>0&&T("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),D()})}),l)return Ne(nt,{flexDirection:"column",children:[Ne(he,{color:"red",children:["Failed to load config: ",l]}),Pe(he,{dimColor:!0,children:"Press Esc or q to return"})]});let w=0;return Ne(nt,{flexDirection:"column",children:[Pe(he,{bold:!0,children:"Settings"}),x&&Pe(he,{color:x.startsWith("Failed")||x.startsWith("This setting")?"yellow":"green",children:x}),M&&M.length>0&&Ne(nt,{flexDirection:"column",marginBottom:1,children:[Ne(he,{color:"yellow",children:[".env differs from DB (",M.length," key(s)): ",M.map(S=>S.envKey).join(", ")]}),Pe(he,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Pe(nt,{marginTop:1,flexDirection:"column",children:Object.entries(Go).map(([S,p])=>Ne(nt,{marginBottom:1,flexDirection:"column",children:[Pe(he,{bold:!0,color:"cyan",children:S}),p.map(I=>{let L=o[I],b=w++===m,B=g.includes(I),_=En[I]??I,ne=L?String(L.value??""):"...";return s==="edit"&&b?Ne(nt,{children:[Ne(he,{color:"cyan",children:["> ",_,": "]}),Pe(vn,{value:y,onChange:u,onSubmit:()=>{H()}}),a&&Pe(he,{color:"yellow",children:" saving..."})]},I):Ne(nt,{children:[Ne(he,{color:b?"cyan":"white",children:[b?"> ":" ",B?" ":"\u{1F512} ",_,": "," "]}),Pe(he,{color:B?"white":"gray",children:ne}),!B&&Pe(he,{dimColor:!0,children:" (restart required)"})]},I)})]},S))}),Pe(he,{dimColor:!0,children:"Enter/e:edit r:refresh Esc/q:back"})]})}import{Box as st,Text as ue,useInput as Bn}from"ink";import{useEffect as wn,useState as ro,useCallback as In}from"react";import{jsx as ie,jsxs as gt}from"react/jsx-runtime";function Ko({onBack:e}){let[t,o]=ro([]),[c,g]=ro(!0),[f,l]=ro(0),{message:i,setMessage:s,clearMessage:r}=Ze(),m=In(()=>{g(!0),T("/plugins").then(({plugins:d})=>{o(d),g(!1)}).catch(()=>g(!1))},[]);return wn(()=>{m()},[m]),Bn((d,y)=>{if(y.escape||d==="q"){e();return}if(y.upArrow){l(u=>Math.max(0,u-1));return}if(y.downArrow){l(u=>Math.min(t.length-1,u+1));return}d==="r"&&(m(),r())}),c?ie(ue,{dimColor:!0,children:"Loading plugins..."}):gt(st,{flexDirection:"column",children:[gt(ue,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&ie(st,{marginTop:1,children:gt(ue,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?ie(st,{marginTop:1,children:ie(ue,{dimColor:!0,children:"No plugins installed."})}):gt(st,{marginTop:1,flexDirection:"column",children:[gt(st,{children:[ie(ue,{dimColor:!0,children:" "}),ie(ue,{dimColor:!0,children:mt("Name",24)}),ie(ue,{dimColor:!0,children:mt("Scope",8)}),ie(ue,{dimColor:!0,children:mt("User",6)}),ie(ue,{dimColor:!0,children:"Path"})]}),t.map((d,y)=>{let u=y===f,x=d.id.split("@")[0];return gt(st,{children:[ie(ue,{color:u?"cyan":void 0,bold:u,children:u?"> ":" "}),ie(ue,{color:u?"cyan":void 0,bold:u,children:mt(x,24)}),ie(ue,{color:u?"cyan":void 0,bold:u,children:mt(d.scope,8)}),ie(ue,{color:d.globalEnabled?"green":"gray",children:mt(d.globalEnabled?"on":"off",6)}),ie(ue,{dimColor:!0,children:d.installPath})]},d.id)})]}),ie(st,{marginTop:1,children:ie(ue,{dimColor:!0,children:"r:refresh"})})]})}function mt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ut,Text as jo,useInput as kn}from"ink";import{useState as Pn}from"react";import{jsx as ft,jsxs as no}from"react/jsx-runtime";var An=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function Qo({onBack:e}){let[t,o]=Pn("tasks");return kn((c,g)=>{if(g.escape||c==="q"){e();return}if(c==="1"){o("tasks");return}if(c==="2"){o("automations");return}if(c==="3"){o("goals");return}}),no(Ut,{flexDirection:"column",children:[no(Ut,{gap:1,marginBottom:1,children:[An.map(c=>{let g=t===c.id;return ft(Ut,{children:no(jo,{color:g?"cyan":"gray",bold:g,underline:g,children:["[",c.key,":",c.label,"]"]})},c.id)}),ft(Ut,{flexGrow:1}),ft(jo,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&ft(Nt,{onBack:e}),t==="automations"&&ft(qt,{onBack:e}),t==="goals"&&ft($t,{onBack:e})]})}import{Box as G,Text as O,useInput as Dn}from"ink";import{useEffect as Rn,useState as Bt}from"react";import{jsx as k,jsxs as re}from"react/jsx-runtime";var Xo={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function zo({onBack:e}){let[t,o]=Bt([]),[c,g]=Bt(!0),[f,l]=Bt(0),[i,s]=Bt(null),[r,m]=Bt("");Rn(()=>{d()},[]);async function d(){try{let x=await T("/channels");o(x.channels)}catch{}g(!1)}async function y(x){if(t.find(a=>a.id===x)?.platform==="wechat")try{m("Starting WeChat QR login...");let a=await T(`/channels/${x}/wechat/qr-start`,{method:"POST"});if(a.qrcodeUrl){m(`Scan QR: ${a.qrcodeUrl}
|
|
6
|
-
Waiting for scan...`);let P=await T(`/channels/${x}/wechat/qr-wait`,{method:"POST",body:{sessionKey:a.sessionKey,timeoutMs:12e4}});m(P.message)}else m(a.message);d()}catch{m("WeChat connect failed")}else try{await T(`/channels/${x}/connect`,{method:"POST"}),m("Connecting..."),d()}catch{m("Connect failed")}}async function u(x){try{await T(`/channels/${x}/disconnect`,{method:"POST"}),m("Disconnected"),d()}catch{m("Disconnect failed")}}return Dn((x,n)=>{if(i){if(n.escape||x==="q"){s(null);return}if(x==="c"){y(i.id);return}if(x==="d"){u(i.id);return}return}if(n.escape){e();return}if(n.upArrow){l(a=>Math.max(0,a-1));return}if(n.downArrow){l(a=>Math.min(t.length-1,a+1));return}if(n.return&&t[f]){s(t[f]),m("");return}}),c?k(G,{flexDirection:"column",children:k(O,{dimColor:!0,children:"Loading channels..."})}):i?re(G,{flexDirection:"column",children:[re(G,{marginBottom:1,children:[re(O,{bold:!0,children:["Channel: ",i.name]}),k(O,{dimColor:!0,children:" (Esc to go back)"})]}),re(G,{flexDirection:"column",gap:0,children:[re(O,{children:["ID: ",i.id]}),re(O,{children:["Platform: ",i.platform]}),re(O,{children:["Status: ",k(O,{color:Xo[i.status]??"white",children:i.status})]}),re(O,{children:["Enabled: ",i.enabled?"yes":"no"]}),re(O,{children:["Messages: ",i.messageCount]}),re(O,{children:["Config: ",JSON.stringify(i.config)]})]}),k(G,{marginTop:1,children:k(O,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&k(O,{color:"yellow",children:r})]}):re(G,{flexDirection:"column",children:[re(G,{marginBottom:1,children:[k(O,{bold:!0,children:"Channels"}),re(O,{dimColor:!0,children:[" (",t.length," total) "]}),k(O,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?k(O,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):re(G,{flexDirection:"column",children:[re(G,{children:[k(G,{width:3,children:k(O,{dimColor:!0,children:" "})}),k(G,{width:12,children:k(O,{bold:!0,dimColor:!0,children:"ID"})}),k(G,{width:16,children:k(O,{bold:!0,dimColor:!0,children:"Name"})}),k(G,{width:12,children:k(O,{bold:!0,dimColor:!0,children:"Platform"})}),k(G,{width:14,children:k(O,{bold:!0,dimColor:!0,children:"Status"})}),k(G,{width:10,children:k(O,{bold:!0,dimColor:!0,children:"Enabled"})}),k(G,{width:10,children:k(O,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((x,n)=>re(G,{children:[k(G,{width:3,children:k(O,{children:n===f?">":" "})}),k(G,{width:12,children:k(O,{inverse:n===f,children:x.id.slice(0,8)})}),k(G,{width:16,children:k(O,{children:x.name})}),k(G,{width:12,children:k(O,{children:x.platform})}),k(G,{width:14,children:re(O,{color:Xo[x.status]??"white",children:[x.status==="connected"?"\u25CF":x.status==="error"?"\u2717":"\u25CB"," ",x.status]})}),k(G,{width:10,children:k(O,{color:x.enabled?"green":"gray",children:x.enabled?"yes":"no"})}),k(G,{width:10,children:k(O,{children:x.messageCount})})]},x.id))]})]})}import{Box as pt,Text as Ke,useInput as Ln}from"ink";import{useEffect as Nn,useState as It,useCallback as _n}from"react";import{Box as V,Text as E,useInput as Mn}from"ink";import Ft from"ink-text-input";import{useEffect as Yo,useState as ae,useCallback as wt}from"react";lo();import{Fragment as Jo,jsx as v,jsxs as R}from"react/jsx-runtime";function Zo({roleId:e,onBack:t}){let[o,c]=ae(null),[g,f]=ae([]),[l,i]=ae(!0),[s,r]=ae("view"),[m,d]=ae(""),[y,u]=ae(0),[x,n]=ae(""),[a,P]=ae([]),[M,z]=ae(0),[U,D]=ae(new Set),[H,w]=ae("inline"),[S,p]=ae(""),[I,L]=ae(""),[_e,b]=ae([]),[B,_]=ae(new Set),[ne,je]=ae(0),{message:W,setMessage:Y}=Ze(),me=wt(()=>{i(!0),T(`/roles/${e}`).then(({role:h,boundPlugins:N})=>{c(h),f(N??[]),d(h.cagPrompt??""),D(new Set(h.allowedTools??[])),w(h.executionMode??"inline"),p(h.model??""),L(h.maxBudgetUsd!=null?String(h.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);Yo(()=>{me()},[me]),Yo(()=>{w(o?.executionMode??"inline"),p(o?.model??""),L(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):"")},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd]);let or=wt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:m}}),Y("CAG prompt saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,m,me,Y]),rr=wt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:$e}}),Y("Directories saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,me,Y]),nr=wt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(U)}}),Y("Tool permissions saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,U,me,Y]),sr=wt(async()=>{if(!o)return;let h={executionMode:H};S!==void 0&&(h.model=S);let N=parseFloat(I);isNaN(N)||(h.maxBudgetUsd=N);try{await T(`/roles/${o.id}`,{method:"PATCH",body:h}),Y("Execution config saved","success"),r("view"),me()}catch(C){Y(`Save failed: ${C instanceof Error?C.message:String(C)}`,"error")}},[o,H,S,I,me,Y]),$e=o?.additionalDirectories??[];return Mn((h,N)=>{if(N.escape){r("view");return}if(h==="r"){me();return}switch(s){case"view":{if(h==="c"){r("edit-cag");return}if(h==="d"){r("edit-dirs"),u(0),n("");return}if(h==="t"){r("edit-tools");return}if(h==="x"){r("edit-exec");return}if(h==="h"){T("/channels?enabled=true").then(({channels:C})=>{b(C.map(J=>({name:J.name,id:J.id}))),_(new Set(o?.allowedChannels??[])),je(0),r("edit-channels")}).catch(()=>Y("Failed to load channels","error"));return}if(h==="i"){if(!o)return;let C=!o.inheritUserSettings;T(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:C}}).then(()=>{Y(`Inherit user settings: ${C?"ON":"OFF"}`,"success"),me()}).catch(()=>Y("Failed to toggle","error"));return}break}case"edit-cag":{if(N.ctrl&&h==="s"){or();return}break}case"edit-dirs":{if(h==="s"){rr();return}if(h==="a"){r("edit-dirs-add");return}if(h==="x"&&$e.length>0){c(C=>C&&{...C,additionalDirectories:$e.filter((J,Qe)=>Qe!==y)}),u(C=>Math.max(0,Math.min(C,$e.length-2)));return}if(N.upArrow){u(C=>Math.max(0,C-1));return}if(N.downArrow){u(C=>Math.min($e.length-1,C+1));return}break}case"edit-dirs-add":{if(N.escape){r("edit-dirs"),n(""),P([]);return}if(N.return&&a.length>0){let C=a[M];C&&(n(C.endsWith("/")?C:C+"/"),P([]));return}if(N.return){let C=x.trim();C&&C.startsWith("/")?(c(J=>J&&{...J,additionalDirectories:[...J.additionalDirectories??[],{path:C}]}),n(""),P([]),r("edit-dirs")):Y("Path must be absolute (must start with /)","error");return}if(N.tab){let C=x.trim();if(!C||!C.startsWith("/"))return;T(`/fs/suggest-dirs?prefix=${encodeURIComponent(C)}`).then(({suggestions:J})=>{J.length===1?(n(J[0]+"/"),P([])):J.length>1&&(P(J),z(0))}).catch(()=>{P([])});return}if(N.upArrow&&a.length>0){z(C=>Math.max(0,C-1));return}if(N.downArrow&&a.length>0){z(C=>Math.min(a.length-1,C+1));return}break}case"edit-tools":{if(h==="s"){nr();return}let C=parseInt(h,10)-1;if(!isNaN(C)&&C>=0&&C<At.length){let J=At[C];D(Qe=>{let Pt=new Set(Qe);return Pt.has(J)?Pt.delete(J):Pt.add(J),Pt});return}break}case"edit-exec":{if(h==="s"){sr();return}if(N.tab){w(C=>C==="inline"?"isolated":"inline");return}break}case"edit-channels":{if(h==="s"){if(!o)return;let C=B.size>0?Array.from(B):[];T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:C}}).then(()=>{Y("Channels saved","success"),r("view"),me()}).catch(()=>Y("Save failed","error"));return}if(h==="u"){if(!o)return;T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{Y("Channels: unrestricted","success"),r("view"),me()}).catch(()=>Y("Save failed","error"));return}if(h===" "){let C=_e[ne];C&&_(J=>{let Qe=new Set(J);return Qe.has(C.name)?Qe.delete(C.name):Qe.add(C.name),Qe});return}if(N.upArrow){je(C=>Math.max(0,C-1));return}if(N.downArrow){je(C=>Math.min(_e.length-1,C+1));return}break}}}),l?v(E,{dimColor:!0,children:"Loading role..."}):o?s==="edit-cag"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),v(Ft,{value:m,onChange:d,placeholder:"Character And Guidance prompt..."}),W&&v(V,{marginTop:1,children:v(E,{color:W.type==="error"?"red":"green",children:W.text})})]}):s==="edit-dirs-add"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),v(Ft,{value:x,onChange:h=>{n(h),P([])},placeholder:"/absolute/path/to/directory"}),a.length>0&&R(V,{flexDirection:"column",marginTop:1,children:[a.map((h,N)=>R(E,{color:N===M?"cyan":void 0,dimColor:N!==M,children:[N===M?"> ":" ",h,"/"]},h)),v(E,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),W&&v(V,{marginTop:1,children:v(E,{color:W.type==="error"?"red":"green",children:W.text})})]}):s==="edit-dirs"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add x:remove s:save Esc:cancel)"}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})}),$e.length===0?v(E,{dimColor:!0,children:"No directories. Press a to add one."}):$e.map((h,N)=>R(V,{children:[v(E,{color:N===y?"cyan":void 0,bold:N===y,children:N===y?"> ":" "}),v(E,{color:N===y?"cyan":void 0,children:h.path})]},h.path))]}):s==="edit-tools"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})}),At.map((h,N)=>{let C=U.has(h);return R(V,{children:[R(E,{dimColor:!0,children:[N+1,". "]}),v(E,{color:C?"green":"red",children:C?"[ON] ":"[OFF] "}),v(E,{children:h})]},h)})]}):s==="edit-exec"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),R(V,{children:[v(E,{bold:!0,children:" Mode: "}),v(E,{color:"cyan",children:H}),v(E,{dimColor:!0,children:" (Tab to toggle)"})]}),R(V,{children:[v(E,{bold:!0,children:" Model: "}),v(Ft,{value:S,onChange:p,placeholder:"sonnet, opus, haiku, or blank"})]}),R(V,{children:[v(E,{bold:!0,children:" Max Budget (USD): "}),v(Ft,{value:I,onChange:L,placeholder:"0 = unlimited"})]}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})})]}):s==="edit-channels"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),_e.length===0?v(E,{dimColor:!0,children:"No channels available"}):_e.map((h,N)=>R(V,{children:[R(E,{children:[N===ne?">":" "," "]}),R(E,{color:B.has(h.name)?"green":"gray",children:["[",B.has(h.name)?"x":" ","] ",h.name]})]},h.id)),R(E,{dimColor:!0,children:["Selected: ",B.size>0?Array.from(B).join(", "):"none (= block all)"]}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})})]}):R(V,{flexDirection:"column",children:[R(E,{bold:!0,children:["Role: ",o.name]}),R(V,{children:[v(E,{dimColor:!0,children:"ID: "}),v(E,{children:o.id})]}),R(V,{children:[v(E,{dimColor:!0,children:"Status: "}),v(E,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&R(V,{children:[v(E,{dimColor:!0,children:"Score: "}),R(E,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),R(V,{children:[v(E,{dimColor:!0,children:"Created: "}),v(E,{children:new Date(o.createdAt).toLocaleString()})]}),R(V,{children:[v(E,{dimColor:!0,children:"Execution: "}),R(E,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),$e.length>0&&R(Jo,{children:[v(E,{bold:!0,children:"Additional Directories:"}),$e.map(h=>R(E,{dimColor:!0,children:[" ",h.path]},h.path))]}),R(V,{children:[v(E,{dimColor:!0,children:"Channels: "}),v(E,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),R(V,{children:[v(E,{dimColor:!0,children:"Inherit User Settings: "}),v(E,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&R(Jo,{children:[v(E,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(h=>R(E,{dimColor:!0,children:[" - ",h]},h))]}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})}),v(V,{marginTop:1,children:v(E,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec h:channels i:inherit r:refresh Esc:back"})})]}):v(E,{dimColor:!0,children:"Role not found."})}import{jsx as Se,jsxs as Wt}from"react/jsx-runtime";function er({onBack:e}){let[t,o]=It([]),[c,g]=It(!0),[f,l]=It(0),[i,s]=It("list"),[r,m]=It(null),{message:d,setMessage:y,clearMessage:u}=Ze(),x=_n(()=>{g(!0),T("/roles").then(({roles:n})=>{o(n.map(a=>({id:a.id,name:a.name,status:a.status,performanceScore:a.performanceScore,createdAt:a.createdAt}))),g(!1)}).catch(()=>g(!1))},[]);return Nn(()=>{x()},[x]),Ln((n,a)=>{if(a.escape||n==="q"){e();return}if(a.upArrow){l(P=>Math.max(0,P-1));return}if(a.downArrow){l(P=>Math.min(t.length-1,P+1));return}if(n==="r"&&(x(),u()),n===`
|
|
7
|
-
`||n==="o"||n==="e"){t.length>0&&(m(t[f].id),s("detail"));return}}),c?Se(Ke,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Se(Zo,{roleId:r,onBack:()=>s("list")}):Wt(pt,{flexDirection:"column",children:[Wt(Ke,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&Se(pt,{marginTop:1,children:Wt(Ke,{color:d.type==="success"?"green":d.type==="error"?"red":"gray",children:[d.type==="success"?"\u2713 ":d.type==="error"?"\u2717 ":"\u2192 ",d.text]})}),t.length===0?Se(pt,{marginTop:1,children:Se(Ke,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Se(pt,{marginTop:1,flexDirection:"column",children:t.map((n,a)=>{let P=a===f,M=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return Wt(pt,{children:[Se(Ke,{color:P?"cyan":void 0,bold:P,children:P?"> ":" "}),Se(Ke,{color:P?"cyan":void 0,bold:P,children:so(n.name,24)}),Se(Ke,{color:$n(n.status),children:so(n.status,12)}),Se(Ke,{dimColor:!0,children:so(M,8)})]},n.id)})}),Se(pt,{marginTop:1,children:Se(Ke,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function $n(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function so(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as Wn,jsx as q,jsxs as Tt}from"react/jsx-runtime";function qn(){let{state:e,dispatch:t}=Xe(),{session:o,sendMessage:c,createNewSession:g,archiveCurrentSession:f}=To(),[l,i]=Vn([]);io(()=>{t({type:"SET_SESSION",session:o})},[o,t]),fo();let{events:s,isStreaming:r,clearEvents:m}=xo(e.activeTaskId),d=s[s.length-1],y=d?.type==="complete"&&!r,u=tr(null),x=tr("");io(()=>{x.current=s.filter(a=>a.type==="reasoning").map(a=>a.content).join("")},[s]),io(()=>{if(y&&e.activeTaskId!==u.current){u.current=e.activeTaskId;let a=d?.content||x.current;a&&i(P=>[...P,{role:"assistant",content:a}])}},[y,d,e.activeTaskId]);let n=async a=>{if(a.startsWith("/")){let M=a.slice(1),z={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"};M==="quit"&&process.exit(0);let U=z[M];if(U){t({type:"SET_VIEW",view:U});return}if(M==="new"){if(await f()){let H=await g();i([]),m(),H&&i([{role:"assistant",content:`Session archived. New session started: ${H.id.slice(0,8)}`}])}return}if(M==="session"){let D=o?`Session: ${o.id}
|
|
8
|
-
Turns: ${o.messageCount}
|
|
9
|
-
Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(H=>[...H,{role:"assistant",content:D}]);return}}i(M=>[...M,{role:"user",content:a}]),m();let P=await c(a);if(!P){i(M=>[...M,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}t({type:"SET_ACTIVE_TASK",taskId:P.taskId}),t({type:"TASK_SUBMITTED"})};return Tt(kt,{flexDirection:"column",paddingX:1,children:[q(ho,{}),Tt(kt,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Tt(Wn,{children:[q(Eo,{messages:l}),q(So,{events:s,isStreaming:r}),!e.connected&&!e.serverUnreachable&&q(kt,{children:q(xt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Tt(kt,{flexDirection:"column",children:[q(xt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),q(xt,{dimColor:!0,children:"Check: adam server logs"}),q(xt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&q(Qo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&q(Nt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&q(Do,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&q(Mo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&q($t,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&q(No,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&q(qt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&q(Oo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&q(Uo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&q(Ko,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&q(er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&q(Ho,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&q(zo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?q(wo,{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(Bo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):q(bo,{onSubmit:n}),e.planTimeoutNotice&&q(Un,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function Un({planId:e,onDismiss:t}){return On(o=>{o==="d"&&t()}),Tt(kt,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Tt(xt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),q(xt,{dimColor:!0,children:" [d] Dismiss"})]})}function Fn(){return q(go,{children:q(qn,{})})}export{Fn as default};
|
package/dist/chunk-EALDBELJ.js
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import{a as _,b as O}from"./chunk-VF6GJGD6.js";import{b as m,d as P}from"./chunk-PCSZW2PE.js";import{f as l,g as y}from"./chunk-SFUS33SO.js";import{c as h}from"./chunk-3DAK2XWP.js";P();import{dirname as v,join as x}from"path";import{fileURLToPath as D}from"url";var b=v(D(import.meta.url)),A=x(b,"..");var I=A,W=h("cli:register-ai-digest"),g="ai-hourly-digest";function L(){try{if(O(g)){console.log(`[INFO] AI Digest template already exists (${g})`);return}}catch{}let r={id:g,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
|
|
2
|
-
|
|
3
|
-
\u641C\u7D22\u6765\u6E90:
|
|
4
|
-
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
5
|
-
2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
|
|
6
|
-
3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
|
|
7
|
-
|
|
8
|
-
\u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
|
|
9
|
-
|
|
10
|
-
\u8F93\u51FA\u683C\u5F0F:
|
|
11
|
-
- \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
|
|
12
|
-
- \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
|
|
13
|
-
- \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
|
|
14
|
-
- \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
|
|
15
|
-
|
|
16
|
-
\u6587\u7AE0\u4FE1\u606F:
|
|
17
|
-
{{search_ai_news.result}}
|
|
18
|
-
|
|
19
|
-
\u8BF7:
|
|
20
|
-
1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
|
|
21
|
-
2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
|
|
22
|
-
3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
|
|
23
|
-
|
|
24
|
-
\u603B\u7ED3\u7ED3\u6784:
|
|
25
|
-
## \u6838\u5FC3\u53D1\u73B0
|
|
26
|
-
[\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
|
|
27
|
-
|
|
28
|
-
## \u6280\u672F\u7EC6\u8282
|
|
29
|
-
[\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
|
|
30
|
-
|
|
31
|
-
## \u5F71\u54CD/\u610F\u4E49
|
|
32
|
-
[\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
|
|
33
|
-
|
|
34
|
-
## \u539F\u6587\u94FE\u63A5
|
|
35
|
-
[\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
|
|
36
|
-
|
|
37
|
-
\u603B\u7ED3\u5185\u5BB9:
|
|
38
|
-
{{summarize_article.result}}
|
|
39
|
-
|
|
40
|
-
\u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
|
|
41
|
-
|
|
42
|
-
osascript ${I}/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
|
|
43
|
-
|
|
44
|
-
\u6CE8\u610F\uFF1A
|
|
45
|
-
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
46
|
-
- \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
|
|
47
|
-
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
48
|
-
|
|
49
|
-
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300,fileAccess:{allowedPaths:["~/.adam/",I],deniedPaths:[]}},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};_(r),console.log(`[INFO] Registered AI Hourly Digest task template (${g})`),console.log("[INFO] Cron schedule: 0 * * * * (every hour at minute 0)")}import.meta.url===`file://${process.argv[1]}`&&(console.log("Initializing database..."),m(),console.log("Registering AI Digest template..."),L(),console.log("Done."),process.exit(0));y();import{readFileSync as T,writeFileSync as N,existsSync as E}from"fs";var f={ANTHROPIC_API_KEY:"anthropic.apiKey",ANTHROPIC_BASE_URL:"anthropic.baseUrl",ANTHROPIC_MODEL:"anthropic.model",ANTHROPIC_DEFAULT_OPUS_MODEL:"anthropic.defaultOpusModel",ANTHROPIC_DEFAULT_SONNET_MODEL:"anthropic.defaultSonnetModel",ANTHROPIC_DEFAULT_HAIKU_MODEL:"anthropic.defaultHaikuModel",ANTHROPIC_SMALL_FAST_MODEL:"anthropic.smallFastModel"},G=Object.fromEntries(Object.entries(f).map(([r,o])=>[o,r]));function S(){if(!E(l))return null;let r=T(l,"utf-8"),o={};for(let s of r.split(`
|
|
50
|
-
`)){let i=s.trim();if(!i||i.startsWith("#"))continue;let c=i.startsWith("export ")?i.slice(7).trim():i,n=c.indexOf("=");if(n===-1)continue;let e=c.slice(0,n).trim();if(!(e in f))continue;let t=c.slice(n+1).trim();(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1)),!(t.includes("$")&&(t=t.replace(/\$\{(\w+)\}|\$(\w+)/g,(p,u,d)=>{let a=u??d;return o[a]??process.env[a]??""}),!t))&&(o[e]=t)}return o}function z(r){let o=S();if(!o)return[];let s=[];for(let[i,c]of Object.entries(f)){let n=r[c],e=o[i];if(e===void 0)continue;let t=n?String(n):"";t!==e&&s.push({configPath:c,envKey:i,dbValue:t,envValue:e})}return s}function q(r){if(!E(l))return 0;let s=T(l,"utf-8").split(`
|
|
51
|
-
`),i=0,c=new Set;for(let n=0;n<s.length;n++){let e=s[n].trim();if(!e||e.startsWith("#"))continue;let t=e.startsWith("export ")?e.slice(7).trim():e,p=t.indexOf("=");if(p===-1)continue;let u=t.slice(0,p).trim(),d=f[u];if(!d)continue;let a=r[d];if(a!=null&&String(a).length>0){let R=e.startsWith("export ")?"export ":"";s[n]=`${R}${u}=${String(a)}`,c.add(u),i++}}for(let[n,e]of Object.entries(f)){if(c.has(n))continue;let t=r[e];t&&String(t).length>0&&(s.push(`${n}=${String(t)}`),i++)}return i>0&&N(l,s.join(`
|
|
52
|
-
`)),i}export{A as a,G as b,S as c,z as d,q as e,L as f};
|
package/dist/chunk-NICRQZ7T.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as E}from"./chunk-UOTDT2KY.js";import{f as x}from"./chunk-KICPHTI2.js";import{b as m}from"./chunk-5ASEAZCR.js";import{e as f}from"./chunk-742NWPTQ.js";import{b as S}from"./chunk-PQ7KPALO.js";import{a as D,b as w,c as o,e as k,f as T,g as P}from"./chunk-FDWW245P.js";import{b as g}from"./chunk-L7426WNY.js";import{a as h}from"./chunk-L7JP7DUO.js";import{c as I}from"./chunk-3DAK2XWP.js";import{v4 as b}from"uuid";var s=I("admin"),y=new Map,u=null,p=null,c=null,v=class{constructor(){h.on("task_status_change",e=>{(e.newStatus==="completed"||e.newStatus==="failed")&&this.handleTaskStatusChange(e.taskId,e.newStatus).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed")})}),h.on("plan_approval_request",e=>{this.handlePlanApprovalRequest(e.taskId,e.planId,e.plan).catch(n=>{s.error({taskId:e.taskId,error:n},"Delivery processing failed (plan_approval)")})}),s.info("DeliveryEngine initialized")}async handlePlanApprovalRequest(e,n,r){let t=g(e),i=this.getSourceChannelForTask(e);if(i){let d=JSON.stringify(r).slice(0,500),{sendApprovalToChannel:R}=await import("./approval-handler-D3J6NCMM.js");await R(i.channelId,i.chatId,n,e,d)}let a=`Plan approval requested for task ${e}: ${JSON.stringify(r).slice(0,500)}`;await this.matchAndDeliver("plan_approval_request",{templateId:t?.templateId,roleId:t?.roleId,prompt:t?.prompt,taskStatus:"pending"},a,e)}getSourceChannelForTask(e){try{let n=f(e);if(!n)return null;let r=m(n.sessionId);return!r||r.source.type!=="channel"||!r.source.channelId||!r.source.chatId?null:{channelId:r.source.channelId,chatId:r.source.chatId}}catch{return null}}async handleTaskStatusChange(e,n){let r=g(e);if(!r)return;let t={templateId:r.templateId,roleId:r.roleId,prompt:r.prompt,taskStatus:n},i=n==="completed"?"task_complete":"task_error",a=r.result??r.error??"";await this.matchAndDeliver(i,t,a,e)}async matchAndDeliver(e,n,r,t){let i=x(e,n);if(i.length!==0){s.debug({eventType:e,ruleCount:i.length,taskId:t},"Matched delivery rules");for(let a of i){if(!this.checkRateLimit(a)){s.warn({ruleId:a.id,maxPerMinute:a.maxPerMinute},"Delivery rate limit exceeded, skipping");continue}if(a.skipOriginChannel&&a.target.type==="channel"&&t&&this.isOriginChannel(t,a.target))continue;let d={id:b(),ruleId:a.id,taskId:t,status:"pending",target:a.target,content:r,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+D,source:"rule"};w(d),await this.attemptDelivery(d,a)}}}async attemptDeliveryPublic(e,n){return this.attemptDelivery(e,n)}async attemptDelivery(e,n){let r=E();try{if(e.target.type==="channel"){let t=e.target.chatId;!t&&e.target.channelId&&(t=S(e.target.channelId)?.config?.userId);let i=await r.send({taskId:e.taskId,channelId:e.target.channelId,chatId:t,content:e.content,messageType:"deliver"});i.success?s.info({entryId:e.id,ruleId:n.id,targetType:"channel"},"Delivery successful"):o(e.id,"failed",i.error??"Gateway returned failure")}else if(e.target.type==="webhook"){let t=await r.send({taskId:e.taskId,webhookUrl:e.target.webhookUrl,content:e.content,messageType:"deliver"});t.success?s.info({entryId:e.id,ruleId:n.id,targetType:"webhook"},"Webhook delivery successful"):o(e.id,"failed",t.error??"Gateway returned failure")}}catch(t){let i=t instanceof Error?t.message:String(t);o(e.id,"failed",i),s.warn({entryId:e.id,error:i},"Delivery attempt failed")}}checkRateLimit(e){let n=Date.now(),r=6e4,t=y.get(e.id);t||(t=[],y.set(e.id,t));let i=n-r;for(;t.length>0&&t[0]<i;)t.shift();return t.length>=e.maxPerMinute?!1:(t.push(n),!0)}isOriginChannel(e,n){try{if(n.type!=="channel"||!n.channelId)return!1;let r=f(e);if(!r)return!1;let t=m(r.sessionId);return t?t.source.type==="channel"&&t.source.channelId===n.channelId&&t.source.chatId===n.chatId:!1}catch{return!1}}async retryPending(){let e=k("rule",50),n=T("rule",50),r=[...e,...n];if(r.length!==0){s.debug({count:r.length},"Retrying pending/failed deliveries");for(let t of r){if(t.attempts>=3){o(t.id,"failed","Max retries (3) exceeded");continue}let i={id:t.ruleId??"retry-synthetic",eventType:"*",matchCriteria:{},target:t.target,maxPerMinute:5,skipOriginChannel:!0,enabled:!0,createdAt:0};await this.attemptDelivery(t,i)}}}};function N(){return c}function U(){c||(c=new v,u=setInterval(()=>{c?.retryPending().catch(l=>{s.error({error:l},"Delivery retry scan failed")})},6e4),p=setInterval(()=>{try{let l=P();l>0&&s.info({cleaned:l},"Expired delivery log entries cleaned up")}catch(l){s.error({error:l},"Delivery cleanup failed")}},36e5),s.info("DeliveryEngine started with retry (60s) and cleanup (1h) timers"))}function W(){u&&(clearInterval(u),u=null),p&&(clearInterval(p),p=null),c=null,y.clear(),s.info("DeliveryEngine stopped")}export{v as a,N as b,U as c,W as d};
|
package/dist/chunk-UOTDT2KY.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{b as $}from"./chunk-PQ7KPALO.js";import{b as k,c as f,d as h}from"./chunk-FDWW245P.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as b}from"./chunk-3DAK2XWP.js";function D(a,c,n){switch(c){case"wechat":return M(a);case"telegram":return a;case"slack":return E(a);case"webhook":return JSON.stringify({result:a,taskId:n,timestamp:new Date().toISOString()});default:return M(a)}}function M(a){return a.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
|
-
|
|
3
|
-
`).trim()}function E(a){return a.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}import{v4 as O}from"uuid";var x=b("adam"),_=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:n,channelId:s,chatId:d,content:y,messageType:i,platform:C,webhookUrl:m,replyMarkup:I}=c,S=i!=="reply"&&!!n;if(S){let t=`${n}:${s??"none"}:${d??"none"}:${i}`,r=this._dedupCache.get(t);if(r&&Date.now()-r.timestamp<300*1e3)return x.debug({dedupKey:t},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:r.logEntryId}}if(s){let t=Date.now(),r=6e4,o=this._rateLimitWindows.get(s);o||(o=[],this._rateLimitWindows.set(s,o));let u=t-r;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let l=O();return x.warn({channelId:s,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:l,error:"rate_limited"}}o.push(t)}let T=C??(s?$(s)?.platform:void 0)??"unknown",v=m?y:D(y,T,n),e=O(),g={id:e,ruleId:void 0,taskId:n??void 0,status:"pending",target:s&&d?{type:"channel",channelId:s,chatId:d}:m?{type:"webhook",webhookUrl:m}:{type:"channel",channelId:s??"",chatId:d??""},content:v,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:i};k(g);try{if(m){let t=await fetch(m,{method:"POST",body:JSON.stringify({result:y,taskId:n,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return h(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:i}),{success:!0,logEntryId:e};{let r=`Webhook returned ${t.status}`;return f(e,"failed",r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:r,messageType:i}),{success:!1,logEntryId:e,error:r}}}else if(s&&d){let{getChannelManager:t}=await import("./channels-WFZAONF3.js"),r=t();if(!r){let l="ChannelManager not available";return f(e,"failed",l),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:l,messageType:i}),{success:!1,logEntryId:e,error:l}}let o={content:v,...I?{replyMarkup:I}:{}},u=await r.sendMessage(s,d,o);if(u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),h(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"delivered",messageType:i}),S){let l=`${n}:${s??"none"}:${d??"none"}:${i}`;this._dedupCache.set(l,{logEntryId:e,timestamp:Date.now()})}return{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return f(e,"failed",t),{success:!1,logEntryId:e,error:t}}}catch(t){let r=t instanceof Error?t.message:String(t);return f(e,"failed",r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:n,target:g.target,status:"failed",error:r,messageType:i}),{success:!1,logEntryId:e,error:r}}}},w=null;function R(){return w||(w=new _),w}function G(a){return R().isRecentlySent(a)}export{_ as a,R as b,G as c};
|