adam-agent-server 1.16.0 → 1.18.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-SIQUVFJY.js +14 -0
- package/dist/approval-handler-BWA7UIKN.js +1 -0
- package/dist/{artifacts-S2KD6W76.js → artifacts-MAYKOTA2.js} +1 -1
- package/dist/audit-diagnostics-K3LUWXTI.js +1 -0
- package/dist/audit-manager-6WL2V6JG.js +1 -0
- package/dist/bree-engine-KYD4GKQK.js +1 -0
- package/dist/channels-2TWTBE6Y.js +1 -0
- package/dist/channels-PWDSTYNR.js +1 -0
- package/dist/chat-tool-calls-WJDFQ54U.js +1 -0
- package/dist/chunk-2A2TXYT3.js +15 -0
- package/dist/chunk-2CE2WUUZ.js +1 -0
- package/dist/chunk-2JIQT2CI.js +1 -0
- package/dist/chunk-3MROEPGR.js +1 -0
- package/dist/chunk-3UFEOB6P.js +143 -0
- package/dist/{chunk-VKKDSXMR.js → chunk-47HJPIUA.js} +1 -1
- package/dist/{chunk-AQAHVNNG.js → chunk-4JHACUZY.js} +5 -5
- package/dist/{chunk-NUJSTEV4.js → chunk-4N5G7ND2.js} +1 -1
- package/dist/{chunk-TLMG5W3L.js → chunk-5G64P4KE.js} +1 -1
- package/dist/{chunk-245WE5AF.js → chunk-5M6IGE5G.js} +1 -1
- package/dist/chunk-5PELJRUQ.js +1 -0
- package/dist/{chunk-VVQ532U2.js → chunk-6WQFYV3N.js} +1 -1
- package/dist/{chunk-N2OLEUAQ.js → chunk-AUSR5JYV.js} +1 -1
- package/dist/{chunk-LVHLUAZW.js → chunk-BE653A45.js} +8 -7
- package/dist/{chunk-OXGWWSKT.js → chunk-BMCNQGUH.js} +1 -1
- package/dist/{chunk-BLCNUT53.js → chunk-EZLBMUQD.js} +1 -1
- package/dist/{chunk-NLTYJUQG.js → chunk-HL373H4P.js} +1 -1
- package/dist/{chunk-6Y2DN2UH.js → chunk-HRPMRWHD.js} +1 -1
- package/dist/{chunk-HJICGOD4.js → chunk-IEBAOZED.js} +2 -2
- package/dist/{chunk-SCUPWMI5.js → chunk-JROGEBP5.js} +1 -1
- package/dist/{chunk-LQVBWVLE.js → chunk-JYZTIE2J.js} +1 -1
- package/dist/{chunk-I44JKROJ.js → chunk-JZBXLN7M.js} +1 -1
- package/dist/{chunk-H4MMEULK.js → chunk-KS24764D.js} +2 -2
- package/dist/chunk-LCD5DVS6.js +1 -0
- package/dist/chunk-LKGYQJMS.js +6 -0
- package/dist/chunk-MTRLUW7Z.js +1 -0
- package/dist/{chunk-3UR2PN5N.js → chunk-NSUXJ2VA.js} +1 -1
- package/dist/{chunk-OGY42NUN.js → chunk-NUOTFUNF.js} +1 -1
- package/dist/chunk-NXGR3PRY.js +1 -0
- package/dist/{chunk-YNS5LQX5.js → chunk-O6L4UVLV.js} +1 -1
- package/dist/{chunk-FYULPPFR.js → chunk-OBD4245G.js} +1 -1
- package/dist/chunk-QTGAK62Z.js +14 -0
- package/dist/chunk-QYI44EP6.js +10 -0
- package/dist/{chunk-R24YRJRG.js → chunk-SGLZAIVL.js} +1 -1
- package/dist/chunk-SKHMWKJT.js +80 -0
- package/dist/chunk-T2Z2JDPY.js +2 -0
- package/dist/chunk-TA5PFK5C.js +5 -0
- package/dist/chunk-TWOJVEO7.js +32 -0
- package/dist/chunk-UCUELFCS.js +61 -0
- package/dist/{chunk-TJTH7LHX.js → chunk-V2MMQ3SH.js} +1 -1
- package/dist/{chunk-WBAPIPST.js → chunk-VO24C673.js} +1 -1
- package/dist/{chunk-HC34HJFF.js → chunk-VPMHZJS2.js} +1 -1
- package/dist/chunk-VWX2B6OM.js +6 -0
- package/dist/{chunk-QL2ZOLMC.js → chunk-WY5BOCQP.js} +180 -33
- package/dist/{chunk-TCBGUVVU.js → chunk-XAPJJAJQ.js} +1 -1
- package/dist/{chunk-HXDS4NWI.js → chunk-Z2APBKIT.js} +1 -1
- package/dist/chunk-ZJ3TS4FL.js +182 -0
- package/dist/{chunk-52FETPCI.js → chunk-ZQN6JZIJ.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/config-U624HJKI.js +1 -0
- package/dist/config-X7A6NA73.js +1 -0
- package/dist/db-XODNIJSJ.js +1 -0
- package/dist/{delivery-log-3O3OHKY4.js → delivery-log-QMQQHES4.js} +1 -1
- package/dist/engine-OQXDHA2R.js +1 -0
- package/dist/evolution-audit-XF4KZZMP.js +1 -0
- package/dist/execution-tools-BR4T4MMW.js +1 -0
- package/dist/{external-api-YMEFVZGG.js → external-api-435WH6V3.js} +1 -1
- package/dist/index.js +67 -47
- package/dist/learner-4CJ7BSCN.js +1 -0
- package/dist/logger-TEZSHFTZ.js +1 -0
- package/dist/{memories-2DY5G6ZN.js → memories-NJFKSOL5.js} +1 -1
- package/dist/memory-extractor-UQI75BBK.js +1 -0
- package/dist/memory-gc-NTZVUGJX.js +1 -0
- package/dist/memory-service-3RLVOF2C.js +1 -0
- package/dist/outbound-gateway-NJNSN2ZX.js +1 -0
- package/dist/presets-SUJRFRJC.js +1 -0
- package/dist/reflection-job-F4BZA2E3.js +23 -0
- package/dist/role-presets-VEYTGYA4.js +1 -0
- package/dist/role-workspace-AIVHPX5P.js +1 -0
- package/dist/roles-WDMUBWQP.js +1 -0
- package/dist/runtime-OMLPOMCA.js +1 -0
- package/dist/server-bus-6QGH2AVL.js +1 -0
- package/dist/session-manager-XFUKWEC7.js +1 -0
- package/dist/skill-registry-LARMNUT5.js +1 -0
- package/dist/target-resolution-RLNUCT6M.js +1 -0
- package/dist/{task-templates-4YPKFFKG.js → task-templates-BIVCRNXA.js} +1 -1
- package/dist/template-dispatch-6FPJQN6A.js +1 -0
- package/dist/trace-context-NVCN6UPC.js +1 -0
- package/package.json +2 -1
- package/web/dist/assets/{ArtifactDetail-9DJdEqCz.js → ArtifactDetail-DDTEAl2E.js} +2 -2
- package/web/dist/assets/{Artifacts-CQ6SAemH.js → Artifacts-BrhnC1Ef.js} +1 -1
- package/web/dist/assets/{Button-xVc-P0vm.js → Button-CRNb8sD3.js} +1 -1
- package/web/dist/assets/{Card-WUD1cwG6.js → Card-Cwvv0An8.js} +1 -1
- package/web/dist/assets/{ChannelDetail-B21nBQwi.js → ChannelDetail-D0FBZoAX.js} +1 -1
- package/web/dist/assets/{Channels-CAeGE1r7.js → Channels-Cztxvsa2.js} +2 -2
- package/web/dist/assets/{Chat-KpFWchPp.js → Chat-Ce72TtUi.js} +2 -2
- package/web/dist/assets/Cost-K8-4xqBe.js +4 -0
- package/web/dist/assets/{Dashboard-DkRwHNmr.js → Dashboard-BXqFb_Vr.js} +1 -1
- package/web/dist/assets/{EmptyState-BLB33cKG.js → EmptyState-BvQA1o5K.js} +1 -1
- package/web/dist/assets/{EnvVarEditor-BchUNrmz.js → EnvVarEditor-FiiJazzp.js} +1 -1
- package/web/dist/assets/{EventDefDetail-DnBwWWfT.js → EventDefDetail-C3S1G0K8.js} +1 -1
- package/web/dist/assets/{Events-ByIzPIs2.js → Events-BKxqZ9j6.js} +1 -1
- package/web/dist/assets/{Evolution-Vh9RKdma.js → Evolution-DFcSm6Rw.js} +1 -1
- package/web/dist/assets/{ExtensionDetail-0CtJh5rF.js → ExtensionDetail-C8aPpyLv.js} +1 -1
- package/web/dist/assets/Extensions-MLZk05j0.js +1 -0
- package/web/dist/assets/{FeatureRequests-XhQbGg_q.js → FeatureRequests-D_4XaQ7F.js} +1 -1
- package/web/dist/assets/{GoalDetail-DIOxf7ES.js → GoalDetail-DVU7c0aR.js} +1 -1
- package/web/dist/assets/{Goals-CZnHu9qC.js → Goals-D3h4WMjU.js} +1 -1
- package/web/dist/assets/LineChart-Ck1vfYHs.js +33 -0
- package/web/dist/assets/Logs-D5MQv6Yw.js +1 -0
- package/web/dist/assets/{Memories-D-EAODUg.js → Memories-Dls71I2i.js} +1 -1
- package/web/dist/assets/{Mistakes-wW78K3cP.js → Mistakes-BZcTg0vP.js} +1 -1
- package/web/dist/assets/{NotFound-BsxIP-Xm.js → NotFound-t66RIvqO.js} +1 -1
- package/web/dist/assets/{PageHeader-D8pqg_wk.js → PageHeader-acLQTYct.js} +1 -1
- package/web/dist/assets/Plugins-CwCHGzI6.js +1 -0
- package/web/dist/assets/RoleDetail-B2M6ALSl.js +3 -0
- package/web/dist/assets/Roles-FEHqm_Jf.js +1 -0
- package/web/dist/assets/{SectionHeader-DZo4QVWr.js → SectionHeader-NZWZgoOs.js} +1 -1
- package/web/dist/assets/Settings-rdVQMfqX.js +1 -0
- package/web/dist/assets/{Strategies-Bg4qlLei.js → Strategies-CwJ9JQ-X.js} +1 -1
- package/web/dist/assets/{Switch-WWPXnSOG.js → Switch-1JjR4Imr.js} +1 -1
- package/web/dist/assets/{Table-XjSmrOyn.js → Table-CvSmzzkm.js} +1 -1
- package/web/dist/assets/{Tabs-CSbcG_5T.js → Tabs-DWk9HyNd.js} +1 -1
- package/web/dist/assets/TaskDetail-h12WxjfG.js +2 -0
- package/web/dist/assets/Work-CfzFRSZX.js +1 -0
- package/web/dist/assets/api-BP4ZP9kk.js +1 -0
- package/web/dist/assets/{es2015-BgPT8VkR.js → es2015-BkFSNOYE.js} +1 -1
- package/web/dist/assets/index-CXEJd-0s.js +12 -0
- package/web/dist/assets/index-CarTGiGO.css +2 -0
- package/web/dist/assets/{useIsMobileLayout-DF2fEEM9.js → useIsMobileLayout-BogOiFTv.js} +1 -1
- package/web/dist/assets/{usePluginsWithUsage-CjU8Lkdn.js → usePluginsWithUsage-4iLJAPjH.js} +1 -1
- package/web/dist/assets/{vendor-icons-H7p0EuQJ.js → vendor-icons-Bc_e_XXa.js} +1 -1
- package/web/dist/assets/{vendor-react-C1yKjxEP.js → vendor-react-bQ_cvNuA.js} +1 -1
- package/web/dist/assets/{vendor-state-D0TNAbOY.js → vendor-state-BMVR_B0I.js} +1 -1
- package/web/dist/index.html +8 -8
- package/dist/App-Z2GJAMX3.js +0 -14
- package/dist/approval-handler-6NPN24UN.js +0 -1
- package/dist/audit-diagnostics-2MDM3IQT.js +0 -1
- package/dist/audit-manager-QG7CMBV2.js +0 -1
- package/dist/bree-engine-3QSLZF3W.js +0 -1
- package/dist/channels-S4AAOOTN.js +0 -1
- package/dist/channels-TYXSSI7D.js +0 -1
- package/dist/chat-tool-calls-2C7O4B2X.js +0 -1
- package/dist/chunk-32LOJEHE.js +0 -32
- package/dist/chunk-3UZIEE2D.js +0 -6
- package/dist/chunk-4234WJJD.js +0 -178
- package/dist/chunk-AG5SADAI.js +0 -5
- package/dist/chunk-ASPPM7TQ.js +0 -1
- package/dist/chunk-C2XFPUFV.js +0 -1
- package/dist/chunk-DRO3DG7X.js +0 -1
- package/dist/chunk-EWYXVBOG.js +0 -61
- package/dist/chunk-FCV2DPZQ.js +0 -1
- package/dist/chunk-FHESRUJY.js +0 -9
- package/dist/chunk-K2TZW4DU.js +0 -132
- package/dist/chunk-K4IE6DPX.js +0 -6
- package/dist/chunk-MNSZE3NV.js +0 -1
- package/dist/chunk-MTQI6B7T.js +0 -15
- package/dist/chunk-P5Q2UINT.js +0 -1
- package/dist/chunk-WVHN54MA.js +0 -14
- package/dist/chunk-XYZVMTNN.js +0 -1
- package/dist/chunk-Z6LHGA27.js +0 -1
- package/dist/config-HDAAV5FV.js +0 -1
- package/dist/config-VHWLMFIN.js +0 -1
- package/dist/db-HFBXO2O5.js +0 -1
- package/dist/dist-HCSYRPJU.js +0 -1
- package/dist/engine-J43ECCH7.js +0 -1
- package/dist/evolution-audit-BSGPFGFK.js +0 -1
- package/dist/execution-tools-HHUPWLCF.js +0 -1
- package/dist/learner-TQQZKRSB.js +0 -1
- package/dist/logger-PAMNFWI3.js +0 -1
- package/dist/memory-extractor-TUOOFST2.js +0 -1
- package/dist/memory-gc-MRO53MEY.js +0 -1
- package/dist/memory-service-23WVAW7T.js +0 -1
- package/dist/onnxruntime_binding-2BPLI7ZQ.node +0 -0
- package/dist/onnxruntime_binding-5J67DTMJ.node +0 -0
- package/dist/onnxruntime_binding-7ZZLEQ2F.node +0 -0
- package/dist/onnxruntime_binding-KDCXAPN5.node +0 -0
- package/dist/onnxruntime_binding-R73P2IQW.node +0 -0
- package/dist/outbound-gateway-VXODXSQR.js +0 -1
- package/dist/presets-KJV6SNNB.js +0 -1
- package/dist/reflection-job-EFFW3WOR.js +0 -23
- package/dist/role-presets-PHHL3OEN.js +0 -1
- package/dist/role-workspace-USY47ZPQ.js +0 -1
- package/dist/roles-3JXNHL7K.js +0 -1
- package/dist/runtime-TWLGJSL6.js +0 -1
- package/dist/server-bus-GEGVMSCA.js +0 -1
- package/dist/session-manager-PI3JEINK.js +0 -1
- package/dist/skill-registry-ROGU2WED.js +0 -1
- package/dist/target-resolution-PSSBM4LX.js +0 -1
- package/dist/template-dispatch-46TN534D.js +0 -1
- package/dist/trace-context-UR7DI5ME.js +0 -1
- package/web/dist/assets/Extensions--O1ulwlC.js +0 -1
- package/web/dist/assets/Logs-DdeG3GiY.js +0 -1
- package/web/dist/assets/Plugins-DDUdX51_.js +0 -1
- package/web/dist/assets/RoleDetail-CU3G9j_q.js +0 -35
- package/web/dist/assets/Roles-BCoSzDBg.js +0 -1
- package/web/dist/assets/Settings-K3usfV-2.js +0 -1
- package/web/dist/assets/TaskDetail-C5roukcV.js +0 -2
- package/web/dist/assets/Work-DGTWSgtc.js +0 -1
- package/web/dist/assets/api-BkdixMz9.js +0 -1
- package/web/dist/assets/index-KNUbHDLy.css +0 -2
- package/web/dist/assets/index-iD-HOtIu.js +0 -12
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import{a as To}from"./chunk-NS6WVZMS.js";import{b as v,d as Vr,e as zo}from"./chunk-HL373H4P.js";import{a as qr,f as Ko,h as Ho}from"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";import{Box as Mr,Text as pr,useInput as il}from"ink";import{useState as al,useEffect as go,useRef as Qt,useReducer as ll}from"react";import{createContext as Rs,useContext as Ds,useReducer as Ms}from"react";import{jsx as _s}from"react/jsx-runtime";var $s={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",selectedTaskId:null,configVersion:0,session:null,version:null};function Ns(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,selectedTaskId:t.selectedTaskId??e.selectedTaskId};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 Xo=Rs(null);function Yo({children:e}){let[t,r]=Ms(Ns,$s);return _s(Xo.Provider,{value:{state:t,dispatch:r},children:e})}function tt(){let e=Ds(Xo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as Qo,useRef as Jo}from"react";var Ls=15e3;function Zo(){let{state:e,dispatch:t}=tt(),r=Jo(null),a=Jo(null);Qo(()=>{a.current=e.session?.id??null},[e.session?.id]),Qo(()=>{let o=!0,u=null,d=()=>{r.current&&(clearTimeout(r.current),r.current=null)},l=()=>{d(),r.current=setTimeout(()=>{o&&t({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},Ls)};return(()=>{try{u=new Vr("/events"),u.on("task_status_change",()=>{}),u.on("approval_request",n=>{if(!o)return;let p=n;t({type:"SET_PENDING_APPROVAL",approval:{taskId:p.taskId,approvalId:p.approvalId,toolName:p.toolName,toolInput:p.toolInput,matchedPattern:p.matchedPattern}})}),u.on("plan_approval_request",n=>{if(!o)return;let p=n;t({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:p.taskId,planId:p.planId,roleId:p.roleId,plan:p.plan}})}),u.on("plan_approval_decision",()=>{o&&t({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),u.on("config_changed",()=>{o&&t({type:"CONFIG_CHANGED"})}),u.on("execution_task_start",n=>{if(!o)return;let p=n,g=a.current;g&&(async()=>{try{let b=await v(`/tasks/${p.taskId}`);o&&b.sourceSessionId===g&&t({type:"SET_ACTIVE_TASK",taskId:p.taskId})}catch{}})()}),u.on("stats_update",n=>{if(!o)return;let p=n;t({type:"UPDATE_STATS",activeTasks:p.activeTasks,queuedTasks:p.queuedTasks,costToday:p.totalCostToday})}),u.connect().then(async()=>{if(o){d(),t({type:"SET_CONNECTED",connected:!0}),t({type:"SET_SERVER_UNREACHABLE",unreachable:!1});try{let n=await v("/version");t({type:"SET_VERSION",version:n.version})}catch{t({type:"SET_VERSION",version:null})}}}).catch(()=>{o&&(t({type:"SET_CONNECTED",connected:!1}),l())})}catch{o&&(t({type:"SET_CONNECTED",connected:!1}),l())}})(),()=>{o=!1,d(),u?.close()}},[t])}import{useEffect as Fs,useRef as Os,useState as en,useCallback as qs}from"react";function tn(e){let[t,r]=en([]),[a,o]=en(!1),u=Os(null),d=qs(()=>{r([]),o(!1)},[]);return Fs(()=>{if(!e)return;let l=!0;r([]),o(!0);try{let i=new zo(e);return u.current=i,i.on("reasoning",n=>{if(!l)return;let g=n.content??"";r(b=>{let y=b[b.length-1];if(y?.type==="reasoning"){let w=[...b];return w[w.length-1]={...y,content:y.content+g},w}return[...b,{type:"reasoning",content:g,timestamp:Date.now()}]})}),i.on("tool_call",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"tool_call",content:p.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:p.toolName}}])}),i.on("tool_result",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"tool_result",content:p.content??"",timestamp:Date.now()}])}),i.on("error",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"error",content:p.error??"unknown error",timestamp:Date.now()}])}),i.on("complete",n=>{if(!l)return;let p=n;r(g=>[...g,{type:"complete",content:p.result??"",timestamp:Date.now(),metadata:{cost:p.costUsd,turns:p.numTurns,duration:p.totalDurationMs}}]),o(!1)}),i.connect().catch(()=>{l&&(r(n=>[...n,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),o(!1))}),()=>{l=!1,i.close()}}catch{o(!1)}},[e]),{events:t,isStreaming:a,clearEvents:d}}import{useState as ho,useEffect as Vs,useCallback as yr}from"react";function yo(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function rn(){let[e,t]=ho(null),[r,a]=ho(!0),[o,u]=ho(null),d=yr(async()=>{try{let b=(await v("/chat/sessions?status=active")).sessions.find(y=>y.source.type==="tui");return b?yo(b):null}catch{return null}},[]),l=yr(async()=>{try{let g=await v("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),b=yo(g.session);return t(b),b}catch{return u("Failed to create session"),null}},[]),i=yr(async g=>{try{let b=await v("/chat/messages",{method:"POST",body:{content:g,source:{type:"tui"}}});return t(y=>y&&{...y,messageCount:y.messageCount+1,lastActiveAt:Date.now()}),b}catch{return null}},[]),n=yr(async()=>{if(!e)return!1;try{return await v(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),p=yr(async()=>{if(e)try{let g=await v(`/chat/sessions/${e.id}`);t(yo(g.session))}catch{t(null)}},[e]);return Vs(()=>{let g=!1;async function b(){a(!0);let y=await d();g||(y?t(y):await l(),g||a(!1))}return b(),()=>{g=!0}},[]),{session:e,loading:r,error:o,sendMessage:i,createNewSession:l,archiveCurrentSession:n,refreshSession:p,setSession:t}}import{useEffect as on,useRef as Us,useState as Ws}from"react";function nn(e){let[t,r]=Ws(null),a=Us(new Set);return on(()=>{if(!e)return;let o=!0,u=null;try{u=new Vr("/chat/stream"),u.on("chat_message",d=>{if(!o)return;let i=d.message;i&&i.sessionId===e&&i.role==="assistant"&&(a.current.has(i.id)||(a.current.add(i.id),r(i)))}),u.connect().catch(()=>{})}catch{}return()=>{o=!1,u?.close()}},[e]),on(()=>{a.current.clear(),r(null)},[e]),{latestMessage:t}}import{Box as bo,Text as We}from"ink";import{Fragment as Ur,jsx as Ee,jsxs as tr}from"react/jsx-runtime";var Gs=90;function sn({children:e}){return Ee(bo,{children:e})}function an(){let{state:e}=tt(),t=e.session,a=(t?Math.floor((Date.now()-t.lastActiveAt)/6e4):1/0)>=25,o=e.connected?"up":"down",u=e.view==="chat"?"Chat":e.view.charAt(0).toUpperCase()+e.view.slice(1),d=t?t.messageCount===0?"new session":`${t.id.slice(0,8)} \xB7 ${t.messageCount}t`:null,i=(process.stdout.columns??100)<Gs,n=tr(Ur,{children:[Ee(We,{bold:!0,children:e.version?`Adam v${e.version}`:"Adam"}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{color:e.connected?"green":"red",children:(e.connected,"\u25CF")}),Ee(We,{children:` ${o}`}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:u.toLowerCase()})]}),p=tr(Ur,{children:[Ee(We,{children:`${e.activeTasks} run / ${e.queuedTasks} q`}),Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:`$${e.costToday.toFixed(2)}`}),e.view==="chat"&&t&&tr(Ur,{children:[Ee(We,{dimColor:!0,children:" | "}),Ee(We,{children:d}),a&&tr(Ur,{children:[Ee(We,{dimColor:!0,children:" | "}),Ee(We,{color:"yellow",children:"timeout"})]})]})]});return i?tr(bo,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,paddingX:1,children:[Ee(sn,{children:n}),Ee(sn,{children:p})]}):tr(bo,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:[n,Ee(We,{dimColor:!0,children:" | "}),p]})}import{Box as Wr,Text as Gr,useInput as Ks}from"ink";import{useState as Co,useMemo as Hs}from"react";import zs from"ink-text-input";var js=[{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:"artifacts",description:"Browse artifacts across tasks"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function vo(e){let t=e.toLowerCase();return js.filter(r=>r.name.startsWith(t))}function ln(e){let t=vo(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as jr,jsxs as br}from"react/jsx-runtime";function cn({onSubmit:e}){let[t,r]=Co(""),[a,o]=Co(0),[u,d]=Co(!1),l=t.startsWith("/")&&t.length>=1,i=t.slice(1),n=Hs(()=>l?vo(i):[],[l,i]),p=y=>{r(y),y.startsWith("/")?(d(!0),o(0)):d(!1)},g=()=>{let y=t.trim();if(y){if(y.startsWith("/")){let w=y.slice(1),s=ln(w);e(s?`/${s.name}`:y)}else e(y);r(""),d(!1)}},b=y=>{e(`/${y.name}`),r(""),d(!1)};return Ks((y,w)=>{if(!(!u||!l||n.length===0)){if(w.upArrow){o(s=>s<=0?n.length-1:s-1);return}if(w.downArrow){o(s=>s>=n.length-1?0:s+1);return}if(w.tab){let s=n[a];s&&b(s);return}if(w.escape){d(!1),r("");return}}},{isActive:u&&l&&n.length>0}),br(Wr,{flexDirection:"column",children:[u&&l&&n.length>0&&jr(Wr,{flexDirection:"column",marginBottom:0,paddingX:1,children:n.map((y,w)=>{let s=w===a;return br(Wr,{children:[jr(Gr,{color:s?"cyan":"gray",bold:s,children:s?"\u25B8 ":" "}),br(Gr,{color:s?"cyan":"white",bold:s,children:["/",y.name]}),br(Gr,{dimColor:!0,children:[" \u2014 ",y.description]})]},y.name)})}),br(Wr,{borderStyle:"round",borderDimColor:!0,children:[jr(Gr,{bold:!0,children:"\u25B8 "}),jr(zs,{value:t,onChange:p,onSubmit:g,placeholder:"Type a message or / for commands..."})]})]})}import{Box as rr,Text as _e,useInput as Xs}from"ink";import{useState as Ys}from"react";import{jsx as ze,jsxs as pt}from"react/jsx-runtime";function Qs({content:e,expanded:t}){let r=e.split(`
|
|
2
|
+
`);return r.length<=5?ze(_e,{color:"green",children:e}):t?ze(_e,{color:"green",children:e}):pt(_e,{color:"green",children:[r.slice(0,3).join(`
|
|
3
|
+
`),`
|
|
4
|
+
`,pt(_e,{dimColor:!0,children:["(",r.length," lines) [Ctrl+O] expand"]})]})}function Js({event:e,expanded:t}){switch(e.type){case"reasoning":return ze(rr,{children:ze(_e,{color:"gray",children:e.content})});case"tool_call":return ze(rr,{children:pt(_e,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return pt(rr,{flexDirection:"column",children:[ze(_e,{color:"blue",dimColor:!0,children:"[result]"}),ze(Qs,{content:e.content,expanded:t})]});case"error":return ze(rr,{children:pt(_e,{color:"red",children:["[error] ",e.content]})});case"complete":return pt(rr,{flexDirection:"column",marginTop:1,children:[e.content&&ze(_e,{children:e.content}),ze(_e,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&pt(_e,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&pt(_e,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&pt(_e,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function dn({events:e,isStreaming:t}){let[r,a]=Ys(!1),o=e.some(u=>u.type==="tool_result"&&u.content.split(`
|
|
5
|
+
`).length>5);return Xs((u,d)=>{d.ctrl&&u==="o"&&a(l=>!l)},{isActive:o}),e.length===0&&!t?null:pt(rr,{flexDirection:"column",children:[t&&e.length===0&&ze(_e,{dimColor:!0,children:"Waiting for response..."}),e.map((u,d)=>ze(Js,{event:u,expanded:r},d)),o&&ze(_e,{dimColor:!0,children:r?"[Ctrl+O] collapse full output":"[Ctrl+O] expand full output"})]})}import{Box as Sn,Text as Jr}from"ink";import{Box as Zs,Text as Kr}from"ink";import ei from"ink-spinner";import{jsx as Hr,jsxs as un}from"react/jsx-runtime";var ti={running:{glyph:"",color:"blue"},completed:{glyph:"\u2713",color:"green"},failed:{glyph:"\u2717",color:"red"},retrying:{glyph:"\u21BB",color:"yellow"},blocked:{glyph:"\u23F8",color:"yellow"}};function mn({content:e,phase:t,taskShortId:r}){let a=ti[t];return un(Zs,{children:[Hr(Kr,{color:a.color,children:t==="running"?Hr(ei,{type:"dots"}):a.glyph}),Hr(Kr,{children:" "}),r&&un(Kr,{dimColor:!0,children:["[",r,"] "]}),Hr(Kr,{dimColor:!0,children:e})]})}import{Box as vr,Text as Yr}from"ink";var fn=["cyan","magenta","green","yellow","blue","red"];function ri(e){let t=5381;for(let r=0;r<e.length;r++)t=(t<<5)+t^e.charCodeAt(r);return Math.abs(t)}function zr(e){return e?fn[ri(e)%fn.length]:"cyan"}function Xr(e){return e?`T-${e.replace(/-/g,"").slice(0,8).toUpperCase()}`:""}import{jsx as Cr,jsxs as Qr}from"react/jsx-runtime";function oi(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function ni(e){if(!e)return"";let t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function si(e){return e.map(t=>{if(t.type==="channel"&&t.channelId)return t.channelId;if(t.type==="webhook"&&t.webhookUrl)try{return new URL(t.webhookUrl).hostname}catch{return t.webhookUrl}return t.type}).join(", ")}function gn(e){let t=zr(e.roleId),r=e.roleName??"?",a=e.taskShortIdLabel?` \xB7 ${e.taskShortIdLabel}`:"";return Qr(vr,{flexDirection:"column",borderStyle:"round",borderColor:t,paddingX:1,children:[Cr(vr,{children:Qr(Yr,{bold:!0,color:t,children:["[",r,a,"]"]})}),Cr(vr,{marginTop:1,children:Cr(Yr,{children:e.content})}),e.attachments&&e.attachments.length>0&&Cr(vr,{flexDirection:"column",marginTop:1,children:e.attachments.map(o=>{let u=o.purpose?`purpose=${o.purpose}, `:"";return Qr(Yr,{dimColor:!0,children:["[file] ",o.filename," (",u,oi(o.size),") \u2192 ",o.locator]},o.artifactId)})}),e.mirroredToTargets&&e.mirroredToTargets.length>0&&Cr(vr,{marginTop:1,children:Qr(Yr,{dimColor:!0,italic:!0,children:["(also delivered to: ",si(e.mirroredToTargets)," @ ",ni(e.createdAt),")"]})})]})}import{Box as Wt,Text as or}from"ink";import ii from"ink-select-input";import{useState as pn}from"react";import{jsx as Bt,jsxs as Sr}from"react/jsx-runtime";var ai=[{label:"\u6279\u51C6 / Yes",value:"\u6279\u51C6"},{label:"\u62D2\u7EDD / No",value:"\u62D2\u7EDD"}];function xn({promptId:e,content:t,shape:r,choices:a,onSubmitted:o,onSubmitFailure:u}){let[d,l]=pn(null),[i,n]=pn(null),p=r==="yes_no"?ai:r==="choose_one"&&a&&a.length>0?a.map(b=>({label:b,value:b})):[],g=async b=>{try{await v("/chat/messages",{method:"POST",body:{content:b.value,source:{type:"tui"},buttonPayload:{promptId:e,value:b.value}}}),l(b.value),o?.(b.value)}catch{n(`Failed to submit. Try again or type "#${e} ${b.value}" in the input bar.`),u?.()}};return Sr(Wt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Sr(or,{bold:!0,color:"yellow",children:["\u26A0 #",e]}),Bt(Wt,{marginTop:1,children:Bt(or,{children:t})}),d?Bt(Wt,{marginTop:1,children:Sr(or,{color:"green",children:["[\u5DF2\u63D0\u4EA4: ",d," \u2713]"]})}):r==="free_input"?Bt(Wt,{marginTop:1,children:Sr(or,{dimColor:!0,children:["Free-input shape: \u8BF7\u56DE\u590D #",e," \u4F60\u7684\u7B54\u590D"]})}):p.length>0?Bt(Wt,{marginTop:1,children:Bt(ii,{items:p,onSelect:g})}):Bt(Wt,{marginTop:1,children:Sr(or,{color:"red",dimColor:!0,children:["(no choices configured for shape=",r,")"]})}),i&&Bt(Wt,{marginTop:1,children:Bt(or,{color:"red",children:i})})]})}import{Box as li,Text as ci}from"ink";import{jsx as ui,jsxs as di}from"react/jsx-runtime";function Tn({content:e}){return ui(li,{children:di(ci,{dimColor:!0,children:["\xB7 ",e]})})}import{Box as So,Text as mi}from"ink";import{jsx as yn,jsxs as hn}from"react/jsx-runtime";function bn({threadRoot:e,roleId:t,roleName:r,taskShortIdLabel:a,brief:o,children:u}){let d=zr(t),l=[a,r,o].filter(Boolean),i=l.length>0?l.join(" / "):e.slice(0,8);return hn(So,{flexDirection:"column",borderStyle:"round",borderColor:d,paddingX:1,marginBottom:1,children:[yn(So,{children:hn(mi,{bold:!0,color:d,children:["[Thread ",i,"]"]})}),yn(So,{flexDirection:"column",marginTop:1,children:u})]})}import{useEffect as fi,useState as vn}from"react";function Cn(){let[e,t]=vn(new Map),[r,a]=vn(!1);return fi(()=>{let o=!1;async function u(){try{let d=await v("/roles");if(o)return;let l=new Map;for(let i of d.roles)l.set(i.id,i.name);t(l)}catch{}finally{o||a(!0)}}return u(),()=>{o=!0}},[]),{getName:o=>o&&e.get(o)||"?",loaded:r}}import{jsx as Lt,jsxs as wo}from"react/jsx-runtime";function gi(e){let t=e.toLowerCase();return t.includes("completed")||t.includes("done")||t.includes("\u6210\u529F")?"completed":t.includes("failed")||t.includes("error")||t.includes("\u5931\u8D25")?"failed":t.includes("retry")||t.includes("\u91CD\u8BD5")?"retrying":t.includes("blocked")||t.includes("auth_required")||t.includes("\u963B\u585E")?"blocked":"running"}function pi(e,t,r){return function(o,u){if(!o.kind||o.kind==="user_message"||o.kind==="assistant_text")return wo(Sn,{flexDirection:"column",marginBottom:1,children:[Lt(Jr,{dimColor:!0,bold:!0,children:o.role==="user"?"You:":"Adam:"}),Lt(Jr,{children:o.content})]},u);if(o.kind==="status_report")return Lt(mn,{content:o.content,phase:gi(o.content),taskShortId:Xr(o.taskId)},u);if(o.kind==="result_delivery")return Lt(gn,{content:o.content,roleId:o.roleId,roleName:e(o.roleId),taskShortIdLabel:Xr(o.taskId),attachments:o.attachments,mirroredToTargets:o.mirroredToTargets,createdAt:o.createdAt},u);if(o.kind==="approval_prompt"&&o.promptId&&o.approvalShape){let d=o.promptId;return Lt(xn,{promptId:d,content:o.content,shape:o.approvalShape,onSubmitted:()=>t?.(d),onSubmitFailure:()=>r?.(d)},u)}return o.kind==="system_note"?Lt(Tn,{content:o.content},u):Lt(Jr,{dimColor:!0,children:o.content},u)}}function xi(e){let t=[],r=0;for(;r<e.length;){let a=e[r];if(a.kind==="status_report"){let o=r;for(;o<e.length&&e[o].kind==="status_report";)o++;let u=o-r;if(u>=3){t.push({__synthetic:!0,count:u,lastContent:e[o-1].content}),r=o;continue}}t.push(a),r++}return t}function wn({messages:e,onApprovalSubmitted:t,onApprovalFailed:r}){let{getName:a}=Cn(),o=pi(a,t,r);if(e.length===0)return null;let u=[],d=new Map;for(let l of e)if(!l.threadRoot)u.push(l);else{let i=d.get(l.threadRoot)??[];i.push(l),d.set(l.threadRoot,i)}return wo(Sn,{flexDirection:"column",children:[u.map((l,i)=>o(l,`free-${l.id??i}`)),Array.from(d.entries()).map(([l,i])=>{let n=i[0],p=xi(i);return Lt(bn,{threadRoot:l,roleId:n.roleId,roleName:a(n.roleId),taskShortIdLabel:Xr(n.taskId),brief:n.content.slice(0,30),children:p.map((g,b)=>"__synthetic"in g?wo(Jr,{dimColor:!0,children:["\u2026 ",g.count," \u6761\u8FDB\u5C55\uFF08\u6700\u8FD1: ",g.lastContent.slice(0,40),"\uFF09"]},`compressed-${b}`):o(g,`${l}-${g.id??b}`))},`thread-${l}`)})]})}import{Box as wr,Text as xt,useInput as Ti}from"ink";import{jsx as Tt,jsxs as kr}from"react/jsx-runtime";function kn({approval:e,onResolved:t}){return Ti(r=>{r==="a"?v(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):r==="r"&&v(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),kr(wr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Tt(xt,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),kr(wr,{marginTop:1,children:[Tt(xt,{children:"Tool: "}),Tt(xt,{bold:!0,children:e.toolName})]}),kr(wr,{children:[Tt(xt,{children:"Input: "}),Tt(xt,{children:JSON.stringify(e.toolInput)})]}),kr(wr,{children:[Tt(xt,{children:"Pattern: "}),Tt(xt,{dimColor:!0,children:e.matchedPattern})]}),kr(wr,{marginTop:1,children:[Tt(xt,{color:"green",children:"[a] Approve"}),Tt(xt,{children:" "}),Tt(xt,{color:"red",children:"[r] Reject"})]})]})}import{Box as Br,Text as Le,useInput as hi}from"ink";import{useState as yi,useEffect as bi}from"react";import{jsx as It,jsxs as at}from"react/jsx-runtime";var vi=300;function Bn({approval:e,onResolved:t,onTimeout:r}){let[a,o]=yi(vi);bi(()=>{let d=setInterval(()=>{o(l=>l<=1?(clearInterval(d),r(),0):l-1)},1e3);return()=>clearInterval(d)},[r]),hi(d=>{d==="a"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):d==="r"?v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):d==="p"&&v(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let u=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return at(Br,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[It(Le,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),at(Le,{dimColor:!0,children:["Plan ID: ",e.planId]}),at(Le,{dimColor:!0,children:["Time remaining: ",a,"s"]}),at(Br,{marginTop:1,children:[It(Le,{children:"Overall Risk: "}),It(Le,{bold:!0,color:u,children:e.plan.overallRisk.toUpperCase()})]}),at(Le,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(d=>{let l=d.riskLevel==="high"?"red":d.riskLevel==="medium"?"yellow":"green";return at(Br,{paddingLeft:2,children:[at(Le,{children:["[",d.index,"] "]}),It(Le,{children:d.description}),at(Le,{dimColor:!0,children:[" (",d.toolsNeeded.join(", "),")"]}),at(Le,{color:l,children:[" [",d.riskLevel,"]"]})]},d.index)}),at(Br,{marginTop:1,children:[It(Le,{dimColor:!0,children:"Permissions: "}),It(Le,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),at(Br,{marginTop:1,children:[It(Le,{color:"green",children:"[a] Allow once "}),It(Le,{color:"green",children:"[p] Allow permanent "}),It(Le,{color:"red",children:"[r] Deny"})]})]})}import{Box as Ae,Text as re,useInput as Pi}from"ink";import{useEffect as Ri,useState as Ft,useCallback as Dn}from"react";import{Box as Be,Text as H,useInput as Ci}from"ink";import{useEffect as Si,useState as nr}from"react";import{jsx as xe,jsxs as J}from"react/jsx-runtime";var In={plan:!0,result:!1,routing:!0,error:!0},wi={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"};function Rn({taskId:e,onBack:t}){let[r,a]=nr(null),[o,u]=nr([]),[d,l]=nr([]),[i,n]=nr(null),[p,g]=nr(In),[b,y]=nr(!1);Si(()=>{let C=!1;return a(null),u([]),l([]),n(null),g(In),y(!1),v(`/tasks/${e}`).then(({task:E})=>{C||a(E)}).catch(E=>{C||n(E instanceof Error?E.message:String(E))}),v(`/tasks/${e}/plan`).then(({plans:E})=>{C||u(E)}).catch(()=>{C||u([])}),v(`/tasks/${e}/delivery-log?limit=8`).then(({logs:E})=>{C||l(E)}).catch(()=>{C||l([])}),()=>{C=!0}},[e]);let w=C=>{g(E=>({...E,[C]:!E[C]}))};if(Ci((C,E)=>{if(C==="b"||E.escape){t();return}C==="1"&&w("plan"),C==="2"&&w("result"),C==="3"&&w("routing"),C==="4"&&w("error"),C==="5"&&y(G=>!G)}),i)return J(Be,{flexDirection:"column",children:[J(H,{color:"red",children:["Task detail failed: ",i]}),xe(H,{dimColor:!0,children:"[b] Back"})]});if(!r)return J(H,{dimColor:!0,children:["Loading task ",e.slice(0,8),"..."]});let s=o[0],c=Ei(r.deliverTo,r.reportTo),I=d.length>0?`${d.length} delivery event${d.length===1?"":"s"}`:"No delivery events";return J(Be,{flexDirection:"column",children:[J(Be,{children:[J(H,{bold:!0,color:"cyan",children:["Task ",r.id.slice(0,8)]}),xe(H,{dimColor:!0,children:" \u2022 "}),xe(H,{color:wi[r.status]??"white",bold:!0,children:r.status.toUpperCase()})]}),J(H,{dimColor:!0,children:[r.roleId?`role ${r.roleId}`:"no role"," \u2022 ",Pn(r.createdAt)," \u2022 ",Ii(r.totalDurationMs)]}),J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{bold:!0,children:"Summary"}),xe(H,{children:b?r.prompt:ki(r.prompt,240)}),r.prompt.length>240&&J(H,{dimColor:!0,children:["[5] ",b?"collapse prompt":"expand prompt"]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{dimColor:!0,children:["Cost: ",Bi(r.costUsd)]}),J(H,{dimColor:!0,children:["Turns: ",r.numTurns??"\u2014"]}),J(H,{dimColor:!0,children:["Template: ",r.templateId??"\u2014"]}),J(H,{dimColor:!0,children:["Source Session: ",r.sourceSessionId?.slice(0,8)??"\u2014"]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[1] Plan ",p.plan?"hide":"show"]}),xe(H,{dimColor:!0,children:s?`${s.plan.steps.length} planned step${s.plan.steps.length===1?"":"s"} \u2022 ${s.plan.overallRisk} risk \u2022 ${s.status}`:"No execution plan"}),p.plan&&s&&J(Be,{marginTop:1,flexDirection:"column",children:[s.plan.steps.map(C=>J(Be,{flexDirection:"column",marginBottom:1,children:[J(H,{children:[C.index,". ",C.description]}),J(H,{dimColor:!0,children:[C.riskLevel," risk \u2022 ",C.toolsNeeded.join(", ")||"no tools listed"]}),C.expectedOutput?J(H,{dimColor:!0,children:["Expected: ",C.expectedOutput]}):null]},C.index)),s.learnedRules&&s.learnedRules.length>0&&J(Be,{flexDirection:"column",children:[xe(H,{color:"blue",bold:!0,children:"Learned Rules"}),s.learnedRules.map((C,E)=>J(H,{dimColor:!0,children:["\u2022 ",C]},E))]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[2] Result ",p.result?"hide":"show"]}),xe(H,{dimColor:!0,children:r.result?"Execution produced output.":"No result captured yet."}),p.result&&xe(Be,{marginTop:1,children:xe(H,{children:r.result?An(r.result,18):"No result yet."})})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[3] Routing ",p.routing?"hide":"show"]}),J(H,{dimColor:!0,children:[c," \u2022 ",I]}),p.routing&&J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{color:"cyan",children:"Deliver To"}),En(r.deliverTo),xe(H,{color:"cyan",children:"Report To"}),En(r.reportTo),d.length>0&&J(Be,{marginTop:1,flexDirection:"column",children:[xe(H,{color:"cyan",children:"Recent Delivery"}),d.map(C=>J(H,{dimColor:!0,children:[C.status," \u2022 ",Ai(C)," \u2022 ",Pn(C.createdAt)]},C.id))]})]})]}),J(Be,{marginTop:1,flexDirection:"column",children:[J(H,{bold:!0,children:["[4] Error ",p.error?"hide":"show"]}),xe(H,{dimColor:!0,children:r.error?"Execution returned an error condition.":"No error recorded."}),p.error&&r.error&&xe(Be,{marginTop:1,children:xe(H,{color:"red",children:An(r.error,16)})})]}),xe(Be,{marginTop:1,children:xe(H,{dimColor:!0,children:"[1] plan [2] result [3] routing [4] error [5] prompt [b] back"})})]})}function En(e){return!e||e.length===0?xe(H,{dimColor:!0,children:" none"}):xe(Be,{flexDirection:"column",children:e.map((t,r)=>xe(H,{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}-${r}`))})}function An(e,t){let r=e.split(`
|
|
6
|
+
`);return r.length<=t?e:`${r.slice(0,t).join(`
|
|
7
|
+
`)}
|
|
8
|
+
\u2026`}function ki(e,t){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:`${r.slice(0,t-1)}\u2026`}function Bi(e){return e!==void 0?`$${e.toFixed(4)}`:"\u2014"}function Ii(e){if(!e)return"waiting";let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let r=Math.floor(t/60),a=t%60;return a===0?`${r}m`:`${r}m ${a}s`}function Pn(e){return new Date(e).toLocaleString()}function Ei(e,t){let r=e?.length??0,a=t?.length??0;return r===0&&a===0?"No delivery targets":`${r} output target${r===1?"":"s"} \u2022 ${a} report target${a===1?"":"s"}`}function Ai(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 Mi,jsx as de,jsxs as ue}from"react/jsx-runtime";var Mn={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray",blocked:"yellow"},Zr=["all","pending","queued","running","completed","failed","cancelled","blocked"],ko=15;function to({onBack:e}){let[t,r]=Ft([]),[a,o]=Ft(!0),[u,d]=Ft("list"),[l,i]=Ft(0),[n,p]=Ft("all"),[g,b]=Ft(0),[y,w]=Ft(0),[s,c]=Ft(null),I=Dn(async()=>{o(!0);try{let N=new URLSearchParams({limit:"100"});n!=="all"&&N.set("status",n);let O=await v(`/tasks?${N}`);r(O.tasks)}catch{r([])}finally{o(!1)}},[n]);Ri(()=>{I()},[I]);let C=Math.max(1,Math.ceil(t.length/ko)),E=t.slice(y*ko,(y+1)*ko),G=Dn(async()=>{let N=E[l];if(N)try{await v(`/tasks/${N.id}/cancel`,{method:"POST"}),c(`Cancelled: ${N.id.slice(0,8)}`),d("list"),I()}catch(O){c(`Failed: ${O instanceof Error?O.message:String(O)}`),d("list")}},[E,l,I]);if(Pi((N,O)=>{if(u==="detail"){(O.escape||O.return||N==="q")&&d("list");return}if(u==="cancelling"){N==="y"?G():d("list");return}if(u==="filter"){if(O.escape){d("list");return}O.upArrow&&g>0&&b(V=>V-1),O.downArrow&&g<Zr.length-1&&b(V=>V+1),O.return&&(p(Zr[g]),w(0),i(0),d("list"));return}if(O.escape||N==="q"){e();return}if(O.upArrow&&l>0&&i(V=>V-1),O.downArrow&&l<E.length-1&&i(V=>V+1),O.return&&E[l]&&d("detail"),N==="x"&&E[l]){let V=E[l];["running","pending","queued","paused"].includes(V.status)?(d("cancelling"),c(null)):c(`Cannot cancel task in status: ${V.status}`)}N==="f"&&(b(Zr.indexOf(n)),d("filter")),N==="r"&&I(),(O.pageDown||N==="n")&&y<C-1&&(w(V=>V+1),i(0)),(O.pageUp||N==="p")&&y>0&&(w(V=>V-1),i(0))}),a)return de(re,{dimColor:!0,children:"Loading tasks..."});if(u==="filter")return ue(Ae,{flexDirection:"column",children:[de(re,{bold:!0,children:"Filter by status:"}),Zr.map((N,O)=>de(Ae,{children:ue(re,{color:O===g?"cyan":"white",children:[O===g?"> ":" ",N,N===n?" (current)":""]})},N)),de(re,{dimColor:!0,children:"Enter: select Esc: cancel"})]});if(u==="detail"&&E[l])return de(Rn,{taskId:E[l].id,onBack:()=>d("list")});if(u==="cancelling"&&E[l])return ue(Ae,{flexDirection:"column",children:[ue(re,{color:"red",children:['Cancel task "',E[l].id.slice(0,8),'"? (y/n)']}),s&&de(re,{color:"red",children:s})]});let Y=E[l]??null;return ue(Ae,{flexDirection:"column",children:[ue(Ae,{children:[ue(re,{bold:!0,children:["Tasks (",t.length,")"]}),n!=="all"&&ue(re,{dimColor:!0,children:[" [filter: ",n,"]"]}),ue(re,{dimColor:!0,children:[" \u2022 Page ",y+1,"/",C]})]}),s&&de(re,{color:s.startsWith("Failed")||s.startsWith("Cannot")?"red":"green",children:s}),t.length===0?ue(re,{dimColor:!0,children:["No tasks found",n!=="all"?` with status "${n}"`:"","."]}):ue(Ae,{marginTop:1,flexDirection:"row",gap:2,children:[de(Ae,{flexDirection:"column",flexGrow:3,children:E.map((N,O)=>{let V=O===l,B=Mn[N.status]??"white";return ue(Ae,{flexDirection:"column",marginBottom:1,children:[ue(Ae,{children:[de(re,{color:V?"cyan":"gray",bold:V,children:V?"\u276F ":" "}),de(re,{color:B,bold:!0,children:N.status.toUpperCase()}),de(re,{dimColor:!0,children:` ${N.id.slice(0,8)}`})]}),de(Ae,{paddingLeft:2,children:de(re,{color:V?"white":void 0,children:eo(N.prompt,V?72:56)})}),de(Ae,{paddingLeft:2,children:ue(re,{dimColor:!0,children:[_n(N.createdAt)," \u2022 ",$n(N)," \u2022 ",Nn(N.costUsd)]})})]},N.id)})}),de(Ae,{flexDirection:"column",flexGrow:2,borderStyle:"round",borderDimColor:!0,paddingX:1,children:Y?ue(Mi,{children:[de(re,{bold:!0,children:"Preview"}),ue(Ae,{marginTop:1,children:[de(re,{color:Mn[Y.status]??"white",bold:!0,children:Y.status.toUpperCase()}),de(re,{dimColor:!0,children:` ${Y.id.slice(0,8)}`})]}),de(re,{children:eo(Y.prompt,220)}),ue(Ae,{marginTop:1,flexDirection:"column",children:[ue(re,{dimColor:!0,children:["Role: ",Y.roleId??Y.agentId??"\u2014"]}),ue(re,{dimColor:!0,children:["Created: ",_n(Y.createdAt)]}),ue(re,{dimColor:!0,children:["Duration: ",$n(Y)]}),ue(re,{dimColor:!0,children:["Cost: ",Nn(Y.costUsd)]}),ue(re,{dimColor:!0,children:["Turns: ",Y.numTurns??"\u2014"]})]}),Y.error?ue(Ae,{marginTop:1,flexDirection:"column",children:[de(re,{color:"red",bold:!0,children:"Error"}),de(re,{color:"red",children:eo(Y.error,180)})]}):Y.result?ue(Ae,{marginTop:1,flexDirection:"column",children:[de(re,{color:"green",bold:!0,children:"Latest Result"}),de(re,{children:eo(Y.result,180)})]}):null,de(Ae,{marginTop:1,children:de(re,{dimColor:!0,children:"Enter opens full detail"})})]}):de(re,{dimColor:!0,children:"Select a task to inspect it."})})]})]})}function Di(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}function eo(e,t){return Di(e.replace(/\s+/g," ").trim(),t)}function $n(e){let t=e.totalDurationMs??(e.startedAt?Date.now()-e.startedAt:void 0);if(!t)return"waiting";let r=Math.max(1,Math.round(t/1e3));if(r<60)return`${r}s`;let a=Math.floor(r/60),o=r%60;return o===0?`${a}m`:`${a}m ${o}s`}function Nn(e){return e!==void 0?`$${e.toFixed(4)}`:"no cost"}function _n(e){let t=Math.max(0,Math.floor((Date.now()-e)/1e3));if(t<60)return`${t}s ago`;let r=Math.floor(t/60);if(r<60)return`${r}m ago`;let a=Math.floor(r/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}Ho();import{Box as Gt,Text as Ge,useInput as $i}from"ink";import{useEffect as Ni,useState as Ln}from"react";import{readFileSync as _i,existsSync as Li}from"fs";import{parse as Fi}from"yaml";import{Fragment as qi,jsx as Fe,jsxs as Xe}from"react/jsx-runtime";function Fn({onBack:e}){let[t,r]=Ln(null),[a,o]=Ln(null);return $i((u,d)=>{(d.escape||u==="q")&&e()}),Ni(()=>{try{let u=Ko;if(!Li(u)){o(`Config file not found: ${u}`);return}let d=_i(u,"utf-8");r(Fi(d))}catch(u){o(u.message)}},[]),a?Xe(Gt,{flexDirection:"column",children:[Fe(Ge,{color:"red",children:a}),Fe(Ge,{dimColor:!0,children:"Press Esc to go back"})]}):t?Xe(Gt,{flexDirection:"column",children:[Fe(Ge,{bold:!0,children:"Configuration (Esc to go back)"}),Fe(Gt,{marginTop:1,flexDirection:"column",children:Fe(Bo,{obj:t,indent:0})})]}):Fe(Ge,{dimColor:!0,children:"Loading config..."})}function Bo({obj:e,indent:t}){let r=" ".repeat(t);return Fe(qi,{children:Object.entries(e).map(([a,o])=>Fe(Oi,{label:a,value:o,indent:t,parentKey:a},a))})}function Oi({label:e,value:t,indent:r,parentKey:a}){let o=" ".repeat(r);return Array.isArray(t)?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),":"]}),t.length===0?Xe(Ge,{dimColor:!0,children:[o," []"]}):t.map((u,d)=>Fe(On,{value:u,indent:r+1,parentKey:a,index:d},`${e}-${d}`))]}):t&&typeof t=="object"?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),":"]}),Fe(Bo,{obj:t,indent:r+1})]}):Xe(Ge,{children:[o,Fe(Ge,{color:"cyan",children:e}),": ",qn(a,Vn(t))]})}function On({value:e,indent:t,parentKey:r,index:a}){let o=" ".repeat(t);return Array.isArray(e)?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,"- [",a,"]"]}),e.map((u,d)=>Fe(On,{value:u,indent:t+1,parentKey:r,index:d},`${a}-${d}`))]}):e&&typeof e=="object"?Xe(Gt,{flexDirection:"column",children:[Xe(Ge,{children:[o,"-"]}),Fe(Bo,{obj:e,indent:t+1})]}):Xe(Ge,{children:[o,"- ",qn(r,Vn(e))]})}function qn(e,t){let r=e.toLowerCase();return r.includes("key")||r.includes("token")||r.includes("secret")||r.includes("password")?!t||t.length<8?"****":t.slice(0,4)+"****":t}function Vn(e){return e===null?"null":e===void 0?"undefined":typeof e=="string"?e:String(e)}import{Box as ro,Text as lt,useInput as Vi}from"ink";import{useEffect as Ui,useState as Io}from"react";import{jsx as Ir,jsxs as ht}from"react/jsx-runtime";function Un({onBack:e}){let[t,r]=Io([]),[a,o]=Io(!0),[u,d]=Io(null);return Vi((l,i)=>{(i.escape||l==="q")&&e()}),Ui(()=>{v("/evolution-audit?limit=20").then(l=>{r(l),o(!1)}).catch(l=>{d(l.message),o(!1)})},[]),a?Ir(lt,{dimColor:!0,children:"Loading evolution log..."}):u?ht(ro,{flexDirection:"column",children:[Ir(lt,{color:"red",children:u}),Ir(lt,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?ht(ro,{flexDirection:"column",children:[Ir(lt,{dimColor:!0,children:"No evolution records yet"}),Ir(lt,{dimColor:!0,children:"Press Esc to go back"})]}):ht(ro,{flexDirection:"column",children:[ht(lt,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(l=>ht(ro,{flexDirection:"column",marginTop:1,children:[ht(lt,{bold:!0,children:["[",new Date(l.timestamp).toLocaleString(),"]"]}),l.triggerTaskId&&ht(lt,{dimColor:!0,children:[" Task: ",l.triggerTaskId.slice(0,8)]}),l.diff.split(`
|
|
9
|
+
`).map((i,n)=>i.startsWith("+")?ht(lt,{color:"green",children:[" ",i]},n):i.startsWith("-")?ht(lt,{color:"red",children:[" ",i]},n):ht(lt,{dimColor:!0,children:[" ",i]},n))]},l.id))]})}import{Box as Et,Text as Te,useInput as Wi}from"ink";import Gi from"ink-text-input";import{useEffect as ji,useState as sr}from"react";import{jsx as je,jsxs as Pe}from"react/jsx-runtime";var Ki={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function Hi(e,t=20){let r=Math.round(e*t),a=t-r;return"\u2588".repeat(r)+"\u2591".repeat(a)}function zi(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function oo({onBack:e}){let[t,r]=sr([]),[a,o]=sr(null),[u,d]=sr("list"),[l,i]=sr(""),[n,p]=sr(!1),[g,b]=sr(null);Wi((s,c)=>{if(u==="create"){c.escape&&(d("list"),i(""),b(null));return}(c.escape||s==="q")&&e(),s==="c"&&(d("create"),b(null)),s==="r"&&y()});let y=()=>{v("/goals?limit=20").then(({goals:s})=>r(s)).catch(s=>o(s.message))};ji(()=>{y()},[]);let w=async s=>{if(s.trim()){p(!0),b(null);try{let c=await v("/goals",{method:"POST",body:{input:s.trim()}});b(`Goal created: ${c.goal.name}`),i(""),d("list"),y()}catch(c){b(`Failed: ${c instanceof Error?c.message:String(c)}`)}finally{p(!1)}}};return a?Pe(Et,{flexDirection:"column",children:[Pe(Te,{color:"red",children:["Failed to load goals: ",a]}),je(Te,{dimColor:!0,children:"Press Esc or q to return"})]}):u==="create"?Pe(Et,{flexDirection:"column",children:[je(Te,{bold:!0,children:"Create Goal"}),je(Te,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),Pe(Et,{marginTop:1,children:[je(Te,{color:"cyan",children:"> "}),je(Gi,{value:l,onChange:i,onSubmit:w})]}),n&&je(Te,{color:"yellow",children:"Creating goal..."}),g&&je(Te,{color:g.startsWith("Failed")?"red":"green",children:g}),je(Te,{dimColor:!0,children:"Press Esc to cancel"})]}):Pe(Et,{flexDirection:"column",children:[Pe(Te,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?je(Te,{dimColor:!0,children:"No goals found. Press c to create one."}):je(Et,{marginTop:1,flexDirection:"column",children:t.map(s=>{let c=s.targetValue>0?s.currentValue/s.targetValue:0,I=Ki[s.status]??"white";return Pe(Et,{marginBottom:1,flexDirection:"column",children:[Pe(Et,{children:[je(Te,{bold:!0,color:I,children:s.name}),Pe(Te,{dimColor:!0,children:[" (",s.role,")"]}),je(Te,{dimColor:!0,children:" \u2014 "}),je(Te,{color:I,children:s.status})]}),Pe(Et,{children:[Pe(Te,{dimColor:!0,children:[" ",Hi(c)," "]}),Pe(Te,{color:c>=1?"green":"white",children:[Math.round(c*100),"%"]}),Pe(Te,{dimColor:!0,children:[" (",s.currentValue,"/",s.targetValue," ",s.metricType,")"]})]}),Pe(Et,{children:[Pe(Te,{dimColor:!0,children:[" \u23F0 ",zi(s.deadline)," left"]}),Pe(Te,{dimColor:!0,children:[" | \u{1F4B0} $",s.budgetUsd]}),Pe(Te,{dimColor:!0,children:[" | ID: ",s.id.slice(0,8)]})]})]},s.id)})}),je(Te,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as ir,Text as rt,useInput as Xi}from"ink";import{useEffect as Yi,useState as Wn}from"react";import{jsx as Pt,jsxs as At}from"react/jsx-runtime";function Qi(e,t,r=15){let a=e/(e+t),o=Math.round(a*r);return"\u2593".repeat(o)+"\u2591".repeat(r-o)}function Gn({onBack:e}){let[t,r]=Wn([]),[a,o]=Wn(null);if(Xi((d,l)=>{(l.escape||d==="q")&&e()}),Yi(()=>{v("/strategies?limit=50").then(d=>r(d.strategies??[])).catch(d=>o(d.message))},[]),a)return At(ir,{flexDirection:"column",children:[At(rt,{color:"red",children:["Failed to load strategies: ",a]}),Pt(rt,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return At(ir,{flexDirection:"column",children:[Pt(rt,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Pt(rt,{dimColor:!0,children:"Press Esc or q to return"})]});let u=new Map;for(let d of t){let l=`${d.role}/${d.taskType}`,i=u.get(l)??[];i.push(d),u.set(l,i)}return At(ir,{flexDirection:"column",children:[Pt(rt,{bold:!0,children:"Strategy Lab"}),Pt(rt,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Pt(ir,{marginTop:1,flexDirection:"column",children:Array.from(u.entries()).map(([d,l])=>At(ir,{marginBottom:1,flexDirection:"column",children:[Pt(rt,{bold:!0,color:"cyan",children:d}),l.sort((i,n)=>{let p=i.alpha/(i.alpha+i.beta);return n.alpha/(n.alpha+n.beta)-p}).map(i=>{let n=i.alpha/(i.alpha+i.beta);return At(ir,{children:[Pt(rt,{dimColor:!0,children:" "}),At(rt,{children:[Qi(i.alpha,i.beta)," "]}),At(rt,{color:n>.6?"green":n>.4?"yellow":"red",children:[(n*100).toFixed(0),"%"]}),At(rt,{dimColor:!0,children:[" ",i.name," (\u03B1=",i.alpha.toFixed(1)," \u03B2=",i.beta.toFixed(1)," trials=",i.totalTrials,")"]})]},i.id)})]},d))}),Pt(rt,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as ye,Text as W,useInput as ra}from"ink";import Eo from"ink-text-input";import{useEffect as oa,useState as Oe,useCallback as yt}from"react";import{CronExpressionParser as na}from"cron-parser";import{useState as Ji,useEffect as Zi,useCallback as jn,useRef as ea}from"react";var ta=3e3;function ot(){let[e,t]=Ji(null),r=ea(null),a=jn(()=>{r.current&&(clearTimeout(r.current),r.current=null),t(null)},[]),o=jn((u,d)=>{r.current&&(clearTimeout(r.current),r.current=null),t({text:u,type:d}),d==="success"&&(r.current=setTimeout(()=>{t(null),r.current=null},ta))},[]);return Zi(()=>()=>{r.current&&clearTimeout(r.current)},[]),{message:e,setMessage:o,clearMessage:a}}import{Fragment as ia,jsx as Z,jsxs as Q}from"react/jsx-runtime";var Ao=["manual","cron","once","template_complete"],Kn=["cron","once","template_complete"],no={name:"",triggerType:"manual",cron:"",targetTemplateId:"",stepPrompt:""};function sa(e){try{return na.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function so({onBack:e}){let[t,r]=Oe([]),[a,o]=Oe(!0),[u,d]=Oe(0),[l,i]=Oe("list"),[n,p]=Oe({...no}),[g,b]=Oe("name"),[y,w]=Oe(null),{message:s,setMessage:c,clearMessage:I}=ot(),[C,E]=Oe(!1),[G,Y]=Oe(!1),[N,O]=Oe({}),[V,B]=Oe(null),[z,se]=Oe(!1),[ne,$e]=Oe(!1),[ge,D]=Oe([]),[ie,L]=Oe({}),ae=yt(async S=>{try{let A=await v(`/template-executions?templateId=${S}&limit=5`);D(A.executions??[])}catch{D([])}},[]),Ce=yt(async(S,A)=>{try{await v(`/executions/${S}/feedback`,{method:"POST",body:{rating:A}}),L($=>({...$,[S]:A}))}catch($){c(`Feedback failed: ${$ instanceof Error?$.message:String($)}`,"error")}},[c]),_=yt(()=>{o(!0),v("/task-templates").then(({templates:S})=>{r(S),new Set(S.flatMap($=>$.steps?.map(le=>le.roleId).filter(Boolean)??[])).size>0?v("/roles").then(({roles:$})=>{if(!Array.isArray($)){O({});return}O(Object.fromEntries($.map(le=>[le.id,le.name])))}).catch(()=>O({})):O({}),o(!1)}).catch(()=>o(!1))},[]);oa(()=>{_()},[_]);let K=l==="create"||l==="edit",ee=yt(async()=>{let S=t[u];if(!(!S||C)){E(!0),c(`Triggering ${S.name}...`,"loading");try{let A=await v(`/task-templates/${S.id}/run`,{method:"POST"});c(`Triggered: ${S.name} (${A.executionId})`,"success")}catch(A){c(`Trigger failed: ${A instanceof Error?A.message:String(A)}`,"error")}finally{E(!1)}}},[t,u,C,c]),pe=yt(async()=>{let S=t[u];if(!S||G)return;if(!Kn.includes(S.trigger?.type??"manual")){c("Toggle not applicable for manual triggers","error");return}let A=!S.enabled;Y(!0),c(`${S.name} \u2192 ${A?"enabling":"disabling"}...`,"loading");try{await v(`/task-templates/${S.id}`,{method:"PATCH",body:{enabled:A}}),r($=>$.map(le=>le.id===S.id?{...le,enabled:A}:le)),c(`${S.name} ${A?"enabled":"disabled"}`,"success")}catch($){c(`Toggle failed: ${$ instanceof Error?$.message:String($)}`,"error")}finally{Y(!1)}},[t,u,G,c]),St=yt(async()=>{if(z)return;let S=t[u];if(S){se(!0);try{let A=await v(`/task-templates/${S.id}/dependents`,{method:"GET"});B({templateId:S.id,templateName:S.name,executionCount:A.dependents.executionCount,taskCount:A.dependents.taskCount}),A.dependents.taskCount===0&&A.dependents.executionCount===0?c(`Delete "${S.name}"? Press d to confirm, Esc to cancel.`,"loading"):c(`"${S.name}" has ${A.dependents.executionCount} template execution${A.dependents.executionCount===1?"":"s"}, ${A.dependents.taskCount} task${A.dependents.taskCount===1?"":"s"}. [d] template only (keep tasks) | [D] template + tasks | [Esc] cancel.`,"loading")}catch(A){c(`Failed to inspect dependents: ${A instanceof Error?A.message:String(A)}`,"error")}finally{se(!1)}}},[t,u,c,z]),gt=yt(async S=>{let A=V;if(A){B(null);try{let $=await v(`/task-templates/${A.templateId}?mode=${S}`,{method:"DELETE"}),le=[];$.deletedCounts.templateExecutions>0&&le.push(`${$.deletedCounts.templateExecutions} template exec`),$.deletedCounts.tasks>0&&le.push(`${$.deletedCounts.tasks} task${$.deletedCounts.tasks===1?"":"s"}`);let Ue=le.length?` (+${le.join(", ")})`:"";c(`Deleted: ${A.templateName}${Ue}`,"success"),_(),d(Ne=>Math.max(0,Math.min(Ne,t.length-2)))}catch($){c(`Delete failed: ${$ instanceof Error?$.message:String($)}`,"error")}}},[V,_,c,t.length]),et=yt(()=>{B(null),I()},[I]),Ut=yt(()=>{let S=t[u];S&&(w(S.id),p({name:S.name,triggerType:S.trigger?.type??"manual",cron:S.trigger?.cron??"",targetTemplateId:S.trigger?.type==="template_complete"?S.trigger.event?.split(":")[1]??"":"",stepPrompt:S.steps?.[0]?.prompt??""}),b("name"),i("edit"))},[t,u]),Jt=yt(async()=>{let S={name:n.name,trigger:{type:n.triggerType,...n.triggerType==="cron"?{cron:n.cron}:{},...n.triggerType==="template_complete"&&n.targetTemplateId?{event:`template_complete:${n.targetTemplateId}`}:{}},steps:[{id:"step-1",prompt:n.stepPrompt}],enabled:!0};try{l==="create"?(await v("/task-templates",{method:"POST",body:S}),c(`Created: ${n.name}`,"success")):l==="edit"&&y&&(await v(`/task-templates/${y}`,{method:"PATCH",body:S}),c(`Updated: ${n.name}`,"success"))}catch(A){c(`Save failed: ${A instanceof Error?A.message:String(A)}`,"error")}i("list"),p({...no}),w(null),_()},[n,l,y,_]);return ra((S,A)=>{if(K){if(A.escape){i("list"),p({...no}),w(null);return}if(A.return){let $=["name","triggerType","cron","stepPrompt"],Ue=n.triggerType==="template_complete"?["name","triggerType","targetTemplateId","stepPrompt"]:$.filter(M=>M!=="targetTemplateId"),Ne=Ue.indexOf(g);if(Ne<Ue.length-1){let M=Ne+1;if(Ue[M]==="cron"&&n.triggerType!=="cron"&&M++,M<Ue.length){b(Ue[M]);return}}Jt();return}if(A.tab&&g==="triggerType"){p($=>{let le=Ao.indexOf($.triggerType);return{...$,triggerType:Ao[(le+1)%Ao.length]}});return}if(A.tab&&g==="targetTemplateId"){p($=>{let le=t.filter(M=>M.id!==y),Ue=le.findIndex(M=>M.id===$.targetTemplateId),Ne=le[(Ue+1)%le.length];return{...$,targetTemplateId:Ne?.id??""}});return}return}if(V){if(A.escape){et();return}if(S==="D"&&A.shift){gt("with_tasks");return}if(S==="d"&&!A.shift){gt("template_only");return}return}if(A.escape||S==="q"){e();return}if(A.upArrow){d($=>Math.max(0,$-1));return}if(A.downArrow){d($=>Math.min(t.length-1,$+1));return}if(S==="t"){ee();return}if(S==="d"&&!A.shift){St();return}if(S==="e"){Ut();return}if(S==="c"){p({...no}),b("name"),i("create");return}if(S==="s"||S===" "){pe();return}if(S==="r"&&(_(),I()),S==="x"){let $=t[u];if(!$)return;ne?($e(!1),D([])):($e(!0),ae($.id));return}if(S==="g"&&ne&&ge.length>0){Ce(ge[0].id,"good");return}if(S==="b"&&ne&&ge.length>0){Ce(ge[0].id,"bad");return}}),a?Z(W,{dimColor:!0,children:"Loading templates..."}):K?Q(ye,{flexDirection:"column",children:[Q(W,{bold:!0,children:[l==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),Q(ye,{marginTop:1,flexDirection:"column",children:[Q(ye,{children:[Q(W,{bold:g==="name",color:g==="name"?"cyan":void 0,children:["Name:"," "]}),g==="name"?Z(Eo,{value:n.name,onChange:S=>p(A=>({...A,name:S})),placeholder:"template name"}):Z(W,{children:n.name||"(empty)"})]}),Q(ye,{children:[Q(W,{bold:g==="triggerType",color:g==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),Z(W,{children:n.triggerType}),g==="triggerType"&&Z(W,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),n.triggerType==="cron"&&Q(ye,{children:[Q(W,{bold:g==="cron",color:g==="cron"?"cyan":void 0,children:["Cron:"," "]}),g==="cron"?Z(Eo,{value:n.cron,onChange:S=>p(A=>({...A,cron:S})),placeholder:"*/5 * * * *"}):Z(W,{children:n.cron||"(empty)"})]}),n.triggerType==="template_complete"&&Q(ye,{children:[Q(W,{bold:g==="targetTemplateId",color:g==="targetTemplateId"?"cyan":void 0,children:["Target:"," "]}),Z(W,{children:(()=>{let S=t.find(A=>A.id===n.targetTemplateId);return S?S.name:n.targetTemplateId?`(id: ${n.targetTemplateId.slice(0,8)})`:"(Tab to select)"})()}),g==="targetTemplateId"&&Z(W,{dimColor:!0,children:" (Tab to cycle)"})]}),Q(ye,{children:[Q(W,{bold:g==="stepPrompt",color:g==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),g==="stepPrompt"?Z(Eo,{value:n.stepPrompt,onChange:S=>p(A=>({...A,stepPrompt:S})),placeholder:"What should this template do?"}):Z(W,{children:n.stepPrompt||"(empty)"})]})]}),Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):Q(ye,{flexDirection:"column",children:[Q(W,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),s&&Z(ye,{marginTop:1,children:Q(W,{color:s.type==="success"?"green":s.type==="error"?"red":"gray",children:[s.type==="success"?"\u2713 ":s.type==="error"?"\u2717 ":"\u2192 ",s.text]})}),t.length===0?Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"No templates found. Press c to create one."})}):Z(ye,{marginTop:1,flexDirection:"column",children:t.map((S,A)=>{let $=A===u,le=S.trigger?.type==="cron"&&S.trigger?.cron?sa(S.trigger.cron):"",Ue=new Set(S.steps?.filter(M=>M.roleId).map(M=>M.roleId)),Ne=S.steps?.length>1?`${S.steps.length} steps${Ue.size>0?` / ${Ue.size} roles`:""}`:`${S.steps?.length??0} step`;return Q(ye,{flexDirection:"column",children:[Q(ye,{children:[Z(W,{color:$?"cyan":void 0,bold:$,children:$?"> ":" "}),Z(W,{color:$?"cyan":void 0,bold:$,children:Er(S.name,24)}),Z(W,{dimColor:!0,children:Er(S.trigger?.type,10)}),Kn.includes(S.trigger?.type??"manual")?Z(W,{color:S.enabled?"green":"gray",children:Er(S.enabled?"on":"off",6)}):Z(W,{dimColor:!0,children:Er("\u2014",6)}),Z(W,{dimColor:!0,children:Er(Ne,18)}),le&&Q(W,{dimColor:!0,children:["next: ",le]})]}),$&&Q(ia,{children:[S.config?.delivery&&Z(ye,{marginLeft:4,marginTop:0,children:Q(W,{dimColor:!0,children:[" Delivery: ",S.config.delivery.mode,S.config.delivery.mode==="primary-artifact"&&S.config.delivery.primaryArtifact&&` (${S.config.delivery.primaryArtifact.stepId}/${S.config.delivery.primaryArtifact.key})`]})}),S.steps&&S.steps.length>1&&Z(ye,{flexDirection:"column",marginLeft:4,marginTop:0,children:S.steps.map((M,Zt)=>Q(ye,{children:[Q(W,{dimColor:!0,children:[" ",Zt+1,". "]}),Z(W,{dimColor:!0,children:M.id}),M.roleId&&Q(W,{color:"yellow",children:[" @",N[M.roleId]??M.roleId]}),M.dependsOn&&M.dependsOn.length>0&&Q(W,{dimColor:!0,children:[" (after: ",M.dependsOn.join(", "),")"]}),M.consumesFrom&&M.consumesFrom.length>0&&Q(W,{dimColor:!0,children:[" [consumes: ",M.consumesFrom.join(", "),"]"]}),M.consumesFromOptional&&M.consumesFromOptional.length>0&&Q(W,{dimColor:!0,children:[" [consumes?: ",M.consumesFromOptional.join(", "),"]"]}),M.persona&&Q(W,{dimColor:!0,children:[" [speak as: ",M.persona.speakAs,M.persona.voiceConstraints?` / ${M.persona.voiceConstraints}`:"","]"]}),M.outputContract&&Q(W,{dimColor:!0,children:[" [",(M.outputContract.contractRules??[]).map(wt=>wt.kind).join(" "),M.outputContract.mustReferenceArtifacts?" ref-artifacts":"","]"]}),M.config&&Q(W,{dimColor:!0,children:[" ","[",[M.config.timeout!==void 0?`timeout:${M.config.timeout}s`:"",M.config.maxTurns!==void 0?`turns:${M.config.maxTurns}`:""].filter(Boolean).join(", "),"]"]})]},M.id))}),$&&ne&&Q(ye,{flexDirection:"column",marginLeft:4,marginTop:0,children:[ge.length===0?Z(W,{dimColor:!0,children:" No recent executions"}):ge.map((M,Zt)=>{let wt=ie[M.id];return Q(ye,{children:[Q(W,{dimColor:!0,children:[" ",Zt===0?">":" "," "]}),Z(W,{color:M.status==="completed"?"green":M.status==="failed"?"red":"gray",children:M.status.padEnd(10)}),Z(W,{dimColor:!0,children:new Date(M.startedAt).toLocaleString().slice(0,16)}),Q(W,{dimColor:!0,children:[" ",M.id.slice(0,8)]}),wt&&Z(W,{color:wt==="good"?"green":"red",children:wt==="good"?" \u{1F44D}":" \u{1F44E}"})]},M.id)}),ge.length>0&&Z(W,{dimColor:!0,children:" g:good b:bad (rates most recent)"})]})]})]},S.id)})}),Z(ye,{marginTop:1,children:Z(W,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh x:executions"})})]})}function Er(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ot,Text as Ye,useInput as aa}from"ink";import la from"ink-text-input";import{useEffect as ca,useState as ar,useCallback as Hn}from"react";import{jsx as qe,jsxs as jt}from"react/jsx-runtime";function zn({onBack:e}){let[t,r]=ar([]),[a,o]=ar(""),[u,d]=ar(!0),[l,i]=ar(!1),[n,p]=ar(""),[g,b]=ar(null),y=Hn(()=>{d(!0),v("/webhooks").then(({webhooks:s,auth:c})=>{r(s),o(c),d(!1)}).catch(()=>d(!1))},[]);ca(()=>{y()},[y]);let w=Hn(async s=>{if(s.trim())try{let c=await v(`/webhooks/${encodeURIComponent(s.trim())}`,{method:"POST"});b(`Triggered: ${c.executionId}`)}catch(c){b(`Trigger failed: ${c instanceof Error?c.message:String(c)}`)}},[]);return aa((s,c)=>{if(l){if(c.escape){i(!1),p("");return}if(c.return){w(n),i(!1),p("");return}return}if(c.escape||s==="q"){e();return}if(s==="t"){i(!0),p(""),b(null);return}s==="r"&&(y(),b(null))}),u?qe(Ye,{dimColor:!0,children:"Loading webhooks..."}):jt(Ot,{flexDirection:"column",children:[jt(Ye,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),jt(Ye,{dimColor:!0,children:["Auth: ",a]}),g&&qe(Ot,{marginTop:1,children:qe(Ye,{color:"yellow",children:g})}),l&&jt(Ot,{marginTop:1,children:[qe(Ye,{bold:!0,color:"cyan",children:"Trigger webhook: "}),qe(la,{value:n,onChange:p,placeholder:"webhook name or ID"}),qe(Ye,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?qe(Ot,{marginTop:1,children:qe(Ye,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):jt(Ot,{marginTop:1,flexDirection:"column",children:[qe(Ot,{children:jt(Ye,{bold:!0,children:[lr("NAME",24),lr("DESCRIPTION",36),lr("TRIGGER",28),"TAGS"]})}),t.map(s=>jt(Ot,{children:[qe(Ye,{children:lr(s.displayName,24)}),qe(Ye,{dimColor:!0,children:lr(da(s.description??"",34),36)}),qe(Ye,{dimColor:!0,children:lr(s.trigger,28)}),qe(Ye,{dimColor:!0,children:s.tags?.join(", ")??""})]},s.name))]}),qe(Ot,{marginTop:1,children:qe(Ye,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function lr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function da(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as bt,Text as Se,useInput as ua}from"ink";import ma from"ink-text-input";import{useEffect as Xn,useState as Rt,useCallback as Po}from"react";import{jsx as we,jsxs as ct}from"react/jsx-runtime";function fa(e){return e>=4?"red":e===3?"yellow":"gray"}function ga(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function pa(e){return new Date(e).toLocaleDateString()}function Qn({onBack:e}){let[t,r]=Rt([]),[a,o]=Rt(0),[u,d]=Rt([]),[l,i]=Rt(!0),[n,p]=Rt(!1),[g,b]=Rt(""),[y,w]=Rt("all"),[s,c]=Rt(null),[I,C]=Rt(!1),E=Po(()=>{v("/agents").then(({agents:B})=>{r(B),i(!1)}).catch(()=>i(!1))},[]);Xn(()=>{E()},[E]);let G=t[a],Y=Po(()=>{G&&(C(!1),v(`/memories/${G.id}`).then(({memories:B})=>{d(B),c(null)}).catch(B=>c(`Failed: ${B instanceof Error?B.message:String(B)}`)))},[G]);Xn(()=>{G&&Y()},[G,Y]);let N=Po(async B=>{if(!(!G||!B.trim()))try{let z=await v("/memories/query",{method:"POST",body:{agentId:G.id,prompt:B.trim()}});d(z.memories),C(!0),c(`Search: ${z.count} results`)}catch(z){c(`Search failed: ${z instanceof Error?z.message:String(z)}`)}},[G]),O=n,V=u.filter(B=>y==="all"?!0:y==="high"?B.importance>3:y==="medium"?B.importance===3:B.importance<3);return ua((B,z)=>{if(O){if(z.escape){p(!1),b("");return}if(z.return){N(g),p(!1),b("");return}return}if(z.escape||B==="q"){e();return}if(B==="a"){o(se=>(se+1)%Math.max(1,t.length));return}if(z.leftArrow){o(se=>(se-1+t.length)%Math.max(1,t.length));return}if(z.rightArrow){o(se=>(se+1)%Math.max(1,t.length));return}if(B==="s"){p(!0),b(""),c(null);return}if(B==="h"){w(se=>se==="high"?"all":"high");return}if(B==="m"){w(se=>se==="medium"?"all":"medium");return}if(B==="l"){w(se=>se==="low"?"all":"low");return}B==="r"&&Y()}),l?we(Se,{dimColor:!0,children:"Loading agents..."}):t.length===0?ct(bt,{flexDirection:"column",children:[we(Se,{dimColor:!0,children:"No agents found"}),we(Se,{dimColor:!0,children:"Press Esc to go back"})]}):ct(bt,{flexDirection:"column",children:[we(Se,{bold:!0,children:"Memories (Esc to go back)"}),ct(bt,{marginTop:1,children:[we(Se,{children:"Agent: "}),we(Se,{bold:!0,color:"cyan",children:G?.name??"?"}),ct(Se,{dimColor:!0,children:[" (",a+1,"/",t.length,") [a/arrows to switch]"]})]}),we(bt,{children:ct(Se,{dimColor:!0,children:["Filter: ",y==="all"?"all":y," | ",I?"search results":"all memories"," (",V.length,")"]})}),s&&we(bt,{children:we(Se,{color:"yellow",children:s})}),n&&ct(bt,{marginTop:1,children:[we(Se,{bold:!0,color:"cyan",children:"Search: "}),we(ma,{value:g,onChange:b,placeholder:"search query..."}),we(Se,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),V.length===0?we(bt,{marginTop:1,children:ct(Se,{dimColor:!0,children:["No memories",y!=="all"?` matching filter '${y}'`:""]})}):we(bt,{marginTop:1,flexDirection:"column",children:V.map(B=>ct(bt,{marginBottom:0,children:[ct(Se,{color:fa(B.importance),bold:!0,children:[ga(B.importance)," "]}),we(Se,{dimColor:!0,children:Yn(B.type??"?",12)}),we(Se,{dimColor:!0,children:Yn(`\xD7${B.retrievedCount??0}`,5)}),ct(Se,{children:[xa(B.content,55)," "]}),we(Se,{dimColor:!0,children:pa(B.createdAt)}),B.score!==void 0&&ct(Se,{dimColor:!0,children:[" (",B.score.toFixed(2),")"]})]},B.id))}),we(bt,{marginTop:1,children:we(Se,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function Yn(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function xa(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as dt,Text as be,useInput as Ta}from"ink";import io from"ink-text-input";import{useState as Ke,useEffect as Jn,useCallback as Ro}from"react";import{jsx as Re,jsxs as Ie}from"react/jsx-runtime";var Zn={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"],"Execution Artifacts":["watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours"]},ha={"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 es({onBack:e}){let{state:t}=tt(),[r,a]=Ke({}),[o,u]=Ke([]),[d,l]=Ke(null),[i,n]=Ke("view"),[p,g]=Ke(0),[b,y]=Ke(""),[w,s]=Ke(null),[c,I]=Ke(!1),[C,E]=Ke([]),[G,Y]=Ke({}),[N,O]=Ke(0),[V,B]=Ke(""),[z,se]=Ke(""),[ne,$e]=Ke(""),ge=Object.values(Zn).flat(),D=Ro(()=>{v("/config").then(_=>{a(_.config),u(_.mutable)}).catch(_=>l(_.message)),v("/config/env-diff").then(_=>{E(_.diffs)}).catch(()=>{}),v("/config/env").then(_=>Y(_.env??{})).catch(()=>{})},[]);Jn(()=>{D()},[D]),Jn(()=>{t.configVersion>0&&D()},[t.configVersion,D]);let ie=Ro(async()=>{let _=ge[p];if(_){I(!0),s(null);try{let K=b,ee=r[_];if(ee&&typeof ee.value=="number"&&(K=Number(b),isNaN(K))){s("Invalid number"),I(!1);return}let pe=await v("/config",{method:"PATCH",body:{[_]:K}});pe.updated.length>0&&(s(`Updated: ${_}`),D()),pe.errors.length>0&&s(pe.errors[0]),n("view")}catch(K){s(`Failed: ${K instanceof Error?K.message:String(K)}`)}finally{I(!1)}}},[ge,p,b,r,D]),L=Object.keys(G),ae=Ro(async _=>{try{await v("/config/env",{method:"PUT",body:_}),s("Env vars saved"),D()}catch(K){s(`Failed: ${K instanceof Error?K.message:String(K)}`)}},[D]);if(Ta((_,K)=>{if(i==="edit"){if(K.escape){n("view");return}return}if(i==="env-list"){if(K.escape){n("view");return}if(K.upArrow&&N>0&&O(ee=>ee-1),K.downArrow&&N<L.length-1&&O(ee=>ee+1),_==="a"){B(""),n("env-add-key");return}if(_==="d"&&L.length>0){let ee=L[N],pe={...G};delete pe[ee],ae(pe),N>=L.length-1&&N>0&&O(St=>St-1);return}if(K.return&&L.length>0){$e(G[L[N]]??""),n("env-edit-value");return}return}if(i==="env-add-key"){if(K.escape){n("env-list");return}return}if(i==="env-add-value"){if(K.escape){n("env-list");return}return}if(i==="env-edit-value"){if(K.escape){n("env-list");return}return}if(K.escape||_==="q"){e();return}if(K.upArrow&&p>0&&g(ee=>ee-1),K.downArrow&&p<ge.length-1&&g(ee=>ee+1),K.return||_==="e"){let ee=ge[p],pe=r[ee];pe&&pe.mutable?(y(String(pe.value??"")),n("edit"),s(null)):pe&&!pe.mutable&&s("This setting requires a restart to change")}_==="v"&&(O(0),n("env-list"),s(null)),_==="r"&&(D(),s("Refreshed")),_==="s"&&C.length>0&&v("/config/sync-to-env",{method:"POST"}).then(()=>{s("Synced to .env"),E([]),D()}),_==="l"&&C.length>0&&v("/config/load-from-env",{method:"POST"}).then(()=>{s("Loaded from .env"),D()})}),d)return Ie(dt,{flexDirection:"column",children:[Ie(be,{color:"red",children:["Failed to load config: ",d]}),Re(be,{dimColor:!0,children:"Press Esc or q to return"})]});let Ce=0;return Ie(dt,{flexDirection:"column",children:[Re(be,{bold:!0,children:"Settings"}),w&&Re(be,{color:w.startsWith("Failed")||w.startsWith("This setting")?"yellow":"green",children:w}),C&&C.length>0&&Ie(dt,{flexDirection:"column",marginBottom:1,children:[Ie(be,{color:"yellow",children:[".env differs from DB (",C.length," key(s)): ",C.map(_=>_.envKey).join(", ")]}),Re(be,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Re(dt,{marginTop:1,flexDirection:"column",children:Object.entries(Zn).map(([_,K])=>Ie(dt,{marginBottom:1,flexDirection:"column",children:[Re(be,{bold:!0,color:"cyan",children:_}),K.map(ee=>{let pe=r[ee],gt=Ce++===p,et=o.includes(ee),Ut=ha[ee]??ee,Jt=pe?String(pe.value??""):"...";return i==="edit"&>?Ie(dt,{children:[Ie(be,{color:"cyan",children:["> ",Ut,": "]}),Re(io,{value:b,onChange:y,onSubmit:()=>{ie()}}),c&&Re(be,{color:"yellow",children:" saving..."})]},ee):Ie(dt,{children:[Ie(be,{color:gt?"cyan":"white",children:[gt?"> ":" ",et?" ":"\u{1F512} ",Ut,": "," "]}),Re(be,{color:et?"white":"gray",children:Jt}),!et&&Re(be,{dimColor:!0,children:" (restart required)"})]},ee)})]},_))}),Re(be,{dimColor:!0,children:"Enter/e:edit v:env vars r:refresh Esc/q:back"}),i.startsWith("env")&&Ie(dt,{flexDirection:"column",marginTop:1,children:[Ie(be,{bold:!0,color:"cyan",children:["Environment Variables (",L.length,")"]}),L.length===0&&i==="env-list"&&Re(be,{dimColor:!0,children:" No env vars. Press a to add."}),L.map((_,K)=>{let ee=K===N;return i==="env-edit-value"&&ee?Ie(dt,{children:[Ie(be,{color:"cyan",children:["> ",_," = "]}),Re(io,{value:ne,onChange:$e,onSubmit:()=>{ae({...G,[_]:ne}),n("env-list")}})]},_):Ie(be,{color:ee&&i==="env-list"?"cyan":"white",children:[ee&&i==="env-list"?"> ":" ",_," = ",G[_]]},_)}),i==="env-add-key"&&Ie(dt,{children:[Re(be,{color:"green",children:" New key: "}),Re(io,{value:V,onChange:B,onSubmit:()=>{V.trim()&&(se(""),n("env-add-value"))}})]}),i==="env-add-value"&&Ie(dt,{children:[Ie(be,{color:"green",children:[" ",V," = "]}),Re(io,{value:z,onChange:se,onSubmit:()=>{ae({...G,[V.trim()]:z}),n("env-list")}})]}),Re(be,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"})]})]})}import{Box as Kt,Text as Ve,useInput as ya}from"ink";import{useEffect as ba,useState as Do,useCallback as va}from"react";import{jsx as Me,jsxs as dr}from"react/jsx-runtime";function ts({onBack:e}){let[t,r]=Do([]),[a,o]=Do(!0),[u,d]=Do(0),{message:l,setMessage:i,clearMessage:n}=ot(),p=va(()=>{o(!0),v("/plugins").then(({plugins:g})=>{r(g),o(!1)}).catch(()=>o(!1))},[]);return ba(()=>{p()},[p]),ya((g,b)=>{if(b.escape||g==="q"){e();return}if(b.upArrow){d(y=>Math.max(0,y-1));return}if(b.downArrow){d(y=>Math.min(t.length-1,y+1));return}g==="r"&&(p(),n())}),a?Me(Ve,{dimColor:!0,children:"Loading plugins..."}):dr(Kt,{flexDirection:"column",children:[dr(Ve,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),l&&Me(Kt,{marginTop:1,children:dr(Ve,{color:l.type==="success"?"green":l.type==="error"?"red":"gray",children:[l.type==="success"?"\u2713 ":l.type==="error"?"\u2717 ":"\u2192 ",l.text]})}),t.length===0?Me(Kt,{marginTop:1,children:Me(Ve,{dimColor:!0,children:"No plugins installed."})}):dr(Kt,{marginTop:1,flexDirection:"column",children:[dr(Kt,{children:[Me(Ve,{dimColor:!0,children:" "}),Me(Ve,{dimColor:!0,children:cr("Name",24)}),Me(Ve,{dimColor:!0,children:cr("Scope",8)}),Me(Ve,{dimColor:!0,children:cr("User",6)}),Me(Ve,{dimColor:!0,children:"Path"})]}),t.map((g,b)=>{let y=b===u,w=g.id.split("@")[0];return dr(Kt,{children:[Me(Ve,{color:y?"cyan":void 0,bold:y,children:y?"> ":" "}),Me(Ve,{color:y?"cyan":void 0,bold:y,children:cr(w,24)}),Me(Ve,{color:y?"cyan":void 0,bold:y,children:cr(g.scope,8)}),Me(Ve,{color:g.globalEnabled?"green":"gray",children:cr(g.globalEnabled?"on":"off",6)}),Me(Ve,{dimColor:!0,children:g.installPath})]},g.id)})]}),Me(Kt,{marginTop:1,children:Me(Ve,{dimColor:!0,children:"r:refresh"})})]})}function cr(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Mo,Text as $o,useInput as Ca}from"ink";import{useState as Sa}from"react";import{jsx as Ht,jsxs as rs}from"react/jsx-runtime";var wa=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function os({onBack:e}){let[t,r]=Sa("tasks");return Ca((a,o)=>{if(o.escape||a==="q"){e();return}if(a==="1"){r("tasks");return}if(a==="2"){r("automations");return}if(a==="3"){r("goals");return}}),rs(Mo,{flexDirection:"column",children:[Ht($o,{bold:!0,children:"Work Surface"}),Ht($o,{dimColor:!0,children:"Browse tasks, automations, and goals without dropping back into chat mode."}),Ht(Mo,{gap:3,marginBottom:1,marginTop:1,children:wa.map(a=>{let o=t===a.id;return Ht(Mo,{children:rs($o,{color:o?"cyan":"gray",bold:o,children:[o?"\u25CF":"\u25CB"," ",a.key,". ",a.label]})},a.id)})}),t==="tasks"&&Ht(to,{onBack:e}),t==="automations"&&Ht(so,{onBack:e}),t==="goals"&&Ht(oo,{onBack:e})]})}import{Box as me,Text as oe,useInput as ka}from"ink";import{useEffect as Ba,useState as Ar}from"react";import{jsx as j,jsxs as De}from"react/jsx-runtime";var ns={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function ss({onBack:e}){let[t,r]=Ar([]),[a,o]=Ar(!0),[u,d]=Ar(0),[l,i]=Ar(null),[n,p]=Ar("");Ba(()=>{g()},[]);async function g(){try{let w=await v("/channels");r(w.channels)}catch{}o(!1)}async function b(w){if(t.find(c=>c.id===w)?.platform==="wechat")try{p("Starting WeChat QR login...");let c=await v(`/channels/${w}/wechat/qr-start`,{method:"POST"});if(c.qrcodeUrl){p(`Scan QR: ${c.qrcodeUrl}
|
|
10
|
+
Waiting for scan...`);let I=await v(`/channels/${w}/wechat/qr-wait`,{method:"POST",body:{sessionKey:c.sessionKey,timeoutMs:12e4}});p(I.message)}else p(c.message);g()}catch{p("WeChat connect failed")}else try{await v(`/channels/${w}/connect`,{method:"POST"}),p("Connecting..."),g()}catch{p("Connect failed")}}async function y(w){try{await v(`/channels/${w}/disconnect`,{method:"POST"}),p("Disconnected"),g()}catch{p("Disconnect failed")}}return ka((w,s)=>{if(l){if(s.escape||w==="q"){i(null);return}if(w==="c"){b(l.id);return}if(w==="d"){y(l.id);return}return}if(s.escape){e();return}if(s.upArrow){d(c=>Math.max(0,c-1));return}if(s.downArrow){d(c=>Math.min(t.length-1,c+1));return}if(s.return&&t[u]){i(t[u]),p("");return}}),a?j(me,{flexDirection:"column",children:j(oe,{dimColor:!0,children:"Loading channels..."})}):l?De(me,{flexDirection:"column",children:[De(me,{marginBottom:1,children:[De(oe,{bold:!0,children:["Channel: ",l.name]}),j(oe,{dimColor:!0,children:" (Esc to go back)"})]}),De(me,{flexDirection:"column",gap:0,children:[De(oe,{children:["ID: ",l.id]}),De(oe,{children:["Platform: ",l.platform]}),De(oe,{children:["Status: ",j(oe,{color:ns[l.status]??"white",children:l.status})]}),De(oe,{children:["Enabled: ",l.enabled?"yes":"no"]}),De(oe,{children:["Messages: ",l.messageCount]}),De(oe,{children:["Config: ",JSON.stringify(l.config)]})]}),j(me,{marginTop:1,children:j(oe,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),n&&j(oe,{color:"yellow",children:n})]}):De(me,{flexDirection:"column",children:[De(me,{marginBottom:1,children:[j(oe,{bold:!0,children:"Channels"}),De(oe,{dimColor:!0,children:[" (",t.length," total) "]}),j(oe,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?j(oe,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):De(me,{flexDirection:"column",children:[De(me,{children:[j(me,{width:3,children:j(oe,{dimColor:!0,children:" "})}),j(me,{width:12,children:j(oe,{bold:!0,dimColor:!0,children:"ID"})}),j(me,{width:16,children:j(oe,{bold:!0,dimColor:!0,children:"Name"})}),j(me,{width:12,children:j(oe,{bold:!0,dimColor:!0,children:"Platform"})}),j(me,{width:14,children:j(oe,{bold:!0,dimColor:!0,children:"Status"})}),j(me,{width:10,children:j(oe,{bold:!0,dimColor:!0,children:"Enabled"})}),j(me,{width:10,children:j(oe,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((w,s)=>De(me,{children:[j(me,{width:3,children:j(oe,{children:s===u?">":" "})}),j(me,{width:12,children:j(oe,{inverse:s===u,children:w.id.slice(0,8)})}),j(me,{width:16,children:j(oe,{children:w.name})}),j(me,{width:12,children:j(oe,{children:w.platform})}),j(me,{width:14,children:De(oe,{color:ns[w.status]??"white",children:[w.status==="connected"?"\u25CF":w.status==="error"?"\u2717":"\u25CB"," ",w.status]})}),j(me,{width:10,children:j(oe,{color:w.enabled?"green":"gray",children:w.enabled?"yes":"no"})}),j(me,{width:10,children:j(oe,{children:w.messageCount})})]},w.id))]})]})}import{Box as ur,Text as mt,useInput as Aa}from"ink";import{useEffect as Pa,useState as Pr,useCallback as Ra}from"react";import{Box as R,Text as x,useInput as Ia}from"ink";import ut from"ink-text-input";import{useEffect as is,useState as X,useCallback as vt}from"react";Ho();import{Fragment as ao,jsx as h,jsxs as k}from"react/jsx-runtime";var Ea=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;function as({roleId:e,onBack:t}){let[r,a]=X(null),[o,u]=X([]),[d,l]=X(!0),[i,n]=X("view"),[p,g]=X(""),[b,y]=X(0),[w,s]=X(""),[c,I]=X([]),[C,E]=X(0),[G,Y]=X(new Set),[N,O]=X("inline"),[V,B]=X(""),[z,se]=X(""),[ne,$e]=X(""),[ge,D]=X([]),[ie,L]=X(new Set),[ae,Ce]=X(0),[_,K]=X("default"),[ee,pe]=X(""),[St,gt]=X(""),[et,Ut]=X("mode"),[Jt,S]=X([]),[A,$]=X(null),[le,Ue]=X([]),[Ne,M]=X([]),[Zt,wt]=X(""),[_t,$r]=X(0),[Nr,Oo]=X(""),[qo,Vo]=X(""),[Uo,Wo]=X(""),[_r,po]=X(0),[Tr,Go]=X([]),[Lr,xo]=X(0),[Fr,Or]=X(!1),[er,Cs]=X(""),{message:F,setMessage:q}=ot(),ce=vt(()=>{l(!0),v(`/roles/${e}`).then(({role:m,projectPlugins:T,workspacePath:f})=>{a(m),u(T??[]),Cs(f??""),g(m.cagPrompt??""),Y(new Set(m.allowedTools??[])),O(m.executionMode??"inline"),B(m.model??""),se(m.effortTier??""),$e(m.maxBudgetUsd!=null?String(m.maxBudgetUsd):""),l(!1)}).catch(()=>l(!1))},[e]);is(()=>{ce(),v("/config").then(m=>{let T=m.config["defaults.deniedReadPaths"]?.value;Array.isArray(T)&&S(T),$(m.sandbox),Ue(m.osCapabilities?.registry??[])}).catch(()=>{})},[ce]),is(()=>{O(r?.executionMode??"inline"),B(r?.model??""),se(r?.effortTier??""),$e(r?.maxBudgetUsd!=null?String(r?.maxBudgetUsd):""),K(r?.permissionMode??"default"),pe((r?.allowedBashPatterns??[]).join(", ")),gt((r?.deniedBashPatterns??[]).join(", ")),M(r?.osCapabilities??[]);let m=r?.osCapabilities?.find(T=>T.id==="automation")?.targets??[];wt(m.join(", "))},[r?.id,r?.executionMode,r?.model,r?.effortTier,r?.maxBudgetUsd,r?.permissionMode,r?.allowedBashPatterns,r?.deniedBashPatterns,r?.osCapabilities]);let Ss=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{cagPrompt:p}}),q("CAG prompt saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,p,ce,q]),ws=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{additionalDirectories:it}}),q("Directories saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,ce,q]),ks=vt(async()=>{if(r)try{await v(`/roles/${r.id}`,{method:"PATCH",body:{allowedTools:Array.from(G)}}),q("Tool permissions saved","success"),n("view"),ce()}catch(m){q(`Save failed: ${m instanceof Error?m.message:String(m)}`,"error")}},[r,G,ce,q]),Bs=vt(async()=>{if(!r)return;let m={executionMode:N};V!==void 0&&(m.model=V),m.effortTier=z===""?null:z;let T=parseFloat(ne);isNaN(T)||(m.maxBudgetUsd=T);try{await v(`/roles/${r.id}`,{method:"PATCH",body:m}),q("Execution config saved","success"),n("view"),ce()}catch(f){q(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,N,V,z,ne,ce,q]),Is=vt(async()=>{if(!r)return;let m={permissionMode:_},T=ee.split(",").map(P=>P.trim()).filter(Boolean),f=St.split(",").map(P=>P.trim()).filter(Boolean);m.allowedBashPatterns=T.length>0?T:[],m.deniedBashPatterns=f.length>0?f:[];try{await v(`/roles/${r.id}`,{method:"PATCH",body:m}),q("Permission config saved","success"),n("view"),ce()}catch(P){q(`Save failed: ${P instanceof Error?P.message:String(P)}`,"error")}},[r,_,ee,St,ce,q]),jo=vt(m=>{let T=new Map;for(let f of m){if(!f.id)continue;let P={id:f.id};f.targets?.length&&(P.targets=Array.from(new Set(f.targets.map(U=>U.trim()).filter(Boolean)))),T.set(f.id,P)}return Array.from(T.values()).sort((f,P)=>f.id.localeCompare(P.id))},[]),Es=vt(async()=>{if(!r)return;let m=jo(Ne),T=m.find(f=>f.id==="automation")?.targets??[];if(m.some(f=>f.id==="automation")&&(T.length===0||T.some(f=>!Ea.test(f)))){q("Automation requires valid bundle id targets","error");return}try{await v(`/roles/${r.id}`,{method:"PATCH",body:{osCapabilities:m}}),q("OS capabilities saved","success"),n("view"),ce()}catch(f){q(`Save failed: ${f instanceof Error?f.message:String(f)}`,"error")}},[r,Ne,jo,ce,q]),As=vt(async m=>{if(!er){q("workspace path not loaded yet","error");return}Or(!0);try{await v(`/plugins/install/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:er})}),q(`Bound ${m.split("@")[0]}`,"success"),ce()}catch(T){q(`Bind failed: ${T instanceof Error?T.message:"unknown"}`,"error")}finally{Or(!1)}},[er,ce,q]),Ps=vt(async m=>{if(!er){q("workspace path not loaded yet","error");return}Or(!0);try{await v(`/plugins/uninstall/${encodeURIComponent(m)}`,{method:"POST",body:JSON.stringify({scope:"project",cwd:er})}),q(`Unbound ${m.split("@")[0]}`,"success"),ce()}catch(T){q(`Unbind failed: ${T instanceof Error?T.message:"unknown"}`,"error")}finally{Or(!1)}},[er,ce,q]),it=r?.additionalDirectories??[];if(Ia((m,T)=>{if(T.escape){n("view");return}if(m==="r"){ce();return}switch(i){case"view":{if(m==="c"){n("edit-cag");return}if(m==="d"){n("edit-dirs"),y(0),s("");return}if(m==="t"){n("edit-tools");return}if(m==="o"){n("edit-oscaps");return}if(m==="x"){n("edit-exec");return}if(m==="h"){v("/channels?enabled=true").then(({channels:f})=>{D(f.map(P=>({name:P.name,id:P.id}))),L(new Set(r?.allowedChannels??[])),Ce(0),n("edit-channels")}).catch(()=>q("Failed to load channels","error"));return}if(m==="p"){K(r?.permissionMode??"default"),pe((r?.allowedBashPatterns??[]).join(", ")),gt((r?.deniedBashPatterns??[]).join(", ")),Ut("mode"),n("edit-permissions");return}if(m==="v"){$r(0),n("edit-env");return}if(m==="b"){po(0),n("edit-plugins");return}if(m==="i"){if(!r)return;let f=!r.inheritUserSettings;v(`/roles/${r.id}`,{method:"PATCH",body:{inheritUserSettings:f}}).then(()=>{q(`Inherit user settings: ${f?"ON":"OFF"}`,"success"),ce()}).catch(()=>q("Failed to toggle","error"));return}if(m==="R"&&r?.presetId){v(`/presets/role/${r.presetId}/restore`,{method:"POST"}).then(()=>{q("Preset restored","success"),ce()}).catch(f=>q(`Restore failed: ${f instanceof Error?f.message:String(f)}`,"error"));return}break}case"edit-cag":{if(T.ctrl&&m==="s"){Ss();return}break}case"edit-dirs":{if(m==="s"){ws();return}if(m==="a"){n("edit-dirs-add");return}if(m==="m"&&it.length>0){let f=it[b];if(f){a(U=>U&&{...U,additionalDirectories:U.additionalDirectories?.map((he,kt)=>kt===b?{...typeof he=="string"?{path:he}:he,mode:he.mode==="ro"?"rw":"ro"}:he)});let P=f.mode==="ro"?"rw":"ro";q(`Mode set to ${P.toUpperCase()}`,"success")}return}if(m==="x"&&it.length>0){a(f=>f&&{...f,additionalDirectories:it.filter((P,U)=>U!==b)}),y(f=>Math.max(0,Math.min(f,it.length-2)));return}if(T.upArrow){y(f=>Math.max(0,f-1));return}if(T.downArrow){y(f=>Math.min(it.length-1,f+1));return}break}case"edit-dirs-add":{if(T.escape){n("edit-dirs"),s(""),I([]);return}if(T.return&&c.length>0){let f=c[C];f&&(s(f.endsWith("/")?f:f+"/"),I([]));return}if(T.return){let f=w.trim();f&&f.startsWith("/")?(a(P=>P&&{...P,additionalDirectories:[...P.additionalDirectories??[],{path:f,mode:"rw"}]}),s(""),I([]),n("edit-dirs")):q("Path must be absolute (must start with /)","error");return}if(T.tab){let f=w.trim();if(!f||!f.startsWith("/"))return;v(`/fs/suggest-dirs?prefix=${encodeURIComponent(f)}`).then(({suggestions:P})=>{P.length===1?(s(P[0]+"/"),I([])):P.length>1&&(I(P),E(0))}).catch(()=>{I([])});return}if(T.upArrow&&c.length>0){E(f=>Math.max(0,f-1));return}if(T.downArrow&&c.length>0){E(f=>Math.min(c.length-1,f+1));return}break}case"edit-tools":{if(m==="s"){ks();return}let f=parseInt(m,10)-1;if(!isNaN(f)&&f>=0&&f<qr.length){let P=qr[f];Y(U=>{let he=new Set(U);return he.has(P)?he.delete(P):he.add(P),he});return}break}case"edit-oscaps":{if(m==="s"){Es();return}if(m==="a"&&Ne.some(U=>U.id==="automation")){let U=Ne.find(he=>he.id==="automation")?.targets??[];wt(U.join(", ")),n("edit-oscaps-targets");return}let f=le.filter(U=>U.editable),P=parseInt(m,10)-1;if(!isNaN(P)&&P>=0&&P<f.length){let U=f[P];M(he=>he.some(hr=>hr.id===U.id)?he.filter(hr=>hr.id!==U.id):[...he,{id:U.id,targets:U.id==="automation"?[]:void 0}]);return}break}case"edit-oscaps-targets":{if(T.return){let f=Zt.split(",").map(P=>P.trim()).filter(Boolean);M(P=>P.map(U=>U.id==="automation"?{...U,targets:f}:U)),n("edit-oscaps");return}break}case"edit-exec":{if(m==="s"){Bs();return}if(T.tab){O(f=>f==="inline"?"isolated":"inline");return}break}case"edit-permissions":{if(m==="s"){Is();return}if(T.tab){Ut(f=>f==="mode"?"allowed":f==="allowed"?"denied":"mode");return}if(et==="mode"&&(T.upArrow||T.downArrow)){let f=["default","acceptEdits","dontAsk","bypassPermissions"],P=f.indexOf(_);T.upArrow&&K(f[Math.max(0,P-1)]),T.downArrow&&K(f[Math.min(f.length-1,P+1)]);return}break}case"edit-channels":{if(m==="s"){if(!r)return;let f=ie.size>0?Array.from(ie):[];v(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:f}}).then(()=>{q("Channels saved","success"),n("view"),ce()}).catch(()=>q("Save failed","error"));return}if(m==="u"){if(!r)return;v(`/roles/${r.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{q("Channels: unrestricted","success"),n("view"),ce()}).catch(()=>q("Save failed","error"));return}if(m===" "){let f=ge[ae];f&&L(P=>{let U=new Set(P);return U.has(f.name)?U.delete(f.name):U.add(f.name),U});return}if(T.upArrow){Ce(f=>Math.max(0,f-1));return}if(T.downArrow){Ce(f=>Math.min(ge.length-1,f+1));return}break}case"edit-env":{let f=Object.keys(r?.envVars??{});if(m==="a"){Oo(""),n("edit-env-add-key");return}if(m==="d"&&f.length>0){let P=f[_t],U={...r?.envVars??{}};delete U[P],v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{q("Deleted","success"),ce()}).catch(()=>q("Delete failed","error")),_t>=f.length-1&&_t>0&&$r(he=>he-1);return}if(T.return&&f.length>0){Wo((r?.envVars??{})[f[_t]]??""),n("edit-env-edit-value");return}T.upArrow&&_t>0&&$r(P=>P-1),T.downArrow&&_t<f.length-1&&$r(P=>P+1);break}case"edit-env-add-key":case"edit-env-add-value":case"edit-env-edit-value":break;case"edit-plugins":{if(Fr)return;if(m==="a"){v("/plugins").then(({plugins:f})=>{let P=new Set(o.map(U=>U.id));Go(f.filter(U=>!P.has(U.id))),xo(0),n("edit-plugins-add")}).catch(()=>q("Failed to load plugins","error"));return}if(m==="x"&&o.length>0){let f=o[_r];f&&Ps(f.id);return}if(T.upArrow){po(f=>Math.max(0,f-1));return}if(T.downArrow){po(f=>Math.min(o.length-1,f+1));return}break}case"edit-plugins-add":{if(Fr)return;if(T.escape){n("edit-plugins"),Go([]);return}if(T.return&&Tr.length>0){let f=Tr[Lr];f&&As(f.id);return}if(T.upArrow){xo(f=>Math.max(0,f-1));return}if(T.downArrow){xo(f=>Math.min(Tr.length-1,f+1));return}break}}}),d)return h(x,{dimColor:!0,children:"Loading role..."});if(!r)return h(x,{dimColor:!0,children:"Role not found."});if(i==="edit-plugins")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Plugins (\u2191\u2193 navigate, x:unbind a:add Esc:cancel)"}),Fr&&h(x,{dimColor:!0,children:"Binding..."}),o.length===0?h(x,{dimColor:!0,children:"No plugins bound. Press a to add."}):o.map((m,T)=>k(R,{children:[k(x,{color:T===_r?"cyan":void 0,bold:T===_r,children:[T===_r?"> ":" ",m.name]}),k(x,{dimColor:!0,children:[" v",m.version]})]},m.id)),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-plugins-add")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Add Plugin (\u2191\u2193 navigate, Enter:bind Esc:cancel)"}),Fr&&h(x,{dimColor:!0,children:"Binding..."}),Tr.length===0?h(x,{dimColor:!0,children:"No available plugins."}):Tr.map((m,T)=>k(R,{children:[k(x,{color:T===Lr?"cyan":void 0,bold:T===Lr,children:[T===Lr?"> ":" ",m.name]}),k(x,{dimColor:!0,children:[" v",m.version]})]},m.id)),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-cag")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),h(ut,{value:p,onChange:g,placeholder:"Character And Guidance prompt..."}),F&&h(R,{marginTop:1,children:h(x,{color:F.type==="error"?"red":"green",children:F.text})})]});if(i==="edit-dirs-add")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),h(ut,{value:w,onChange:m=>{s(m),I([])},placeholder:"/absolute/path/to/directory"}),c.length>0&&k(R,{flexDirection:"column",marginTop:1,children:[c.map((m,T)=>k(x,{color:T===C?"cyan":void 0,dimColor:T!==C,children:[T===C?"> ":" ",m,"/"]},m)),h(x,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),F&&h(R,{marginTop:1,children:h(x,{color:F.type==="error"?"red":"green",children:F.text})})]});if(i==="edit-dirs")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add m:mode x:remove s:save Esc:cancel)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),it.length===0?h(x,{dimColor:!0,children:"No directories. Press a to add one."}):it.map((m,T)=>{let f=typeof m=="string"?{path:m,mode:"rw"}:m,P=f.mode!=="ro";return k(R,{children:[h(x,{color:T===b?"cyan":void 0,bold:T===b,children:T===b?"> ":" "}),k(x,{color:P?"green":"yellow",children:["[",P?"RW":"RO","]"," "]}),h(x,{color:T===b?"cyan":void 0,children:f.path})]},f.path)})]});if(i==="edit-tools")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),qr.map((m,T)=>{let f=G.has(m);return k(R,{children:[k(x,{dimColor:!0,children:[T+1,". "]}),h(x,{color:f?"green":"red",children:f?"[ON] ":"[OFF] "}),h(x,{children:m})]},m)})]});if(i==="edit-oscaps"){let m=le.filter(T=>T.editable);return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"OS Capabilities \u2014 toggle with number key (a:automation targets s:save Esc:cancel)"}),A&&k(x,{dimColor:!0,children:["Platform: ",A.platform," ",A.available?"(sandbox active)":"(sandbox unavailable)"]}),le.map(T=>{let f=m.findIndex(kt=>kt.id===T.id),P=Ne.some(kt=>kt.id===T.id),U=f>=0?`${f+1}.`:" -",he=T.id==="automation"?(()=>{let kt=Ne.find(hr=>hr.id===T.id)?.targets??[];return kt.length>0?` targets: ${kt.join(", ")}`:" targets: (none)"})():"";return k(R,{flexDirection:"column",marginBottom:1,children:[k(x,{color:P?"green":T.editable?"red":"gray",children:[U," ",P?"[ON]":"[OFF]"," ",T.label," [",T.availability,"]"]}),k(x,{dimColor:!0,children:[" ",T.description,he]}),T.effectiveDisabledReason&&!T.editable&&k(x,{dimColor:!0,children:[" ",T.effectiveDisabledReason]})]},T.id)}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]})}if(i==="edit-oscaps-targets")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Automation Targets (comma-separated bundle ids; Enter confirm, Esc cancel)"}),h(ut,{value:Zt,onChange:wt,placeholder:"com.apple.mail, com.apple.systemevents"}),h(x,{dimColor:!0,children:"Example: com.apple.mail, com.apple.systemevents"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-exec")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),k(R,{children:[h(x,{bold:!0,children:" Mode: "}),h(x,{color:"cyan",children:N}),h(x,{dimColor:!0,children:" (Tab to toggle)"})]}),k(R,{children:[h(x,{bold:!0,children:" Model: "}),h(ut,{value:V,onChange:B,placeholder:"sonnet, opus, haiku, or blank"})]}),k(R,{children:[h(x,{bold:!0,children:" Effort Tier: "}),h(ut,{value:z,onChange:se,placeholder:"low, medium, high, or blank to inherit"})]}),k(R,{children:[h(x,{bold:!0,children:" Max Budget (USD): "}),h(ut,{value:ne,onChange:$e,placeholder:"0 = unlimited"})]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-permissions")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Permission Config (Tab:cycle field, \u2191\u2193:mode, s:save, Esc:cancel)"}),k(R,{children:[h(x,{bold:!0,color:et==="mode"?"cyan":void 0,children:" Mode: "}),["default","acceptEdits","dontAsk","bypassPermissions"].map(T=>k(x,{color:T===_?"green":"gray",children:[T===_?`[${T}]`:` ${T} `," "]},T))]}),k(R,{children:[h(x,{bold:!0,color:et==="allowed"?"cyan":void 0,children:" Allowed Bash: "}),et==="allowed"?h(ut,{value:ee,onChange:pe,placeholder:"git add *, pnpm test*"}):h(x,{children:ee||"(none)"})]}),k(R,{children:[h(x,{bold:!0,color:et==="denied"?"cyan":void 0,children:" Denied Bash: "}),et==="denied"?h(ut,{value:St,onChange:gt,placeholder:"rm -rf *, ssh *"}):h(x,{children:St||"(none)"})]}),h(x,{dimColor:!0,children:"Patterns: comma-separated, glob syntax (* = wildcard)"}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i==="edit-channels")return k(R,{flexDirection:"column",children:[h(x,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),ge.length===0?h(x,{dimColor:!0,children:"No channels available"}):ge.map((m,T)=>k(R,{children:[k(x,{children:[T===ae?">":" "," "]}),k(x,{color:ie.has(m.name)?"green":"gray",children:["[",ie.has(m.name)?"x":" ","] ",m.name]})]},m.id)),k(x,{dimColor:!0,children:["Selected: ",ie.size>0?Array.from(ie).join(", "):"none (= block all)"]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})})]});if(i.startsWith("edit-env")){let m=Object.keys(r.envVars??{});return k(R,{flexDirection:"column",children:[k(x,{bold:!0,children:["Environment Variables (",m.length,")"]}),m.length===0&&i==="edit-env"&&h(x,{dimColor:!0,children:" No env vars. Press a to add."}),m.map((T,f)=>{let P=f===_t;return i==="edit-env-edit-value"&&P?k(R,{children:[k(x,{color:"cyan",children:["> ",T," = "]}),h(ut,{value:Uo,onChange:Wo,onSubmit:()=>{let U={...r.envVars??{},[T]:Uo};v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:U}}).then(()=>{q("Saved","success"),ce(),n("edit-env")}).catch(()=>q("Save failed","error"))}})]},T):k(x,{color:P&&i==="edit-env"?"cyan":"white",children:[P&&i==="edit-env"?"> ":" ",T," = ",(r.envVars??{})[T]]},T)}),i==="edit-env-add-key"&&k(R,{children:[h(x,{color:"green",children:" New key: "}),h(ut,{value:Nr,onChange:Oo,onSubmit:()=>{Nr.trim()&&(Vo(""),n("edit-env-add-value"))}})]}),i==="edit-env-add-value"&&k(R,{children:[k(x,{color:"green",children:[" ",Nr," = "]}),h(ut,{value:qo,onChange:Vo,onSubmit:()=>{let T={...r.envVars??{},[Nr.trim()]:qo};v(`/roles/${r.id}`,{method:"PATCH",body:{envVars:T}}).then(()=>{q("Added","success"),ce(),n("edit-env")}).catch(()=>q("Add failed","error"))}})]}),h(x,{dimColor:!0,children:"a:add Enter:edit d:delete Esc:back"}),F&&h(x,{color:F.type==="error"?"red":"green",children:F.text})]})}return k(R,{flexDirection:"column",children:[k(x,{bold:!0,children:["Role: ",r.name]}),k(R,{children:[h(x,{dimColor:!0,children:"ID: "}),h(x,{children:r.id})]}),k(R,{children:[h(x,{dimColor:!0,children:"Status: "}),h(x,{color:r.status==="active"?"green":r.status==="probation"?"yellow":"red",children:r.status})]}),r.performanceScore!=null&&k(R,{children:[h(x,{dimColor:!0,children:"Score: "}),k(x,{children:[(r.performanceScore*100).toFixed(0),"%"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"Created: "}),h(x,{children:new Date(r.createdAt).toLocaleString()})]}),k(R,{children:[h(x,{dimColor:!0,children:"Execution: "}),k(x,{children:[r.executionMode??"inline"," / tier:",r.effortTier??"\u2014"," / model:",r.model??"inherit"," / ",r.maxBudgetUsd!=null?`$${r.maxBudgetUsd}`:"no limit"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"OS Capabilities: "}),h(x,{children:(r.osCapabilities?.length??0)>0?r.osCapabilities.map(m=>m.id==="automation"&&m.targets?.length?`automation(${m.targets.join(",")})`:m.id).join(", "):"None"})]}),A&&k(R,{children:[h(x,{dimColor:!0,children:"Sandbox Platform: "}),k(x,{children:[A.platform," ",A.available?"(active)":"(unavailable)"]})]}),it.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Additional Directories:"}),it.map(m=>k(x,{dimColor:!0,children:[" ",m.path]},m.path))]}),k(R,{children:[h(x,{dimColor:!0,children:"Permission: "}),h(x,{children:r.permissionMode??"default"})]}),(r.allowedBashPatterns?.length??0)>0&&k(R,{children:[h(x,{dimColor:!0,children:" Bash Allow: "}),h(x,{children:r.allowedBashPatterns.join(", ")})]}),(r.deniedBashPatterns?.length??0)>0&&k(R,{children:[h(x,{dimColor:!0,children:" Bash Deny: "}),h(x,{children:r.deniedBashPatterns.join(", ")})]}),Jt.length>0&&k(R,{flexDirection:"column",children:[h(x,{dimColor:!0,children:"Denied Read Paths (global):"}),Jt.map(m=>k(x,{dimColor:!0,children:[" ",m]},m)),k(x,{dimColor:!0,italic:!0,children:[" (Settings ",">"," Advanced)"]})]}),k(R,{children:[h(x,{dimColor:!0,children:"Channels: "}),h(x,{children:r.allowedChannels===void 0?"Unrestricted":r.allowedChannels.length===0?"Blocked":r.allowedChannels.join(", ")})]}),k(R,{children:[h(x,{dimColor:!0,children:"Inherit User Settings: "}),h(x,{color:r.inheritUserSettings?"green":"gray",children:r.inheritUserSettings?"Yes":"No"})]}),r.learnedRules.stylePreferences.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Style Preferences:"}),r.learnedRules.stylePreferences.map(m=>k(x,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.avoidedActions.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Avoided Actions:"}),r.learnedRules.avoidedActions.map(m=>k(x,{dimColor:!0,children:[" - ",m]},m))]}),r.learnedRules.pinnedParameters.length>0&&k(ao,{children:[h(x,{bold:!0,children:"Pinned Parameters:"}),r.learnedRules.pinnedParameters.map(m=>{let T=Object.entries(m.params).map(([P,U])=>`${P}=${JSON.stringify(U)}`).join(", "),f=m.condition?` [when: ${m.condition}]`:"";return k(x,{dimColor:!0,children:[" - ",m.tool," \u2192 ",T,f]},`${m.tool}-${m.pinnedAt}`)})]}),k(R,{children:[h(x,{dimColor:!0,children:"Plugins: "}),o.length===0?h(x,{dimColor:!0,children:"None"}):o.map(m=>k(x,{children:[m.name," "]},m.id))]}),F&&h(R,{children:h(x,{color:F.type==="error"?"red":F.type==="success"?"green":"gray",children:F.text})}),h(R,{marginTop:1,children:k(x,{dimColor:!0,children:["c:CAG d:dirs t:tools b:plugins o:oscaps x:exec p:perms h:channels v:env i:inherit"," ",r?.presetId?"R:restore-preset ":"","r:refresh Esc:back"]})})]})}import{jsx as Qe,jsxs as Rr}from"react/jsx-runtime";function ls({onBack:e}){let[t,r]=Pr([]),[a,o]=Pr(!0),[u,d]=Pr(0),[l,i]=Pr("list"),[n,p]=Pr(null),{message:g,setMessage:b,clearMessage:y}=ot(),w=Ra(()=>{o(!0),v("/roles").then(({roles:s})=>{r(s.map(c=>({id:c.id,name:c.name,status:c.status,performanceScore:c.performanceScore,createdAt:c.createdAt,presetId:c.presetId,contractComplianceEma:c.contractComplianceEma}))),o(!1)}).catch(()=>o(!1))},[]);return Pa(()=>{w()},[w]),Aa((s,c)=>{if(c.escape||s==="q"){e();return}if(c.upArrow){d(I=>Math.max(0,I-1));return}if(c.downArrow){d(I=>Math.min(t.length-1,I+1));return}if(s==="r"&&(w(),y()),s===`
|
|
11
|
+
`||s==="o"||s==="e"){t.length>0&&(p(t[u].id),i("detail"));return}}),a?Qe(mt,{dimColor:!0,children:"Loading roles..."}):l==="detail"&&n?Qe(as,{roleId:n,onBack:()=>i("list")}):Rr(ur,{flexDirection:"column",children:[Rr(mt,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),g&&Qe(ur,{marginTop:1,children:Rr(mt,{color:g.type==="success"?"green":g.type==="error"?"red":"gray",children:[g.type==="success"?"\u2713 ":g.type==="error"?"\u2717 ":"\u2192 ",g.text]})}),t.length===0?Qe(ur,{marginTop:1,children:Qe(mt,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Qe(ur,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let I=c===u,C=s.performanceScore!=null?`${(s.performanceScore*100).toFixed(0)}%`:"\u2014",E=s.contractComplianceEma!=null?`[\u5951\u7EA6 ${s.contractComplianceEma.toFixed(2)}]`:"[\u5951\u7EA6 \u2014]";return Rr(ur,{children:[Qe(mt,{color:I?"cyan":void 0,bold:I,children:I?"> ":" "}),Qe(mt,{color:I?"cyan":void 0,bold:I,children:No(s.name,24)}),s.presetId&&Rr(mt,{dimColor:!0,children:["[",s.presetId,"]"]}),Qe(mt,{color:Da(s.status),children:No(s.status,12)}),Qe(mt,{dimColor:!0,children:No(C,8)}),Qe(mt,{dimColor:!0,children:E})]},s.id)})}),Qe(ur,{marginTop:1,children:Qe(mt,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function Da(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function No(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ma,Text as _o}from"ink";import $a from"react";import{jsx as lo,jsxs as _a}from"react/jsx-runtime";var He={key:"Esc",label:"back"},Na={work:[{key:"1",label:"tasks"},{key:"2",label:"automations"},{key:"3",label:"goals"},He],tasks:[{key:"\u2191\u2193",label:"move"},{key:"Enter",label:"detail"},{key:"x",label:"cancel"},{key:"f",label:"filter"},{key:"r",label:"refresh"},He],config:[He],evolution:[He],goals:[{key:"c",label:"create"},{key:"r",label:"refresh"},He],strategies:[He],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"},He],webhooks:[He],memories:[He],plugins:[{key:"\u2191\u2193",label:"move"},{key:"r",label:"refresh"},He],roles:[He],settings:[He],channels:[He]};function cs(){let{state:e}=tt(),t=Na[e.view]??[He];return lo(Ma,{borderStyle:"round",borderDimColor:!0,paddingX:1,children:t.map((r,a)=>_a($a.Fragment,{children:[a>0&&lo(_o,{dimColor:!0,children:" "}),lo(_o,{color:"cyan",children:r.key}),lo(_o,{dimColor:!0,children:` ${r.label}`})]},`${r.key}-${r.label}`))})}import{Box as mr,Text as nt,useInput as La}from"ink";import{useEffect as Fa,useState as co,useCallback as Oa}from"react";import{jsx as Mt,jsxs as Dt}from"react/jsx-runtime";function ds({onBack:e}){let[t,r]=co([]),[a,o]=co(!0),[u,d]=co(0),[l,i]=co("all"),{message:n,setMessage:p}=ot(),g=Oa(()=>{o(!0);let c=l!=="all"?`?status=${l}`:"";v(`/feature-requests${c}`).then(({featureRequests:I})=>{r(I),d(0),o(!1)}).catch(()=>o(!1))},[l]);Fa(()=>{g()},[g]);let b=async(c,I)=>{try{await v(`/feature-requests/${c}/status`,{method:"PATCH",body:{status:I}}),p(`Marked as ${I}`,"success"),await g()}catch(C){p(`Failed: ${C instanceof Error?C.message:String(C)}`,"error")}},y=t;La((c,I)=>{if(I.escape||c==="q"){e();return}if(I.upArrow){d(E=>Math.max(0,E-1));return}if(I.downArrow){d(E=>Math.min(y.length-1,E+1));return}if(c==="r"){g();return}let C={0:"all",1:"new",2:"reviewed",3:"dismissed",4:"converted"};if(C[c]){i(C[c]);return}if(c==="s"&&y.length>0){let E=y[u];if(E&&E.status==="new"){b(E.id,"reviewed");return}}if(c==="d"&&y.length>0){let E=y[u];if(E){b(E.id,"dismissed");return}}if(c==="c"&&y.length>0){let E=y[u];if(E){b(E.id,"converted");return}}});let w=c=>c==="new"?"cyan":c==="reviewed"?"green":c==="dismissed"?"gray":c==="converted"?"yellow":"white",s=c=>{let I=Date.now()-c;if(Math.floor(I/6e4)<1)return"now";let E=Math.floor(I/36e5);return E<24?`${E}h ago`:`${Math.floor(E/24)}d ago`};return Dt(mr,{flexDirection:"column",children:[Dt(nt,{bold:!0,children:["Feature Requests (",y.length,") (Esc:back q:quit r:refresh)"]}),n&&Mt(mr,{marginTop:1,children:Dt(nt,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),Mt(nt,{dimColor:!0,children:"Filters: 0=all 1=new 2=reviewed 3=dismissed 4=converted"}),Mt(nt,{dimColor:!0,children:"Actions: s=reviewed d=dismissed c=converted"}),a?Mt(nt,{dimColor:!0,children:"Loading..."}):y.length===0?Mt(nt,{dimColor:!0,children:"No feature requests found."}):Mt(mr,{marginTop:1,flexDirection:"column",children:y.map((c,I)=>{let C=I===u,E=c.content.length>80?c.content.slice(0,80)+"...":c.content;return Dt(mr,{flexDirection:"column",children:[Dt(mr,{children:[Mt(nt,{color:C?"cyan":void 0,bold:C,children:C?"> ":" "}),Dt(nt,{color:w(c.status),children:["[",c.status,"]"]}),Dt(nt,{dimColor:!0,children:[" ",s(c.extractedAt)]}),c.tags&&c.tags.length>0&&Dt(nt,{dimColor:!0,children:[" ",c.tags.slice(0,3).join(", ")]})]}),Dt(mr,{paddingLeft:4,flexDirection:"column",children:[c.summary&&Mt(nt,{color:C?"cyan":"white",children:c.summary}),Mt(nt,{dimColor:!0,children:E})]})]},c.id)})})]})}import{Box as fr,Text as Je,useInput as qa}from"ink";import{useEffect as Va,useState as uo,useCallback as Ua}from"react";import{jsx as $t,jsxs as Ct}from"react/jsx-runtime";function us({onBack:e}){let[t,r]=uo([]),[a,o]=uo(!0),[u,d]=uo(0),[l,i]=uo("all"),{message:n,setMessage:p}=ot(),g=Ua(()=>{o(!0);let s=l!=="all"?`?status=${l}`:"";v(`/mistake-patterns${s}`).then(({mistakePatterns:c})=>{r(c),d(0),o(!1)}).catch(()=>o(!1))},[l]);Va(()=>{g()},[g]);let b=async(s,c)=>{try{await v(`/mistake-patterns/${s}`,{method:"PATCH",body:{status:c}}),p(`Marked as ${c}`,"success"),await g()}catch(I){p(`Failed: ${I instanceof Error?I.message:String(I)}`,"error")}};qa((s,c)=>{if(c.escape||s==="q"){e();return}if(c.upArrow){d(C=>Math.max(0,C-1));return}if(c.downArrow){d(C=>Math.min(t.length-1,C+1));return}if(s==="r"){g();return}let I={0:"all",1:"new",2:"acknowledged",3:"dismissed"};if(I[s]){i(I[s]);return}if(s==="a"&&t.length>0){let C=t[u];if(C&&C.status!=="acknowledged"){b(C.id,"acknowledged");return}}if(s==="d"&&t.length>0){let C=t[u];if(C&&C.status!=="dismissed"){b(C.id,"dismissed");return}}if(s==="n"&&t.length>0){let C=t[u];if(C&&C.status!=="new"){b(C.id,"new");return}}});let y=s=>s==="new"?"cyan":s==="acknowledged"?"green":s==="dismissed"?"gray":"white",w=s=>{let c=Date.now()-s;if(Math.floor(c/6e4)<1)return"now";let C=Math.floor(c/36e5);return C<24?`${C}h ago`:`${Math.floor(C/24)}d ago`};return Ct(fr,{flexDirection:"column",children:[Ct(Je,{bold:!0,children:["Mistake Patterns (",t.length,") (Esc:back q:quit r:refresh)"]}),n&&$t(fr,{marginTop:1,children:Ct(Je,{color:n.type==="error"?"red":"green",children:[n.type==="success"?"\u2713 ":"\u2717 ",n.text]})}),$t(Je,{dimColor:!0,children:"Filters: 0=all 1=new 2=acknowledged 3=dismissed"}),$t(Je,{dimColor:!0,children:"Actions: a=acknowledge d=dismiss n=mark new"}),a?$t(Je,{dimColor:!0,children:"Loading..."}):t.length===0?$t(Je,{dimColor:!0,children:"No mistake patterns found."}):$t(fr,{marginTop:1,flexDirection:"column",children:t.map((s,c)=>{let I=c===u,C=s.dimensionValue.length>80?s.dimensionValue.slice(0,80)+"...":s.dimensionValue;return Ct(fr,{flexDirection:"column",children:[Ct(fr,{children:[$t(Je,{color:I?"cyan":void 0,bold:I,children:I?"> ":" "}),Ct(Je,{color:y(s.status),children:["[",s.status,"]"]}),Ct(Je,{dimColor:!0,children:[" ",w(s.lastSeen)]}),Ct(Je,{dimColor:!0,children:[" [",s.dimensionType,"]"]}),Ct(Je,{dimColor:!0,children:[" ",s.roleIds.length," role(s)"]}),Ct(Je,{dimColor:!0,children:[" x",s.count]})]}),$t(fr,{paddingLeft:4,flexDirection:"column",children:$t(Je,{color:I?"cyan":"white",children:C})})]},s.id)})})]})}import{Box as Nt,Text as ke,useInput as hs}from"ink";import{useEffect as tl,useState as ft,useCallback as ys,useRef as bs}from"react";import{readFileSync as Wa,existsSync as Ga}from"fs";import{join as ja}from"path";import{homedir as Ka}from"os";function Ha(){if(process.env.ADAM_API_KEY)return process.env.ADAM_API_KEY;let e=ja(Ka(),".adam","adam.key");if(Ga(e))return Wa(e,"utf8").trim();throw new Error("ADAM_API_KEY env or ~/.adam/adam.key required")}function za(){return Number(process.env.ADAM_PORT??7100)}async function mo(e,t={}){let r={"x-api-key":Ha(),...t.headers??{}};t.body&&(r["Content-Type"]??="application/json");let a=await fetch(`http://localhost:${za()}${e}`,{...t,headers:r});if(!a.ok)throw new Error(`${a.status}: ${await a.text()}`);if(a.status!==204)return a.json()}function ms(e={}){let t=new URLSearchParams(Object.entries(e).map(([r,a])=>[r,String(a)])).toString();return mo(`/artifacts${t?"?"+t:""}`)}function fs(e){return mo(`/artifacts/${encodeURIComponent(e)}`)}function Lo(e,t=!1){return mo(`/artifacts/${encodeURIComponent(e)}${t?"?confirm=true":""}`,{method:"DELETE"})}function gs(e,t){return mo(`/artifacts/${encodeURIComponent(e)}/redeliver`,{method:"POST",body:JSON.stringify(t)})}import{spawn as Xa}from"child_process";async function ps(e){let t=process.platform==="darwin"?"pbcopy":process.platform==="linux"?"xclip":null;return t?new Promise(r=>{try{let a=process.platform==="linux"?["-selection","clipboard"]:[],o=Xa(t,a);o.on("error",()=>r(!1)),o.on("close",u=>r(u===0)),o.stdin.write(e),o.stdin.end()}catch{r(!1)}}):!1}import{Box as gr,Text as qt,useInput as Ya}from"ink";import{jsx as ve,jsxs as zt}from"react/jsx-runtime";function Qa(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`}function Ja(e){return new Date(e).toLocaleString()}function Ze({label:e,value:t}){return zt(gr,{children:[ve(qt,{dimColor:!0,children:e.padEnd(20)}),ve(qt,{color:"cyan",children:t})]})}function xs({artifact:e,deliveryLog:t,onBack:r}){return Ya((a,o)=>{o.escape&&r()}),zt(gr,{flexDirection:"column",children:[ve(qt,{bold:!0,children:"Artifact Detail (Esc to go back)"}),zt(gr,{flexDirection:"column",marginTop:1,children:[ve(Ze,{label:"ID",value:e.id}),ve(Ze,{label:"Source",value:e.sourceKind}),ve(Ze,{label:"Role",value:e.producedByRole??e.roleId??"\u2014"}),ve(Ze,{label:"Mime",value:e.mime??"\u2014"}),ve(Ze,{label:"Kind",value:e.kind}),ve(Ze,{label:"Size",value:Qa(e.sizeBytes)}),ve(Ze,{label:"Created",value:Ja(e.createdAt)}),ve(Ze,{label:"Key",value:e.key??"\u2014"}),ve(Ze,{label:"Blob path",value:e.blobPath??"\u2014"}),e.executionId&&ve(Ze,{label:"Execution ID",value:e.executionId}),e.taskId&&ve(Ze,{label:"Task ID",value:e.taskId}),e.chatSessionId&&ve(Ze,{label:"Chat Session",value:e.chatSessionId}),e.originalFilename&&ve(Ze,{label:"Filename",value:e.originalFilename})]}),t.length>0&&zt(gr,{flexDirection:"column",marginTop:1,children:[zt(qt,{bold:!0,dimColor:!0,children:["Delivery Log (",t.length,")"]}),t.map((a,o)=>zt(gr,{children:[ve(qt,{dimColor:!0,children:" "}),ve(qt,{color:a.status==="delivered"?"green":a.status==="failed"?"red":"yellow",children:a.status}),zt(qt,{dimColor:!0,children:[" \u2192 ",a.target?.channelId??"\u2014",a.createdAt?` (${new Date(a.createdAt).toLocaleTimeString()})`:""]})]},o))]}),t.length===0&&ve(gr,{marginTop:1,children:ve(qt,{dimColor:!0,children:"No delivery log entries."})})]})}import{Box as fo,Text as Vt,useInput as Za}from"ink";import{useEffect as el,useState as Fo}from"react";import{jsx as Xt,jsxs as Dr}from"react/jsx-runtime";function Ts({onSelect:e,onCancel:t,fetchChannels:r}){let[a,o]=Fo([]),[u,d]=Fo(!0),[l,i]=Fo(null);return el(()=>{r().then(n=>{o(n.channels),d(!1)}).catch(n=>{i(`Failed to load channels: ${n instanceof Error?n.message:String(n)}`),d(!1)})},[r]),Za((n,p)=>{if(p.escape){t();return}let g=parseInt(n,10);if(!isNaN(g)&&g>=1&&g<=a.length){let b=a[g-1];b&&e(b.id)}}),u?Xt(fo,{children:Xt(Vt,{dimColor:!0,children:"Loading channels..."})}):l?Dr(fo,{children:[Xt(Vt,{color:"red",children:l}),Xt(Vt,{dimColor:!0,children:" (Esc to cancel)"})]}):Dr(fo,{flexDirection:"column",children:[Xt(Vt,{bold:!0,children:"Select channel to redeliver (Esc to cancel):"}),a.length===0?Xt(Vt,{dimColor:!0,children:"No channels configured."}):a.map((n,p)=>Dr(fo,{children:[Dr(Vt,{children:["[",p+1,"] "]}),Xt(Vt,{color:"cyan",children:n.name}),Dr(Vt,{dimColor:!0,children:[" (",n.platform,")"]})]},n.id))]})}import{jsx as fe,jsxs as Yt}from"react/jsx-runtime";function rl(e){return e?e.replace(/[\x00-\x1F\x7F]/g,""):""}function st(e,t){return e.length>=t?e.slice(0,t):e+" ".repeat(t-e.length)}function ol(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(0)}K`:`${(e/(1024*1024)).toFixed(1)}M`}function nl(e){let t=Date.now()-e,r=Math.floor(t/1e3),a=Math.floor(r/60),o=Math.floor(a/60);if(r<60)return"just now";if(a<60)return`${a}m ago`;if(o<24)return`${o}h ago`;let u=new Date(e);return`${String(u.getMonth()+1).padStart(2,"0")}-${String(u.getDate()).padStart(2,"0")}`}function sl(e){return e==="template_step"?"tmpl":e==="task_published"?"task":e==="chat_sent"?"chat":e.slice(0,6)}function vs({onBack:e,onSelect:t,onAction:r}){let{dispatch:a}=tt(),[o,u]=ft([]),[d,l]=ft(0),[i,n]=ft(!0),[p,g]=ft(null),[b,y]=ft(0),[w,s]=ft("list"),[c,I]=ft(null),[C,E]=ft([]),[G,Y]=ft(null),[N,O]=ft(null),[V,B]=ft(null),z=bs(null),se=bs(null);function ne(D){B(D),se.current&&clearTimeout(se.current),se.current=setTimeout(()=>B(null),2e3)}let $e=ys(()=>{z.current&&z.current.abort(),z.current=new AbortController,n(!0),g(null),ms({limit:100}).then(D=>{u(D.artifacts),l(D.total),y(0),n(!1)}).catch(D=>{D.name!=="AbortError"&&(g(`Failed to load: ${D instanceof Error?D.message:String(D)}`),n(!1))})},[]);tl(()=>($e(),()=>{z.current&&z.current.abort(),se.current&&clearTimeout(se.current)}),[$e]),hs((D,ie)=>{if(G)if(D==="y"){let L=G;Y(null),Lo(L.id,!0).then(()=>{ne("Deleted"),$e()}).catch(ae=>ne(`Delete failed: ${ae instanceof Error?ae.message:String(ae)}`))}else(D==="n"||ie.escape)&&Y(null)}),hs((D,ie)=>{if(G||N)return;if(ie.escape||D==="q"){e();return}if(ie.upArrow||D==="k"){y(ae=>Math.max(0,ae-1));return}if(ie.downArrow||D==="j"){y(ae=>Math.min(Math.max(0,o.length-1),ae+1));return}if(D==="\r"||D===`
|
|
12
|
+
`||D==="o"){if(o.length>0&&o[b]){let ae=o[b];t(ae),fs(ae.id).then(Ce=>{I(Ce.artifact),E(Ce.deliveryLog),s("detail")}).catch(()=>{I(ae),E([]),s("detail")})}return}let L=o.length>0?o[b]:void 0;if(L){if(D==="d"){r("d",L),To(L.mime)?Y(L):Lo(L.id,!1).then(()=>{ne("Deleted"),$e()}).catch(Ce=>ne(`Delete failed: ${Ce instanceof Error?Ce.message:String(Ce)}`));return}if(D==="r"){r("r",L),O(L);return}if(D==="c"){r("c",L);let ae=L.blobPath??"";ps(ae).then(Ce=>{ne(Ce?`Copied: ${ae.slice(-40)}`:"Clipboard unavailable")}).catch(()=>ne("Clipboard unavailable"));return}if(D==="t"){r("t",L);let ae=L.taskId??L.executionId;a({type:"SET_VIEW",view:"tasks",selectedTaskId:ae});return}}});let ge=ys(()=>{let{getApiKey:D,getPort:ie}={getApiKey:()=>process.env.ADAM_API_KEY??"",getPort:()=>Number(process.env.ADAM_PORT??7100)};return fetch(`http://localhost:${ie()}/channels`,{headers:{"x-api-key":D()}}).then(L=>L.json())},[]);if(w==="detail"&&c)return fe(xs,{artifact:c,deliveryLog:C,onBack:()=>s("list")});if(N){let D=N;return fe(Ts,{fetchChannels:ge,onSelect:ie=>{O(null),gs(D.id,{channelId:ie}).then(L=>ne(`Redeliver queued: ${L.status}`)).catch(L=>ne(`Redeliver failed: ${L instanceof Error?L.message:String(L)}`))},onCancel:()=>O(null)})}return i?Yt(Nt,{flexDirection:"column",children:[fe(ke,{bold:!0,children:"Artifacts"}),fe(ke,{dimColor:!0,children:"Loading..."})]}):p?Yt(Nt,{flexDirection:"column",children:[fe(ke,{bold:!0,children:"Artifacts"}),fe(ke,{color:"red",children:p}),fe(ke,{dimColor:!0,children:"Press Esc to go back or r to retry"})]}):Yt(Nt,{flexDirection:"column",children:[Yt(ke,{bold:!0,children:["Artifacts (",d,") (Esc to go back)"]}),fe(Nt,{children:Yt(ke,{dimColor:!0,bold:!0,children:[" ",st("#",3),st("Source",12),st("Role",12),st("Mime",16),st("Size",8),st("Created",16),"Delivered"]})}),o.length===0?fe(Nt,{marginTop:1,children:fe(ke,{dimColor:!0,children:"No artifacts found."})}):o.map((D,ie)=>{let L=ie===b,ae=D.mime??"unknown",Ce=D.producedByRole??D.roleId??"\u2014";return Yt(Nt,{children:[fe(ke,{color:L?"cyan":void 0,bold:L,children:L?"> ":" "}),fe(ke,{color:L?"cyan":void 0,bold:L,children:st(String(ie+1),3)}),fe(ke,{color:L?"cyan":void 0,children:st(sl(D.sourceKind),12)}),fe(ke,{color:L?"cyan":void 0,children:st(rl(Ce).slice(0,11),12)}),fe(ke,{color:L?"cyan":void 0,children:st(ae.slice(0,15),16)}),fe(ke,{color:L?"cyan":void 0,children:st(ol(D.sizeBytes),8)}),fe(ke,{color:L?"cyan":void 0,children:st(nl(D.createdAt),16)}),fe(ke,{color:L?"cyan":void 0,children:"\u2014"})]},D.id)}),G&&fe(Nt,{marginTop:1,children:Yt(ke,{color:"red",children:["Delete this ",To(G.mime)," file? (y/n)"]})}),V&&!G&&fe(Nt,{marginTop:1,children:fe(ke,{color:"green",children:V})}),fe(Nt,{marginTop:1,children:fe(ke,{dimColor:!0,children:"j/k=navigate enter=detail d=delete r=redeliver c=copy t=task"})})]})}import{Fragment as ml,jsx as te,jsxs as xr}from"react/jsx-runtime";function cl(){let{state:e,dispatch:t}=tt(),{session:r,sendMessage:a,createNewSession:o,archiveCurrentSession:u}=rn(),[d,l]=al([]);go(()=>{t({type:"SET_SESSION",session:r})},[r,t]),Zo();let{latestMessage:i}=nn(r?.id??null),n=Qt(null),p=Qt(new Set),g=Qt(new Set),b=Qt(new Set),y=Qt(new Set),[,w]=ll(B=>B+1,0);go(()=>{if(!i||i.id===n.current)return;n.current=i.id;let B=!i.kind||i.kind==="result_delivery"||i.kind==="assistant_text";if(B&&i.taskId&&g.current.has(i.taskId)){p.current.add(i.taskId);return}B&&i.taskId&&p.current.add(i.taskId),l(z=>[...z,{id:i.id,role:"assistant",content:i.content,taskId:i.taskId,createdAt:i.createdAt,kind:i.kind,threadRoot:i.threadRoot,parentMessageId:i.parentMessageId,promptId:i.promptId,approvalShape:i.approvalShape,roleId:i.roleId,attachments:i.attachments,mirroredToTargets:i.mirroredToTargets,platformMessageId:i.platformMessageId,seq:i.seq}])},[i]);let{events:s,isStreaming:c,clearEvents:I}=tn(e.activeTaskId),C=s[s.length-1],E=C?.type==="complete"&&!c,G=Qt(null),Y=Qt("");go(()=>{Y.current=s.filter(B=>B.type==="reasoning").map(B=>B.content).join("")},[s]),go(()=>{if(E&&e.activeTaskId!==G.current){if(G.current=e.activeTaskId,e.activeTaskId&&p.current.has(e.activeTaskId))return;let B=C?.content||Y.current;B&&(e.activeTaskId&&g.current.add(e.activeTaskId),l(z=>[...z,{role:"assistant",content:B,taskId:e.activeTaskId??void 0,kind:"assistant_text"}]))}},[E,C,e.activeTaskId]);let N=async B=>{let z=B.trim().toLowerCase();if(["quit","exit","/quit","/exit"].includes(z)&&process.exit(0),B.startsWith("/")){let ne=B.slice(1),ge={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins","feature-requests":"featureRequests",mistakes:"mistakes",artifacts:"artifacts",back:"chat"}[ne];if(ge){t({type:"SET_VIEW",view:ge});return}if(ne==="new"){if(await u()){let ie=await o();l([]),I(),p.current.clear(),g.current.clear(),b.current.clear(),y.current.clear(),ie&&l([{role:"assistant",content:`Session archived. New session started: ${ie.id.slice(0,8)}`}])}return}if(ne==="session"){let D=r?`Session: ${r.id}
|
|
13
|
+
Turns: ${r.messageCount}
|
|
14
|
+
Last active: ${new Date(r.lastActiveAt).toLocaleString()}`:"No active session";l(ie=>[...ie,{role:"assistant",content:D}]);return}}if(l(ne=>[...ne,{role:"user",content:B}]),I(),!await a(B)){l(ne=>[...ne,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}},O=d.some(B=>B.kind==="approval_prompt"&&B.promptId&&!b.current.has(B.promptId)&&!y.current.has(B.promptId)),V=e.view==="chat"&&!e.pendingPlanApproval&&!e.pendingApproval&&!O;return xr(Mr,{flexDirection:"column",paddingX:1,children:[te(an,{}),xr(Mr,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&xr(ml,{children:[te(wn,{messages:d,onApprovalSubmitted:B=>{b.current.add(B),w()},onApprovalFailed:B=>{y.current.add(B),w()}}),te(dn,{events:s,isStreaming:c}),!e.connected&&!e.serverUnreachable&&te(Mr,{children:te(pr,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&xr(Mr,{flexDirection:"column",children:[te(pr,{color:"red",bold:!0,children:"Server unreachable after 15s."}),te(pr,{dimColor:!0,children:"Check: adam server logs"}),te(pr,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&te(os,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&te(to,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&te(Fn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&te(Un,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&te(oo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&te(Gn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&te(so,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&te(zn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&te(Qn,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&te(ts,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&te(ls,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="featureRequests"&&te(ds,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="mistakes"&&te(us,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&te(es,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&te(ss,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="artifacts"&&te(vs,{onBack:()=>t({type:"SET_VIEW",view:"chat"}),onSelect:()=>{},onAction:()=>{}})]}),e.pendingPlanApproval?te(Bn,{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?te(kn,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):V?te(cn,{onSubmit:N}):te(cs,{}),e.planTimeoutNotice&&te(dl,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function dl({planId:e,onDismiss:t}){return il(r=>{r==="d"&&t()}),xr(Mr,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[xr(pr,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),te(pr,{dimColor:!0,children:" [d] Dismiss"})]})}function ul(){return te(Yo,{children:te(cl,{})})}export{ul as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e}from"./chunk-JROGEBP5.js";import"./chunk-TWOJVEO7.js";import"./chunk-JYZTIE2J.js";import"./chunk-HRPMRWHD.js";import"./chunk-TA5PFK5C.js";import"./chunk-OBD4245G.js";import"./chunk-4JHACUZY.js";import"./chunk-VWX2B6OM.js";import"./chunk-L7JP7DUO.js";import"./chunk-2A2TXYT3.js";import"./chunk-6WQFYV3N.js";import"./chunk-NUOTFUNF.js";import"./chunk-NXGR3PRY.js";import"./chunk-3MROEPGR.js";import"./chunk-BE653A45.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{b as formatPlanForChannel,e as getPendingApprovalRequestIds,d as handleInboundForApproval,a as parseApprovalReply,c as sendApprovalToChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-BE653A45.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";r();export{n as appendArtifactToCollection,o as convertPrimaryFileToCollectionInTransaction,a as createArtifact,j as deleteArtifactById,h as deleteArtifactsByExecution,i as deleteArtifactsByExecutionAndStep,m as ensureUniqueArtifactKey,b as getArtifact,c as getArtifactById,l as isArtifactCollectionManifest,q as listArtifacts,f as listArtifactsByChatSession,d as listArtifactsByExecution,g as listArtifactsByRole,e as listArtifactsByTask,p as listExpiredExecutions,k as removeArtifact};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,d as c}from"./chunk-OBD4245G.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";c();export{b as listAuditDiagnostics,a as recordAuditDiagnostic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{L as a,M as b,N as c,O as d,P as e,Q as f,R as g}from"./chunk-ZJ3TS4FL.js";import"./chunk-QMW7VEPC.js";import"./chunk-UCUELFCS.js";import"./chunk-XAPJJAJQ.js";import"./chunk-SKHMWKJT.js";import"./chunk-LCD5DVS6.js";import"./chunk-SGLZAIVL.js";import"./chunk-IEBAOZED.js";import"./chunk-JYZTIE2J.js";import"./chunk-O6L4UVLV.js";import"./chunk-QTGAK62Z.js";import"./chunk-MTRLUW7Z.js";import"./chunk-Z2APBKIT.js";import"./chunk-4JHACUZY.js";import"./chunk-NSUXJ2VA.js";import"./chunk-VWX2B6OM.js";import"./chunk-L7JP7DUO.js";import"./chunk-LKGYQJMS.js";import"./chunk-2JIQT2CI.js";import"./chunk-QYI44EP6.js";import"./chunk-T2Z2JDPY.js";import"./chunk-V2MMQ3SH.js";import"./chunk-2A2TXYT3.js";import"./chunk-AUSR5JYV.js";import"./chunk-NUOTFUNF.js";import"./chunk-NXGR3PRY.js";import"./chunk-3MROEPGR.js";import"./chunk-BE653A45.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{e as auditAssistantCommitment,f as auditDeliveryClaims,a as evaluateTaskCompletion,g as getSecurityPosture,d as reportViolation,b as startAuditManager,c as stopAuditManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-BMCNQGUH.js";import"./chunk-3UFEOB6P.js";import"./chunk-UCUELFCS.js";import"./chunk-XAPJJAJQ.js";import"./chunk-SKHMWKJT.js";import"./chunk-LCD5DVS6.js";import"./chunk-2CE2WUUZ.js";import"./chunk-4N5G7ND2.js";import"./chunk-IEBAOZED.js";import"./chunk-NNMQGISW.js";import"./chunk-TWOJVEO7.js";import"./chunk-JYZTIE2J.js";import"./chunk-HRPMRWHD.js";import"./chunk-TA5PFK5C.js";import"./chunk-OBD4245G.js";import"./chunk-MTRLUW7Z.js";import"./chunk-Z2APBKIT.js";import"./chunk-4JHACUZY.js";import"./chunk-NSUXJ2VA.js";import"./chunk-VWX2B6OM.js";import"./chunk-L7JP7DUO.js";import"./chunk-T2Z2JDPY.js";import"./chunk-V2MMQ3SH.js";import"./chunk-2A2TXYT3.js";import"./chunk-6WQFYV3N.js";import"./chunk-NUOTFUNF.js";import"./chunk-47HJPIUA.js";import"./chunk-NXGR3PRY.js";import"./chunk-5G64P4KE.js";import"./chunk-3MROEPGR.js";import"./chunk-BE653A45.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h}from"./chunk-6WQFYV3N.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,g as getRecipientCap,d as listChannels,h as setRecipientCap,c as updateChannel,f as updateChannelStatus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as a,j as b,k as c}from"./chunk-VPMHZJS2.js";import"./chunk-IEBAOZED.js";import"./chunk-NNMQGISW.js";import"./chunk-HRPMRWHD.js";import"./chunk-TA5PFK5C.js";import"./chunk-OBD4245G.js";import"./chunk-6WQFYV3N.js";import"./chunk-NXGR3PRY.js";import"./chunk-3MROEPGR.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5M6IGE5G.js";import"./chunk-5PELJRUQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c}from"./chunk-JZBXLN7M.js";import"./chunk-WY5BOCQP.js";import"./chunk-VO24C673.js";import"./chunk-EZLBMUQD.js";import"./chunk-5PELJRUQ.js";export{c as hasAnyToolCallInTurn,b as listChatToolCallsByTrace,a as recordChatToolCall};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{a as m,g as L}from"./chunk-NUOTFUNF.js";import{n as o,p as x}from"./chunk-WY5BOCQP.js";import{b as u,h as _}from"./chunk-VO24C673.js";import{c as v,e as N}from"./chunk-5M6IGE5G.js";import{b as l}from"./chunk-5PELJRUQ.js";var f,p,T=l(()=>{"use strict";f={stylePreferences:[],avoidedActions:[],pinnedParameters:[]},p=class extends Error{constructor(n,r,i,s){super(`Role '${r}' has ${i} active task(s) (${s.join(", ")}) and cannot be deleted without the force flag.`);this.roleId=n;this.roleName=r;this.activeTaskCount=i;this.taskStatuses=s;this.name="RoleHasActiveTasksError"}roleId;roleName;activeTaskCount;taskStatuses;code="ROLE_HAS_ACTIVE_TASKS"}});import*as R from"os";import*as C from"path";function g(e){return e.startsWith("~/")||e==="~"?C.join(R.homedir(),e.slice(1)):e}var S=l(()=>{"use strict";_()});function E(e){return k.includes(e)}function I(e){return A[e]}function B(){return k.map(e=>A[e])}function te(e,t=e!=="none"){return B().map(n=>J(n,e,t))}function J(e,t,n=t!=="none"){return process.platform==="darwin"?e.status==="runtime-enforced"&&(t!=="sandbox-exec"||!n)?{...e,availability:"runtime-unavailable",editable:!1,effectiveDisabledReason:"Current runtime has no macOS sandbox backend; Adam cannot enforce this capability on Roles."}:e.status==="runtime-enforced"?{...e,availability:"editable",editable:!0}:{...e,availability:e.status,editable:!1,effectiveDisabledReason:e.disabledReason}:{...e,availability:"platform-unsupported",editable:!1,effectiveDisabledReason:"macOS only"}}function re(e){if(!e?.length)return;for(let n of e)if(!E(n.id))throw new Error(`Unknown OS capability: ${n.id}`);let t=c(e);if(t?.length){for(let n of t){let r=I(n.id);if(r.status!=="runtime-enforced")throw new Error(`OS capability '${r.label}' is not editable in Role settings`);if(r.supportsTargets){if(!n.targets?.length)throw new Error(`OS capability '${r.label}' requires at least one target bundle id`);for(let i of n.targets)if(!F(i))throw new Error(`Invalid automation target bundle id: ${i}`)}else if(n.targets?.length)throw new Error(`OS capability '${r.label}' does not accept targets`)}return t}}function c(e){if(!e||e.length===0)return;let t=new Set,n=[];for(let r of e){if(!E(r.id))throw new Error(`Unknown OS capability: ${r.id}`);if(t.has(r.id))continue;t.add(r.id);let i=I(r.id),s={id:r.id};i.supportsTargets&&r.targets?.length&&(s.targets=[...new Set(r.targets.map(a=>a.trim()).filter(Boolean))]),n.push(s)}return n.length>0?n.sort((r,i)=>r.id.localeCompare(i.id)):void 0}function F(e){return U.test(e)}var k,A,U,w=l(()=>{"use strict";k=["location-services","calendars","contacts","files-and-folders","full-disk-access","homekit","media-and-apple-music","passkeys-access-for-web-browsers","photos","reminders","accessibility","app-management","automation","bluetooth","camera","developer-tools","focus","input-monitoring","local-network","microphone","motion-and-fitness","remote-desktop","screen-and-system-audio-recording","speech-recognition"],A={"location-services":{id:"location-services",label:"Location Services",description:"Access device location and region context.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},calendars:{id:"calendars",label:"Calendars",description:"Access Calendar data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},contacts:{id:"contacts",label:"Contacts",description:"Access Contacts data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"files-and-folders":{id:"files-and-folders",label:"Files & Folders",description:"Host-level file access categories managed outside Role sandboxing.",platform:"darwin",status:"host-only",disabledReason:"Role file boundaries are already controlled by visiblePaths and deniedReadPaths."},"full-disk-access":{id:"full-disk-access",label:"Full Disk Access",description:"Host-level macOS grant for protected storage locations.",platform:"darwin",status:"host-only",disabledReason:"This is a host app permission, not a Role-level control."},homekit:{id:"homekit",label:"HomeKit",description:"Access HomeKit devices and home automation data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"media-and-apple-music":{id:"media-and-apple-music",label:"Media & Apple Music",description:"Access Apple Music and media library data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"passkeys-access-for-web-browsers":{id:"passkeys-access-for-web-browsers",label:"Passkeys Access for Web Browsers",description:"Access passkeys for browser-integrated authentication.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},photos:{id:"photos",label:"Photos",description:"Access the Photos library via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},reminders:{id:"reminders",label:"Reminders",description:"Access Reminder data via macOS privacy controls.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},accessibility:{id:"accessibility",label:"Accessibility",description:"Control desktop UI and accessibility automation surfaces.",platform:"darwin",status:"runtime-enforced"},"app-management":{id:"app-management",label:"App Management",description:"Manage or inspect other installed applications.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},automation:{id:"automation",label:"Automation",description:"Launch and control other apps via Apple Events.",platform:"darwin",status:"runtime-enforced",supportsTargets:!0},bluetooth:{id:"bluetooth",label:"Bluetooth",description:"Access nearby Bluetooth devices.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},camera:{id:"camera",label:"Camera",description:"Capture camera input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"developer-tools":{id:"developer-tools",label:"Developer Tools",description:"Use system developer tooling privileges.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},focus:{id:"focus",label:"Focus",description:"Access Focus state and related automation.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"input-monitoring":{id:"input-monitoring",label:"Input Monitoring",description:"Observe keyboard and input device activity.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"local-network":{id:"local-network",label:"Local Network",description:"Discover and communicate with devices on the local network.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},microphone:{id:"microphone",label:"Microphone",description:"Capture microphone input.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"motion-and-fitness":{id:"motion-and-fitness",label:"Motion & Fitness",description:"Access motion and fitness sensor data.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"remote-desktop":{id:"remote-desktop",label:"Remote Desktop",description:"Control or observe remote desktop sessions.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"screen-and-system-audio-recording":{id:"screen-and-system-audio-recording",label:"Screen & System Audio Recording",description:"Capture the screen and system audio.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."},"speech-recognition":{id:"speech-recognition",label:"Speech Recognition",description:"Use system speech recognition services.",platform:"darwin",status:"registered-unwired",disabledReason:"Not wired into Adam runtime yet."}},U=/^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/});function b(e){return{id:e.id,parentId:e.parent_id??void 0,status:e.status,prompt:e.prompt,originalPrompt:e.original_prompt??void 0,config:JSON.parse(e.config),result:e.result??void 0,error:e.error??void 0,sdkSessionId:e.sdk_session_id??void 0,templateId:e.template_id??void 0,roleId:e.role_id??void 0,stepId:e.step_id??void 0,sourceSessionId:e.source_session_id??void 0,deliverTo:e.deliver_to?JSON.parse(e.deliver_to):void 0,reportTo:e.report_to?JSON.parse(e.report_to):void 0,createdAt:e.created_at,startedAt:e.started_at??void 0,completedAt:e.completed_at??void 0,costUsd:e.cost_usd??void 0,costBreakdown:e.cost_breakdown?JSON.parse(e.cost_breakdown):void 0,tokenUsage:e.token_usage?JSON.parse(e.token_usage):void 0,numTurns:e.num_turns??void 0,totalDurationMs:e.total_duration_ms??void 0,blockReason:e.block_reason_json?JSON.parse(e.block_reason_json):void 0,traceId:e.trace_id??void 0,errorCategory:e.error_category??void 0,retryCount:e.retry_count}}function oe(e){o().prepare(`
|
|
2
|
+
INSERT INTO tasks (id, parent_id, status, prompt, original_prompt, config, result, error,
|
|
3
|
+
sdk_session_id, template_id, role_id, step_id, source_session_id, notify_targets, deliver_to, report_to,
|
|
4
|
+
created_at, started_at, completed_at,
|
|
5
|
+
cost_usd, token_usage, num_turns, total_duration_ms, trace_id, error_category, retry_count, cost_breakdown)
|
|
6
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
7
|
+
`).run(e.id,e.parentId??null,e.status,e.prompt,e.originalPrompt??null,JSON.stringify(e.config),e.result??null,e.error??null,e.sdkSessionId??null,e.templateId??null,e.roleId??null,e.stepId??null,e.sourceSessionId??null,null,e.deliverTo?JSON.stringify(e.deliverTo):null,e.reportTo?JSON.stringify(e.reportTo):null,e.createdAt,e.startedAt??null,e.completedAt??null,e.costUsd??null,e.tokenUsage?JSON.stringify(e.tokenUsage):null,e.numTurns??null,e.totalDurationMs??null,e.traceId??v()??null,e.errorCategory??null,e.retryCount??0,e.costBreakdown?JSON.stringify(e.costBreakdown):null)}function W(e){let n=o().prepare("SELECT * FROM tasks WHERE id = ?").get(e);return n?b(n):void 0}function H(e,t){let n=o(),r=[],i=[],s={parentId:"parent_id",status:"status",prompt:"prompt",result:"result",error:"error",sdkSessionId:"sdk_session_id",templateId:"template_id",roleId:"role_id",stepId:"step_id",sourceSessionId:"source_session_id",originalPrompt:"original_prompt",startedAt:"started_at",completedAt:"completed_at",costUsd:"cost_usd",numTurns:"num_turns",totalDurationMs:"total_duration_ms",errorCategory:"error_category",retryCount:"retry_count"};for(let[a,d]of Object.entries(s))a in t&&(r.push(`${d} = ?`),i.push(t[a]??null));"config"in t&&(r.push("config = ?"),i.push(JSON.stringify(t.config))),"tokenUsage"in t&&(r.push("token_usage = ?"),i.push(t.tokenUsage?JSON.stringify(t.tokenUsage):null)),"costBreakdown"in t&&(r.push("cost_breakdown = ?"),i.push(t.costBreakdown?JSON.stringify(t.costBreakdown):null)),"deliverTo"in t&&(r.push("deliver_to = ?"),i.push(t.deliverTo?JSON.stringify(t.deliverTo):null)),"reportTo"in t&&(r.push("report_to = ?"),i.push(t.reportTo?JSON.stringify(t.reportTo):null)),"blockReason"in t&&(r.push("block_reason_json = ?"),i.push(t.blockReason?JSON.stringify(t.blockReason):null)),"contextMeta"in t&&(r.push("context_meta = ?"),i.push(t.contextMeta?JSON.stringify(t.contextMeta):null)),r.length!==0&&(i.push(e),n.prepare(`UPDATE tasks SET ${r.join(", ")} WHERE id = ?`).run(...i))}function ae(e,t){let n=W(e);if(!n)return;let r={...n.config??{},...t};H(e,{config:r})}function O(e,t=100,n=0,r){let i=o(),s="SELECT * FROM tasks",a=[],d=[];return e&&(a.push("status = ?"),d.push(e)),r&&(a.push("role_id = ?"),d.push(r)),a.length>0&&(s+=" WHERE "+a.join(" AND ")),s+=" ORDER BY created_at DESC LIMIT ? OFFSET ?",d.push(t,n),i.prepare(s).all(...d).map(b)}function de(e){return o().prepare("SELECT * FROM tasks WHERE parent_id = ? ORDER BY created_at ASC").all(e).map(b)}function le(e){return o().prepare("SELECT COALESCE(SUM(cost_usd), 0) as total FROM tasks WHERE completed_at >= ? AND cost_usd IS NOT NULL").get(e).total}function ce(e){return o().prepare("SELECT trace_id FROM tasks WHERE id = ?").get(e)?.trace_id??void 0}function ue(e){let t=o();return t.prepare("UPDATE tasks SET retry_count = retry_count + 1 WHERE id = ?").run(e),t.prepare("SELECT retry_count FROM tasks WHERE id = ?").get(e)?.retry_count??1}function q(e){return{id:e.id,taskId:e.task_id,retryAt:e.retry_at,createdAt:e.created_at}}function pe(e){o().prepare("INSERT INTO delayed_retries (id, task_id, retry_at, created_at) VALUES (?, ?, ?, ?)").run(e.id,e.taskId,e.retryAt,e.createdAt)}function ge(e){return o().prepare("SELECT * FROM delayed_retries WHERE retry_at <= ? ORDER BY retry_at ASC").all(e).map(q)}function me(e){o().prepare("DELETE FROM delayed_retries WHERE id = ?").run(e)}function V(e,t){let n=o();n.transaction(()=>{let r=n.prepare("SELECT context_meta FROM tasks WHERE id = ?").get(e),i=(()=>{if(r?.context_meta)try{return JSON.parse(r.context_meta)}catch{return{}}return{}})();t(i),n.prepare("UPDATE tasks SET context_meta = ? WHERE id = ?").run(JSON.stringify(i),e)})()}function fe(e){let n=o().prepare("SELECT context_meta FROM tasks WHERE id = ?").get(e);if(!n||n.context_meta===null)return null;try{return JSON.parse(n.context_meta)}catch{return null}}function be(e,t){t.length!==0&&V(e,n=>{let r=Array.isArray(n.usedMemoryIds)?n.usedMemoryIds:[];n.usedMemoryIds=Array.from(new Set([...r,...t]))})}var P=l(()=>{"use strict";x();N()});import{existsSync as K}from"fs";import{resolve as y}from"path";function M(e){if(e==null)return{...f};if(Array.isArray(e))return{stylePreferences:e.filter(t=>typeof t=="string"),avoidedActions:[],pinnedParameters:[]};if(typeof e=="object"){let t=e;return{stylePreferences:Array.isArray(t.stylePreferences)?t.stylePreferences.filter(n=>typeof n=="string"):[],avoidedActions:Array.isArray(t.avoidedActions)?t.avoidedActions.filter(n=>typeof n=="string"):[],pinnedParameters:Array.isArray(t.pinnedParameters)?t.pinnedParameters.filter(n=>n!==null&&typeof n=="object"&&typeof n.tool=="string"):[]}}return{...f}}function D(e,t){for(let n of e){let r=typeof n=="string"?n:n.path;if(!r.startsWith("/")&&!r.startsWith("~/")&&r!=="~")throw new Error(`additionalDirectories must be absolute paths: '${r}' is not absolute`);let i=y(g(r));if(!i.startsWith("/"))throw new Error(`additionalDirectories must be absolute paths: '${r}' is not absolute`);for(let s of u){let a=y(g(s));if(i.startsWith(a))throw new Error(`additionalDirectories cannot include hardcoded denied path: '${r}' matches '${s}'`)}if(t?.length)for(let s of t){let a=y(g(s));if(i.startsWith(a)||a.startsWith(i))throw new Error(`additionalDirectories cannot overlap with deniedReadPaths: '${r}' conflicts with '${s}'`)}if(!K(i))throw new Error(`additionalDirectories path does not exist: '${r}'`)}}function h(e){return{id:e.id,name:e.name,cagPrompt:e.cag_prompt,learnedRules:M(e.learned_rules?JSON.parse(e.learned_rules):null),memoryStreamId:e.memory_stream_id,status:e.status,performanceScore:e.performance_score??void 0,preferences:e.preferences?JSON.parse(e.preferences):{},createdAt:e.created_at,updatedAt:e.updated_at??void 0,allowedTools:e.allowed_tools?JSON.parse(e.allowed_tools):void 0,disallowedTools:e.disallowed_tools?JSON.parse(e.disallowed_tools):void 0,evaluationCriteria:e.evaluation_criteria?JSON.parse(e.evaluation_criteria):void 0,executionMode:e.execution_mode??void 0,model:e.model??void 0,maxBudgetUsd:e.max_budget_usd??void 0,approvalRequired:e.approval_required?JSON.parse(e.approval_required):void 0,source:e.source??void 0,additionalDirectories:(()=>{if(e.additional_directories!==null)try{let t=JSON.parse(e.additional_directories);return Array.isArray(t)?t.map(n=>typeof n=="string"?{path:n}:n):void 0}catch{return}})(),allowedChannels:e.allowed_channels?JSON.parse(e.allowed_channels):void 0,mcpServers:e.mcp_servers?JSON.parse(e.mcp_servers):void 0,inheritUserSettings:e.inherit_user_settings===1?!0:void 0,permissionMode:e.permission_mode??void 0,allowedBashPatterns:e.allowed_bash_patterns?JSON.parse(e.allowed_bash_patterns):void 0,deniedBashPatterns:e.denied_bash_patterns?JSON.parse(e.denied_bash_patterns):void 0,envVars:e.env_vars?JSON.parse(e.env_vars):void 0,osCapabilities:e.os_capabilities?c(JSON.parse(e.os_capabilities)):void 0,presetId:e.preset_id??void 0,effortTier:e.effort_tier??void 0,skills:e.skills?JSON.parse(e.skills):void 0}}function Ae(e){let t=m("defaults.deniedReadPaths")??[...u];e.additionalDirectories&&D(e.additionalDirectories,t),o().prepare(`
|
|
8
|
+
INSERT INTO roles (id, name, cag_prompt, learned_rules, memory_stream_id, status,
|
|
9
|
+
performance_score, preferences, created_at, updated_at,
|
|
10
|
+
allowed_tools, disallowed_tools, evaluation_criteria, execution_mode, model,
|
|
11
|
+
max_budget_usd, approval_required, source, additional_directories, allowed_channels, mcp_servers, inherit_user_settings,
|
|
12
|
+
permission_mode, allowed_bash_patterns, denied_bash_patterns, env_vars, os_capabilities, preset_id,
|
|
13
|
+
effort_tier, skills)
|
|
14
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
15
|
+
`).run(e.id,e.name,e.cagPrompt,JSON.stringify(e.learnedRules),e.memoryStreamId,e.status,e.performanceScore??null,e.preferences?JSON.stringify(e.preferences):null,e.createdAt,e.updatedAt??null,e.allowedTools?JSON.stringify(e.allowedTools):null,e.disallowedTools?JSON.stringify(e.disallowedTools):null,e.evaluationCriteria?JSON.stringify(e.evaluationCriteria):null,e.executionMode??null,e.model??null,e.maxBudgetUsd??null,e.approvalRequired?JSON.stringify(e.approvalRequired):null,e.source??null,e.additionalDirectories?JSON.stringify(e.additionalDirectories):null,e.allowedChannels?JSON.stringify(e.allowedChannels):null,e.mcpServers?JSON.stringify(e.mcpServers):null,e.inheritUserSettings?1:0,e.permissionMode??null,e.allowedBashPatterns?JSON.stringify(e.allowedBashPatterns):null,e.deniedBashPatterns?JSON.stringify(e.deniedBashPatterns):null,e.envVars?JSON.stringify(e.envVars):null,e.osCapabilities?JSON.stringify(c(e.osCapabilities)):null,e.presetId??null,e.effortTier??null,e.skills?JSON.stringify(e.skills):null)}function j(e){let n=o().prepare("SELECT * FROM roles WHERE id = ?").get(e);return n?h(n):void 0}function Ee(e){let n=o().prepare("SELECT * FROM roles WHERE name = ?").get(e);return n?h(n):void 0}function Ie(e,t){let n=o(),r=[],i=[];if("name"in t&&(r.push("name = ?"),i.push(t.name)),"cagPrompt"in t&&(r.push("cag_prompt = ?"),i.push(t.cagPrompt)),"learnedRules"in t&&(r.push("learned_rules = ?"),i.push(JSON.stringify(M(t.learnedRules)))),"memoryStreamId"in t&&(r.push("memory_stream_id = ?"),i.push(t.memoryStreamId)),"status"in t&&(r.push("status = ?"),i.push(t.status)),"performanceScore"in t&&(r.push("performance_score = ?"),i.push(t.performanceScore??null)),"preferences"in t&&(r.push("preferences = ?"),i.push(t.preferences?JSON.stringify(t.preferences):null)),"updatedAt"in t&&(r.push("updated_at = ?"),i.push(t.updatedAt??null)),"allowedTools"in t&&(r.push("allowed_tools = ?"),i.push(t.allowedTools?JSON.stringify(t.allowedTools):null)),"disallowedTools"in t&&(r.push("disallowed_tools = ?"),i.push(t.disallowedTools?JSON.stringify(t.disallowedTools):null)),"evaluationCriteria"in t&&(r.push("evaluation_criteria = ?"),i.push(t.evaluationCriteria?JSON.stringify(t.evaluationCriteria):null)),"executionMode"in t&&(r.push("execution_mode = ?"),i.push(t.executionMode??null)),"model"in t&&(r.push("model = ?"),i.push(t.model??null)),"maxBudgetUsd"in t&&(r.push("max_budget_usd = ?"),i.push(t.maxBudgetUsd??null)),"approvalRequired"in t&&(r.push("approval_required = ?"),i.push(t.approvalRequired?JSON.stringify(t.approvalRequired):null)),"source"in t&&(r.push("source = ?"),i.push(t.source??null)),"additionalDirectories"in t){let s=m("defaults.deniedReadPaths")??[...u];t.additionalDirectories&&D(t.additionalDirectories,s),r.push("additional_directories = ?"),i.push(t.additionalDirectories?JSON.stringify(t.additionalDirectories):null)}"allowedChannels"in t&&(r.push("allowed_channels = ?"),i.push(t.allowedChannels?JSON.stringify(t.allowedChannels):null)),"mcpServers"in t&&(r.push("mcp_servers = ?"),i.push(t.mcpServers?JSON.stringify(t.mcpServers):null)),"inheritUserSettings"in t&&(r.push("inherit_user_settings = ?"),i.push(t.inheritUserSettings?1:0)),"permissionMode"in t&&(r.push("permission_mode = ?"),i.push(t.permissionMode??null)),"allowedBashPatterns"in t&&(r.push("allowed_bash_patterns = ?"),i.push(t.allowedBashPatterns?JSON.stringify(t.allowedBashPatterns):null)),"deniedBashPatterns"in t&&(r.push("denied_bash_patterns = ?"),i.push(t.deniedBashPatterns?JSON.stringify(t.deniedBashPatterns):null)),"envVars"in t&&(r.push("env_vars = ?"),i.push(t.envVars?JSON.stringify(t.envVars):null)),"osCapabilities"in t&&(r.push("os_capabilities = ?"),i.push(t.osCapabilities?JSON.stringify(c(t.osCapabilities)):null)),"presetId"in t&&(r.push("preset_id = ?"),i.push(t.presetId??null)),"effortTier"in t&&(r.push("effort_tier = ?"),i.push(t.effortTier??null)),"skills"in t&&(r.push("skills = ?"),i.push(t.skills?JSON.stringify(t.skills):null)),r.length!==0&&(i.push(e),n.prepare(`UPDATE roles SET ${r.join(", ")} WHERE id = ?`).run(...i))}function we(e,t,n=0){let r=o(),i="SELECT * FROM roles",s=[];return e&&(i+=" WHERE status = ?",s.push(e)),i+=" ORDER BY COALESCE(updated_at, created_at) DESC",typeof t=="number"&&(i+=" LIMIT ? OFFSET ?",s.push(t,n)),r.prepare(i).all(...s).map(h)}function G(e){let t=["pending","queued","running"],r=O(void 0,1e3,0,e).filter(s=>t.includes(s.status)),i=[...new Set(r.map(s=>s.status))];return{hasActive:r.length>0,count:r.length,statuses:i}}function Oe(e,t=!1){if(!t){let{hasActive:r,count:i,statuses:s}=G(e);if(r){let a=j(e);throw new p(e,a?.name??e,i,s)}}o().prepare("DELETE FROM roles WHERE id = ?").run(e)}function Pe(e){o().prepare("UPDATE roles SET task_seq = task_seq + 1 WHERE id = ?").run(e)}function Me(e){return o().prepare("SELECT task_seq FROM roles WHERE id = ?").get(e)?.task_seq??0}var $=l(()=>{x();T();_();S();L();w();P()});export{oe as a,W as b,H as c,ae as d,O as e,de as f,le as g,ce as h,ue as i,pe as j,ge as k,me as l,V as m,fe as n,be as o,P as p,p as q,T as r,g as s,S as t,k as u,U as v,I as w,te as x,re as y,c as z,w as A,D as B,Ae as C,j as D,Ee as E,Ie as F,we as G,G as H,Oe as I,Pe as J,Me as K,$ as L};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as x,e as C}from"./chunk-IEBAOZED.js";import{a as y,b as u,c,d as m,e as h,g as v}from"./chunk-TA5PFK5C.js";import{a as i}from"./chunk-L7JP7DUO.js";import{b as l}from"./chunk-T2Z2JDPY.js";import{a as g}from"./chunk-V2MMQ3SH.js";import{e as f}from"./chunk-47HJPIUA.js";import{v4 as D}from"uuid";import{v4 as I}from"uuid";function _(e){if(e.length<20)return null;let t=e.trim();return t.length>300?{content:`User request: ${t.slice(0,280)}...`,importance:3,type:"thought"}:{content:`User request: ${t}`,importance:3,type:"thought"}}function b(e){if(e.length<20)return null;let t=e.trim();return t.length>400?{content:`Assistant response: ${t.slice(0,370)}...`,importance:2,type:"event"}:{content:`Assistant response: ${t}`,importance:2,type:"event"}}function N(e){let t=x(e,200,0),s=[];for(let o of t){let r=o.role==="user"?_(o.content):b(o.content);r&&s.push(r)}return{facts:s}}function $(e){let t=e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(s=>s.length>2);return[...new Set(t)].slice(0,20)}async function A(e,t){let{facts:s}=N(e),o=0;for(let r of s){let p=r.content.slice(0,500),S;try{S=await l(p)}catch{}let M=$(p),T={id:I(),roleId:t,type:r.type,content:p,embedding:S,keywords:M,importance:r.importance,sourceType:"session_archive",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0,tier:"episodic"};g(T),o++}return o}var n=new Map,a;function w(e){return`${e.type}:${e.channelId??""}:${e.chatId??""}`}function F(){n.clear();let e=m("active",1e3);for(let t of e)n.set(t.id,t)}function V(e,t){let s=Date.now(),o={id:D(),status:"active",source:e,createdAt:s,lastActiveAt:s,messageCount:0};return y(o),n.set(o.id,o),i.emit({type:"session_created",session:o}),o}function W(e){for(let s of n.values())if(w(s.source)===w(e))return s;let t=h(e);return t&&n.set(t.id,t),t}function B(e){let t=n.get(e);return t||u(e)}function E(e){let t=Date.now();c(e,{status:"archived",archivedAt:t}),f().archiveExtractMemory&&u(e)&&A(e,"role-chat-manager").catch(()=>{}),n.delete(e),i.emit({type:"session_archived",sessionId:e})}function X(e){c(e,{status:"active",archivedAt:void 0});let t=u(e);return t&&(n.set(t.id,t),i.emit({type:"session_restored",session:t})),t}function Y(e){C(e),v(e),n.delete(e),i.emit({type:"session_deleted",sessionId:e})}function Z(e){let t=Date.now();c(e,{lastActiveAt:t});let s=n.get(e);s&&(s.lastActiveAt=t)}function ee(e){let t=B(e);if(t){let s=t.messageCount+1;c(e,{messageCount:s});let o=n.get(e);o&&(o.messageCount=s)}}function te(e){return m(e)}function P(){let t=f().sessionTimeoutMinutes*60*1e3,s=Date.now();for(let o of n.values())if(s-o.lastActiveAt>t)try{E(o.id)}catch{}}function R(e=6e4){d(),a=setInterval(P,e)}function d(){a&&(clearInterval(a),a=void 0)}function se(){return a}function oe(){F(),R()}function ne(){d(),n.clear()}function re(){d(),n.clear()}export{F as a,V as b,W as c,B as d,E as e,X as f,Y as g,Z as h,ee as i,te as j,R as k,d as l,se as m,oe as n,ne as o,re as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{g as u,h as n}from"./chunk-QYI44EP6.js";import{e as r}from"./chunk-3MROEPGR.js";var m=.995,i=.2,d=.3;function c(){try{let e=r().memory?.scope;return{decayBase:e?.decayBase??m,archiveThreshold:e?.archiveThreshold??i,emaAlpha:e?.emaAlpha??d}}catch{return{decayBase:m,archiveThreshold:i,emaAlpha:d}}}function l(e,s){if(e.successEma==null)return null;let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();return e.successEma*Math.pow(t,a)}function h(e,s){if(e.successEma==null)e.successEma=.5;else{let a=Math.max(0,s-e.lastUsedAt),{decayBase:t}=c();e.successEma=e.successEma*Math.pow(t,a)}e.lastUsedAt=s}function E(e,s){h(e,s),n(e.id,e.successEma,s)}function A(e,s,a){h(e,a);let{emaAlpha:t}=c(),o=(1-t)*e.successEma+t*s;e.successEma=o,n(e.id,o,a)}function B(e,s){let a=l(e,s);return a==null?!1:a<c().archiveThreshold}function v(e){u(e,"archived")}export{l as a,E as b,A as c,B as d,v as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function d(e){return e==null||!isFinite(e)||isNaN(e)?0:e}function V(e,i,o){let t=Object.entries(e);if(t.length===0)return{costUsd:0,perModel:[],pricingStatus:"none",unknownModels:[],sdkTotalCostUsd:o};let n=[],r=[],s=0,u=0;for(let[m,p]of t){let f=d(p.inputTokens),h=d(p.outputTokens),y=d(p.cacheReadInputTokens),b=d(p.cacheCreationInputTokens),c=i[m];if(c!==void 0){let w=f/1e6*c.input+h/1e6*c.output+y/1e6*c.cacheRead+b/1e6*c.cacheCreation;s+=w,u++,n.push({model:m,priced:!0,estimated:c.estimated===!0,inputTokens:f,outputTokens:h,cacheReadTokens:y,cacheCreationTokens:b,costUsd:w})}else r.push(m),n.push({model:m,priced:!1,estimated:!1,inputTokens:f,outputTokens:h,cacheReadTokens:y,cacheCreationTokens:b,costUsd:0})}let l;return u===0?l="unknown":u===t.length?l="priced":l="partial",{costUsd:s,perModel:n,pricingStatus:l,unknownModels:r,sdkTotalCostUsd:o}}var P=["input","output","cacheRead","cacheCreation"];function k(e){if(e===null||typeof e!="object"||Array.isArray(e))return"pricing.models must be a plain object (not null, not an array).";let i=e;for(let[o,t]of Object.entries(i)){if(t===null||typeof t!="object"||Array.isArray(t))return`pricing.models["${o}"] must be a plain object.`;let n=t;for(let r of P){let s=n[r];if(typeof s!="number"||!isFinite(s)||isNaN(s)||s<0)return`pricing.models["${o}"].${r} must be a finite non-negative number (got ${JSON.stringify(s)}).`}if("estimated"in n&&typeof n.estimated!="boolean")return`pricing.models["${o}"].estimated must be a boolean if present (got ${JSON.stringify(n.estimated)}).`}return null}var _=["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout","logging.level","roles.evolution.triggerEvery","roles.evolution.reflectionThreshold","identity.ownerViewerKey","chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory","chat.artifactThresholdChars","chat.maxConcurrentLiveSessions","chat.liveSessionIdleMinutes","chat.commitmentDetection.locales","chat.commitmentDetection.blockedText.zh","chat.commitmentDetection.blockedText.en","chat.commitmentDetection.unsupportedSuccessText.zh","chat.commitmentDetection.unsupportedSuccessText.en","chat.commitmentDetection.unsupportedFailureText.zh","chat.commitmentDetection.unsupportedFailureText.en","chat.commitmentDetection.unsupportedMutationText.zh","chat.commitmentDetection.unsupportedMutationText.en","memory.midTaskInjection.enabled","memory.midTaskInjection.toolCallThreshold","memory.midTaskInjection.cooldownMs","memory.midTaskInjection.topK","memory.midTaskInjection.maxTokens","memory.retrievalWeights.cosSim","memory.retrievalWeights.recency","memory.retrievalWeights.tokenCost","memory.globalBudgetTokens","memory.retrievalDecayDays","memory.attributionThresholds.high","memory.attributionThresholds.low","memory.antiFlipMinUses","memory.antiFlipSuccessEmaThreshold","memory.reflection.maxBudgetUsd","memory.scope.emaAlpha","memory.scope.humanFeedbackWeight","memory.scope.reflectionPoolMax","memory.scope.decayBase","memory.scope.archiveThreshold","memory.embeddingModel","server.timezone","anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel","audit.intentEval.maxBudgetUsd","audit.intentEval.timeoutMs","evaluation.model","defaults.approvalTimeout","defaults.deniedReadPaths","defaults.approvalRequired","watchdog.rules.artifactCleanup.enabled","watchdog.rules.artifactCleanup.ttlDays","watchdog.rules.artifactCleanup.orphanGcMinAgeHours","watchdog.rules.staleTemplateExecutions.enabled","watchdog.rules.staleTemplateExecutions.action","watchdog.rules.staleTemplateExecutions.maxOrphanMinutes","emailGateway.enabled","emailGateway.address","emailGateway.displayName","emailGateway.imap.host","emailGateway.imap.port","emailGateway.imap.secure","emailGateway.imap.auth.user","emailGateway.imap.auth.pass","emailGateway.imap.mailbox","emailGateway.smtp.host","emailGateway.smtp.port","emailGateway.smtp.secure","emailGateway.smtp.auth.user","emailGateway.smtp.auth.pass","emailGateway.smtp.from","emailGateway.subjectPrefix","storage.localProfile","pricing.models","cost.dailyThresholdUsd"],v=["server.port","server.host","server.apiKey"],D={"anthropic.apiKey":"ANTHROPIC_API_KEY","anthropic.baseUrl":"ANTHROPIC_BASE_URL","anthropic.model":"ANTHROPIC_MODEL","anthropic.defaultOpusModel":"ANTHROPIC_DEFAULT_OPUS_MODEL","anthropic.defaultSonnetModel":"ANTHROPIC_DEFAULT_SONNET_MODEL","anthropic.defaultHaikuModel":"ANTHROPIC_DEFAULT_HAIKU_MODEL","anthropic.smallFastModel":"ANTHROPIC_SMALL_FAST_MODEL"},T=null,I=["ADAM_EMAIL_"],O={"audit.intentEval.maxBudgetUsd":e=>x(e)?null:"must be a positive number.","audit.intentEval.timeoutMs":e=>a(e)?null:"must be a positive integer in milliseconds.","memory.reflection.maxBudgetUsd":e=>x(e)?null:"must be a positive number (USD).","memory.scope.emaAlpha":e=>typeof e=="number"&&e>=0&&e<=1?null:"must be a number between 0 and 1.","memory.scope.humanFeedbackWeight":e=>typeof e=="number"&&e>=1?null:"must be a number >= 1.","memory.scope.decayBase":e=>typeof e=="number"&&e>0&&e<1?null:"must be a number between 0 and 1 (exclusive).","memory.scope.archiveThreshold":e=>typeof e=="number"&&e>=0&&e<=1?null:"must be a number between 0 and 1.","memory.scope.reflectionPoolMax":e=>a(e)?null:"must be a positive integer.","memory.antiFlipSuccessEmaThreshold":e=>typeof e=="number"&&e>=0&&e<=1?null:"must be a number between 0 and 1.","chat.artifactThresholdChars":e=>a(e)?null:"must be a positive integer (chars).","chat.maxConcurrentLiveSessions":e=>a(e)?null:"must be a positive integer (>= 1).","chat.liveSessionIdleMinutes":e=>a(e)?null:"must be a positive integer (minutes).","storage.localProfile":e=>typeof e=="string"&&/^[a-zA-Z0-9_-]+$/.test(e)?null:"must match /^[a-zA-Z0-9_-]+$/ (no path separators, no special chars).","pricing.models":e=>k(e),"chat.commitmentDetection.locales":e=>Array.isArray(e)&&e.length>0&&e.every(i=>i==="zh"||i==="en")?null:"must be a non-empty array of 'zh' | 'en'.","chat.commitmentDetection.blockedText.zh":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.blockedText.en":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.unsupportedSuccessText.zh":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.unsupportedSuccessText.en":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.unsupportedFailureText.zh":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.unsupportedFailureText.en":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.unsupportedMutationText.zh":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","chat.commitmentDetection.unsupportedMutationText.en":e=>typeof e=="string"&&e.length>0?null:"must be a non-empty string.","emailGateway.address":e=>M(e,{allowEmpty:!1})?null:"must be a single valid email address.","emailGateway.imap.host":e=>A(e)?null:"must be a non-empty host without protocol.","emailGateway.imap.port":e=>a(e)?null:"must be a positive integer port.","emailGateway.imap.mailbox":e=>F(e)?null:"must be a non-empty mailbox without NUL bytes.","emailGateway.smtp.host":e=>A(e)?null:"must be a non-empty host without protocol.","emailGateway.smtp.port":e=>a(e)?null:"must be a positive integer port.","emailGateway.smtp.from":e=>M(e,{allowEmpty:!0})?null:"must be empty or a single valid email address.","identity.ownerViewerKey":e=>typeof e=="string"&&e.trim().length>0?null:"must be a non-empty string.","cost.dailyThresholdUsd":e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?null:"must be a finite number >= 0 (USD; 0 = disabled)."};function B(e){T=JSON.parse(JSON.stringify(e))}function g(){if(!T)throw new Error("Runtime config not initialized. Call initRuntimeConfig first.");return T}function $(e){let i=g(),o=e();for(let[t,n]of Object.entries(o))S(t,n)||C(i,t,n)}function U(){let e=g(),i={};for(let[o,t]of Object.entries(D)){let n=N(e,o);n&&typeof n=="string"&&n.length>0?i[t]=n:process.env[t]&&(i[t]=process.env[t])}return i}function E(e){let i={};for(let[o,t]of Object.entries(e))o.startsWith("ANTHROPIC_")||(i[o]=t);return i}var R=/key|token|secret|password|credential/i;function K(e){let i={};for(let[o,t]of Object.entries(e))i[o]=R.test(o)&&t.length>4?t.slice(0,4)+"****":R.test(o)&&t.length>0?"****":t;return i}function W(e){let o=g().defaults?.env??{};return j({...process.env,...o,...U(),...E(e?.roleEnvVars??{}),...E(e?.taskEnv??{}),DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1"})}function J(e,i){let o=g(),t=[],n=[];for(let[r,s]of Object.entries(e)){if(!G(r)){L(r)?n.push(`"${r}" requires restart. Cannot modify at runtime.`):n.push(`"${r}" is not a recognized config path.`);continue}let u=S(r,s);if(u){n.push(`"${r}" ${u}`);continue}C(o,r,s)&&(t.push(r),i?.(r,s))}return{success:n.length===0,updated:t,errors:n}}function C(e,i,o){let t=i.split("."),n=e;for(let r=0;r<t.length-1;r++)if(n&&typeof n=="object")n=n[t[r]];else return!1;return n&&typeof n=="object"?(n[t[t.length-1]]=o,!0):!1}function N(e,i){let o=i.split("."),t=e;for(let n of o)if(t&&typeof t=="object")t=t[n];else return;return t}function G(e){return _.includes(e)}function L(e){return v.includes(e)}function S(e,i){return O[e]?.(i)??null}function x(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function a(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}function A(e){return typeof e=="string"&&e.trim().length>0&&!/^[a-z][a-z0-9+.-]*:\/\//i.test(e.trim())}function F(e){return typeof e=="string"&&e.trim().length>0&&!e.includes("\0")}function M(e,i){if(typeof e!="string")return!1;let o=e.trim();return o?o.includes(",")||/[<>]/.test(o)?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o):i.allowEmpty}function j(e){let i={};for(let[o,t]of Object.entries(e))I.some(n=>o.startsWith(n))||(i[o]=t);return i}export{V as a,_ as b,v as c,B as d,g as e,$ as f,U as g,E as h,K as i,W as j,J as k,N as l,G as m,L as n};
|