adam-agent-server 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +11 -19
  2. package/dist/App-G2WZKRUH.js +9 -0
  3. package/dist/adam-tools-Q4BRKX3U.js +1 -0
  4. package/dist/approval-handler-D3J6NCMM.js +4 -0
  5. package/dist/bree-engine-SQMSKGAP.js +1 -0
  6. package/dist/channels-VEUBY2NZ.js +1 -0
  7. package/dist/channels-WFZAONF3.js +1 -0
  8. package/dist/{chunk-5GMYXCL3.js → chunk-2EP27EGS.js} +1 -1
  9. package/dist/chunk-2GXYBWLS.js +10 -0
  10. package/dist/chunk-2VKE7ONM.js +86 -0
  11. package/dist/{chunk-HMXDNPFE.js → chunk-5ASEAZCR.js} +1 -1
  12. package/dist/chunk-5JLMSNIW.js +1 -0
  13. package/dist/{chunk-MMIO6BCA.js → chunk-742NWPTQ.js} +3 -3
  14. package/dist/chunk-7SPKRIMZ.js +15 -0
  15. package/dist/chunk-AXMXXUPO.js +5 -0
  16. package/dist/{chunk-5AKFAMQL.js → chunk-B6S2AEOD.js} +1 -1
  17. package/dist/chunk-DT2LX4XI.js +49 -0
  18. package/dist/{chunk-VURJZLM6.js → chunk-EALDBELJ.js} +6 -3
  19. package/dist/{chunk-ZN5Q3YET.js → chunk-ETQ7KC73.js} +1 -1
  20. package/dist/chunk-FDWW245P.js +5 -0
  21. package/dist/chunk-FUGJMHY4.js +1 -0
  22. package/dist/chunk-FYDFMYUP.js +1 -0
  23. package/dist/chunk-HAWA62R2.js +26 -0
  24. package/dist/chunk-IXF3XBGX.js +5 -0
  25. package/dist/chunk-JXD6ZPV7.js +2 -0
  26. package/dist/chunk-KICPHTI2.js +5 -0
  27. package/dist/chunk-L7426WNY.js +7 -0
  28. package/dist/{chunk-WGRTN6TX.js → chunk-L7JP7DUO.js} +1 -1
  29. package/dist/chunk-NICRQZ7T.js +1 -0
  30. package/dist/{chunk-3HM54J2N.js → chunk-NSJAV7IH.js} +1 -1
  31. package/dist/{chunk-W6JITSZF.js → chunk-PCSZW2PE.js} +28 -11
  32. package/dist/{chunk-EJJDJY34.js → chunk-PQ7KPALO.js} +1 -1
  33. package/dist/{chunk-F2IS5LWD.js → chunk-SFUS33SO.js} +1 -1
  34. package/dist/chunk-T25NLVMY.js +1 -0
  35. package/dist/chunk-TN6H2WM2.js +19 -0
  36. package/dist/chunk-U36NBCR3.js +17 -0
  37. package/dist/chunk-UOTDT2KY.js +3 -0
  38. package/dist/chunk-VF6GJGD6.js +6 -0
  39. package/dist/chunk-WXN3PSVX.js +6 -0
  40. package/dist/chunk-WZOMGJSY.js +1 -0
  41. package/dist/{chunk-62PXAOD6.js → chunk-XNWZZYAV.js} +1 -1
  42. package/dist/cli.js +15 -13
  43. package/dist/config-WHXCZCI4.js +1 -0
  44. package/dist/config-Y4QWELO3.js +1 -0
  45. package/dist/{db-ZDEA7EUY.js → db-PNZ3UJOE.js} +1 -1
  46. package/dist/delivery-log-VYTYUFCK.js +1 -0
  47. package/dist/engine-V5MOGOLN.js +1 -0
  48. package/dist/{evolution-audit-MDA2ZVJW.js → evolution-audit-B7WKMOVR.js} +1 -1
  49. package/dist/{external-api-T7FFXVHL.js → external-api-XGEOKAWR.js} +1 -1
  50. package/dist/index.js +41 -63
  51. package/dist/learner-VMD5NQCD.js +1 -0
  52. package/dist/memories-EFQ4SFZG.js +1 -0
  53. package/dist/memory-extractor-GOISDQTO.js +6 -0
  54. package/dist/memory-service-BKLZIRK6.js +1 -0
  55. package/dist/monitor-K7CGTLA6.js +1 -0
  56. package/dist/outbound-gateway-FIPC4BZO.js +1 -0
  57. package/dist/role-presets-FN2RWUCP.js +1 -0
  58. package/dist/{roles-CMV5FMIA.js → roles-SG2YAR64.js} +1 -1
  59. package/dist/runtime-6UTYEONR.js +1 -0
  60. package/dist/server-bus-GEGVMSCA.js +1 -0
  61. package/dist/session-manager-45LFTPBA.js +1 -0
  62. package/dist/{task-templates-AKQB7RRB.js → task-templates-7LSQ6OST.js} +1 -1
  63. package/dist/token-estimator-HMPVGDCN.js +1 -0
  64. package/package.json +2 -2
  65. package/web/dist/assets/{Card-BpwkRtmi.js → Card-BecEmnPW.js} +1 -1
  66. package/web/dist/assets/{ChannelDetail-050qK78l.js → ChannelDetail-dZfZlLgQ.js} +1 -1
  67. package/web/dist/assets/{Channels-DA4gN6nU.js → Channels-Cw04c7YJ.js} +1 -1
  68. package/web/dist/assets/{Chat-LzhfKGQ5.js → Chat-D4PHqHPE.js} +1 -1
  69. package/web/dist/assets/Dashboard-BFewwmAg.js +1 -0
  70. package/web/dist/assets/{EmptyState-B08f3BH6.js → EmptyState-DBFJc4PL.js} +1 -1
  71. package/web/dist/assets/{Evolution-BwsOuVbZ.js → Evolution-DY1OC6Oc.js} +4 -1
  72. package/web/dist/assets/{GoalDetail-Zo16ZrYD.js → GoalDetail-DZIEpHs2.js} +1 -1
  73. package/web/dist/assets/Goals-COCCVLnp.js +1 -0
  74. package/web/dist/assets/{Logs-CYfQ9k_6.js → Logs-DsDeimLt.js} +1 -1
  75. package/web/dist/assets/Memories-D5IEEI1u.js +1 -0
  76. package/web/dist/assets/NotFound-Cidygwnn.js +1 -0
  77. package/web/dist/assets/{Plugins-DHgIfely.js → Plugins-DUwZVjPc.js} +1 -1
  78. package/web/dist/assets/RoleDetail-B-GKMfMG.js +33 -0
  79. package/web/dist/assets/{Roles-DGpN5Vm6.js → Roles-JeVjD0Ew.js} +1 -1
  80. package/web/dist/assets/Settings-CvEyZp5t.js +1 -0
  81. package/web/dist/assets/{Strategies-DBp2jYdi.js → Strategies-KAmpqrcQ.js} +1 -1
  82. package/web/dist/assets/{Switch-yk5-dsti.js → Switch-Jpdn6Yux.js} +1 -1
  83. package/web/dist/assets/{Table-DWR4p9xA.js → Table-tkJ-cuiE.js} +1 -1
  84. package/web/dist/assets/TaskDetail-C4NpqwNT.js +2 -0
  85. package/web/dist/assets/Work-DhaxNYnd.js +1 -0
  86. package/web/dist/assets/dist-HyCSN_hp.js +1 -0
  87. package/web/dist/assets/index-CfKqiQIe.js +52 -0
  88. package/web/dist/assets/index-LDFr0VVR.css +2 -0
  89. package/web/dist/assets/rolldown-runtime-Dw2cE7zH.js +1 -0
  90. package/web/dist/assets/vendor-icons-ZPvC5PUS.js +1 -0
  91. package/web/dist/assets/vendor-react--nRVf2Ep.js +12 -0
  92. package/web/dist/assets/{vendor-state-CRsbPXtF.js → vendor-state-CH64feAE.js} +1 -1
  93. package/web/dist/index.html +7 -7
  94. package/dist/App-23CRAK2P.js +0 -9
  95. package/dist/adam-tools-MKUMZWCR.js +0 -1
  96. package/dist/approval-handler-SBFVVFGH.js +0 -4
  97. package/dist/channels-CNLMTKHM.js +0 -1
  98. package/dist/channels-VNG7U6UQ.js +0 -1
  99. package/dist/chunk-37OAKNKA.js +0 -15
  100. package/dist/chunk-3OYRYMJW.js +0 -11
  101. package/dist/chunk-5BAD3NCT.js +0 -1
  102. package/dist/chunk-B3CVXD44.js +0 -104
  103. package/dist/chunk-CV3ROBUM.js +0 -1
  104. package/dist/chunk-FUBKGVWI.js +0 -8
  105. package/dist/chunk-J5YZQQTS.js +0 -3
  106. package/dist/chunk-Q3N5LVPZ.js +0 -5
  107. package/dist/chunk-QOPUUA7O.js +0 -1
  108. package/dist/chunk-TGQYM4TH.js +0 -6
  109. package/dist/chunk-TYR3QUCL.js +0 -23
  110. package/dist/config-42ZJPZDM.js +0 -1
  111. package/dist/delivery-log-7DQ36UGP.js +0 -1
  112. package/dist/engine-7VBPXTGK.js +0 -1
  113. package/dist/memories-BUNOVQVG.js +0 -1
  114. package/dist/role-presets-2X3VW75D.js +0 -1
  115. package/dist/runtime-772O2XKZ.js +0 -1
  116. package/dist/server-bus-N5LCY73J.js +0 -1
  117. package/dist/session-manager-KO4CR3W6.js +0 -1
  118. package/web/dist/assets/Dashboard-Bh32YC_E.js +0 -1
  119. package/web/dist/assets/Goals-BmfVadFN.js +0 -1
  120. package/web/dist/assets/Memories-CgSb60RC.js +0 -1
  121. package/web/dist/assets/RoleDetail-CNJkMSuz.js +0 -1
  122. package/web/dist/assets/Settings-PjFyeX8n.js +0 -1
  123. package/web/dist/assets/TaskDetail-DMg-JAbC.js +0 -2
  124. package/web/dist/assets/Work-BYgMw2qj.js +0 -1
  125. package/web/dist/assets/dist-jv3vbjrx.js +0 -1
  126. package/web/dist/assets/index-CWY8H-cU.js +0 -52
  127. package/web/dist/assets/index-OXMtvYRJ.css +0 -2
  128. package/web/dist/assets/rolldown-runtime-DF2fYuay.js +0 -1
  129. package/web/dist/assets/vendor-icons-DqHipOFA.js +0 -1
  130. package/web/dist/assets/vendor-react-C2hDj0vl.js +0 -11
package/README.md CHANGED
@@ -19,6 +19,7 @@
19
19
  </p>
20
20
 
21
21
  <p align="center">
22
+ <a href="https://www.npmjs.com/package/adam-agent-server"><img src="https://img.shields.io/npm/v/adam-agent-server" alt="npm" /></a>
22
23
  <img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen" alt="Node.js" />
23
24
  <img src="https://img.shields.io/badge/typescript-5.x-blue" alt="TypeScript" />
24
25
  <img src="https://img.shields.io/badge/tests-987%20passed-brightgreen" alt="Tests" />
@@ -86,20 +87,14 @@ Manages task lifecycle, multi-worker process isolation, real-time streaming, rem
86
87
  ### Install
87
88
 
88
89
  ```bash
90
+ # Option A: npm (recommended)
91
+ npm install -g adam-agent-server
92
+
93
+ # Option B: From source
89
94
  git clone https://github.com/n0rvyn/adam.git
90
95
  cd adam
91
-
92
- # Server
93
- pnpm install
94
- pnpm build
95
-
96
- # Web UI
96
+ pnpm install && pnpm build
97
97
  cd web && pnpm install && pnpm build && cd ..
98
-
99
- # (Optional) Register global CLI command
100
- # If prompted about global bin directory, run this first:
101
- pnpm setup
102
- source ~/.bashrc # Or restart your terminal / source your shell config file
103
98
  pnpm link --global
104
99
  ```
105
100
 
@@ -343,19 +338,16 @@ Adam 是一个基于 [Claude Agent SDK](https://docs.anthropic.com/en/docs/agent
343
338
  ## 快速开始
344
339
 
345
340
  ```bash
346
- # 前置条件: Node.js >= 20, pnpm >= 9, ANTHROPIC_API_KEY 环境变量
341
+ # 前置条件: Node.js >= 20, ANTHROPIC_API_KEY 环境变量
342
+
343
+ # 方式 A: npm 安装(推荐)
344
+ npm install -g adam-agent-server
347
345
 
346
+ # 方式 B: 从源码
348
347
  git clone https://github.com/n0rvyn/adam.git
349
348
  cd adam
350
-
351
- # 安装 + 构建
352
349
  pnpm install && pnpm build
353
350
  cd web && pnpm install && pnpm build && cd ..
354
-
355
- # (可选)注册全局 CLI 命令
356
- # 如果提示找不到 global bin directory,先执行:
357
- pnpm setup
358
- source ~/.bashrc # 或重启终端 / 重新加载你的 shell 配置文件
359
351
  pnpm link --global
360
352
 
361
353
  # 启动
@@ -0,0 +1,9 @@
1
+ import{b as T,d as co,e as uo}from"./chunk-NSJAV7IH.js";import{a as At,e as ao,g as lo}from"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{Box as kt,Text as xt,useInput as On}from"ink";import{useState as Vn,useEffect as io,useRef as tr}from"react";import{createContext as ir,useContext as ar,useReducer as lr}from"react";import{jsx as ur}from"react/jsx-runtime";var cr={connected:!1,serverInfo:null,activeTasks:0,queuedTasks:0,costToday:0,activeTaskId:null,activeTaskSubmitted:!1,pendingApproval:null,pendingPlanApproval:null,planTimeoutNotice:null,serverUnreachable:!1,view:"chat",configVersion:0,session:null};function dr(e,t){switch(t.type){case"SET_CONNECTED":return{...e,connected:t.connected};case"SET_SERVER_INFO":return{...e,serverInfo:t.info};case"UPDATE_STATS":return{...e,activeTasks:t.activeTasks,queuedTasks:t.queuedTasks,costToday:t.costToday};case"SET_ACTIVE_TASK":return{...e,activeTaskId:t.taskId,activeTaskSubmitted:!1};case"TASK_SUBMITTED":return{...e,activeTaskSubmitted:!0};case"SET_PENDING_APPROVAL":return{...e,pendingApproval:t.approval};case"SET_SERVER_UNREACHABLE":return{...e,serverUnreachable:t.unreachable};case"SET_VIEW":return{...e,view:t.view};case"CONFIG_CHANGED":return{...e,configVersion:e.configVersion+1};case"SET_SESSION":return{...e,session:t.session};case"SET_PENDING_PLAN_APPROVAL":return{...e,pendingPlanApproval:t.approval};case"SET_PLAN_TIMEOUT_NOTICE":return{...e,pendingPlanApproval:null,planTimeoutNotice:t.planId?{planId:t.planId}:null};default:return e}}var mo=ir(null);function go({children:e}){let[t,o]=lr(dr,cr);return ur(mo.Provider,{value:{state:t,dispatch:o},children:e})}function Xe(){let e=ar(mo);if(!e)throw new Error("useTuiState must be used within TuiProvider");return e}import{useEffect as mr,useRef as gr}from"react";var fr=15e3;function fo(){let{dispatch:e}=Xe(),t=gr(null);mr(()=>{let o=!0,c=null,g=()=>{t.current&&(clearTimeout(t.current),t.current=null)},f=()=>{g(),t.current=setTimeout(()=>{o&&e({type:"SET_SERVER_UNREACHABLE",unreachable:!0})},fr)};return(()=>{try{c=new co("/events"),c.on("task_status_change",()=>{}),c.on("approval_request",i=>{if(!o)return;let s=i;e({type:"SET_PENDING_APPROVAL",approval:{taskId:s.taskId,approvalId:s.approvalId,toolName:s.toolName,toolInput:s.toolInput,matchedPattern:s.matchedPattern}})}),c.on("plan_approval_request",i=>{if(!o)return;let s=i;e({type:"SET_PENDING_PLAN_APPROVAL",approval:{taskId:s.taskId,planId:s.planId,roleId:s.roleId,plan:s.plan}})}),c.on("plan_approval_decision",()=>{o&&e({type:"SET_PENDING_PLAN_APPROVAL",approval:null})}),c.on("config_changed",()=>{o&&e({type:"CONFIG_CHANGED"})}),c.on("stats_update",i=>{if(!o)return;let s=i;e({type:"UPDATE_STATS",activeTasks:s.activeTasks,queuedTasks:s.queuedTasks,costToday:s.totalCostToday})}),c.connect().then(()=>{o&&(g(),e({type:"SET_CONNECTED",connected:!0}),e({type:"SET_SERVER_UNREACHABLE",unreachable:!1}))}).catch(()=>{o&&(e({type:"SET_CONNECTED",connected:!1}),f())})}catch{o&&(e({type:"SET_CONNECTED",connected:!1}),f())}})(),()=>{o=!1,g(),c?.close()}},[e])}import{useEffect as pr,useRef as xr,useState as po,useCallback as Tr}from"react";function xo(e){let[t,o]=po([]),[c,g]=po(!1),f=xr(null),l=Tr(()=>{o([]),g(!1)},[]);return pr(()=>{if(!e)return;let i=!0;o([]),g(!0);try{let s=new uo(e);return f.current=s,s.on("reasoning",r=>{if(!i)return;let d=r.content??"";o(y=>{let u=y[y.length-1];if(u?.type==="reasoning"){let x=[...y];return x[x.length-1]={...u,content:u.content+d},x}return[...y,{type:"reasoning",content:d,timestamp:Date.now()}]})}),s.on("tool_call",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"tool_call",content:m.toolName??"unknown tool",timestamp:Date.now(),metadata:{toolName:m.toolName}}])}),s.on("tool_result",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"tool_result",content:m.content??"",timestamp:Date.now()}])}),s.on("error",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"error",content:m.error??"unknown error",timestamp:Date.now()}])}),s.on("complete",r=>{if(!i)return;let m=r;o(d=>[...d,{type:"complete",content:m.result??"",timestamp:Date.now(),metadata:{cost:m.costUsd,turns:m.numTurns,duration:m.totalDurationMs}}]),g(!1)}),s.connect().catch(()=>{i&&(o(r=>[...r,{type:"error",content:"Failed to connect to task stream",timestamp:Date.now()}]),g(!1))}),()=>{i=!1,s.close()}}catch{g(!1)}},[e]),{events:t,isStreaming:c,clearEvents:l}}import{useState as Gt,useEffect as hr,useCallback as ht}from"react";function Ht(e){return{id:e.id,status:e.status,messageCount:e.messageCount,createdAt:e.createdAt,lastActiveAt:e.lastActiveAt,title:e.title}}function To(){let[e,t]=Gt(null),[o,c]=Gt(!0),[g,f]=Gt(null),l=ht(async()=>{try{let y=(await T("/chat/sessions?status=active")).sessions.find(u=>u.source.type==="tui");return y?Ht(y):null}catch{return null}},[]),i=ht(async()=>{try{let d=await T("/chat/sessions",{method:"POST",body:{source:{type:"tui"}}}),y=Ht(d.session);return t(y),y}catch{return f("Failed to create session"),null}},[]),s=ht(async d=>{try{let y=await T("/chat/messages",{method:"POST",body:{content:d,source:{type:"tui"}}});return t(u=>u&&{...u,messageCount:u.messageCount+1,lastActiveAt:Date.now()}),y}catch{return null}},[]),r=ht(async()=>{if(!e)return!1;try{return await T(`/chat/sessions/${e.id}/archive`,{method:"POST"}),t(null),!0}catch{return!1}},[e]),m=ht(async()=>{if(e)try{let d=await T(`/chat/sessions/${e.id}`);t(Ht(d.session))}catch{t(null)}},[e]);return hr(()=>{let d=!1;async function y(){c(!0);let u=await l();d||(u?t(u):await i(),d||c(!1))}return y(),()=>{d=!0}},[]),{session:e,loading:o,error:g,sendMessage:s,createNewSession:i,archiveCurrentSession:r,refreshSession:m,setSession:t}}import{Box as jt,Text as ve}from"ink";import Ce from"chalk";var Kt={connected:Ce.green,disconnected:Ce.red,warning:Ce.yellow,reasoning:Ce.gray,toolCall:Ce.blue,toolResult:Ce.green,error:Ce.red,dim:Ce.dim,bold:Ce.bold,statusUp:Ce.green("\u25CF"),statusDown:Ce.red("\u25CF")};import{Fragment as yr,jsx as tt,jsxs as ze}from"react/jsx-runtime";function ho(){let{state:e}=Xe(),t=e.connected?`${Kt.statusUp} Server: up`:`${Kt.statusDown} Disconnected`,o=e.activeTasks>0?`${e.activeTasks} running, ${e.queuedTasks} queued`:"No active tasks",c=e.session,f=(c?Math.floor((Date.now()-c.lastActiveAt)/6e4):1/0)>=25;return ze(jt,{flexDirection:"column",borderStyle:"round",borderDimColor:!0,children:[ze(jt,{children:[tt(ve,{bold:!0,children:"Adam v0.2.0"}),tt(ve,{children:" \u2502 "}),tt(ve,{children:t}),tt(ve,{children:" \u2502 "}),ze(ve,{children:["Tasks: ",e.activeTasks," active"]}),e.view==="chat"&&c&&ze(yr,{children:[tt(ve,{children:" \u2502 "}),ze(ve,{children:["Session: ",c.messageCount===0?"(new)":`${c.id.slice(0,8)} (${c.messageCount} turns)`]}),f&&tt(ve,{color:"yellow",children:" timeout soon"})]})]}),ze(jt,{children:[ze(ve,{children:["Tasks: ",o]}),tt(ve,{children:" \u2502 "}),ze(ve,{children:["Cost: $",e.costToday.toFixed(2)," today"]})]})]})}import{Box as Dt,Text as Rt,useInput as Sr}from"ink";import{useState as Xt,useMemo as Cr}from"react";import vr from"ink-text-input";var br=[{name:"work",description:"Tasks, Automations & Goals"},{name:"config",description:"Configuration"},{name:"evolution",description:"Evolution audit"},{name:"webhooks",description:"Webhook triggers"},{name:"memories",description:"Memory browser"},{name:"strategies",description:"Strategy lab"},{name:"plugins",description:"Plugin management"},{name:"roles",description:"Role management"},{name:"settings",description:"Runtime settings"},{name:"back",description:"Return to chat"},{name:"quit",description:"Exit TUI"}];function Qt(e){let t=e.toLowerCase();return br.filter(o=>o.name.startsWith(t))}function yo(e){let t=Qt(e.toLowerCase());return t.length===1?t[0]:void 0}import{jsx as Mt,jsxs as yt}from"react/jsx-runtime";function bo({onSubmit:e}){let[t,o]=Xt(""),[c,g]=Xt(0),[f,l]=Xt(!1),i=t.startsWith("/")&&t.length>=1,s=t.slice(1),r=Cr(()=>i?Qt(s):[],[i,s]),m=u=>{o(u),u.startsWith("/")?(l(!0),g(0)):l(!1)},d=()=>{let u=t.trim();if(u){if(u.startsWith("/")){let x=u.slice(1),n=yo(x);e(n?`/${n.name}`:u)}else e(u);o(""),l(!1)}},y=u=>{e(`/${u.name}`),o(""),l(!1)};return Sr((u,x)=>{if(!(!f||!i||r.length===0)){if(x.upArrow){g(n=>n<=0?r.length-1:n-1);return}if(x.downArrow){g(n=>n>=r.length-1?0:n+1);return}if(x.tab){let n=r[c];n&&y(n);return}if(x.escape){l(!1),o("");return}}},{isActive:f&&i&&r.length>0}),yt(Dt,{flexDirection:"column",children:[f&&i&&r.length>0&&Mt(Dt,{flexDirection:"column",marginBottom:0,paddingX:1,children:r.map((u,x)=>{let n=x===c;return yt(Dt,{children:[Mt(Rt,{color:n?"cyan":"gray",bold:n,children:n?"\u25B8 ":" "}),yt(Rt,{color:n?"cyan":"white",bold:n,children:["/",u.name]}),yt(Rt,{dimColor:!0,children:[" \u2014 ",u.description]})]},u.name)})}),yt(Dt,{borderStyle:"round",borderDimColor:!0,children:[Mt(Rt,{bold:!0,children:"\u25B8 "}),Mt(vr,{value:t,onChange:m,onSubmit:d,placeholder:"Type a message or / for commands..."})]})]})}import{Box as it,Text as ge}from"ink";import{useState as Er}from"react";import{jsx as ye,jsxs as Ae}from"react/jsx-runtime";function Br({content:e}){let[t,o]=Er(!1),c=e.split(`
2
+ `);return c.length<=5?ye(ge,{color:"green",children:e}):t?ye(ge,{color:"green",children:e}):Ae(ge,{color:"green",children:[c.slice(0,3).join(`
3
+ `),`
4
+ `,Ae(ge,{dimColor:!0,children:["(",c.length," lines) \u25B8 \u5C55\u5F00"]})]})}function wr({event:e}){switch(e.type){case"reasoning":return ye(it,{children:ye(ge,{color:"gray",children:e.content})});case"tool_call":return ye(it,{children:Ae(ge,{color:"blue",children:["[tool] ",e.metadata?.toolName??e.content]})});case"tool_result":return Ae(it,{flexDirection:"column",children:[ye(ge,{color:"blue",dimColor:!0,children:"[result]"}),ye(Br,{content:e.content})]});case"error":return ye(it,{children:Ae(ge,{color:"red",children:["[error] ",e.content]})});case"complete":return Ae(it,{flexDirection:"column",marginTop:1,children:[e.content&&ye(ge,{children:e.content}),ye(ge,{dimColor:!0,children:"\u2500\u2500\u2500 Task complete \u2500\u2500\u2500"}),e.metadata?.cost!==void 0&&Ae(ge,{dimColor:!0,children:["Cost: $",e.metadata.cost.toFixed(4)]}),e.metadata?.turns!==void 0&&Ae(ge,{dimColor:!0,children:["Turns: ",e.metadata.turns]}),e.metadata?.duration!==void 0&&Ae(ge,{dimColor:!0,children:["Duration: ",(e.metadata.duration/1e3).toFixed(1),"s"]})]});default:return null}}function So({events:e,isStreaming:t}){return e.length===0&&!t?null:Ae(it,{flexDirection:"column",children:[t&&e.length===0&&ye(ge,{dimColor:!0,children:"Waiting for response..."}),e.map((o,c)=>ye(wr,{event:o},c))]})}import{Box as Co,Text as vo}from"ink";import{jsx as zt,jsxs as Ir}from"react/jsx-runtime";function Eo({messages:e}){return e.length===0?null:zt(Co,{flexDirection:"column",children:e.map((t,o)=>Ir(Co,{flexDirection:"column",marginBottom:1,children:[zt(vo,{dimColor:!0,bold:!0,children:t.role==="user"?"You:":"Adam:"}),zt(vo,{children:t.content})]},o))})}import{Box as bt,Text as De,useInput as kr}from"ink";import{jsx as Re,jsxs as St}from"react/jsx-runtime";function Bo({approval:e,onResolved:t}){return kr(o=>{o==="a"?T(`/tasks/${e.taskId}/approve`,{method:"POST",body:{approvalId:e.approvalId}}).then(()=>t()).catch(()=>t()):o==="r"&&T(`/tasks/${e.taskId}/reject`,{method:"POST",body:{approvalId:e.approvalId,reason:"rejected by user"}}).then(()=>t()).catch(()=>t())}),St(bt,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Re(De,{bold:!0,color:"yellow",children:"\u26A0 APPROVAL REQUIRED"}),St(bt,{marginTop:1,children:[Re(De,{children:"Tool: "}),Re(De,{bold:!0,children:e.toolName})]}),St(bt,{children:[Re(De,{children:"Input: "}),Re(De,{children:JSON.stringify(e.toolInput)})]}),St(bt,{children:[Re(De,{children:"Pattern: "}),Re(De,{dimColor:!0,children:e.matchedPattern})]}),St(bt,{marginTop:1,children:[Re(De,{color:"green",children:"[a] Approve"}),Re(De,{children:" "}),Re(De,{color:"red",children:"[r] Reject"})]})]})}import{Box as Ct,Text as le,useInput as Pr}from"ink";import{useState as Ar,useEffect as Dr}from"react";import{jsx as Oe,jsxs as Ee}from"react/jsx-runtime";var Rr=300;function wo({approval:e,onResolved:t,onTimeout:o}){let[c,g]=Ar(Rr);Dr(()=>{let l=setInterval(()=>{g(i=>i<=1?(clearInterval(l),o(),0):i-1)},1e3);return()=>clearInterval(l)},[o]),Pr(l=>{l==="a"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"once"}}).then(()=>t()).catch(()=>t()):l==="r"?T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"deny",reason:"rejected by user"}}).then(()=>t()).catch(()=>t()):l==="p"&&T(`/tasks/${e.taskId}/approve-plan`,{method:"POST",body:{planId:e.planId,decision:"allow",approvalType:"permanent"}}).then(()=>t()).catch(()=>t())});let f=e.plan.overallRisk==="high"?"red":e.plan.overallRisk==="medium"?"yellow":"green";return Ee(Ct,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[Oe(le,{bold:!0,color:"cyan",children:"EXECUTION PLAN \u2014 APPROVAL REQUIRED"}),Ee(le,{dimColor:!0,children:["Plan ID: ",e.planId]}),Ee(le,{dimColor:!0,children:["Time remaining: ",c,"s"]}),Ee(Ct,{marginTop:1,children:[Oe(le,{children:"Overall Risk: "}),Oe(le,{bold:!0,color:f,children:e.plan.overallRisk.toUpperCase()})]}),Ee(le,{bold:!0,children:["Steps (",e.plan.steps.length,"):"]}),e.plan.steps.map(l=>{let i=l.riskLevel==="high"?"red":l.riskLevel==="medium"?"yellow":"green";return Ee(Ct,{paddingLeft:2,children:[Ee(le,{children:["[",l.index,"] "]}),Oe(le,{children:l.description}),Ee(le,{dimColor:!0,children:[" (",l.toolsNeeded.join(", "),")"]}),Ee(le,{color:i,children:[" [",l.riskLevel,"]"]})]},l.index)}),Ee(Ct,{marginTop:1,children:[Oe(le,{dimColor:!0,children:"Permissions: "}),Oe(le,{children:Object.keys(e.plan.requiredPermissions).join(", ")||"none"})]}),Ee(Ct,{marginTop:1,children:[Oe(le,{color:"green",children:"[a] Allow once "}),Oe(le,{color:"green",children:"[p] Allow permanent "}),Oe(le,{color:"red",children:"[r] Deny"})]})]})}import{Box as ot,Text as Z,useInput as Nr}from"ink";import{useEffect as _r,useState as Ve,useCallback as ko}from"react";import{Box as Q,Text as A,useInput as Mr}from"ink";import{useState as Yt,useEffect as Lr}from"react";import{jsx as $,jsxs as F}from"react/jsx-runtime";function Io({taskId:e,onBack:t}){let[o,c]=Yt(null),[g,f]=Yt([]),[l,i]=Yt(null);if(Lr(()=>{T(`/tasks/${e}`).then(r=>c(r)).catch(r=>i(r instanceof Error?r.message:String(r))),T(`/tasks/${e}/plan`).then(r=>f(r.plans)).catch(()=>f([]))},[e]),Mr((r,m)=>{(r==="b"||m.escape)&&t()}),l)return F(Q,{flexDirection:"column",children:[F(A,{color:"red",children:["Error: ",l]}),$(A,{dimColor:!0,children:"[b] Back"})]});if(!o)return F(A,{dimColor:!0,children:["Loading task ",e,"..."]});let s=g[0];return F(Q,{flexDirection:"column",children:[$(A,{bold:!0,color:"cyan",children:"Task Detail"}),F(Q,{marginTop:1,flexDirection:"column",children:[F(Q,{children:[$(A,{children:"ID: "}),$(A,{dimColor:!0,children:String(o.id)})]}),F(Q,{children:[$(A,{children:"Status: "}),$(A,{bold:!0,children:String(o.status)})]}),F(Q,{children:[$(A,{children:"Prompt: "}),$(A,{children:String(o.prompt)})]}),o.result?F(Q,{children:[$(A,{children:"Result: "}),$(A,{children:String(o.result).slice(0,200)})]}):null,o.error?F(Q,{children:[$(A,{color:"red",children:"Error: "}),$(A,{children:String(o.error)})]}):null,o.deliverTo?.length?F(Q,{children:[$(A,{children:"DeliverTo: "}),$(A,{dimColor:!0,children:o.deliverTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null,o.reportTo?.length?F(Q,{children:[$(A,{children:"ReportTo: "}),$(A,{dimColor:!0,children:o.reportTo.map(r=>r.type==="channel"?`channel ${r.channelId?.slice(0,8)}`:`session ${r.sessionId?.slice(0,8)}`).join(", ")})]}):null]}),s&&F(Q,{marginTop:1,flexDirection:"column",children:[$(A,{bold:!0,color:"cyan",children:"Execution Plan"}),F(Q,{children:[$(A,{children:"Plan ID: "}),$(A,{dimColor:!0,children:s.id})]}),F(Q,{children:[$(A,{children:"Status: "}),$(A,{children:s.status})]}),s.plan.overallRisk&&F(Q,{children:[$(A,{children:"Overall Risk: "}),$(A,{bold:!0,color:s.plan.overallRisk==="high"?"red":s.plan.overallRisk==="medium"?"yellow":"green",children:s.plan.overallRisk.toUpperCase()})]}),F(A,{bold:!0,children:["Steps (",s.plan.steps.length,"):"]}),s.plan.steps.map(r=>{let m=r.riskLevel==="high"?"red":r.riskLevel==="medium"?"yellow":"green";return F(Q,{paddingLeft:2,children:[F(A,{children:["[",r.index,"] ",r.description]}),F(A,{color:m,children:[" [",r.riskLevel,"]"]})]},r.index)}),s.deviationReport&&F(Q,{marginTop:1,flexDirection:"column",children:[$(A,{bold:!0,color:"yellow",children:"Deviation Report"}),F(A,{children:["Planned: ",s.deviationReport.stepsPlanned," | Executed: ",s.deviationReport.stepsExecuted," | Accuracy: ",(s.deviationReport.overallAccuracy*100).toFixed(0),"%"]}),s.deviationReport.deviations.map((r,m)=>F(Q,{paddingLeft:2,children:[F(A,{color:"yellow",children:["[",r.deviationType,"] "]}),F(A,{children:["Step ",r.stepIndex,": ",r.actual]})]},m))]}),s.learnedRules&&s.learnedRules.length>0&&F(Q,{marginTop:1,flexDirection:"column",children:[$(A,{bold:!0,color:"blue",children:"Learned Rules"}),s.learnedRules.map((r,m)=>$(Q,{paddingLeft:2,children:F(A,{children:["* ",r]})},m))]})]}),!s&&g.length===0&&$(Q,{marginTop:1,children:$(A,{dimColor:!0,children:"No execution plan for this task."})}),$(Q,{marginTop:1,children:$(A,{dimColor:!0,children:"[b] Back"})})]})}import{Fragment as Vr,jsx as ce,jsxs as pe}from"react/jsx-runtime";var $r={pending:"gray",queued:"gray",running:"yellow",paused:"yellow",completed:"green",failed:"red",cancelled:"gray"},Lt=["all","pending","queued","running","completed","failed","cancelled"],Jt=15;function Nt({onBack:e}){let[t,o]=Ve([]),[c,g]=Ve(!0),[f,l]=Ve("list"),[i,s]=Ve(0),[r,m]=Ve("all"),[d,y]=Ve(0),[u,x]=Ve(0),[n,a]=Ve(null),[P,M]=Ve([]),z=ko(async()=>{g(!0);try{let w=new URLSearchParams({limit:"100"});r!=="all"&&w.set("status",r);let S=await T(`/tasks?${w}`);o(S.tasks)}catch{o([])}finally{g(!1)}},[r]);_r(()=>{z()},[z]);let U=Math.max(1,Math.ceil(t.length/Jt)),D=t.slice(u*Jt,(u+1)*Jt),H=ko(async()=>{let w=D[i];if(w)try{await T(`/tasks/${w.id}/cancel`,{method:"POST"}),a(`Cancelled: ${w.id.slice(0,8)}`),l("list"),z()}catch(S){a(`Failed: ${S instanceof Error?S.message:String(S)}`),l("list")}},[D,i,z]);return Nr((w,S)=>{if(f==="detail"){(S.escape||S.return||w==="q")&&l("list");return}if(f==="cancelling"){w==="y"?H():l("list");return}if(f==="filter"){if(S.escape){l("list");return}S.upArrow&&d>0&&y(p=>p-1),S.downArrow&&d<Lt.length-1&&y(p=>p+1),S.return&&(m(Lt[d]),x(0),s(0),l("list"));return}if(S.escape||w==="q"){e();return}if(S.upArrow&&i>0&&s(p=>p-1),S.downArrow&&i<D.length-1&&s(p=>p+1),S.return){let p=D[i];p&&(M([]),l("detail"),T(`/tasks/${p.id}/logs?limit=20`).then(({logs:I})=>M(I)).catch(()=>M([])))}if(w==="x"&&D[i]){let p=D[i];["running","pending","queued","paused"].includes(p.status)?(l("cancelling"),a(null)):a(`Cannot cancel task in status: ${p.status}`)}w==="f"&&(y(Lt.indexOf(r)),l("filter")),w==="r"&&z(),(S.pageDown||w==="n")&&u<U-1&&(x(p=>p+1),s(0)),(S.pageUp||w==="p")&&u>0&&(x(p=>p-1),s(0))}),c?ce(Z,{dimColor:!0,children:"Loading tasks..."}):f==="filter"?pe(ot,{flexDirection:"column",children:[ce(Z,{bold:!0,children:"Filter by status:"}),Lt.map((w,S)=>ce(ot,{children:pe(Z,{color:S===d?"cyan":"white",children:[S===d?"> ":" ",w,w===r?" (current)":""]})},w)),ce(Z,{dimColor:!0,children:"Enter: select Esc: cancel"})]}):f==="detail"&&D[i]?ce(Io,{taskId:D[i].id,onBack:()=>l("list")}):f==="cancelling"&&D[i]?pe(ot,{flexDirection:"column",children:[pe(Z,{color:"red",children:['Cancel task "',D[i].id.slice(0,8),'"? (y/n)']}),n&&ce(Z,{color:"red",children:n})]}):pe(ot,{flexDirection:"column",children:[pe(ot,{children:[pe(Z,{bold:!0,children:["Tasks (",t.length,")"]}),r!=="all"&&pe(Z,{dimColor:!0,children:[" [filter: ",r,"]"]}),pe(Z,{dimColor:!0,children:[" \u2014 Page ",u+1,"/",U]})]}),n&&ce(Z,{color:n.startsWith("Failed")||n.startsWith("Cannot")?"red":"green",children:n}),t.length===0?pe(Z,{dimColor:!0,children:["No tasks found",r!=="all"?` with status "${r}"`:"","."]}):pe(Vr,{children:[ce(ot,{marginTop:1,children:pe(Z,{bold:!0,children:[" ",Ye("ID",10),Ye("STATUS",12),Ye("PROMPT",40),Ye("DURATION",10),"COST"]})}),D.map((w,S)=>{let p=S===i,I=w.totalDurationMs?`${(w.totalDurationMs/1e3).toFixed(0)}s`:"\u2014",L=w.costUsd!==void 0?`$${w.costUsd.toFixed(4)}`:"\u2014",_e=$r[w.status]??"white";return pe(ot,{children:[ce(Z,{color:p?"cyan":"white",children:p?"> ":" "}),ce(Z,{dimColor:!0,children:Ye(w.id.slice(0,8),10)}),ce(Z,{color:_e,children:Ye(w.status,12)}),ce(Z,{children:Ye(Or(w.prompt,38),40)}),ce(Z,{dimColor:!0,children:Ye(I,10)}),ce(Z,{dimColor:!0,children:L})]},w.id)})]}),ce(Z,{dimColor:!0,children:"Enter:detail x:cancel f:filter n/p:page r:refresh Esc/q:back"})]})}function Ye(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Or(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}lo();import{Box as vt,Text as Be,useInput as qr}from"ink";import{useEffect as Ur,useState as Po}from"react";import{readFileSync as Fr,existsSync as Wr}from"fs";import{parse as Gr}from"yaml";import{Fragment as Hr,jsx as we,jsxs as Je}from"react/jsx-runtime";function Do({onBack:e}){let[t,o]=Po(null),[c,g]=Po(null);return qr((f,l)=>{(l.escape||f==="q")&&e()}),Ur(()=>{try{let f=ao;if(!Wr(f)){g(`Config file not found: ${f}`);return}let l=Fr(f,"utf-8");o(Gr(l))}catch(f){g(f.message)}},[]),c?Je(vt,{flexDirection:"column",children:[we(Be,{color:"red",children:c}),we(Be,{dimColor:!0,children:"Press Esc to go back"})]}):t?Je(vt,{flexDirection:"column",children:[we(Be,{bold:!0,children:"Configuration (Esc to go back)"}),we(vt,{marginTop:1,flexDirection:"column",children:we(Ro,{obj:t,indent:0})})]}):we(Be,{dimColor:!0,children:"Loading config..."})}function Ro({obj:e,indent:t}){let o=" ".repeat(t);return we(Hr,{children:Object.entries(e).map(([c,g])=>g&&typeof g=="object"&&!Array.isArray(g)?Je(vt,{flexDirection:"column",children:[Je(Be,{children:[o,we(Be,{color:"cyan",children:c}),":"]}),we(Ro,{obj:g,indent:t+1})]},c):Array.isArray(g)?Je(vt,{flexDirection:"column",children:[Je(Be,{children:[o,we(Be,{color:"cyan",children:c}),":"]}),g.map((f,l)=>Je(Be,{children:[o," - ",Ao(c,String(f))]},l))]},c):Je(Be,{children:[o,we(Be,{color:"cyan",children:c}),": ",Ao(c,String(g))]},c))})}function Ao(e,t){return e.toLowerCase().includes("key")||e.toLowerCase().includes("token")?!t||t.length<8?"****":t.slice(0,4)+"****":t}import{Box as _t,Text as Ie,useInput as Kr}from"ink";import{useEffect as jr,useState as Zt}from"react";import{jsx as Et,jsxs as Me}from"react/jsx-runtime";function Mo({onBack:e}){let[t,o]=Zt([]),[c,g]=Zt(!0),[f,l]=Zt(null);return Kr((i,s)=>{(s.escape||i==="q")&&e()}),jr(()=>{T("/evolution-audit?limit=20").then(i=>{o(i),g(!1)}).catch(i=>{l(i.message),g(!1)})},[]),c?Et(Ie,{dimColor:!0,children:"Loading evolution log..."}):f?Me(_t,{flexDirection:"column",children:[Et(Ie,{color:"red",children:f}),Et(Ie,{dimColor:!0,children:"Press Esc to go back"})]}):t.length===0?Me(_t,{flexDirection:"column",children:[Et(Ie,{dimColor:!0,children:"No evolution records yet"}),Et(Ie,{dimColor:!0,children:"Press Esc to go back"})]}):Me(_t,{flexDirection:"column",children:[Me(Ie,{bold:!0,children:["Evolution Audit Log (",t.length," records) \u2014 Esc to go back"]}),t.map(i=>Me(_t,{flexDirection:"column",marginTop:1,children:[Me(Ie,{bold:!0,children:["[",new Date(i.timestamp).toLocaleString(),"]"]}),i.triggerTaskId&&Me(Ie,{dimColor:!0,children:[" Task: ",i.triggerTaskId.slice(0,8)]}),i.diff.split(`
5
+ `).map((s,r)=>s.startsWith("+")?Me(Ie,{color:"green",children:[" ",s]},r):s.startsWith("-")?Me(Ie,{color:"red",children:[" ",s]},r):Me(Ie,{dimColor:!0,children:[" ",s]},r))]},i.id))]})}import{Box as qe,Text as X,useInput as Qr}from"ink";import Xr from"ink-text-input";import{useEffect as zr,useState as at}from"react";import{jsx as fe,jsxs as oe}from"react/jsx-runtime";var Yr={pending:"gray",planning:"cyan",executing:"yellow",evaluating:"blue",replanning:"magenta",completed:"green",failed:"red",paused:"gray"};function Jr(e,t=20){let o=Math.round(e*t),c=t-o;return"\u2588".repeat(o)+"\u2591".repeat(c)}function Zr(e){let t=Math.max(0,Math.floor((e-Date.now())/864e5));return t===0?"< 1d":`${t}d`}function $t({onBack:e}){let[t,o]=at([]),[c,g]=at(null),[f,l]=at("list"),[i,s]=at(""),[r,m]=at(!1),[d,y]=at(null);Qr((n,a)=>{if(f==="create"){a.escape&&(l("list"),s(""),y(null));return}(a.escape||n==="q")&&e(),n==="c"&&(l("create"),y(null)),n==="r"&&u()});let u=()=>{T("/goals?limit=20").then(({goals:n})=>o(n)).catch(n=>g(n.message))};zr(()=>{u()},[]);let x=async n=>{if(n.trim()){m(!0),y(null);try{let a=await T("/goals",{method:"POST",body:{input:n.trim()}});y(`Goal created: ${a.goal.name}`),s(""),l("list"),u()}catch(a){y(`Failed: ${a instanceof Error?a.message:String(a)}`)}finally{m(!1)}}};return c?oe(qe,{flexDirection:"column",children:[oe(X,{color:"red",children:["Failed to load goals: ",c]}),fe(X,{dimColor:!0,children:"Press Esc or q to return"})]}):f==="create"?oe(qe,{flexDirection:"column",children:[fe(X,{bold:!0,children:"Create Goal"}),fe(X,{dimColor:!0,children:"Describe your SMART goal in natural language:"}),oe(qe,{marginTop:1,children:[fe(X,{color:"cyan",children:"> "}),fe(Xr,{value:i,onChange:s,onSubmit:x})]}),r&&fe(X,{color:"yellow",children:"Creating goal..."}),d&&fe(X,{color:d.startsWith("Failed")?"red":"green",children:d}),fe(X,{dimColor:!0,children:"Press Esc to cancel"})]}):oe(qe,{flexDirection:"column",children:[oe(X,{bold:!0,children:["Goal Dashboard (",t.length,")"]}),t.length===0?fe(X,{dimColor:!0,children:"No goals found. Press c to create one."}):fe(qe,{marginTop:1,flexDirection:"column",children:t.map(n=>{let a=n.targetValue>0?n.currentValue/n.targetValue:0,P=Yr[n.status]??"white";return oe(qe,{marginBottom:1,flexDirection:"column",children:[oe(qe,{children:[fe(X,{bold:!0,color:P,children:n.name}),oe(X,{dimColor:!0,children:[" (",n.role,")"]}),fe(X,{dimColor:!0,children:" \u2014 "}),fe(X,{color:P,children:n.status})]}),oe(qe,{children:[oe(X,{dimColor:!0,children:[" ",Jr(a)," "]}),oe(X,{color:a>=1?"green":"white",children:[Math.round(a*100),"%"]}),oe(X,{dimColor:!0,children:[" (",n.currentValue,"/",n.targetValue," ",n.metricType,")"]})]}),oe(qe,{children:[oe(X,{dimColor:!0,children:[" \u23F0 ",Zr(n.deadline)," left"]}),oe(X,{dimColor:!0,children:[" | \u{1F4B0} $",n.budgetUsd]}),oe(X,{dimColor:!0,children:[" | ID: ",n.id.slice(0,8)]})]})]},n.id)})}),fe(X,{dimColor:!0,children:"c:create r:refresh Esc/q:back"})]})}import{Box as lt,Text as be,useInput as en}from"ink";import{useEffect as tn,useState as Lo}from"react";import{jsx as Fe,jsxs as Ue}from"react/jsx-runtime";function on(e,t,o=15){let c=e/(e+t),g=Math.round(c*o);return"\u2593".repeat(g)+"\u2591".repeat(o-g)}function No({onBack:e}){let[t,o]=Lo([]),[c,g]=Lo(null);if(en((l,i)=>{(i.escape||l==="q")&&e()}),tn(()=>{T("/strategies?limit=50").then(l=>o(l.strategies??[])).catch(l=>g(l.message))},[]),c)return Ue(lt,{flexDirection:"column",children:[Ue(be,{color:"red",children:["Failed to load strategies: ",c]}),Fe(be,{dimColor:!0,children:"Press Esc or q to return"})]});if(t.length===0)return Ue(lt,{flexDirection:"column",children:[Fe(be,{dimColor:!0,children:"No strategies yet. Strategies are created when goals are executed."}),Fe(be,{dimColor:!0,children:"Press Esc or q to return"})]});let f=new Map;for(let l of t){let i=`${l.role}/${l.taskType}`,s=f.get(i)??[];s.push(l),f.set(i,s)}return Ue(lt,{flexDirection:"column",children:[Fe(be,{bold:!0,children:"Strategy Lab"}),Fe(be,{dimColor:!0,children:"Thompson Sampling populations \u2014 higher bar = higher selection probability"}),Fe(lt,{marginTop:1,flexDirection:"column",children:Array.from(f.entries()).map(([l,i])=>Ue(lt,{marginBottom:1,flexDirection:"column",children:[Fe(be,{bold:!0,color:"cyan",children:l}),i.sort((s,r)=>{let m=s.alpha/(s.alpha+s.beta);return r.alpha/(r.alpha+r.beta)-m}).map(s=>{let r=s.alpha/(s.alpha+s.beta);return Ue(lt,{children:[Fe(be,{dimColor:!0,children:" "}),Ue(be,{children:[on(s.alpha,s.beta)," "]}),Ue(be,{color:r>.6?"green":r>.4?"yellow":"red",children:[(r*100).toFixed(0),"%"]}),Ue(be,{dimColor:!0,children:[" ",s.name," (\u03B1=",s.alpha.toFixed(1)," \u03B2=",s.beta.toFixed(1)," trials=",s.totalTrials,")"]})]},s.id)})]},l))}),Fe(be,{dimColor:!0,children:"Press Esc or q to return"})]})}import{Box as xe,Text as K,useInput as ln}from"ink";import eo from"ink-text-input";import{useEffect as cn,useState as We,useCallback as ct}from"react";import{CronExpressionParser as dn}from"cron-parser";import{useState as rn,useEffect as nn,useCallback as _o,useRef as sn}from"react";var an=3e3;function Ze(){let[e,t]=rn(null),o=sn(null),c=_o(()=>{o.current&&(clearTimeout(o.current),o.current=null),t(null)},[]),g=_o((f,l)=>{o.current&&(clearTimeout(o.current),o.current=null),t({text:f,type:l}),l==="success"&&(o.current=setTimeout(()=>{t(null),o.current=null},an))},[]);return nn(()=>()=>{o.current&&clearTimeout(o.current)},[]),{message:e,setMessage:g,clearMessage:c}}import{jsx as j,jsxs as se}from"react/jsx-runtime";var to=["manual","cron","event"],Ot={name:"",triggerType:"manual",cron:"",stepPrompt:""};function un(e){try{return dn.parse(e).next().toDate().toLocaleString()}catch{return"invalid"}}function qt({onBack:e}){let[t,o]=We([]),[c,g]=We(!0),[f,l]=We(0),[i,s]=We("list"),[r,m]=We({...Ot}),[d,y]=We("name"),[u,x]=We(null),{message:n,setMessage:a,clearMessage:P}=Ze(),[M,z]=We(!1),[U,D]=We(!1),H=ct(()=>{g(!0),T("/task-templates").then(({templates:b})=>{o(b),g(!1)}).catch(()=>g(!1))},[]);cn(()=>{H()},[H]);let w=i==="create"||i==="edit",S=ct(async()=>{let b=t[f];if(!(!b||M)){z(!0),a(`Triggering ${b.name}...`,"loading");try{let B=await T(`/task-templates/${b.id}/run`,{method:"POST"});a(`Triggered: ${b.name} (${B.executionId})`,"success")}catch(B){a(`Trigger failed: ${B instanceof Error?B.message:String(B)}`,"error")}finally{z(!1)}}},[t,f,M,a]),p=ct(async()=>{let b=t[f];if(!b||U)return;if(b.trigger?.type!=="cron"&&b.trigger?.type!=="event"){a("Toggle not applicable for manual triggers","error");return}let B=!b.enabled;D(!0),a(`${b.name} \u2192 ${B?"enabling":"disabling"}...`,"loading");try{await T(`/task-templates/${b.id}`,{method:"PATCH",body:{enabled:B}}),o(_=>_.map(ne=>ne.id===b.id?{...ne,enabled:B}:ne)),a(`${b.name} ${B?"enabled":"disabled"}`,"success")}catch(_){a(`Toggle failed: ${_ instanceof Error?_.message:String(_)}`,"error")}finally{D(!1)}},[t,f,U,a]),I=ct(async()=>{let b=t[f];if(b)try{await T(`/task-templates/${b.id}`,{method:"DELETE"}),a(`Deleted: ${b.name}`,"success"),H(),l(B=>Math.max(0,Math.min(B,t.length-2)))}catch(B){a(`Delete failed: ${B instanceof Error?B.message:String(B)}`,"error")}},[t,f,H]),L=ct(()=>{let b=t[f];b&&(x(b.id),m({name:b.name,triggerType:b.trigger?.type??"manual",cron:b.trigger?.cron??"",stepPrompt:b.steps?.[0]?.prompt??""}),y("name"),s("edit"))},[t,f]),_e=ct(async()=>{let b={name:r.name,trigger:{type:r.triggerType,...r.triggerType==="cron"?{cron:r.cron}:{}},steps:[{id:"step-1",prompt:r.stepPrompt}],enabled:!0};try{i==="create"?(await T("/task-templates",{method:"POST",body:b}),a(`Created: ${r.name}`,"success")):i==="edit"&&u&&(await T(`/task-templates/${u}`,{method:"PATCH",body:b}),a(`Updated: ${r.name}`,"success"))}catch(B){a(`Save failed: ${B instanceof Error?B.message:String(B)}`,"error")}s("list"),m({...Ot}),x(null),H()},[r,i,u,H]);return ln((b,B)=>{if(w){if(B.escape){s("list"),m({...Ot}),x(null);return}if(B.return){let _=["name","triggerType","cron","stepPrompt"],ne=_.indexOf(d);if(ne<_.length-1){let je=ne+1;if(_[je]==="cron"&&r.triggerType!=="cron"&&je++,je<_.length){y(_[je]);return}}_e();return}if(B.tab&&d==="triggerType"){m(_=>{let ne=to.indexOf(_.triggerType);return{..._,triggerType:to[(ne+1)%to.length]}});return}return}if(B.escape||b==="q"){e();return}if(B.upArrow){l(_=>Math.max(0,_-1));return}if(B.downArrow){l(_=>Math.min(t.length-1,_+1));return}if(b==="t"){S();return}if(b==="d"){I();return}if(b==="e"){L();return}if(b==="c"){m({...Ot}),y("name"),s("create");return}if(b==="s"||b===" "){p();return}b==="r"&&(H(),P())}),c?j(K,{dimColor:!0,children:"Loading templates..."}):w?se(xe,{flexDirection:"column",children:[se(K,{bold:!0,children:[i==="create"?"Create Template":"Edit Template"," (Esc to cancel)"]}),se(xe,{marginTop:1,flexDirection:"column",children:[se(xe,{children:[se(K,{bold:d==="name",color:d==="name"?"cyan":void 0,children:["Name:"," "]}),d==="name"?j(eo,{value:r.name,onChange:b=>m(B=>({...B,name:b})),placeholder:"template name"}):j(K,{children:r.name||"(empty)"})]}),se(xe,{children:[se(K,{bold:d==="triggerType",color:d==="triggerType"?"cyan":void 0,children:["Trigger:"," "]}),j(K,{children:r.triggerType}),d==="triggerType"&&j(K,{dimColor:!0,children:" (Tab to cycle, Enter to continue)"})]}),r.triggerType==="cron"&&se(xe,{children:[se(K,{bold:d==="cron",color:d==="cron"?"cyan":void 0,children:["Cron:"," "]}),d==="cron"?j(eo,{value:r.cron,onChange:b=>m(B=>({...B,cron:b})),placeholder:"*/5 * * * *"}):j(K,{children:r.cron||"(empty)"})]}),se(xe,{children:[se(K,{bold:d==="stepPrompt",color:d==="stepPrompt"?"cyan":void 0,children:["Step Prompt:"," "]}),d==="stepPrompt"?j(eo,{value:r.stepPrompt,onChange:b=>m(B=>({...B,stepPrompt:b})),placeholder:"What should this template do?"}):j(K,{children:r.stepPrompt||"(empty)"})]})]}),j(xe,{marginTop:1,children:j(K,{dimColor:!0,children:"Enter: next field / submit | Esc: cancel"})})]}):se(xe,{flexDirection:"column",children:[se(K,{bold:!0,children:["Automations (",t.length,") (Esc to go back)"]}),n&&j(xe,{marginTop:1,children:se(K,{color:n.type==="success"?"green":n.type==="error"?"red":"gray",children:[n.type==="success"?"\u2713 ":n.type==="error"?"\u2717 ":"\u2192 ",n.text]})}),t.length===0?j(xe,{marginTop:1,children:j(K,{dimColor:!0,children:"No templates found. Press c to create one."})}):j(xe,{marginTop:1,flexDirection:"column",children:t.map((b,B)=>{let _=B===f,ne=b.trigger?.type==="cron"&&b.trigger?.cron?un(b.trigger.cron):"";return se(xe,{children:[j(K,{color:_?"cyan":void 0,bold:_,children:_?"> ":" "}),j(K,{color:_?"cyan":void 0,bold:_,children:Vt(b.name,24)}),j(K,{dimColor:!0,children:Vt(b.trigger?.type,10)}),b.trigger?.type!=="cron"&&b.trigger?.type!=="event"?j(K,{dimColor:!0,children:Vt("\u2014",6)}):j(K,{color:b.enabled?"green":"gray",children:Vt(b.enabled?"on":"off",6)}),ne&&se(K,{dimColor:!0,children:["next: ",ne]})]},b.id)})}),j(xe,{marginTop:1,children:j(K,{dimColor:!0,children:"t:trigger s:toggle d:delete e:edit c:create r:refresh"})})]})}function Vt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as et,Text as Te,useInput as mn}from"ink";import gn from"ink-text-input";import{useEffect as fn,useState as dt,useCallback as $o}from"react";import{jsx as de,jsxs as rt}from"react/jsx-runtime";function Oo({onBack:e}){let[t,o]=dt([]),[c,g]=dt(""),[f,l]=dt(!0),[i,s]=dt(!1),[r,m]=dt(""),[d,y]=dt(null),u=$o(()=>{l(!0),T("/webhooks").then(({webhooks:n,auth:a})=>{o(n),g(a),l(!1)}).catch(()=>l(!1))},[]);fn(()=>{u()},[u]);let x=$o(async n=>{if(n.trim())try{let a=await T(`/webhooks/${encodeURIComponent(n.trim())}`,{method:"POST"});y(`Triggered: ${a.executionId}`)}catch(a){y(`Trigger failed: ${a instanceof Error?a.message:String(a)}`)}},[]);return mn((n,a)=>{if(i){if(a.escape){s(!1),m("");return}if(a.return){x(r),s(!1),m("");return}return}if(a.escape||n==="q"){e();return}if(n==="t"){s(!0),m(""),y(null);return}n==="r"&&(u(),y(null))}),f?de(Te,{dimColor:!0,children:"Loading webhooks..."}):rt(et,{flexDirection:"column",children:[rt(Te,{bold:!0,children:["Webhooks (",t.length,") (Esc to go back)"]}),rt(Te,{dimColor:!0,children:["Auth: ",c]}),d&&de(et,{marginTop:1,children:de(Te,{color:"yellow",children:d})}),i&&rt(et,{marginTop:1,children:[de(Te,{bold:!0,color:"cyan",children:"Trigger webhook: "}),de(gn,{value:r,onChange:m,placeholder:"webhook name or ID"}),de(Te,{dimColor:!0,children:" (Enter to trigger, Esc to cancel)"})]}),t.length===0?de(et,{marginTop:1,children:de(Te,{dimColor:!0,children:"No webhooks available. Create templates with triggers to expose webhooks."})}):rt(et,{marginTop:1,flexDirection:"column",children:[de(et,{children:rt(Te,{bold:!0,children:[ut("NAME",24),ut("DESCRIPTION",36),ut("TRIGGER",28),"TAGS"]})}),t.map(n=>rt(et,{children:[de(Te,{children:ut(n.displayName,24)}),de(Te,{dimColor:!0,children:ut(pn(n.description??"",34),36)}),de(Te,{dimColor:!0,children:ut(n.trigger,28)}),de(Te,{dimColor:!0,children:n.tags?.join(", ")??""})]},n.name))]}),de(et,{marginTop:1,children:de(Te,{dimColor:!0,children:"t:trigger r:refresh"})})]})}function ut(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function pn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as Le,Text as ee,useInput as xn}from"ink";import Tn from"ink-text-input";import{useEffect as Vo,useState as Ge,useCallback as oo}from"react";import{jsx as te,jsxs as ke}from"react/jsx-runtime";function hn(e){return e>=4?"red":e===3?"yellow":"gray"}function yn(e){return e>=4?"HIGH":e===3?"MED ":"LOW "}function bn(e){return new Date(e).toLocaleDateString()}function Uo({onBack:e}){let[t,o]=Ge([]),[c,g]=Ge(0),[f,l]=Ge([]),[i,s]=Ge(!0),[r,m]=Ge(!1),[d,y]=Ge(""),[u,x]=Ge("all"),[n,a]=Ge(null),[P,M]=Ge(!1),z=oo(()=>{T("/agents").then(({agents:p})=>{o(p),s(!1)}).catch(()=>s(!1))},[]);Vo(()=>{z()},[z]);let U=t[c],D=oo(()=>{U&&(M(!1),T(`/memories/${U.id}`).then(({memories:p})=>{l(p),a(null)}).catch(p=>a(`Failed: ${p instanceof Error?p.message:String(p)}`)))},[U]);Vo(()=>{U&&D()},[U,D]);let H=oo(async p=>{if(!(!U||!p.trim()))try{let I=await T("/memories/query",{method:"POST",body:{agentId:U.id,prompt:p.trim()}});l(I.memories),M(!0),a(`Search: ${I.count} results`)}catch(I){a(`Search failed: ${I instanceof Error?I.message:String(I)}`)}},[U]),w=r,S=f.filter(p=>u==="all"?!0:u==="high"?p.importance>3:u==="medium"?p.importance===3:p.importance<3);return xn((p,I)=>{if(w){if(I.escape){m(!1),y("");return}if(I.return){H(d),m(!1),y("");return}return}if(I.escape||p==="q"){e();return}if(p==="a"){g(L=>(L+1)%Math.max(1,t.length));return}if(I.leftArrow){g(L=>(L-1+t.length)%Math.max(1,t.length));return}if(I.rightArrow){g(L=>(L+1)%Math.max(1,t.length));return}if(p==="s"){m(!0),y(""),a(null);return}if(p==="h"){x(L=>L==="high"?"all":"high");return}if(p==="m"){x(L=>L==="medium"?"all":"medium");return}if(p==="l"){x(L=>L==="low"?"all":"low");return}p==="r"&&D()}),i?te(ee,{dimColor:!0,children:"Loading agents..."}):t.length===0?ke(Le,{flexDirection:"column",children:[te(ee,{dimColor:!0,children:"No agents found"}),te(ee,{dimColor:!0,children:"Press Esc to go back"})]}):ke(Le,{flexDirection:"column",children:[te(ee,{bold:!0,children:"Memories (Esc to go back)"}),ke(Le,{marginTop:1,children:[te(ee,{children:"Agent: "}),te(ee,{bold:!0,color:"cyan",children:U?.name??"?"}),ke(ee,{dimColor:!0,children:[" (",c+1,"/",t.length,") [a/arrows to switch]"]})]}),te(Le,{children:ke(ee,{dimColor:!0,children:["Filter: ",u==="all"?"all":u," | ",P?"search results":"all memories"," (",S.length,")"]})}),n&&te(Le,{children:te(ee,{color:"yellow",children:n})}),r&&ke(Le,{marginTop:1,children:[te(ee,{bold:!0,color:"cyan",children:"Search: "}),te(Tn,{value:d,onChange:y,placeholder:"search query..."}),te(ee,{dimColor:!0,children:" (Enter to search, Esc to cancel)"})]}),S.length===0?te(Le,{marginTop:1,children:ke(ee,{dimColor:!0,children:["No memories",u!=="all"?` matching filter '${u}'`:""]})}):te(Le,{marginTop:1,flexDirection:"column",children:S.map(p=>ke(Le,{marginBottom:0,children:[ke(ee,{color:hn(p.importance),bold:!0,children:[yn(p.importance)," "]}),te(ee,{dimColor:!0,children:qo(p.type??"?",12)}),te(ee,{dimColor:!0,children:qo(`\xD7${p.retrievedCount??0}`,5)}),ke(ee,{children:[Sn(p.content,55)," "]}),te(ee,{dimColor:!0,children:bn(p.createdAt)}),p.score!==void 0&&ke(ee,{dimColor:!0,children:[" (",p.score.toFixed(2),")"]})]},p.id))}),te(Le,{marginTop:1,children:te(ee,{dimColor:!0,children:"s:search h:high m:medium l:low a:agent r:refresh"})})]})}function qo(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}function Sn(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}import{Box as nt,Text as he,useInput as Cn}from"ink";import vn from"ink-text-input";import{useState as He,useEffect as Fo,useCallback as Wo}from"react";import{jsx as Pe,jsxs as Ne}from"react/jsx-runtime";var Go={Anthropic:["anthropic.apiKey","anthropic.baseUrl","anthropic.model","anthropic.defaultOpusModel","anthropic.defaultSonnetModel","anthropic.defaultHaikuModel","anthropic.smallFastModel"],Defaults:["defaults.model","defaults.effort","defaults.maxTurns","defaults.maxBudgetUsd","defaults.timeout"],Server:["server.port","server.host","server.apiKey","server.timezone"],Logging:["logging.level"],Evolution:["roles.evolution.triggerEvery","roles.evolution.reflectionThreshold"],Chat:["chat.sessionTimeoutMinutes","chat.maxSessionTurns","chat.autoTitle","chat.archiveExtractMemory"]},En={"anthropic.apiKey":"API Key","anthropic.baseUrl":"Base URL","anthropic.model":"Model","anthropic.defaultOpusModel":"Default Opus","anthropic.defaultSonnetModel":"Default Sonnet","anthropic.defaultHaikuModel":"Default Haiku","anthropic.smallFastModel":"Small Fast","defaults.model":"Default Model","defaults.effort":"Effort","defaults.maxTurns":"Max Turns","defaults.maxBudgetUsd":"Max Budget (USD)","defaults.timeout":"Timeout (sec)","server.port":"Port","server.host":"Host","server.apiKey":"API Key","server.timezone":"Timezone","logging.level":"Log Level","roles.evolution.triggerEvery":"Evolution Trigger Every","chat.sessionTimeoutMinutes":"Session Timeout (min)","chat.maxSessionTurns":"Max Session Turns","chat.autoTitle":"Auto Title","chat.archiveExtractMemory":"Archive Extract Memory","roles.evolution.reflectionThreshold":"Reflection Threshold"};function Ho({onBack:e}){let{state:t}=Xe(),[o,c]=He({}),[g,f]=He([]),[l,i]=He(null),[s,r]=He("view"),[m,d]=He(0),[y,u]=He(""),[x,n]=He(null),[a,P]=He(!1),[M,z]=He([]),U=Object.values(Go).flat(),D=Wo(()=>{T("/config").then(S=>{c(S.config),f(S.mutable)}).catch(S=>i(S.message)),T("/config/env-diff").then(S=>{z(S.diffs)}).catch(()=>{})},[]);Fo(()=>{D()},[D]),Fo(()=>{t.configVersion>0&&D()},[t.configVersion,D]);let H=Wo(async()=>{let S=U[m];if(S){P(!0),n(null);try{let p=y,I=o[S];if(I&&typeof I.value=="number"&&(p=Number(y),isNaN(p))){n("Invalid number"),P(!1);return}let L=await T("/config",{method:"PATCH",body:{[S]:p}});L.updated.length>0&&(n(`Updated: ${S}`),D()),L.errors.length>0&&n(L.errors[0]),r("view")}catch(p){n(`Failed: ${p instanceof Error?p.message:String(p)}`)}finally{P(!1)}}},[U,m,y,o,D]);if(Cn((S,p)=>{if(s==="edit"){if(p.escape){r("view");return}return}if(p.escape||S==="q"){e();return}if(p.upArrow&&m>0&&d(I=>I-1),p.downArrow&&m<U.length-1&&d(I=>I+1),p.return||S==="e"){let I=U[m],L=o[I];L&&L.mutable?(u(String(L.value??"")),r("edit"),n(null)):L&&!L.mutable&&n("This setting requires a restart to change")}S==="r"&&(D(),n("Refreshed")),S==="s"&&M.length>0&&T("/config/sync-to-env",{method:"POST"}).then(()=>{n("Synced to .env"),z([]),D()}),S==="l"&&M.length>0&&T("/config/load-from-env",{method:"POST"}).then(()=>{n("Loaded from .env"),D()})}),l)return Ne(nt,{flexDirection:"column",children:[Ne(he,{color:"red",children:["Failed to load config: ",l]}),Pe(he,{dimColor:!0,children:"Press Esc or q to return"})]});let w=0;return Ne(nt,{flexDirection:"column",children:[Pe(he,{bold:!0,children:"Settings"}),x&&Pe(he,{color:x.startsWith("Failed")||x.startsWith("This setting")?"yellow":"green",children:x}),M&&M.length>0&&Ne(nt,{flexDirection:"column",marginBottom:1,children:[Ne(he,{color:"yellow",children:[".env differs from DB (",M.length," key(s)): ",M.map(S=>S.envKey).join(", ")]}),Pe(he,{dimColor:!0,children:"s:sync DB\u2192.env l:load .env\u2192DB"})]}),Pe(nt,{marginTop:1,flexDirection:"column",children:Object.entries(Go).map(([S,p])=>Ne(nt,{marginBottom:1,flexDirection:"column",children:[Pe(he,{bold:!0,color:"cyan",children:S}),p.map(I=>{let L=o[I],b=w++===m,B=g.includes(I),_=En[I]??I,ne=L?String(L.value??""):"...";return s==="edit"&&b?Ne(nt,{children:[Ne(he,{color:"cyan",children:["> ",_,": "]}),Pe(vn,{value:y,onChange:u,onSubmit:()=>{H()}}),a&&Pe(he,{color:"yellow",children:" saving..."})]},I):Ne(nt,{children:[Ne(he,{color:b?"cyan":"white",children:[b?"> ":" ",B?" ":"\u{1F512} ",_,": "," "]}),Pe(he,{color:B?"white":"gray",children:ne}),!B&&Pe(he,{dimColor:!0,children:" (restart required)"})]},I)})]},S))}),Pe(he,{dimColor:!0,children:"Enter/e:edit r:refresh Esc/q:back"})]})}import{Box as st,Text as ue,useInput as Bn}from"ink";import{useEffect as wn,useState as ro,useCallback as In}from"react";import{jsx as ie,jsxs as gt}from"react/jsx-runtime";function Ko({onBack:e}){let[t,o]=ro([]),[c,g]=ro(!0),[f,l]=ro(0),{message:i,setMessage:s,clearMessage:r}=Ze(),m=In(()=>{g(!0),T("/plugins").then(({plugins:d})=>{o(d),g(!1)}).catch(()=>g(!1))},[]);return wn(()=>{m()},[m]),Bn((d,y)=>{if(y.escape||d==="q"){e();return}if(y.upArrow){l(u=>Math.max(0,u-1));return}if(y.downArrow){l(u=>Math.min(t.length-1,u+1));return}d==="r"&&(m(),r())}),c?ie(ue,{dimColor:!0,children:"Loading plugins..."}):gt(st,{flexDirection:"column",children:[gt(ue,{bold:!0,children:["Plugins (",t.length,") (Esc to go back)"]}),i&&ie(st,{marginTop:1,children:gt(ue,{color:i.type==="success"?"green":i.type==="error"?"red":"gray",children:[i.type==="success"?"\u2713 ":i.type==="error"?"\u2717 ":"\u2192 ",i.text]})}),t.length===0?ie(st,{marginTop:1,children:ie(ue,{dimColor:!0,children:"No plugins installed."})}):gt(st,{marginTop:1,flexDirection:"column",children:[gt(st,{children:[ie(ue,{dimColor:!0,children:" "}),ie(ue,{dimColor:!0,children:mt("Name",24)}),ie(ue,{dimColor:!0,children:mt("Scope",8)}),ie(ue,{dimColor:!0,children:mt("User",6)}),ie(ue,{dimColor:!0,children:"Path"})]}),t.map((d,y)=>{let u=y===f,x=d.id.split("@")[0];return gt(st,{children:[ie(ue,{color:u?"cyan":void 0,bold:u,children:u?"> ":" "}),ie(ue,{color:u?"cyan":void 0,bold:u,children:mt(x,24)}),ie(ue,{color:u?"cyan":void 0,bold:u,children:mt(d.scope,8)}),ie(ue,{color:d.globalEnabled?"green":"gray",children:mt(d.globalEnabled?"on":"off",6)}),ie(ue,{dimColor:!0,children:d.installPath})]},d.id)})]}),ie(st,{marginTop:1,children:ie(ue,{dimColor:!0,children:"r:refresh"})})]})}function mt(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Box as Ut,Text as jo,useInput as kn}from"ink";import{useState as Pn}from"react";import{jsx as ft,jsxs as no}from"react/jsx-runtime";var An=[{key:"1",id:"tasks",label:"Tasks"},{key:"2",id:"automations",label:"Automations"},{key:"3",id:"goals",label:"Goals"}];function Qo({onBack:e}){let[t,o]=Pn("tasks");return kn((c,g)=>{if(g.escape||c==="q"){e();return}if(c==="1"){o("tasks");return}if(c==="2"){o("automations");return}if(c==="3"){o("goals");return}}),no(Ut,{flexDirection:"column",children:[no(Ut,{gap:1,marginBottom:1,children:[An.map(c=>{let g=t===c.id;return ft(Ut,{children:no(jo,{color:g?"cyan":"gray",bold:g,underline:g,children:["[",c.key,":",c.label,"]"]})},c.id)}),ft(Ut,{flexGrow:1}),ft(jo,{dimColor:!0,children:"Esc: back"})]}),t==="tasks"&&ft(Nt,{onBack:e}),t==="automations"&&ft(qt,{onBack:e}),t==="goals"&&ft($t,{onBack:e})]})}import{Box as G,Text as O,useInput as Dn}from"ink";import{useEffect as Rn,useState as Bt}from"react";import{jsx as k,jsxs as re}from"react/jsx-runtime";var Xo={connected:"green",connecting:"yellow",disconnected:"gray",error:"red"};function zo({onBack:e}){let[t,o]=Bt([]),[c,g]=Bt(!0),[f,l]=Bt(0),[i,s]=Bt(null),[r,m]=Bt("");Rn(()=>{d()},[]);async function d(){try{let x=await T("/channels");o(x.channels)}catch{}g(!1)}async function y(x){if(t.find(a=>a.id===x)?.platform==="wechat")try{m("Starting WeChat QR login...");let a=await T(`/channels/${x}/wechat/qr-start`,{method:"POST"});if(a.qrcodeUrl){m(`Scan QR: ${a.qrcodeUrl}
6
+ Waiting for scan...`);let P=await T(`/channels/${x}/wechat/qr-wait`,{method:"POST",body:{sessionKey:a.sessionKey,timeoutMs:12e4}});m(P.message)}else m(a.message);d()}catch{m("WeChat connect failed")}else try{await T(`/channels/${x}/connect`,{method:"POST"}),m("Connecting..."),d()}catch{m("Connect failed")}}async function u(x){try{await T(`/channels/${x}/disconnect`,{method:"POST"}),m("Disconnected"),d()}catch{m("Disconnect failed")}}return Dn((x,n)=>{if(i){if(n.escape||x==="q"){s(null);return}if(x==="c"){y(i.id);return}if(x==="d"){u(i.id);return}return}if(n.escape){e();return}if(n.upArrow){l(a=>Math.max(0,a-1));return}if(n.downArrow){l(a=>Math.min(t.length-1,a+1));return}if(n.return&&t[f]){s(t[f]),m("");return}}),c?k(G,{flexDirection:"column",children:k(O,{dimColor:!0,children:"Loading channels..."})}):i?re(G,{flexDirection:"column",children:[re(G,{marginBottom:1,children:[re(O,{bold:!0,children:["Channel: ",i.name]}),k(O,{dimColor:!0,children:" (Esc to go back)"})]}),re(G,{flexDirection:"column",gap:0,children:[re(O,{children:["ID: ",i.id]}),re(O,{children:["Platform: ",i.platform]}),re(O,{children:["Status: ",k(O,{color:Xo[i.status]??"white",children:i.status})]}),re(O,{children:["Enabled: ",i.enabled?"yes":"no"]}),re(O,{children:["Messages: ",i.messageCount]}),re(O,{children:["Config: ",JSON.stringify(i.config)]})]}),k(G,{marginTop:1,children:k(O,{dimColor:!0,children:"[c] Connect [d] Disconnect [Esc] Back"})}),r&&k(O,{color:"yellow",children:r})]}):re(G,{flexDirection:"column",children:[re(G,{marginBottom:1,children:[k(O,{bold:!0,children:"Channels"}),re(O,{dimColor:!0,children:[" (",t.length," total) "]}),k(O,{dimColor:!0,children:"Arrow keys to select, Enter for detail, Esc to return"})]}),t.length===0?k(O,{dimColor:!0,children:"No channels configured. Add channels via API or config."}):re(G,{flexDirection:"column",children:[re(G,{children:[k(G,{width:3,children:k(O,{dimColor:!0,children:" "})}),k(G,{width:12,children:k(O,{bold:!0,dimColor:!0,children:"ID"})}),k(G,{width:16,children:k(O,{bold:!0,dimColor:!0,children:"Name"})}),k(G,{width:12,children:k(O,{bold:!0,dimColor:!0,children:"Platform"})}),k(G,{width:14,children:k(O,{bold:!0,dimColor:!0,children:"Status"})}),k(G,{width:10,children:k(O,{bold:!0,dimColor:!0,children:"Enabled"})}),k(G,{width:10,children:k(O,{bold:!0,dimColor:!0,children:"Messages"})})]}),t.map((x,n)=>re(G,{children:[k(G,{width:3,children:k(O,{children:n===f?">":" "})}),k(G,{width:12,children:k(O,{inverse:n===f,children:x.id.slice(0,8)})}),k(G,{width:16,children:k(O,{children:x.name})}),k(G,{width:12,children:k(O,{children:x.platform})}),k(G,{width:14,children:re(O,{color:Xo[x.status]??"white",children:[x.status==="connected"?"\u25CF":x.status==="error"?"\u2717":"\u25CB"," ",x.status]})}),k(G,{width:10,children:k(O,{color:x.enabled?"green":"gray",children:x.enabled?"yes":"no"})}),k(G,{width:10,children:k(O,{children:x.messageCount})})]},x.id))]})]})}import{Box as pt,Text as Ke,useInput as Ln}from"ink";import{useEffect as Nn,useState as It,useCallback as _n}from"react";import{Box as V,Text as E,useInput as Mn}from"ink";import Ft from"ink-text-input";import{useEffect as Yo,useState as ae,useCallback as wt}from"react";lo();import{Fragment as Jo,jsx as v,jsxs as R}from"react/jsx-runtime";function Zo({roleId:e,onBack:t}){let[o,c]=ae(null),[g,f]=ae([]),[l,i]=ae(!0),[s,r]=ae("view"),[m,d]=ae(""),[y,u]=ae(0),[x,n]=ae(""),[a,P]=ae([]),[M,z]=ae(0),[U,D]=ae(new Set),[H,w]=ae("inline"),[S,p]=ae(""),[I,L]=ae(""),[_e,b]=ae([]),[B,_]=ae(new Set),[ne,je]=ae(0),{message:W,setMessage:Y}=Ze(),me=wt(()=>{i(!0),T(`/roles/${e}`).then(({role:h,boundPlugins:N})=>{c(h),f(N??[]),d(h.cagPrompt??""),D(new Set(h.allowedTools??[])),w(h.executionMode??"inline"),p(h.model??""),L(h.maxBudgetUsd!=null?String(h.maxBudgetUsd):""),i(!1)}).catch(()=>i(!1))},[e]);Yo(()=>{me()},[me]),Yo(()=>{w(o?.executionMode??"inline"),p(o?.model??""),L(o?.maxBudgetUsd!=null?String(o?.maxBudgetUsd):"")},[o?.id,o?.executionMode,o?.model,o?.maxBudgetUsd]);let or=wt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{cagPrompt:m}}),Y("CAG prompt saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,m,me,Y]),rr=wt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{additionalDirectories:$e}}),Y("Directories saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,me,Y]),nr=wt(async()=>{if(o)try{await T(`/roles/${o.id}`,{method:"PATCH",body:{allowedTools:Array.from(U)}}),Y("Tool permissions saved","success"),r("view"),me()}catch(h){Y(`Save failed: ${h instanceof Error?h.message:String(h)}`,"error")}},[o,U,me,Y]),sr=wt(async()=>{if(!o)return;let h={executionMode:H};S!==void 0&&(h.model=S);let N=parseFloat(I);isNaN(N)||(h.maxBudgetUsd=N);try{await T(`/roles/${o.id}`,{method:"PATCH",body:h}),Y("Execution config saved","success"),r("view"),me()}catch(C){Y(`Save failed: ${C instanceof Error?C.message:String(C)}`,"error")}},[o,H,S,I,me,Y]),$e=o?.additionalDirectories??[];return Mn((h,N)=>{if(N.escape){r("view");return}if(h==="r"){me();return}switch(s){case"view":{if(h==="c"){r("edit-cag");return}if(h==="d"){r("edit-dirs"),u(0),n("");return}if(h==="t"){r("edit-tools");return}if(h==="x"){r("edit-exec");return}if(h==="h"){T("/channels?enabled=true").then(({channels:C})=>{b(C.map(J=>({name:J.name,id:J.id}))),_(new Set(o?.allowedChannels??[])),je(0),r("edit-channels")}).catch(()=>Y("Failed to load channels","error"));return}if(h==="i"){if(!o)return;let C=!o.inheritUserSettings;T(`/roles/${o.id}`,{method:"PATCH",body:{inheritUserSettings:C}}).then(()=>{Y(`Inherit user settings: ${C?"ON":"OFF"}`,"success"),me()}).catch(()=>Y("Failed to toggle","error"));return}break}case"edit-cag":{if(N.ctrl&&h==="s"){or();return}break}case"edit-dirs":{if(h==="s"){rr();return}if(h==="a"){r("edit-dirs-add");return}if(h==="x"&&$e.length>0){c(C=>C&&{...C,additionalDirectories:$e.filter((J,Qe)=>Qe!==y)}),u(C=>Math.max(0,Math.min(C,$e.length-2)));return}if(N.upArrow){u(C=>Math.max(0,C-1));return}if(N.downArrow){u(C=>Math.min($e.length-1,C+1));return}break}case"edit-dirs-add":{if(N.escape){r("edit-dirs"),n(""),P([]);return}if(N.return&&a.length>0){let C=a[M];C&&(n(C.endsWith("/")?C:C+"/"),P([]));return}if(N.return){let C=x.trim();C&&C.startsWith("/")?(c(J=>J&&{...J,additionalDirectories:[...J.additionalDirectories??[],{path:C}]}),n(""),P([]),r("edit-dirs")):Y("Path must be absolute (must start with /)","error");return}if(N.tab){let C=x.trim();if(!C||!C.startsWith("/"))return;T(`/fs/suggest-dirs?prefix=${encodeURIComponent(C)}`).then(({suggestions:J})=>{J.length===1?(n(J[0]+"/"),P([])):J.length>1&&(P(J),z(0))}).catch(()=>{P([])});return}if(N.upArrow&&a.length>0){z(C=>Math.max(0,C-1));return}if(N.downArrow&&a.length>0){z(C=>Math.min(a.length-1,C+1));return}break}case"edit-tools":{if(h==="s"){nr();return}let C=parseInt(h,10)-1;if(!isNaN(C)&&C>=0&&C<At.length){let J=At[C];D(Qe=>{let Pt=new Set(Qe);return Pt.has(J)?Pt.delete(J):Pt.add(J),Pt});return}break}case"edit-exec":{if(h==="s"){sr();return}if(N.tab){w(C=>C==="inline"?"isolated":"inline");return}break}case"edit-channels":{if(h==="s"){if(!o)return;let C=B.size>0?Array.from(B):[];T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:C}}).then(()=>{Y("Channels saved","success"),r("view"),me()}).catch(()=>Y("Save failed","error"));return}if(h==="u"){if(!o)return;T(`/roles/${o.id}`,{method:"PATCH",body:{allowedChannels:null}}).then(()=>{Y("Channels: unrestricted","success"),r("view"),me()}).catch(()=>Y("Save failed","error"));return}if(h===" "){let C=_e[ne];C&&_(J=>{let Qe=new Set(J);return Qe.has(C.name)?Qe.delete(C.name):Qe.add(C.name),Qe});return}if(N.upArrow){je(C=>Math.max(0,C-1));return}if(N.downArrow){je(C=>Math.min(_e.length-1,C+1));return}break}}}),l?v(E,{dimColor:!0,children:"Loading role..."}):o?s==="edit-cag"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"CAG Prompt \u2014 Edit (Esc cancel, Ctrl+S save)"}),v(Ft,{value:m,onChange:d,placeholder:"Character And Guidance prompt..."}),W&&v(V,{marginTop:1,children:v(E,{color:W.type==="error"?"red":"green",children:W.text})})]}):s==="edit-dirs-add"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Add Directory (Enter confirm, Esc cancel, Tab:complete)"}),v(Ft,{value:x,onChange:h=>{n(h),P([])},placeholder:"/absolute/path/to/directory"}),a.length>0&&R(V,{flexDirection:"column",marginTop:1,children:[a.map((h,N)=>R(E,{color:N===M?"cyan":void 0,dimColor:N!==M,children:[N===M?"> ":" ",h,"/"]},h)),v(E,{dimColor:!0,children:"\u2191\u2193 navigate, Enter select, Tab:confirm"})]}),W&&v(V,{marginTop:1,children:v(E,{color:W.type==="error"?"red":"green",children:W.text})})]}):s==="edit-dirs"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Additional Directories (\u2191\u2193 navigate, a:add x:remove s:save Esc:cancel)"}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})}),$e.length===0?v(E,{dimColor:!0,children:"No directories. Press a to add one."}):$e.map((h,N)=>R(V,{children:[v(E,{color:N===y?"cyan":void 0,bold:N===y,children:N===y?"> ":" "}),v(E,{color:N===y?"cyan":void 0,children:h.path})]},h.path))]}):s==="edit-tools"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Tool Permissions \u2014 toggle with number key (s:save Esc:cancel)"}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})}),At.map((h,N)=>{let C=U.has(h);return R(V,{children:[R(E,{dimColor:!0,children:[N+1,". "]}),v(E,{color:C?"green":"red",children:C?"[ON] ":"[OFF] "}),v(E,{children:h})]},h)})]}):s==="edit-exec"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Execution Config (Tab:cycle mode, Enter on field, s:save Esc:cancel)"}),R(V,{children:[v(E,{bold:!0,children:" Mode: "}),v(E,{color:"cyan",children:H}),v(E,{dimColor:!0,children:" (Tab to toggle)"})]}),R(V,{children:[v(E,{bold:!0,children:" Model: "}),v(Ft,{value:S,onChange:p,placeholder:"sonnet, opus, haiku, or blank"})]}),R(V,{children:[v(E,{bold:!0,children:" Max Budget (USD): "}),v(Ft,{value:I,onChange:L,placeholder:"0 = unlimited"})]}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})})]}):s==="edit-channels"?R(V,{flexDirection:"column",children:[v(E,{bold:!0,children:"Allowed Channels (Space:toggle, u:unrestricted, s:save, Esc:cancel)"}),_e.length===0?v(E,{dimColor:!0,children:"No channels available"}):_e.map((h,N)=>R(V,{children:[R(E,{children:[N===ne?">":" "," "]}),R(E,{color:B.has(h.name)?"green":"gray",children:["[",B.has(h.name)?"x":" ","] ",h.name]})]},h.id)),R(E,{dimColor:!0,children:["Selected: ",B.size>0?Array.from(B).join(", "):"none (= block all)"]}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})})]}):R(V,{flexDirection:"column",children:[R(E,{bold:!0,children:["Role: ",o.name]}),R(V,{children:[v(E,{dimColor:!0,children:"ID: "}),v(E,{children:o.id})]}),R(V,{children:[v(E,{dimColor:!0,children:"Status: "}),v(E,{color:o.status==="active"?"green":o.status==="probation"?"yellow":"red",children:o.status})]}),o.performanceScore!=null&&R(V,{children:[v(E,{dimColor:!0,children:"Score: "}),R(E,{children:[(o.performanceScore*100).toFixed(0),"%"]})]}),R(V,{children:[v(E,{dimColor:!0,children:"Created: "}),v(E,{children:new Date(o.createdAt).toLocaleString()})]}),R(V,{children:[v(E,{dimColor:!0,children:"Execution: "}),R(E,{children:[o.executionMode??"inline"," / ",o.model??"inherit"," / ",o.maxBudgetUsd!=null?`$${o.maxBudgetUsd}`:"no limit"]})]}),$e.length>0&&R(Jo,{children:[v(E,{bold:!0,children:"Additional Directories:"}),$e.map(h=>R(E,{dimColor:!0,children:[" ",h.path]},h.path))]}),R(V,{children:[v(E,{dimColor:!0,children:"Channels: "}),v(E,{children:o.allowedChannels===void 0?"Unrestricted":o.allowedChannels.length===0?"Blocked":o.allowedChannels.join(", ")})]}),R(V,{children:[v(E,{dimColor:!0,children:"Inherit User Settings: "}),v(E,{color:o.inheritUserSettings?"green":"gray",children:o.inheritUserSettings?"Yes":"No"})]}),o.learnedRules.length>0&&R(Jo,{children:[v(E,{bold:!0,children:"Learned Rules:"}),o.learnedRules.map(h=>R(E,{dimColor:!0,children:[" - ",h]},h))]}),W&&v(V,{children:v(E,{color:W.type==="error"?"red":W.type==="success"?"green":"gray",children:W.text})}),v(V,{marginTop:1,children:v(E,{dimColor:!0,children:"c:CAG d:dirs t:tools x:exec h:channels i:inherit r:refresh Esc:back"})})]}):v(E,{dimColor:!0,children:"Role not found."})}import{jsx as Se,jsxs as Wt}from"react/jsx-runtime";function er({onBack:e}){let[t,o]=It([]),[c,g]=It(!0),[f,l]=It(0),[i,s]=It("list"),[r,m]=It(null),{message:d,setMessage:y,clearMessage:u}=Ze(),x=_n(()=>{g(!0),T("/roles").then(({roles:n})=>{o(n.map(a=>({id:a.id,name:a.name,status:a.status,performanceScore:a.performanceScore,createdAt:a.createdAt}))),g(!1)}).catch(()=>g(!1))},[]);return Nn(()=>{x()},[x]),Ln((n,a)=>{if(a.escape||n==="q"){e();return}if(a.upArrow){l(P=>Math.max(0,P-1));return}if(a.downArrow){l(P=>Math.min(t.length-1,P+1));return}if(n==="r"&&(x(),u()),n===`
7
+ `||n==="o"||n==="e"){t.length>0&&(m(t[f].id),s("detail"));return}}),c?Se(Ke,{dimColor:!0,children:"Loading roles..."}):i==="detail"&&r?Se(Zo,{roleId:r,onBack:()=>s("list")}):Wt(pt,{flexDirection:"column",children:[Wt(Ke,{bold:!0,children:["Roles (",t.length,") (Esc to go back)"]}),d&&Se(pt,{marginTop:1,children:Wt(Ke,{color:d.type==="success"?"green":d.type==="error"?"red":"gray",children:[d.type==="success"?"\u2713 ":d.type==="error"?"\u2717 ":"\u2192 ",d.text]})}),t.length===0?Se(pt,{marginTop:1,children:Se(Ke,{dimColor:!0,children:"No roles found. Roles define agent behavior and bind plugins."})}):Se(pt,{marginTop:1,flexDirection:"column",children:t.map((n,a)=>{let P=a===f,M=n.performanceScore!=null?`${(n.performanceScore*100).toFixed(0)}%`:"\u2014";return Wt(pt,{children:[Se(Ke,{color:P?"cyan":void 0,bold:P,children:P?"> ":" "}),Se(Ke,{color:P?"cyan":void 0,bold:P,children:so(n.name,24)}),Se(Ke,{color:$n(n.status),children:so(n.status,12)}),Se(Ke,{dimColor:!0,children:so(M,8)})]},n.id)})}),Se(pt,{marginTop:1,children:Se(Ke,{dimColor:!0,children:"Enter/O/E:open Esc:back r:refresh"})})]})}function $n(e){return e==="active"?"green":e==="probation"?"yellow":e==="retired"||e==="dead"?"red":"gray"}function so(e,t){return e?e.length>=t?e:e+" ".repeat(t-e.length):" ".repeat(t)}import{Fragment as Wn,jsx as q,jsxs as Tt}from"react/jsx-runtime";function qn(){let{state:e,dispatch:t}=Xe(),{session:o,sendMessage:c,createNewSession:g,archiveCurrentSession:f}=To(),[l,i]=Vn([]);io(()=>{t({type:"SET_SESSION",session:o})},[o,t]),fo();let{events:s,isStreaming:r,clearEvents:m}=xo(e.activeTaskId),d=s[s.length-1],y=d?.type==="complete"&&!r,u=tr(null),x=tr("");io(()=>{x.current=s.filter(a=>a.type==="reasoning").map(a=>a.content).join("")},[s]),io(()=>{if(y&&e.activeTaskId!==u.current){u.current=e.activeTaskId;let a=d?.content||x.current;a&&i(P=>[...P,{role:"assistant",content:a}])}},[y,d,e.activeTaskId]);let n=async a=>{if(a.startsWith("/")){let M=a.slice(1),z={work:"work",tasks:"tasks",config:"config",evolution:"evolution",templates:"templates",memories:"memories",goals:"goals",strategies:"strategies",roles:"roles",settings:"settings",channels:"channels",plugins:"plugins",back:"chat"};M==="quit"&&process.exit(0);let U=z[M];if(U){t({type:"SET_VIEW",view:U});return}if(M==="new"){if(await f()){let H=await g();i([]),m(),H&&i([{role:"assistant",content:`Session archived. New session started: ${H.id.slice(0,8)}`}])}return}if(M==="session"){let D=o?`Session: ${o.id}
8
+ Turns: ${o.messageCount}
9
+ Last active: ${new Date(o.lastActiveAt).toLocaleString()}`:"No active session";i(H=>[...H,{role:"assistant",content:D}]);return}}i(M=>[...M,{role:"user",content:a}]),m();let P=await c(a);if(!P){i(M=>[...M,{role:"assistant",content:"Failed to send message. Server may be disconnected."}]);return}t({type:"SET_ACTIVE_TASK",taskId:P.taskId}),t({type:"TASK_SUBMITTED"})};return Tt(kt,{flexDirection:"column",paddingX:1,children:[q(ho,{}),Tt(kt,{flexGrow:1,flexDirection:"column",paddingY:1,children:[e.view==="chat"&&Tt(Wn,{children:[q(Eo,{messages:l}),q(So,{events:s,isStreaming:r}),!e.connected&&!e.serverUnreachable&&q(kt,{children:q(xt,{color:"red",children:"Server disconnected. Attempting to reconnect..."})}),e.serverUnreachable&&Tt(kt,{flexDirection:"column",children:[q(xt,{color:"red",bold:!0,children:"Server unreachable after 15s."}),q(xt,{dimColor:!0,children:"Check: adam server logs"}),q(xt,{dimColor:!0,children:"Type /quit to exit."})]})]}),e.view==="work"&&q(Qo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="tasks"&&q(Nt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="config"&&q(Do,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="evolution"&&q(Mo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="goals"&&q($t,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="strategies"&&q(No,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="templates"&&q(qt,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="webhooks"&&q(Oo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="memories"&&q(Uo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="plugins"&&q(Ko,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="roles"&&q(er,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="settings"&&q(Ho,{onBack:()=>t({type:"SET_VIEW",view:"chat"})}),e.view==="channels"&&q(zo,{onBack:()=>t({type:"SET_VIEW",view:"chat"})})]}),e.pendingPlanApproval?q(wo,{approval:e.pendingPlanApproval,onResolved:()=>t({type:"SET_PENDING_PLAN_APPROVAL",approval:null}),onTimeout:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:e.pendingPlanApproval.planId})}):e.pendingApproval?q(Bo,{approval:e.pendingApproval,onResolved:()=>t({type:"SET_PENDING_APPROVAL",approval:null})}):q(bo,{onSubmit:n}),e.planTimeoutNotice&&q(Un,{planId:e.planTimeoutNotice.planId,onDismiss:()=>t({type:"SET_PLAN_TIMEOUT_NOTICE",planId:null})})]})}function Un({planId:e,onDismiss:t}){return On(o=>{o==="d"&&t()}),Tt(kt,{borderStyle:"round",borderColor:"yellow",paddingX:1,children:[Tt(xt,{color:"yellow",children:["Plan ",e," was auto-denied after 300s timeout."]}),q(xt,{dimColor:!0,children:" [d] Dismiss"})]})}function Fn(){return q(go,{children:q(qn,{})})}export{Fn as default};
@@ -0,0 +1 @@
1
+ import{x as a,y as b}from"./chunk-2VKE7ONM.js";import"./chunk-5JLMSNIW.js";import"./chunk-IXF3XBGX.js";import"./chunk-AXMXXUPO.js";import"./chunk-KICPHTI2.js";import"./chunk-FUGJMHY4.js";import"./chunk-5ASEAZCR.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-2GXYBWLS.js";import"./chunk-WZOMGJSY.js";import"./chunk-WXN3PSVX.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-VF6GJGD6.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-U36NBCR3.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{b as createAdamTools,a as getToolsFingerprint};
@@ -0,0 +1,4 @@
1
+ import{b as y}from"./chunk-UOTDT2KY.js";import{b as m}from"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import{c as f}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var s=f("channels"),c=new Map,h=3e5,v=new Set(["telegram"]);function A(n){let a=n.trim().toLowerCase().match(/^(yes|y|是|允许|no|n|否|拒绝)\s+(\S+)$/);if(!a)return null;let[,p,d]=a,i=["yes","y","\u662F","\u5141\u8BB8"].includes(p);return{requestId:d,decision:i?"allow":"deny"}}function I(n){let r=m(n);return r?v.has(r.platform):!1}async function b(n,r,a,p,d,i=h){let e=a;c.set(e,{planId:a,taskId:p,channelId:n,chatId:r,requestId:e,timestamp:Date.now(),timeoutMs:i});let l=y(),o=I(n);if(o){let t=`\u{1F510} Plan approval requested
2
+
3
+ ${d.slice(0,200)}`;await l.send({channelId:n,chatId:r,content:t,messageType:"approval",replyMarkup:{inlineKeyboard:[[{text:"\u2705 Allow",callbackData:`yes ${e}`},{text:"\u274C Deny",callbackData:`no ${e}`}]]}})}else{let t=["\u{1F510} Plan approval requested",d.slice(0,200),"",`Reply 'yes ${e}' or 'no ${e}'`].join(`
4
+ `);await l.send({channelId:n,chatId:r,content:t,messageType:"approval"})}setTimeout(()=>{let t=c.get(e);if(t&&Date.now()-t.timestamp>=t.timeoutMs){c.delete(e),s.warn({requestId:e,taskId:p},"Approval timed out, auto-denying"),l.send({channelId:t.channelId,chatId:t.chatId,content:`\u23F0 Approval ${e} timed out (5 min). Plan denied.`,messageType:"approval"}).catch(u=>s.error({requestId:e,error:u},"Failed to notify timeout"));let g=process.env.ADAM_PORT??"7100";fetch(`http://localhost:${g}/tasks/${t.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:t.planId,decision:"deny"})}).catch(u=>s.error({requestId:e,error:u},"Failed to auto-deny"))}},i+1e3),s.info({channelId:n,chatId:r,planId:a,requestId:e,interactive:o},"Interactive approval sent to channel")}async function C(n,r,a,p){let i=A(p??a);if(!i)return!1;let{requestId:e,decision:l}=i,o=c.get(e);if(!o)return!1;if(o.channelId!==n||o.chatId!==r)return s.debug({requestId:e,expectedChannel:o.channelId,gotChannel:n},"Approval reply from different channel"),!1;c.delete(e),s.info({requestId:e,decision:l},"Channel approval reply received");try{let t=process.env.ADAM_PORT??"7100",g=await fetch(`http://localhost:${t}/tasks/${o.taskId}/approve-plan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({planId:o.planId,decision:l}),signal:AbortSignal.timeout(1e4)});g.ok||s.error({requestId:e,status:g.status},"Failed to forward approval to API")}catch(t){s.error({requestId:e,error:t},"Error forwarding approval to API")}return!0}function $(){return[...c.keys()]}export{$ as getPendingApprovalRequestIds,C as handleInboundForApproval,A as parseApprovalReply,b as sendApprovalToChannel};
@@ -0,0 +1 @@
1
+ import{a,b,c}from"./chunk-DT2LX4XI.js";import"./chunk-WXN3PSVX.js";import"./chunk-L7426WNY.js";import"./chunk-L7JP7DUO.js";import"./chunk-HAWA62R2.js";import"./chunk-VF6GJGD6.js";import"./chunk-T25NLVMY.js";import"./chunk-ETQ7KC73.js";import"./chunk-FYDFMYUP.js";import"./chunk-XNWZZYAV.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as BreeEngine,b as getBreeEngine,c as setBreeEngine};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f}from"./chunk-PQ7KPALO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-FCV2DPZQ.js";export{a as createChannel,e as deleteChannel,b as getChannel,d as listChannels,c as updateChannel,f as updateChannelStatus};
@@ -0,0 +1 @@
1
+ import{b as a,c as b,d as c}from"./chunk-2EP27EGS.js";import"./chunk-742NWPTQ.js";import"./chunk-PQ7KPALO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{c as channelRoutes,b as getChannelManager,a as setChannelManager};
@@ -1 +1 @@
1
- import{a as re,b,c as z,d as ie,e as se}from"./chunk-EJJDJY34.js";import{e as ne}from"./chunk-MMIO6BCA.js";import{c as f}from"./chunk-3DAK2XWP.js";import{z as c}from"zod/v4";import{v4 as Ut}from"uuid";import{randomUUID as ue}from"crypto";import We from"crypto";var oe="1.0.0",S="";function qe(e){let t=e.split(".").map(r=>parseInt(r,10)),i=t[0]??0,s=t[1]??0,n=t[2]??0;return(i&255)<<16|(s&255)<<8|n&255}var V=qe(oe),je=35e3,ae=15e3,ze=1e4;function P(){return{channel_version:oe}}function Ve(e){return e.endsWith("/")?e:`${e}/`}function Qe(){let e=We.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function Ge(e){let t={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":Qe(),"iLink-App-Id":S,"iLink-App-ClientVersion":String(V)};return e.token?.trim()&&(t.Authorization=`Bearer ${e.token.trim()}`),e.routeTag&&(t.SKRouteTag=e.routeTag),t}async function A(e){let t=Ve(e.baseUrl),i=new URL(e.endpoint,t),s=Ge({token:e.token,routeTag:e.routeTag,body:e.body}),n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs);try{let o=await fetch(i.toString(),{method:"POST",headers:s,body:e.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${e.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function de(e){let t=e.timeoutMs??je;try{let i=await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:t,label:"getUpdates"});return JSON.parse(i)}catch(i){if(i instanceof Error&&i.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw i}}async function v(e){await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ae,label:"sendMessage"})}async function ce(e){await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ze,label:"sendTyping"})}async function le(e){let t=await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ae,label:"getUploadUrl"});return JSON.parse(t)}var Ke=5*6e4,He=35e3,ge="3",y=new Map;function Q(e){return Date.now()-e.startedAt<Ke}function Xe(){for(let[e,t]of y)Q(t)||y.delete(e)}async function pe(e,t,i){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(t)}`,s),r={"iLink-App-Id":S};i&&(r.SKRouteTag=i);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function Je(e,t,i){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(t)}`,s),r={"iLink-App-Id":S,"iLink-App-ClientVersion":String(V)};i&&(r.SKRouteTag=i);let o=new AbortController,a=setTimeout(()=>o.abort(),He);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);let l=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(l)}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function me(e){let t=e.accountId||ue();Xe();let i=y.get(t);if(!e.force&&i&&Q(i)&&i.qrcodeUrl)return{qrcodeUrl:i.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:t};if(!e.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:t};try{let s=e.botType||ge,n=await pe(e.apiBaseUrl,s,e.routeTag),r={sessionKey:t,id:ue(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return y.set(t,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:t}}catch(s){return{message:`Failed to start login: ${String(s)}`,sessionKey:t}}}var Ye=3;async function fe(e){let t=y.get(e.sessionKey);if(!t)return{connected:!1,message:"No active login session. Start QR login first."};if(!Q(t))return y.delete(e.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let i=Math.max(e.timeoutMs??48e4,1e3),s=Date.now()+i,n=1;for(;Date.now()<s;){try{let r=await Je(e.apiBaseUrl,t.qrcode,e.routeTag);switch(t.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>Ye)return y.delete(e.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=e.botType||ge,a=await pe(e.apiBaseUrl,o,e.routeTag);t.qrcode=a.qrcode,t.qrcodeUrl=a.qrcode_img_content,t.startedAt=Date.now()}catch(o){return y.delete(e.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(y.delete(e.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(y.delete(e.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return y.delete(e.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return y.delete(e.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import k,{promises as Y}from"fs";import C from"path";import{homedir as Z}from"os";var O={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},F={NONE:0,USER:1,BOT:2},m={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},N={NEW:0,GENERATING:1,FINISH:2},ye={TYPING:1,CANCEL:2};var Ze=f("channels"),G=-14,$=3600*1e3,R=new Map;function he(e){let t=Date.now()+$;R.set(e,t),Ze.info({channelId:e},`Session paused until ${new Date(t).toISOString()} (${$/1e3}s)`)}function L(e){let t=R.get(e);return t===void 0?!1:Date.now()>=t?(R.delete(e),!1):!0}function be(e){let t=R.get(e);if(t===void 0)return 0;let i=t-Date.now();return i<=0?(R.delete(e),0):i}function _e(e){R.delete(e)}import Ee from"fs";import Se from"path";import{homedir as at}from"os";import{createCipheriv as et,createDecipheriv as tt}from"crypto";function we(e,t){let i=et("aes-128-ecb",t,null);return Buffer.concat([i.update(e),i.final()])}function xe(e,t){let i=tt("aes-128-ecb",t,null);return Buffer.concat([i.update(e),i.final()])}function Ie(e){return Math.ceil((e+1)/16)*16}function K(e,t){return`${t}/download?encrypted_query_param=${encodeURIComponent(e)}`}function Te(e){return`${e.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(e.uploadParam)}&filekey=${encodeURIComponent(e.filekey)}`}var Wt=f("channels");function nt(e){let t=Buffer.from(e,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${t.length} bytes`)}async function Ue(e){let t=await fetch(e);if(!t.ok)throw new Error(`CDN download ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}async function M(e){let{encryptQueryParam:t,aesKeyBase64:i,cdnBaseUrl:s,fullUrl:n}=e,r=nt(i),o=n?.trim()||(t?K(t,s):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Ue(o);return xe(a,r)}async function ke(e){let{encryptQueryParam:t,cdnBaseUrl:i,fullUrl:s}=e,n=s?.trim()||(t?K(t,i):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Ue(n)}var B=f("channels"),Re=24e3;function rt(e,t){let i=e.byteLength,s=44+i,n=Buffer.allocUnsafe(s),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(s-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(t,r),r+=4,n.writeUInt32LE(t*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(i,r),r+=4,Buffer.from(e.buffer,e.byteOffset,e.byteLength).copy(n,r),n}async function Ce(e){try{let{decode:t}=await import("silk-wasm");B.debug(`silkToWav: decoding ${e.length} bytes of SILK`);let i=await t(e,Re);B.debug(`silkToWav: decoded duration=${i.duration}ms pcmBytes=${i.data.byteLength}`);let s=rt(i.data,Re);return B.debug(`silkToWav: WAV size=${s.length}`),s}catch(t){return B.warn(`silkToWav: transcode failed, will use raw silk err=${String(t)}`),null}}import it from"path";var st={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},ot={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function D(e){let t=it.extname(e).toLowerCase();return st[t]??"application/octet-stream"}function Me(e){let t=e.split(";")[0].trim().toLowerCase();return ot[t]??".bin"}var U=f("channels"),Pe=100*1024*1024;function dt(e){return Me(e)??".bin"}async function E(e,t,i,s,n=Pe,r){if(e.length>n)throw new Error(`Media too large: ${e.length} bytes exceeds ${n} bytes`);let o=Se.join(at(),".adam","wechat","media",s,i);await Ee.promises.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let l=t?dt(t):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${l}`}let d=Se.join(o,a);return await Ee.promises.writeFile(d,e),U.debug(`saveMedia: saved ${e.length} bytes to ${d}`),d}async function Ae(e,t){let{cdnBaseUrl:i,channelId:s}=t;if(e.type===m.IMAGE){let n=e.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await M({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:i,fullUrl:n.media?.full_url}):await ke({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:i,fullUrl:n.media?.full_url});return{path:await E(o,"image/png","inbound",s),mimeType:"image/png",type:"image"}}catch(o){return U.error({channelId:s},`Image download/decrypt failed: ${String(o)}`),null}}if(e.type===m.VOICE){let n=e.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url}),o=await Ce(r);if(o){let a=await E(o,"audio/wav","inbound",s);return U.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await E(r,"audio/silk","inbound",s);return U.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return U.error({channelId:s},`Voice download/transcode failed: ${String(r)}`),null}}if(e.type===m.FILE){let n=e.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url}),o=D(n.file_name??"file.bin");return{path:await E(r,o,"inbound",s,Pe,n.file_name),mimeType:o,type:"file"}}catch(r){return U.error({channelId:s},`File download failed: ${String(r)}`),null}}if(e.type===m.VIDEO){let n=e.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url});return{path:await E(r,"video/mp4","inbound",s),mimeType:"video/mp4",type:"video"}}catch(r){return U.error({channelId:s},`Video download failed: ${String(r)}`),null}}return null}import ut from"path";import H from"crypto";import ct from"fs/promises";var I=f("channels"),W=3;async function lt(e){let{buf:t,uploadFullUrl:i,uploadParam:s,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=e,d=we(t,a),l=i?.trim(),u;if(l)u=l;else if(s)u=Te({cdnBaseUrl:r,uploadParam:s,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);I.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,_;for(let h=1;h<=W;h++)try{let g=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(g.status>=400&&g.status<500){let x=g.headers.get("x-error-message")??await g.text();throw I.error(`${o}: CDN client error attempt=${h} status=${g.status} errMsg=${x}`),new Error(`CDN upload client error ${g.status}: ${x}`)}if(g.status!==200){let x=g.headers.get("x-error-message")??`status ${g.status}`;throw I.error(`${o}: CDN server error attempt=${h} status=${g.status} errMsg=${x}`),new Error(`CDN upload server error: ${x}`)}if(p=g.headers.get("x-encrypted-param")??void 0,!p)throw I.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");I.debug(`${o}: CDN upload success attempt=${h}`);break}catch(g){if(_=g,g instanceof Error&&g.message.includes("client error"))throw g;h<W?I.warn(`${o}: attempt ${h} failed, retrying... err=${String(g)}`):I.error(`${o}: all ${W} attempts failed err=${String(g)}`)}if(!p)throw _ instanceof Error?_:new Error(`CDN upload failed after ${W} attempts`);return{downloadParam:p}}async function X(e){let{filePath:t,toUserId:i,opts:s,cdnBaseUrl:n,mediaType:r,label:o}=e,a=await ct.readFile(t),d=a.length,l=H.createHash("md5").update(a).digest("hex"),u=Ie(d),p=H.randomBytes(16).toString("hex"),_=H.randomBytes(16);I.debug(`${o}: file=${t} rawsize=${d} filesize=${u} md5=${l} filekey=${p}`);let h=await le({...s,filekey:p,media_type:r,to_user_id:i,rawsize:d,rawfilemd5:l,filesize:u,no_need_thumb:!0,aeskey:_.toString("hex")}),g=h.upload_full_url?.trim(),x=h.upload_param;if(!g&&!x)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:De}=await lt({buf:a,uploadFullUrl:g||void 0,uploadParam:x??void 0,filekey:p,cdnBaseUrl:n,aeskey:_,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:De,aeskey:_.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function ve(e){return X({...e,mediaType:O.IMAGE,label:"uploadImageToWeixin"})}async function Oe(e){return X({...e,mediaType:O.VIDEO,label:"uploadVideoToWeixin"})}async function Fe(e){return X({...e,mediaType:O.FILE,label:"uploadFileAttachmentToWeixin"})}var q=f("channels");function gt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function pt(e){let t=e;return t=t.replace(/```[^\n]*\n?([\s\S]*?)```/g,(i,s)=>s.trim()),t=t.replace(/!\[[^\]]*\]\([^)]*\)/g,""),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/^\|[\s:|-]+\|$/gm,""),t=t.replace(/^\|(.+)\|$/gm,(i,s)=>s.split("|").map(n=>n.trim()).join(" ")),t}async function J(e){let{to:t,text:i,mediaItem:s,opts:n,label:r}=e,o=[],a=pt(i);a&&o.push({type:m.TEXT,text_item:{text:a}}),o.push(s);let d="";for(let l of o){d=gt();let u={msg:{from_user_id:"",to_user_id:t,client_id:d,message_type:F.BOT,message_state:N.FINISH,item_list:[l],context_token:n.contextToken}};await v({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return q.debug(`${r}: sent to=${t} messageId=${d}`),{messageId:d}}async function mt(e){let{to:t,text:i,uploaded:s,opts:n}=e,r={type:m.IMAGE,image_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},mid_size:s.fileSizeCiphertext}};return J({to:t,text:i,mediaItem:r,opts:n,label:"sendImageMessage"})}async function ft(e){let{to:t,text:i,uploaded:s,opts:n}=e,r={type:m.VIDEO,video_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},video_size:s.fileSizeCiphertext}};return J({to:t,text:i,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function yt(e){let{to:t,text:i,fileName:s,uploaded:n,opts:r}=e,o={type:m.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:s,len:String(n.fileSize)}};return J({to:t,text:i,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Ne(e){let{filePath:t,to:i,text:s,opts:n,cdnBaseUrl:r}=e,o=D(t),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){q.debug(`sendWeixinMediaFile: uploading video filePath=${t} to=${i}`);let u=await Oe({filePath:t,toUserId:i,opts:a,cdnBaseUrl:r});return ft({to:i,text:s,uploaded:u,opts:n})}if(o.startsWith("image/")){q.debug(`sendWeixinMediaFile: uploading image filePath=${t} to=${i}`);let u=await ve({filePath:t,toUserId:i,opts:a,cdnBaseUrl:r});return mt({to:i,text:s,uploaded:u,opts:n})}let d=ut.basename(t);q.debug(`sendWeixinMediaFile: uploading file attachment filePath=${t} name=${d} to=${i}`);let l=await Fe({filePath:t,fileName:d,toUserId:i,opts:a,cdnBaseUrl:r});return yt({to:i,text:s,fileName:d,uploaded:l,opts:n})}var w=f("channels"),ee=new Map;function Le(e){return C.join(Z(),".adam","wechat",`${e}.context-tokens.json`)}function ht(e){let t=Le(e);try{let i=k.readFileSync(t,"utf-8"),s=JSON.parse(i);for(let[n,r]of Object.entries(s))typeof r=="string"&&r&&ee.set(`${e}:${n}`,r);w.debug({channelId:e,count:Object.keys(s).length},"Restored context tokens from disk")}catch{}}function bt(e,t,i){let s=Le(e);try{let n={};try{let o=k.readFileSync(s,"utf-8");n=JSON.parse(o)}catch{}n[t]=i;let r=C.dirname(s);k.mkdirSync(r,{recursive:!0}),k.writeFileSync(s,JSON.stringify(n),"utf-8")}catch(n){w.warn({channelId:e,userId:t},`Failed to persist context token: ${String(n)}`)}}function _t(e,t,i){ee.set(`${e}:${t}`,i),bt(e,t,i)}function $e(e,t){return ee.get(`${e}:${t}`)}function Be(e){return C.join(Z(),".adam","wechat",`${e}.sync`)}function wt(e){try{return k.readFileSync(Be(e),"utf-8")}catch{return""}}function xt(e,t){let i=Be(e);k.mkdirSync(C.dirname(i),{recursive:!0}),k.writeFileSync(i,t,"utf-8")}var It=0;function Tt(){return`adam-wechat-${Date.now()}-${++It}`}var j=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";constructor(t,i){if(this.id=t,!i.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=i}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=wt(this.id),ht(this.id),this.pollAbort=new AbortController,this.status="connected",w.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",w.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){return this.status==="connected"&&L(this.id)?"error":this.status}async sendMessage(t,i){if(L(this.id)){let o=Math.ceil(be(this.id)/6e4);throw new Error(`WeChat session paused, ${o} min remaining. Re-scan QR to reconnect.`)}let s=Tt(),n=$e(this.id,t),r=this.config.cdnBaseUrl??this.config.baseUrl;if(i.mediaUrl)try{let o=await fetch(i.mediaUrl);if(!o.ok)throw new Error(`Failed to fetch media: ${o.status}`);let a=Buffer.from(await o.arrayBuffer()),d=C.join(Z(),".adam","wechat","media","outbound-tmp");await Y.mkdir(d,{recursive:!0});let l=this.getExtensionFromMediaType(i.mediaType),u=C.join(d,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${l}`);await Y.writeFile(u,a);let p=await Ne({filePath:u,to:t,text:i.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:n},cdnBaseUrl:r});return await Y.unlink(u).catch(()=>{}),p.messageId}catch(o){throw w.error({channelId:this.id},`sendMessage media handling failed: ${String(o)}`),o}return await v({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:t,client_id:s,message_type:F.BOT,message_state:N.FINISH,item_list:i.content?[{type:m.TEXT,text_item:{text:i.content}}]:void 0,context_token:n}}}),s}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(L(this.id))return;let i=$e(this.id,t);try{await ce({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:t,status:ye.TYPING}})}catch{}}updateConfig(t){Object.assign(this.config,t)}async startLongPoll(){let t=this.pollAbort?.signal,i=0,s=3,n=3e4,r=2e3;for(;!t?.aborted;)try{let o=await de({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===G||o.errcode===G){he(this.id),this.status="error",w.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep($,t),_e(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){i++,w.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),i>=s?(i=0,await this.sleep(n,t)):await this.sleep(r,t);continue}i=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,xt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(t?.aborted)return;i++,w.error({channelId:this.id,error:o},"getUpdates error"),i>=s?(i=0,await this.sleep(n,t)):await this.sleep(r,t)}}async processInbound(t){if(!this.messageHandler)return;t.context_token&&t.from_user_id&&_t(this.id,t.from_user_id??"",t.context_token);let i="",s,n=[];for(let a of t.item_list??[])a.type===m.TEXT&&a.text_item?.text&&(i+=a.text_item.text),a.type===m.IMAGE&&(s="image",n.push(a)),a.type===m.VOICE&&(s="audio",n.push(a),a.voice_item?.text&&!i&&(i=a.voice_item.text)),a.type===m.FILE&&(s="file",n.push(a)),a.type===m.VIDEO&&(s="video",n.push(a));if(!i&&!s)return;let r;if(n.length>0){let a=this.config.cdnBaseUrl??this.config.baseUrl;try{let d=await Ae(n[0],{cdnBaseUrl:a,channelId:this.id});d&&(r=d.path,s=d.type)}catch(d){w.error({channelId:this.id},`Media download failed: ${String(d)}`)}}let o={channelId:this.id,platform:"wechat",chatId:t.from_user_id??"",senderId:t.from_user_id??"",content:i,mediaType:s,mediaPath:r,isGroup:!1,timestamp:t.create_time_ms??Date.now(),raw:t};this.messageHandler(o)}getExtensionFromMediaType(t){switch(t){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(t,i){return new Promise((s,n)=>{let r=setTimeout(s,t);i?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};var T=c.object({id:c.string().uuid()}),kt=c.object({name:c.string().min(1,"name is required"),platform:c.string().min(1,"platform is required"),config:c.record(c.string(),c.unknown()),enabled:c.boolean().optional().default(!0),linkedRoleId:c.string().optional(),allowedChatIds:c.array(c.string()).optional()}),Rt=c.object({name:c.string().min(1).optional(),enabled:c.boolean().optional(),config:c.record(c.string(),c.unknown()).optional(),linkedRoleId:c.string().optional(),allowedChatIds:c.array(c.string()).optional()}),te;function On(e){te=e}function Fn(){return te}async function Nn(e){let t=te;e.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(i,s)=>({channels:ie(i.query.enabled)})),e.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(i,s)=>{let n=kt.safeParse(i.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:l,allowedChatIds:u}=n.data,p={id:Ut(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:l,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return re(p),s.status(201).send({channel:p})}),e.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);return r?{channel:r}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Rt.safeParse(i.body);return o.success?(z(r.id,o.data),{channel:b(r.id)}):s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(o.error)})}),e.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);return r?(se(r.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!t.hasAdapter(r.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await t.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),e.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=b(n.data.id);return r?(await t.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=i.query;return{messages:ne(r.id,o,a)}}),e.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await me({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),e.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=i.body??{},l=await fe({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(l.connected&&l.botToken){let u={...o,botToken:l.botToken,accountId:l.accountId,baseUrl:l.baseUrl??o.baseUrl,userId:l.userId};if(z(r.id,{config:u}),t){let p=new j(r.id,u),_=b(r.id);_&&await t.addChannel(_,p)}}return{connected:l.connected,accountId:l.accountId,message:l.message}})}export{j as a,On as b,Fn as c,Nn as d};
1
+ import{f as ne}from"./chunk-742NWPTQ.js";import{a as re,b,c as z,d as ie,e as se}from"./chunk-PQ7KPALO.js";import{c as f}from"./chunk-3DAK2XWP.js";import{z as c}from"zod/v4";import{v4 as Ut}from"uuid";import{randomUUID as ue}from"crypto";import We from"crypto";var oe="1.0.0",S="";function qe(e){let t=e.split(".").map(r=>parseInt(r,10)),i=t[0]??0,s=t[1]??0,n=t[2]??0;return(i&255)<<16|(s&255)<<8|n&255}var V=qe(oe),je=35e3,ae=15e3,ze=1e4;function P(){return{channel_version:oe}}function Ve(e){return e.endsWith("/")?e:`${e}/`}function Qe(){let e=We.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function Ge(e){let t={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":Qe(),"iLink-App-Id":S,"iLink-App-ClientVersion":String(V)};return e.token?.trim()&&(t.Authorization=`Bearer ${e.token.trim()}`),e.routeTag&&(t.SKRouteTag=e.routeTag),t}async function A(e){let t=Ve(e.baseUrl),i=new URL(e.endpoint,t),s=Ge({token:e.token,routeTag:e.routeTag,body:e.body}),n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs);try{let o=await fetch(i.toString(),{method:"POST",headers:s,body:e.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${e.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function de(e){let t=e.timeoutMs??je;try{let i=await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:t,label:"getUpdates"});return JSON.parse(i)}catch(i){if(i instanceof Error&&i.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw i}}async function v(e){await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ae,label:"sendMessage"})}async function ce(e){await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ze,label:"sendTyping"})}async function le(e){let t=await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ae,label:"getUploadUrl"});return JSON.parse(t)}var Ke=5*6e4,He=35e3,ge="3",y=new Map;function Q(e){return Date.now()-e.startedAt<Ke}function Xe(){for(let[e,t]of y)Q(t)||y.delete(e)}async function pe(e,t,i){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(t)}`,s),r={"iLink-App-Id":S};i&&(r.SKRouteTag=i);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function Je(e,t,i){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(t)}`,s),r={"iLink-App-Id":S,"iLink-App-ClientVersion":String(V)};i&&(r.SKRouteTag=i);let o=new AbortController,a=setTimeout(()=>o.abort(),He);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);let l=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(l)}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function me(e){let t=e.accountId||ue();Xe();let i=y.get(t);if(!e.force&&i&&Q(i)&&i.qrcodeUrl)return{qrcodeUrl:i.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:t};if(!e.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:t};try{let s=e.botType||ge,n=await pe(e.apiBaseUrl,s,e.routeTag),r={sessionKey:t,id:ue(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return y.set(t,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:t}}catch(s){return{message:`Failed to start login: ${String(s)}`,sessionKey:t}}}var Ye=3;async function fe(e){let t=y.get(e.sessionKey);if(!t)return{connected:!1,message:"No active login session. Start QR login first."};if(!Q(t))return y.delete(e.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let i=Math.max(e.timeoutMs??48e4,1e3),s=Date.now()+i,n=1;for(;Date.now()<s;){try{let r=await Je(e.apiBaseUrl,t.qrcode,e.routeTag);switch(t.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>Ye)return y.delete(e.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=e.botType||ge,a=await pe(e.apiBaseUrl,o,e.routeTag);t.qrcode=a.qrcode,t.qrcodeUrl=a.qrcode_img_content,t.startedAt=Date.now()}catch(o){return y.delete(e.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(y.delete(e.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(y.delete(e.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return y.delete(e.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return y.delete(e.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import k,{promises as Y}from"fs";import C from"path";import{homedir as Z}from"os";var O={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},F={NONE:0,USER:1,BOT:2},m={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},N={NEW:0,GENERATING:1,FINISH:2},ye={TYPING:1,CANCEL:2};var Ze=f("channels"),G=-14,$=3600*1e3,R=new Map;function he(e){let t=Date.now()+$;R.set(e,t),Ze.info({channelId:e},`Session paused until ${new Date(t).toISOString()} (${$/1e3}s)`)}function L(e){let t=R.get(e);return t===void 0?!1:Date.now()>=t?(R.delete(e),!1):!0}function be(e){let t=R.get(e);if(t===void 0)return 0;let i=t-Date.now();return i<=0?(R.delete(e),0):i}function _e(e){R.delete(e)}import Ee from"fs";import Se from"path";import{homedir as at}from"os";import{createCipheriv as et,createDecipheriv as tt}from"crypto";function we(e,t){let i=et("aes-128-ecb",t,null);return Buffer.concat([i.update(e),i.final()])}function xe(e,t){let i=tt("aes-128-ecb",t,null);return Buffer.concat([i.update(e),i.final()])}function Ie(e){return Math.ceil((e+1)/16)*16}function K(e,t){return`${t}/download?encrypted_query_param=${encodeURIComponent(e)}`}function Te(e){return`${e.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(e.uploadParam)}&filekey=${encodeURIComponent(e.filekey)}`}var Wt=f("channels");function nt(e){let t=Buffer.from(e,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${t.length} bytes`)}async function Ue(e){let t=await fetch(e);if(!t.ok)throw new Error(`CDN download ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}async function M(e){let{encryptQueryParam:t,aesKeyBase64:i,cdnBaseUrl:s,fullUrl:n}=e,r=nt(i),o=n?.trim()||(t?K(t,s):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Ue(o);return xe(a,r)}async function ke(e){let{encryptQueryParam:t,cdnBaseUrl:i,fullUrl:s}=e,n=s?.trim()||(t?K(t,i):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Ue(n)}var B=f("channels"),Re=24e3;function rt(e,t){let i=e.byteLength,s=44+i,n=Buffer.allocUnsafe(s),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(s-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(t,r),r+=4,n.writeUInt32LE(t*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(i,r),r+=4,Buffer.from(e.buffer,e.byteOffset,e.byteLength).copy(n,r),n}async function Ce(e){try{let{decode:t}=await import("silk-wasm");B.debug(`silkToWav: decoding ${e.length} bytes of SILK`);let i=await t(e,Re);B.debug(`silkToWav: decoded duration=${i.duration}ms pcmBytes=${i.data.byteLength}`);let s=rt(i.data,Re);return B.debug(`silkToWav: WAV size=${s.length}`),s}catch(t){return B.warn(`silkToWav: transcode failed, will use raw silk err=${String(t)}`),null}}import it from"path";var st={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},ot={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function D(e){let t=it.extname(e).toLowerCase();return st[t]??"application/octet-stream"}function Me(e){let t=e.split(";")[0].trim().toLowerCase();return ot[t]??".bin"}var U=f("channels"),Pe=100*1024*1024;function dt(e){return Me(e)??".bin"}async function E(e,t,i,s,n=Pe,r){if(e.length>n)throw new Error(`Media too large: ${e.length} bytes exceeds ${n} bytes`);let o=Se.join(at(),".adam","wechat","media",s,i);await Ee.promises.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let l=t?dt(t):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${l}`}let d=Se.join(o,a);return await Ee.promises.writeFile(d,e),U.debug(`saveMedia: saved ${e.length} bytes to ${d}`),d}async function Ae(e,t){let{cdnBaseUrl:i,channelId:s}=t;if(e.type===m.IMAGE){let n=e.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await M({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:i,fullUrl:n.media?.full_url}):await ke({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:i,fullUrl:n.media?.full_url});return{path:await E(o,"image/png","inbound",s),mimeType:"image/png",type:"image"}}catch(o){return U.error({channelId:s},`Image download/decrypt failed: ${String(o)}`),null}}if(e.type===m.VOICE){let n=e.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url}),o=await Ce(r);if(o){let a=await E(o,"audio/wav","inbound",s);return U.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await E(r,"audio/silk","inbound",s);return U.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return U.error({channelId:s},`Voice download/transcode failed: ${String(r)}`),null}}if(e.type===m.FILE){let n=e.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url}),o=D(n.file_name??"file.bin");return{path:await E(r,o,"inbound",s,Pe,n.file_name),mimeType:o,type:"file"}}catch(r){return U.error({channelId:s},`File download failed: ${String(r)}`),null}}if(e.type===m.VIDEO){let n=e.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url});return{path:await E(r,"video/mp4","inbound",s),mimeType:"video/mp4",type:"video"}}catch(r){return U.error({channelId:s},`Video download failed: ${String(r)}`),null}}return null}import ut from"path";import H from"crypto";import ct from"fs/promises";var I=f("channels"),W=3;async function lt(e){let{buf:t,uploadFullUrl:i,uploadParam:s,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=e,d=we(t,a),l=i?.trim(),u;if(l)u=l;else if(s)u=Te({cdnBaseUrl:r,uploadParam:s,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);I.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,_;for(let h=1;h<=W;h++)try{let g=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(g.status>=400&&g.status<500){let x=g.headers.get("x-error-message")??await g.text();throw I.error(`${o}: CDN client error attempt=${h} status=${g.status} errMsg=${x}`),new Error(`CDN upload client error ${g.status}: ${x}`)}if(g.status!==200){let x=g.headers.get("x-error-message")??`status ${g.status}`;throw I.error(`${o}: CDN server error attempt=${h} status=${g.status} errMsg=${x}`),new Error(`CDN upload server error: ${x}`)}if(p=g.headers.get("x-encrypted-param")??void 0,!p)throw I.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");I.debug(`${o}: CDN upload success attempt=${h}`);break}catch(g){if(_=g,g instanceof Error&&g.message.includes("client error"))throw g;h<W?I.warn(`${o}: attempt ${h} failed, retrying... err=${String(g)}`):I.error(`${o}: all ${W} attempts failed err=${String(g)}`)}if(!p)throw _ instanceof Error?_:new Error(`CDN upload failed after ${W} attempts`);return{downloadParam:p}}async function X(e){let{filePath:t,toUserId:i,opts:s,cdnBaseUrl:n,mediaType:r,label:o}=e,a=await ct.readFile(t),d=a.length,l=H.createHash("md5").update(a).digest("hex"),u=Ie(d),p=H.randomBytes(16).toString("hex"),_=H.randomBytes(16);I.debug(`${o}: file=${t} rawsize=${d} filesize=${u} md5=${l} filekey=${p}`);let h=await le({...s,filekey:p,media_type:r,to_user_id:i,rawsize:d,rawfilemd5:l,filesize:u,no_need_thumb:!0,aeskey:_.toString("hex")}),g=h.upload_full_url?.trim(),x=h.upload_param;if(!g&&!x)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:De}=await lt({buf:a,uploadFullUrl:g||void 0,uploadParam:x??void 0,filekey:p,cdnBaseUrl:n,aeskey:_,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:De,aeskey:_.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function ve(e){return X({...e,mediaType:O.IMAGE,label:"uploadImageToWeixin"})}async function Oe(e){return X({...e,mediaType:O.VIDEO,label:"uploadVideoToWeixin"})}async function Fe(e){return X({...e,mediaType:O.FILE,label:"uploadFileAttachmentToWeixin"})}var q=f("channels");function gt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function pt(e){let t=e;return t=t.replace(/```[^\n]*\n?([\s\S]*?)```/g,(i,s)=>s.trim()),t=t.replace(/!\[[^\]]*\]\([^)]*\)/g,""),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/^\|[\s:|-]+\|$/gm,""),t=t.replace(/^\|(.+)\|$/gm,(i,s)=>s.split("|").map(n=>n.trim()).join(" ")),t}async function J(e){let{to:t,text:i,mediaItem:s,opts:n,label:r}=e,o=[],a=pt(i);a&&o.push({type:m.TEXT,text_item:{text:a}}),o.push(s);let d="";for(let l of o){d=gt();let u={msg:{from_user_id:"",to_user_id:t,client_id:d,message_type:F.BOT,message_state:N.FINISH,item_list:[l],context_token:n.contextToken}};await v({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return q.debug(`${r}: sent to=${t} messageId=${d}`),{messageId:d}}async function mt(e){let{to:t,text:i,uploaded:s,opts:n}=e,r={type:m.IMAGE,image_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},mid_size:s.fileSizeCiphertext}};return J({to:t,text:i,mediaItem:r,opts:n,label:"sendImageMessage"})}async function ft(e){let{to:t,text:i,uploaded:s,opts:n}=e,r={type:m.VIDEO,video_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},video_size:s.fileSizeCiphertext}};return J({to:t,text:i,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function yt(e){let{to:t,text:i,fileName:s,uploaded:n,opts:r}=e,o={type:m.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:s,len:String(n.fileSize)}};return J({to:t,text:i,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Ne(e){let{filePath:t,to:i,text:s,opts:n,cdnBaseUrl:r}=e,o=D(t),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){q.debug(`sendWeixinMediaFile: uploading video filePath=${t} to=${i}`);let u=await Oe({filePath:t,toUserId:i,opts:a,cdnBaseUrl:r});return ft({to:i,text:s,uploaded:u,opts:n})}if(o.startsWith("image/")){q.debug(`sendWeixinMediaFile: uploading image filePath=${t} to=${i}`);let u=await ve({filePath:t,toUserId:i,opts:a,cdnBaseUrl:r});return mt({to:i,text:s,uploaded:u,opts:n})}let d=ut.basename(t);q.debug(`sendWeixinMediaFile: uploading file attachment filePath=${t} name=${d} to=${i}`);let l=await Fe({filePath:t,fileName:d,toUserId:i,opts:a,cdnBaseUrl:r});return yt({to:i,text:s,fileName:d,uploaded:l,opts:n})}var w=f("channels"),ee=new Map;function Le(e){return C.join(Z(),".adam","wechat",`${e}.context-tokens.json`)}function ht(e){let t=Le(e);try{let i=k.readFileSync(t,"utf-8"),s=JSON.parse(i);for(let[n,r]of Object.entries(s))typeof r=="string"&&r&&ee.set(`${e}:${n}`,r);w.debug({channelId:e,count:Object.keys(s).length},"Restored context tokens from disk")}catch{}}function bt(e,t,i){let s=Le(e);try{let n={};try{let o=k.readFileSync(s,"utf-8");n=JSON.parse(o)}catch{}n[t]=i;let r=C.dirname(s);k.mkdirSync(r,{recursive:!0}),k.writeFileSync(s,JSON.stringify(n),"utf-8")}catch(n){w.warn({channelId:e,userId:t},`Failed to persist context token: ${String(n)}`)}}function _t(e,t,i){ee.set(`${e}:${t}`,i),bt(e,t,i)}function $e(e,t){return ee.get(`${e}:${t}`)}function Be(e){return C.join(Z(),".adam","wechat",`${e}.sync`)}function wt(e){try{return k.readFileSync(Be(e),"utf-8")}catch{return""}}function xt(e,t){let i=Be(e);k.mkdirSync(C.dirname(i),{recursive:!0}),k.writeFileSync(i,t,"utf-8")}var It=0;function Tt(){return`adam-wechat-${Date.now()}-${++It}`}var j=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";constructor(t,i){if(this.id=t,!i.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=i}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=wt(this.id),ht(this.id),this.pollAbort=new AbortController,this.status="connected",w.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",w.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){return this.status==="connected"&&L(this.id)?"error":this.status}async sendMessage(t,i){if(L(this.id)){let o=Math.ceil(be(this.id)/6e4);throw new Error(`WeChat session paused, ${o} min remaining. Re-scan QR to reconnect.`)}let s=Tt(),n=$e(this.id,t),r=this.config.cdnBaseUrl??this.config.baseUrl;if(i.mediaUrl)try{let o=await fetch(i.mediaUrl);if(!o.ok)throw new Error(`Failed to fetch media: ${o.status}`);let a=Buffer.from(await o.arrayBuffer()),d=C.join(Z(),".adam","wechat","media","outbound-tmp");await Y.mkdir(d,{recursive:!0});let l=this.getExtensionFromMediaType(i.mediaType),u=C.join(d,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${l}`);await Y.writeFile(u,a);let p=await Ne({filePath:u,to:t,text:i.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:n},cdnBaseUrl:r});return await Y.unlink(u).catch(()=>{}),p.messageId}catch(o){throw w.error({channelId:this.id},`sendMessage media handling failed: ${String(o)}`),o}return await v({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:t,client_id:s,message_type:F.BOT,message_state:N.FINISH,item_list:i.content?[{type:m.TEXT,text_item:{text:i.content}}]:void 0,context_token:n}}}),s}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(L(this.id))return;let i=$e(this.id,t);try{await ce({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:t,status:ye.TYPING}})}catch{}}updateConfig(t){Object.assign(this.config,t)}async startLongPoll(){let t=this.pollAbort?.signal,i=0,s=3,n=3e4,r=2e3;for(;!t?.aborted;)try{let o=await de({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===G||o.errcode===G){he(this.id),this.status="error",w.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep($,t),_e(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){i++,w.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),i>=s?(i=0,await this.sleep(n,t)):await this.sleep(r,t);continue}i=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,xt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(t?.aborted)return;i++,w.error({channelId:this.id,error:o},"getUpdates error"),i>=s?(i=0,await this.sleep(n,t)):await this.sleep(r,t)}}async processInbound(t){if(!this.messageHandler)return;t.context_token&&t.from_user_id&&_t(this.id,t.from_user_id??"",t.context_token);let i="",s,n=[];for(let a of t.item_list??[])a.type===m.TEXT&&a.text_item?.text&&(i+=a.text_item.text),a.type===m.IMAGE&&(s="image",n.push(a)),a.type===m.VOICE&&(s="audio",n.push(a),a.voice_item?.text&&!i&&(i=a.voice_item.text)),a.type===m.FILE&&(s="file",n.push(a)),a.type===m.VIDEO&&(s="video",n.push(a));if(!i&&!s)return;let r;if(n.length>0){let a=this.config.cdnBaseUrl??this.config.baseUrl;try{let d=await Ae(n[0],{cdnBaseUrl:a,channelId:this.id});d&&(r=d.path,s=d.type)}catch(d){w.error({channelId:this.id},`Media download failed: ${String(d)}`)}}let o={channelId:this.id,platform:"wechat",chatId:t.from_user_id??"",senderId:t.from_user_id??"",content:i,mediaType:s,mediaPath:r,isGroup:!1,timestamp:t.create_time_ms??Date.now(),raw:t};this.messageHandler(o)}getExtensionFromMediaType(t){switch(t){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(t,i){return new Promise((s,n)=>{let r=setTimeout(s,t);i?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};var T=c.object({id:c.string().uuid()}),kt=c.object({name:c.string().min(1,"name is required"),platform:c.string().min(1,"platform is required"),config:c.record(c.string(),c.unknown()),enabled:c.boolean().optional().default(!0),linkedRoleId:c.string().optional(),allowedChatIds:c.array(c.string()).optional()}),Rt=c.object({name:c.string().min(1).optional(),enabled:c.boolean().optional(),config:c.record(c.string(),c.unknown()).optional(),linkedRoleId:c.string().optional(),allowedChatIds:c.array(c.string()).optional()}),te;function On(e){te=e}function Fn(){return te}async function Nn(e){let t=te;e.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(i,s)=>({channels:ie(i.query.enabled)})),e.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(i,s)=>{let n=kt.safeParse(i.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:l,allowedChatIds:u}=n.data,p={id:Ut(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:l,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return re(p),s.status(201).send({channel:p})}),e.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);return r?{channel:r}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Rt.safeParse(i.body);return o.success?(z(r.id,o.data),{channel:b(r.id)}):s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(o.error)})}),e.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);return r?(se(r.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!t.hasAdapter(r.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await t.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),e.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=b(n.data.id);return r?(await t.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=i.query;return{messages:ne(r.id,o,a)}}),e.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await me({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),e.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=i.body??{},l=await fe({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(l.connected&&l.botToken){let u={...o,botToken:l.botToken,accountId:l.accountId,baseUrl:l.baseUrl??o.baseUrl,userId:l.userId};if(z(r.id,{config:u}),t){let p=new j(r.id,u),_=b(r.id);_&&await t.addChannel(_,p)}}return{connected:l.connected,accountId:l.accountId,message:l.message}})}export{j as a,On as b,Fn as c,Nn as d};
@@ -0,0 +1,10 @@
1
+ import{a as l}from"./chunk-WZOMGJSY.js";import{d as f,k as g,m as p,n as h,o as M,q as b}from"./chunk-HAWA62R2.js";function v(t,n){let i=0,s=0,m=0;for(let e=0;e<t.length;e++)i+=t[e]*n[e],s+=t[e]*t[e],m+=n[e]*n[e];let o=Math.sqrt(s)*Math.sqrt(m);return o===0?0:i/o}async function S(t,n,i={}){let s=i.topK??10,m=i.hybridConfig??M,o;try{o=await l(n)}catch{}let e=o??new Float32Array(384),a=b(t,e,n,s*2,m,{excludeSuperseded:!0}),d=t?h(t):g,y=a.map(r=>{let u=r.embedding?v(e,r.embedding):0,C=Math.min(.3,(r.retrievedCount??0)*.05),x=p(r.createdAt,u,r.importance,d)+C;return{...r,score:x}});y.sort((r,u)=>u.score-r.score);let c=y.slice(0,s);for(let r of c)f(r.id);return c}async function T(t,n,i=5,s=2e3){try{let{estimateTokens:m}=await import("./token-estimator-HMPVGDCN.js"),o=await S(n,t,{topK:i});if(o.length===0)return"";let e=[],a=0,d=m(`[Memory Context \u2014 retrieved from prior interactions]
2
+
3
+ [User Request]
4
+ `);for(let c of o){let r=m(`- [${c.tier??"episodic"}] ${c.content}
5
+ `);if(a+r+d>s)break;e.push(c),a+=r}return e.length===0?"":`[Memory Context \u2014 retrieved from prior interactions]
6
+ ${e.map(c=>`- [${c.tier??"episodic"}] ${c.content}`).join(`
7
+ `)}
8
+
9
+ [User Request]
10
+ `}catch{return""}}async function q(t,n,i,s={}){return(await S(t,n,s)).filter(o=>i.includes(o.tier??"episodic"))}export{S as a,T as b,q as c};