adam-agent-server 1.2.1 → 1.2.2

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 (24) hide show
  1. package/README.md +4 -7
  2. package/dist/index.js +1 -1
  3. package/package.json +1 -1
  4. package/web/dist/assets/{ChannelDetail-DoQs1auJ.js → ChannelDetail-eWtIGhAd.js} +1 -1
  5. package/web/dist/assets/{Channels-Dc6QduC1.js → Channels-2veauYsm.js} +1 -1
  6. package/web/dist/assets/{Chat-NrKA_MiZ.js → Chat-Bha4vXwT.js} +1 -1
  7. package/web/dist/assets/{Dashboard-C67v0x7e.js → Dashboard-cDHpOWnY.js} +1 -1
  8. package/web/dist/assets/EnvVarEditor-CaCpNT3y.js +1 -0
  9. package/web/dist/assets/{Evolution-CbFOTN2o.js → Evolution-Ao-gdHbS.js} +1 -1
  10. package/web/dist/assets/{GoalDetail-DYUbYJpT.js → GoalDetail-CX2i9A5a.js} +1 -1
  11. package/web/dist/assets/{Goals-7eD9_7Qo.js → Goals-DdM0tFus.js} +1 -1
  12. package/web/dist/assets/{Logs-CDFbfvQT.js → Logs-DJhpDtCA.js} +1 -1
  13. package/web/dist/assets/{Memories-D0J8Es-o.js → Memories-CYN99g2T.js} +1 -1
  14. package/web/dist/assets/{Plugins-CXCUhsEZ.js → Plugins-gcMpBdyq.js} +1 -1
  15. package/web/dist/assets/{RoleDetail-C2lXyAjt.js → RoleDetail-s7u-Shk3.js} +2 -2
  16. package/web/dist/assets/{Roles-Bia_f3ml.js → Roles-CCy1H7PY.js} +1 -1
  17. package/web/dist/assets/{Settings-CzgdtkLo.js → Settings-JbgBxBeo.js} +1 -1
  18. package/web/dist/assets/{Strategies-CRdpzdUe.js → Strategies-CO4LwZjS.js} +1 -1
  19. package/web/dist/assets/{Switch-B05Q1L98.js → Switch-CTAIxUd_.js} +1 -1
  20. package/web/dist/assets/{TaskDetail-4yYEVV6Z.js → TaskDetail-DEg_oUwx.js} +1 -1
  21. package/web/dist/assets/{Work-CE6TB6LG.js → Work-BpKK_uXA.js} +1 -1
  22. package/web/dist/assets/{index-oA-kWqT5.js → index-rvaixveh.js} +5 -5
  23. package/web/dist/index.html +1 -1
  24. package/web/dist/assets/EnvVarEditor-DeCQryTm.js +0 -1
package/README.md CHANGED
@@ -95,8 +95,7 @@ npm install -g adam-agent-server
95
95
  # Option B: From source
96
96
  git clone https://github.com/n0rvyn/adam.git
97
97
  cd adam
98
- pnpm install && pnpm build
99
- cd web && pnpm install && pnpm build && cd ..
98
+ pnpm install && pnpm build:all
100
99
  pnpm link --global
101
100
  ```
102
101
 
@@ -347,9 +346,8 @@ pnpm test:coverage # Coverage report
347
346
  pnpm typecheck # Type check
348
347
 
349
348
  # Web UI development
350
- cd web
351
- pnpm dev # Vite dev server (hot reload)
352
- pnpm build # Production build
349
+ pnpm --filter adam-web dev # Vite dev server (hot reload)
350
+ pnpm --filter adam-web build # Production build
353
351
  ```
354
352
 
355
353
  ## License
@@ -390,8 +388,7 @@ npm install -g adam-agent-server
390
388
  # 方式 B: 从源码
391
389
  git clone https://github.com/n0rvyn/adam.git
392
390
  cd adam
393
- pnpm install && pnpm build
394
- cd web && pnpm install && pnpm build && cd ..
391
+ pnpm install && pnpm build:all
395
392
  pnpm link --global
396
393
 
397
394
  # 启动
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import{a as fs,b as hs,c as mt,d as gt,e as mr,f as gr,g as yr,h as fr,j as hr,k as br,m as vr,n as yt}from"./chunk-ITUBFUJQ.js";import{c as Rr,d as Ir}from"./chunk-KKLZIXBN.js";import"./chunk-2HN2TSP6.js";import{a as xs,c as js}from"./chunk-JNRCXAW3.js";import{b as or,c as ir}from"./chunk-QN6BEJF5.js";import{a as cr,b as dr,c as lr,e as pr}from"./chunk-IHP7JV6J.js";import{b as ur}from"./chunk-EGS6U3V5.js";import{a as ds,b as $s,c as Hs,d as Ks,e as zs,f as Qs,g as Ys,h as Xs,i as Zs,j as Js,k as er,l as tr,m as ce,o as ut}from"./chunk-IZWULGUS.js";import{a as Gs}from"./chunk-5V36ACKZ.js";import{c as dt,d as bs,e as _e,f as vs,g as Rs,h as Is,j as ks}from"./chunk-OEKM2W3K.js";import{c as cs}from"./chunk-EJVUUIAV.js";import{b as Je}from"./chunk-GMCIKDTC.js";import{a as sr,b as De,c as rr,d as ar,e as nr}from"./chunk-6YURWVQG.js";import{b as se,c as Oe,d as Fs,e as Ds}from"./chunk-CDVIT7L5.js";import{a as Ze,b as F,c as X,d as W,e as Yt,f as Xt}from"./chunk-W3554FQ7.js";import{b as Fe,c as qs,d as M,e as Ls,f as Ms,g as Bs,h as pt,i as z,j as Us,n as Ws,o as Vs}from"./chunk-RPTHFQX7.js";import{b as gs,c as ys}from"./chunk-AJVN3KPM.js";import{a as K,b as ct,c as us,e as ms}from"./chunk-AR2IZMM2.js";import{b as Ns,d as ye,f as ie}from"./chunk-SWPXG2CY.js";import{a as rs}from"./chunk-BIIP363C.js";import{a as rt,b as es,c as ts,d as wa,e as te,f as at,g as nt,h as ot,j as ss}from"./chunk-KLQOILIJ.js";import{h as os,i as is}from"./chunk-OFOVSC72.js";import{a as f}from"./chunk-L7JP7DUO.js";import{a as lt,c as As}from"./chunk-GUQAIWCQ.js";import{a as it,b as ls}from"./chunk-2CMR5AG7.js";import{a as Ts,b as Ee,c as Ss,g as ws,j as Cs}from"./chunk-4TCP2AT7.js";import{a as as,b as Pe,c as ns,d as kr}from"./chunk-PMHNW5IL.js";import{b as ps}from"./chunk-Z5ET7WW2.js";import{a as Ps,b as Z,c as _s,d as Es,g as Os}from"./chunk-6DXNXLYG.js";import{b as Ht,c as Kt,d as zt,e as Qt}from"./chunk-SBX3HMDA.js";import{a as Bt}from"./chunk-ZM6YED5F.js";import{a as Ye,b as Ut,c as Wt,d as Vt,e as Gt}from"./chunk-7IFLU3CY.js";import{a as Ie,b as ze,c as Nt,d as E,e as ke,i as qt,j as Lt,k as Qe}from"./chunk-6HD6NYIB.js";import{d as et,e as L,f as tt,g as Ce,h as ge,i as st,k as Ae}from"./chunk-B4WHT7DX.js";import{b as oe,c as we,d as Zt,g as Jt}from"./chunk-7LBDLAUQ.js";import{b as U,c as Xe,d as Se}from"./chunk-KVSO3KGZ.js";import{c as Mt,d as O,h as me}from"./chunk-WBAPIPST.js";import{a as $t,c as q,d as Te,h as Y}from"./chunk-INNDBLZE.js";import"./chunk-FCV2DPZQ.js";import{writeFileSync as ha,mkdirSync as ba,unlinkSync as $n}from"fs";import{join as He}from"path";me();import{readFileSync as Ca,existsSync as Aa}from"fs";import{resolve as ft}from"path";function Tr(o=O){let s=[],e=[],r=process.env.ADAM_ENV_FILE;r&&e.push(ft(o,r)),e.push(ft(o,".env.local")),e.push(ft(o,".env"));for(let t of e){if(!Aa(t))continue;Pa(t)>0&&s.push(t)}return s}function Pa(o){let e=Ca(o,"utf-8").split(`
2
- `),r=0;for(let t of e){let a=t.trim();if(!a||a.startsWith("#"))continue;a.startsWith("export ")&&(a=a.slice(7).trim());let n=a.indexOf("=");if(n===-1)continue;let i=a.slice(0,n).trim();if(!i)continue;let c=a.slice(n+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),c=c.replace(/\$\{(\w+)\}|\$(\w+)/g,(l,d,m)=>{let b=d??m;return process.env[b]??""}),(i.startsWith("ANTHROPIC_")||process.env[i]===void 0)&&(process.env[i]=c,r++)}return r}Se();Ae();ss();import{existsSync as Sr}from"fs";import wr from"path";import _a from"fastify";import Ea from"@fastify/cors";import Oa from"@fastify/static";import Fa from"@fastify/websocket";import Da from"@fastify/swagger";import xa from"@fastify/swagger-ui";import{timingSafeEqual as ja}from"crypto";function Ar(o,s){let e=_a({logger:!1});if(e.register(Da,{openapi:{info:{title:"Adam API",description:"Agent orchestration server built on Claude Agent SDK. Multi-agent system with parallel task execution, intelligent agent routing, self-evolving personas, and REST/WebSocket API.",version:Pe()},servers:[{url:"http://localhost:7100"}],tags:[{name:"Tasks",description:"Task lifecycle management"},{name:"Roles",description:"Role CRUD and workspace management"},{name:"Skills",description:"Skill CRUD and permissions"},{name:"Memories",description:"Agent memory search and retrieval"},{name:"Goals",description:"Goal-driven task management"},{name:"Strategies",description:"Thompson Sampling strategy engine"},{name:"Templates",description:"Task template CRUD and triggers"},{name:"Webhooks",description:"External system integration"},{name:"Config",description:"Runtime configuration management"},{name:"Evolution",description:"Agent evolution audit log"},{name:"Health",description:"Server health checks"}],components:{securitySchemes:{apiKey:{type:"apiKey",in:"header",name:"x-api-key",description:"API key for webhook endpoints"}}}}}),e.register(xa,{routePrefix:"/docs"}),e.register(Ea,{origin:!0}),e.register(Fa,{options:{maxPayload:1024*1024*16}}),s){let t=Buffer.from(s);e.addHook("onRequest",async(a,n)=>{let i=a.url;if(i==="/healthz"||i==="/readyz"||i.startsWith("/docs")||i.startsWith("/ui"))return;let c=a.headers["x-api-key"];if(c&&Cr(c,t))return;let l=a.query,d=l.api_key||l["x-api-key"];if(!(d&&Cr(d,t)))return n.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"})})}let r=wr.join(as,"web/dist");return Sr(r)&&(e.register(Oa,{root:r,prefix:"/ui/",wildcard:!0}),e.get("/ui",async(t,a)=>a.sendFile("index.html",r))),e.setErrorHandler((t,a,n)=>{if(t.validation){let c=t.validation.map(l=>{let d=l.instancePath||l.params?.missingProperty||"";return d?`${d}: ${l.message}`:l.message});return n.status(400).send({code:"VALIDATION_ERROR",message:c.join("; ")})}let i=t.statusCode??500;return n.status(i).send({code:"INTERNAL_ERROR",message:t.message})}),e.setNotFoundHandler((t,a)=>{let n=t.url.split("?")[0];return t.url.startsWith("/ui")&&Sr(r)&&!wr.extname(n)?a.sendFile("index.html",r):a.status(404).send({code:"NOT_FOUND",message:"Route not found"})}),e}function Cr(o,s){try{let e=Buffer.from(o);return e.length!==s.length?!1:ja(e,s)}catch{return!1}}import{z as u}from"zod/v4";import{v4 as Va}from"uuid";var Na=o=>({...o,nullable:!0}),S={type:"object",properties:{code:{type:"string"},message:{type:"string"}}},qa={type:"object",additionalProperties:!0,properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}},La={type:"object",additionalProperties:!0,properties:{type:{type:"string"},cron:{type:"string"},event:{type:"string"}}},Pr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},trigger:La,steps:{type:"array",items:qa},agentPreference:{type:"string"},config:{type:"object",additionalProperties:!0},tags:{type:"array",items:{type:"string"}},enabled:{type:"boolean"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Ma={type:"object",properties:{input:{type:"number"},output:{type:"number"}}},_r={type:"object",additionalProperties:!0,properties:{id:{type:"string"},parentId:{type:"string"},status:{type:"string"},prompt:{type:"string"},originalPrompt:{type:"string"},config:{type:"object",additionalProperties:!0},result:{type:"string"},error:{type:"string"},sdkSessionId:{type:"string"},roleId:{type:"string"},templateId:{type:"string"},createdAt:{type:"number"},startedAt:{type:"number"},completedAt:{type:"number"},costUsd:{type:"number"},tokenUsage:Ma,numTurns:{type:"number"},totalDurationMs:{type:"number"}}},Ba={type:"object",additionalProperties:!0,properties:{model:{type:"string"},effort:{type:"string"},maxTurns:{type:"number"}}},xe={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},source:{type:"string"},traits:{type:"array",items:{type:"string"}},background:{type:"string"},preferences:Ba,learnedRules:{type:"array",items:{type:"string"}},memoryStreamId:{type:"string"},status:{type:"string"},createdAt:{type:"number"},lastActiveAt:{type:"number"},taskCount:{type:"number"},performanceScore:{type:"number"},role:{type:"string"},toolProfile:{type:"array",items:{type:"string"}},evaluationCriteria:{type:"object",additionalProperties:{type:"number"}},strategyPoolId:{type:"string"}}},ht={type:"object",additionalProperties:!0,properties:{id:{type:"string"},roleId:{type:"string"},type:{type:"string"},content:{type:"string"},keywords:{type:"array",items:{type:"string"}},importance:{type:"number"},sourceType:{type:"string"},sourceTaskId:{type:"string"},evidence:{type:"array",items:{type:"string"}},createdAt:{type:"number"},lastAccessed:{type:"number"},retrievedCount:{type:"number"},score:{type:"number"}}},Ua={type:"object",additionalProperties:!0,properties:{id:{type:"string"},role:{type:"string"},taskType:{type:"string"},name:{type:"string"},promptTemplate:{type:"string"},alpha:{type:"number"},beta:{type:"number"},totalTrials:{type:"number"},avgReward:{type:"number"},toolProfile:{type:"array",items:{type:"string"}},createdAt:{type:"number"},updatedAt:{type:"number"}}},bt={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},role:{type:"string"},metricType:{type:"string"},targetValue:{type:"number"},currentValue:{type:"number"},deadline:{type:"number"},budgetUsd:{type:"number"},status:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Wa={type:"object",additionalProperties:!0,properties:{name:{type:"string"},displayName:{type:"string"},description:{type:"string"},tags:{type:"array",items:{type:"string"}},trigger:{type:"string"}}},R={templateCreated:{201:{type:"object",properties:{templateId:{type:"string"}}}},templateList:{200:{type:"object",properties:{templates:{type:"array",items:Pr}}}},templateDetail:{200:{type:"object",properties:{template:Pr}},404:S},templateUpdated:{200:{type:"object",properties:{templateId:{type:"string"}}},404:S},templateDeleted:{200:{type:"object",properties:{templateId:{type:"string"},deleted:{type:"boolean"}}},404:S},templateRun:{200:{type:"object",properties:{executionId:{type:"string"},status:{type:"string"}}},404:S},taskCreated:{201:{type:"object",properties:{taskId:{type:"string"}}},400:S},taskList:{200:{type:"object",properties:{tasks:{type:"array",items:_r}}}},taskDetail:{200:{type:"object",properties:{task:_r}},404:S},taskAction:{200:{type:"object",additionalProperties:!0,properties:{taskId:{type:"string"}}},400:S,404:S},approvalAction:{200:{type:"object",properties:{approvalId:{type:"string"},decision:{type:"string"}}},404:S},agentList:{200:{type:"object",properties:{roles:{type:"array",items:xe}}}},agentDetail:{200:{type:"object",properties:{agent:xe}},404:S},agentCreated:{201:{type:"object",properties:{agent:xe}}},agentUpdated:{200:{type:"object",properties:{agent:xe}},404:S},agentDeleted:{200:{type:"object",properties:{agentId:{type:"string"},deleted:{type:"boolean"}}},400:S,404:S},agentPersona:{200:{type:"object",properties:{persona:Na({type:"string"})}},404:S},memoryList:{200:{type:"object",properties:{memories:{type:"array",items:ht},count:{type:"number"}}},404:S},memoryQuery:{200:{type:"object",properties:{memories:{type:"array",items:ht},count:{type:"number"}}},404:S},memoryCreated:{201:{type:"object",properties:{memory:ht}},400:S,404:S},memoryUpdated:{200:{type:"object",properties:{memoryId:{type:"string"},updated:{type:"boolean"},embeddingUpdated:{type:"boolean"}}},400:S,404:S},memoryDeleted:{200:{type:"object",properties:{memoryId:{type:"string"},deleted:{type:"boolean"}}},404:S},strategyList:{200:{type:"object",properties:{strategies:{type:"array",items:Ua}}}},strategyProbabilities:{200:{type:"object",additionalProperties:!0,properties:{role:{type:"string"},taskType:{type:"string"},stats:{type:"object",additionalProperties:!0},probabilities:{type:"object",additionalProperties:{type:"number"}}}}},goalList:{200:{type:"object",properties:{goals:{type:"array",items:bt}}}},goalDetail:{200:{type:"object",properties:{goal:bt}},404:S},goalCreated:{201:{type:"object",properties:{goal:bt}},400:{...S,additionalProperties:!0,properties:{...S.properties,errors:{type:"array",items:{type:"string"}},warnings:{type:"array",items:{type:"string"}}}}},webhookTriggered:{202:{type:"object",properties:{code:{type:"string"},message:{type:"string"},executionId:{type:"string"},templateId:{type:"string"}}},401:S,404:S,409:S,500:S},webhookList:{200:{type:"object",properties:{webhooks:{type:"array",items:Wa},auth:{type:"string"}}}},configGet:{200:{type:"object",additionalProperties:!0,properties:{config:{type:"object",additionalProperties:{type:"object",additionalProperties:!0,properties:{value:{},mutable:{type:"boolean"}}}},mutable:{type:"array",items:{type:"string"}},restartRequired:{type:"array",items:{type:"string"}}}}},configPatch:{200:{type:"object",additionalProperties:!0,properties:{success:{type:"boolean"},updated:{type:"array",items:{type:"string"}},errors:{type:"array",items:{type:"string"}},message:{type:"string"}}}},healthz:{200:{type:"object",properties:{status:{type:"string"}}}},readyz:{200:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}},503:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}}}};var Er=u.union([u.object({type:u.literal("session"),sessionId:u.string()}),u.object({type:u.literal("channel"),channelId:u.string(),chatId:u.string().optional()})]),Ga=u.object({prompt:u.string().min(1,"prompt is required"),roleId:u.string().optional(),deliverTo:u.array(Er).optional(),reportTo:u.array(Er).optional(),config:u.object({allowedTools:u.array(u.string()).optional(),disallowedTools:u.array(u.string()).optional(),maxTurns:u.number().optional(),maxBudgetUsd:u.number().optional(),mcpServers:u.record(u.string(),u.unknown()).optional(),model:u.string().optional(),effort:u.enum(["low","medium","high","max"]).optional(),settingSources:u.array(u.string()).optional(),workspacePath:u.string().optional(),timeout:u.number().optional(),approvalRequired:u.array(u.string()).optional(),approvalTimeout:u.number().optional(),env:u.record(u.string(),u.string()).optional(),plugins:u.array(u.string()).optional()}).optional()}),re=u.object({id:u.string().uuid()}),$a=["pending","queued","running","paused","completed","failed","cancelled"],Ha=u.object({status:u.enum($a).optional(),roleId:u.string().optional(),limit:u.coerce.number().min(1).max(100).default(100),offset:u.coerce.number().min(0).default(0)});async function Or(o){let s=new ds;o.post("/tasks",{schema:{tags:["Tasks"],summary:"Create a task",description:"Create a new task with a prompt and optional agent/config overrides. The task enters 'pending' status and is picked up by the scheduler.",body:{type:"object",required:["prompt"],properties:{prompt:{type:"string",minLength:1,description:"Task prompt"},roleId:{type:"string",description:"Role to assign"},config:{type:"object",description:"Optional task configuration overrides",properties:{model:{type:"string"},maxTurns:{type:"integer"},maxBudgetUsd:{type:"number"},timeout:{type:"integer"},effort:{type:"string",enum:["low","medium","high","max"]}}}}},response:R.taskCreated}},async(a,n)=>{let i=Ga.safeParse(a.body);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let{prompt:c,roleId:l,config:d,deliverTo:m,reportTo:b}=i.data,I=zt(),y={timeout:d?.timeout??I.timeout,approvalRequired:d?.approvalRequired??I.approvalRequired,approvalTimeout:d?.approvalTimeout??I.approvalTimeout,allowedTools:d?.allowedTools??I.allowedTools,disallowedTools:d?.disallowedTools??I.disallowedTools,maxTurns:d?.maxTurns??I.maxTurns,maxBudgetUsd:d?.maxBudgetUsd??I.maxBudgetUsd,mcpServers:d?.mcpServers,model:d?.model||I.model||void 0,effort:d?.effort??I.effort,settingSources:d?.settingSources??I.settingSources,workspacePath:d?.workspacePath,env:d?.env??I.env,claudeCodePath:I.claudeCodePath,plugins:d?.plugins},g={id:Va(),status:"pending",prompt:c,roleId:l,config:y,deliverTo:m,reportTo:b,createdAt:Date.now()};return Ze(g),f.emit({type:"task_created",taskId:g.id}),n.status(201).send({taskId:g.id})}),o.get("/tasks",{schema:{tags:["Tasks"],summary:"List tasks",description:"List tasks with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["pending","queued","running","paused","completed","failed","cancelled"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}},response:R.taskList}},async(a,n)=>{let i=Ha.safeParse(a.query);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let{status:c,roleId:l,limit:d,offset:m}=i.data;return{tasks:W(c,d,m,l)}}),o.get("/tasks/:id",{schema:{tags:["Tasks"],summary:"Get task by ID",description:"Retrieve a single task by its UUID.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskDetail}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=F(i.data.id);return c?{task:c}:n.status(404).send({code:"NOT_FOUND",message:"Task not found"})}),o.post("/tasks/:id/cancel",{schema:{tags:["Tasks"],summary:"Cancel a task",description:"Cancel a running, queued, pending, or paused task. Returns 400 if the task is in a terminal state.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskAction}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=F(i.data.id);return c?c.status!=="running"&&c.status!=="queued"&&c.status!=="pending"&&c.status!=="paused"?n.status(400).send({code:"INVALID_STATE",message:`Cannot cancel task in status: ${c.status}`}):(s.cancelTask(c.id),{taskId:c.id,status:"cancelled"}):n.status(404).send({code:"NOT_FOUND",message:"Task not found"})});let e=u.object({taskIds:u.array(u.string()).min(1).max(500)});o.post("/tasks/batch-cancel",{schema:{tags:["Tasks"],summary:"Batch cancel tasks",description:"Cancel multiple tasks at once. Skips tasks that are already in terminal state. Returns count of cancelled tasks.",body:{type:"object",required:["taskIds"],properties:{taskIds:{type:"array",items:{type:"string"},minItems:1,maxItems:500}}}}},async(a,n)=>{let i=e.safeParse(a.body);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=new Set(["pending","queued","running","paused"]),l=0,d=[];for(let m of i.data.taskIds){let b=F(m);if(!b){d.push({taskId:m,reason:"not found"});continue}if(!c.has(b.status)){d.push({taskId:m,reason:`already ${b.status}`});continue}s.cancelTask(m),l++}return{cancelled:l,total:i.data.taskIds.length,errors:d.length>0?d:void 0}}),o.get("/tasks/:id/logs",{schema:{tags:["Tasks"],summary:"Get task step logs",description:"Returns execution step logs for a task (reasoning, tool calls, results).",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(a,n)=>{let i=F(a.params.id);if(!i)return n.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:c=50,offset:l=0}=a.query;return{logs:Je(i.id,c,l)}});let r=u.object({approvalId:u.string().uuid(),reason:u.string().optional()});o.post("/tasks/:id/approve",{schema:{tags:["Tasks"],summary:"Approve a pending approval",description:"Approve a tool-use approval request for a paused task. The skill agent resumes execution with the approved tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=r.safeParse(a.body);return c.success?F(i.data.id)?s.resolveApproval(c.data.approvalId,"allow",c.data.reason)?{approvalId:c.data.approvalId,decision:"allow"}:n.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):n.status(404).send({code:"NOT_FOUND",message:"Task not found"}):n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(c.error)})}),o.post("/tasks/:id/reject",{schema:{tags:["Tasks"],summary:"Reject a pending approval",description:"Reject a tool-use approval request for a paused task. The skill agent skips the denied tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=r.safeParse(a.body);return c.success?F(i.data.id)?s.resolveApproval(c.data.approvalId,"deny",c.data.reason)?{approvalId:c.data.approvalId,decision:"deny"}:n.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):n.status(404).send({code:"NOT_FOUND",message:"Task not found"}):n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(c.error)})});let t=u.object({planId:u.string(),decision:u.enum(["allow","deny"]),approvalType:u.enum(["once","permanent"]).optional(),reason:u.string().optional()});o.post("/tasks/:id/approve-plan",{schema:{tags:["Tasks"],summary:"Approve or deny an execution plan",description:"Respond to a plan approval request. Allow once (single task), allow permanent (create rule for similar tasks), or deny.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["planId","decision"],properties:{planId:{type:"string"},decision:{type:"string",enum:["allow","deny"]},approvalType:{type:"string",enum:["once","permanent"]},reason:{type:"string"}}}}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=t.safeParse(a.body);if(!c.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(c.error)});if(!F(i.data.id))return n.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{planId:d,decision:m,approvalType:b,reason:I}=c.data;return s.resolvePlanApproval(d,m,b,I)?{planId:d,decision:m,approvalType:b}:n.status(404).send({code:"NOT_FOUND",message:"Plan approval not found or already resolved"})}),o.get("/tasks/:id/plan",{schema:{tags:["Tasks"],summary:"Get execution plans for a task",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(a,n)=>{let i=re.safeParse(a.params);return i.success?F(i.data.id)?{plans:cs(i.data.id)}:n.status(404).send({code:"NOT_FOUND",message:"Task not found"}):n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)})}),o.get("/tasks/:id/delivery-log",{schema:{tags:["Tasks"],summary:"Get delivery log for a task",description:"Returns delivery log entries for a task, including channel and webhook delivery attempts.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50}}}}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=F(i.data.id);if(!c)return n.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:l=50}=a.query;return{logs:os(c.id,l)}})}Se();Ae();async function Fr(o,s){o.get("/healthz",{schema:{tags:["Health"],summary:"Health check",description:"Basic liveness probe. Returns 200 if the server process is running.",response:R.healthz}},async(e,r)=>({status:"ok"})),o.get("/readyz",{schema:{tags:["Health"],summary:"Readiness check",description:"Readiness probe that checks database, roles, config, embedding model, and task hub. Returns 503 if any check fails.",response:R.readyz}},async(e,r)=>{let t={database:!1,manager:!1,config:!1};try{U().prepare("SELECT 1").get(),t.database=!0}catch{t.database=!1}t.manager=!0,t.config=!!s.server;try{let n=ge(void 0,1,0);t.agents=n.length>0}catch{t.agents=!1}return t.embedding=ls(),t.taskHub=!0,Object.values(t).every(n=>n)?{status:"ready",checks:t}:r.status(503).send({status:"not_ready",checks:t})}),o.get("/stats",{schema:{tags:["Health"],summary:"Runtime statistics",description:"Returns execution pool status, active/pending task counts, and cost summary."}},async(e,r)=>{let a=E().execution?.maxConcurrent??5,n=W("running"),i=W("pending"),c=Xt(ps());return{executionPool:{active:n.length,max:a,queued:i.length},totalCostToday:c}}),o.get("/version",{schema:{tags:["Health"],summary:"Server version",description:"Returns the server version from package.json.",response:{200:{type:"object",properties:{name:{type:"string"},version:{type:"string"}}}}}},async(e,r)=>({name:ns(),version:Pe()}))}import{timingSafeEqual as xr}from"crypto";import{z as jr}from"zod/v4";var vt=class{connections=new Map;eventBuffers=new Map;eventIndices=new Map;addConnection(s,e){this.connections.has(s)||this.connections.set(s,new Set),this.connections.get(s).add(e);let r=this.getBufferedEvents(s);for(let t of r)e.readyState===1&&e.send(JSON.stringify(t));e.on("close",()=>{this.removeConnection(s,e)})}removeConnection(s,e){let r=this.connections.get(s);r&&(r.delete(e),r.size===0&&this.connections.delete(s))}broadcast(s,e){this.addToBuffer(s,e);let r=this.connections.get(s);if(!r||r.size===0)return;let t=JSON.stringify(e);for(let a of r)a.readyState===1&&a.send(t)}addToBuffer(s,e){let r=this.eventBuffers.get(s);r||(r=[],this.eventBuffers.set(s,r)),r.push(e),r.length>100&&r.shift(),this.eventIndices.set(s,e.index)}getBufferedEvents(s){return this.eventBuffers.get(s)??[]}getNextIndex(s){let r=(this.eventIndices.get(s)??0)+1;return this.eventIndices.set(s,r),r}},Dr=new vt;var Ka=jr.object({id:jr.string().uuid()});async function Nr(o,s){o.get("/tasks/:id/stream",{websocket:!0},(e,r)=>{if(s&&!za(r,s)){e.close(4401,"Unauthorized");return}let t=Ka.safeParse(r.params);if(!t.success){e.close(1008,"Invalid task ID");return}let{id:a}=t.data;if(!F(a)){e.close(1008,"Task not found");return}Dr.addConnection(a,e)})}function za(o,s){let e=o.headers["x-api-key"];if(e)try{let a=Buffer.from(e),n=Buffer.from(s);if(a.length===n.length&&xr(a,n))return!0}catch{}let r=o.query,t=r.api_key||r["x-api-key"];if(t)try{let a=Buffer.from(t),n=Buffer.from(s);if(a.length===n.length&&xr(a,n))return!0}catch{}return!1}import{timingSafeEqual as qr}from"crypto";Y();var Qa=q("ws"),je=new Set;function Lr(o,s){o.get("/events",{websocket:!0},(e,r)=>{if(s&&!Ya(r,s)){e.close(4401,"Unauthorized");return}je.add(e),e.on("close",()=>{je.delete(e)}),e.on("error",t=>{Qa.error({error:t},"WebSocket error"),je.delete(e)})}),f.on("task_status_change",e=>{B(e)}),f.on("approval_request",e=>{B(e)}),f.on("stats_update",e=>{B(e)}),f.on("log_event",e=>{B(e)}),f.on("config_changed",e=>{B(e)}),f.on("plan_approval_request",e=>{(()=>{try{let t=ms(e.taskId);if(!t)return!1;let a=gs(t.sessionId);return a?a.source.type==="channel"&&!!a.source.channelId:!1}catch{return!1}})()||B(e)}),f.on("plan_approval_decision",e=>{B(e)}),f.on("task_created",e=>{B(e)}),f.on("execution_slot_change",e=>{B(e)}),f.on("execution_task_start",e=>{B(e)}),f.on("execution_task_end",e=>{B(e)}),f.on("delivery_status_change",e=>{B(e)})}function B(o){let s=JSON.stringify(o);for(let e of je)e.readyState===1&&e.send(s)}function Ya(o,s){let e=o.headers["x-api-key"];if(e)try{let a=Buffer.from(e),n=Buffer.from(s);if(a.length===n.length&&qr(a,n))return!0}catch{}let r=o.query,t=r.api_key||r["x-api-key"];if(t)try{let a=Buffer.from(t),n=Buffer.from(s);if(a.length===n.length&&qr(a,n))return!0}catch{}return!1}Se();function Xa(o){return{id:o.id,sdkSessionId:o.sdk_session_id??void 0,userTaskSessionId:o.user_task_session_id??void 0,workspacePath:o.workspace_path??void 0,toolsFingerprint:o.tools_fingerprint??void 0,createdAt:o.created_at,lastActiveAt:o.last_active_at??void 0}}function Rt(){let o=U(),s=o.prepare("SELECT * FROM server_state WHERE id = 1").get();if(s)return Xa(s);let e=Date.now();return o.prepare("INSERT INTO server_state (id, created_at) VALUES (1, ?)").run(e),{id:1,createdAt:e}}function fe(o){let s=U(),e=[],r=[];"sdkSessionId"in o&&(e.push("sdk_session_id = ?"),r.push(o.sdkSessionId??null)),"userTaskSessionId"in o&&(e.push("user_task_session_id = ?"),r.push(o.userTaskSessionId??null)),"workspacePath"in o&&(e.push("workspace_path = ?"),r.push(o.workspacePath??null)),"lastActiveAt"in o&&(e.push("last_active_at = ?"),r.push(o.lastActiveAt??null)),"toolsFingerprint"in o&&(e.push("tools_fingerprint = ?"),r.push(o.toolsFingerprint??null)),e.length!==0&&(Rt(),r.push(1),s.prepare(`UPDATE server_state SET ${e.join(", ")} WHERE id = ?`).run(...r))}function Ne(o){fe({sdkSessionId:o,lastActiveAt:Date.now()})}function Mr(){fe({sdkSessionId:void 0,lastActiveAt:Date.now()})}function Br(o){fe({workspacePath:o})}Ae();ss();import{z as p}from"zod/v4";import{v4 as Ur}from"uuid";ks();wa();import{rmSync as Za,existsSync as It}from"fs";var Wr=p.object({model:p.string().optional(),effort:p.enum(["low","medium","high","max"]).optional(),maxTurns:p.number().optional()}),Vr=p.object({path:p.string(),mode:p.enum(["ro","rw"]).default("rw"),inheritPlugins:p.boolean().optional(),inheritMcp:p.boolean().optional(),inheritPermissions:p.boolean().optional()}),Ja=p.string().max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Env var key must match POSIX format: [A-Za-z_][A-Za-z0-9_]*").check(p.refine(o=>!o.startsWith("ANTHROPIC_"),"ANTHROPIC_* keys are managed globally in Settings")),Gr=p.record(Ja,p.string().max(4096)).optional().check(p.refine(o=>!o||Object.keys(o).length<=100,"Maximum 100 environment variables per role")),en=p.object({name:p.string().min(1,"name is required").regex(/^[\p{L}\p{N}_-]+$/u,"name must contain only letters, numbers, underscores, or hyphens"),cagPrompt:p.string().optional(),learnedRules:p.array(p.string()).optional(),allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),evaluationCriteria:p.record(p.string(),p.number()).optional(),executionMode:p.enum(["isolated","inline"]).optional(),model:p.string().optional(),maxBudgetUsd:p.number().optional(),approvalRequired:p.array(p.string()).optional(),preferences:Wr.optional(),additionalDirectories:p.array(Vr).optional(),allowedChannels:p.array(p.string()).optional(),inheritUserSettings:p.boolean().optional(),envVars:Gr}),tn=p.object({name:p.string().min(1).optional(),cagPrompt:p.string().optional(),learnedRules:p.array(p.string()).optional(),status:p.enum(["active","inactive","retired"]).optional(),allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),evaluationCriteria:p.record(p.string(),p.number()).optional(),executionMode:p.enum(["isolated","inline"]).optional(),model:p.string().optional(),maxBudgetUsd:p.number().optional(),approvalRequired:p.array(p.string()).optional(),preferences:Wr.optional(),additionalDirectories:p.array(Vr).optional(),allowedChannels:p.array(p.string()).nullable().optional(),inheritUserSettings:p.boolean().optional(),envVars:Gr}),qe=p.object({id:p.string().min(1)}),sn=p.object({status:p.enum(["active","inactive","retired"]).optional(),limit:p.coerce.number().min(1).max(100).default(100),offset:p.coerce.number().min(0).default(0)}),rn=p.object({path:p.string().min(1)});async function $r(o){o.get("/roles",{schema:{tags:["Roles"],summary:"List all roles",description:"List all roles with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["active","inactive","retired"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(s,e)=>{let r=sn.safeParse(s.query);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let{status:t,limit:a,offset:n}=r.data;return{roles:ge(t,a,n).map(c=>({...c,workspacePath:te(c.name)}))}}),o.post("/roles",{schema:{tags:["Roles"],summary:"Create a role",description:"Create a new role with a name, CAG prompt, and optional preferences.",body:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(s,e)=>{let r=en.safeParse(s.body);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let{name:t,cagPrompt:a,learnedRules:n,allowedTools:i,disallowedTools:c,evaluationCriteria:l,executionMode:d,model:m,maxBudgetUsd:b,approvalRequired:I,preferences:y,additionalDirectories:g,allowedChannels:A,inheritUserSettings:V,envVars:ne}=r.data;if(tt(t))return e.status(409).send({code:"CONFLICT",message:`Role with name '${t}' already exists`});let H={id:`role-${Ur().slice(0,8)}`,name:t,cagPrompt:a??"",learnedRules:n??[],memoryStreamId:`mem-${Ur().slice(0,8)}`,status:"active",preferences:y??{},allowedTools:i,disallowedTools:c,evaluationCriteria:l,executionMode:d,model:m,maxBudgetUsd:b,approvalRequired:I,additionalDirectories:g,allowedChannels:A,inheritUserSettings:V,envVars:ne,createdAt:Date.now()};return et(H),at(H),e.status(201).send({role:H})}),o.get("/roles/:id",{schema:{tags:["Roles"],summary:"Get role by ID",description:"Retrieve a single role with its project-scope plugins.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=L(r.data.id);if(!t)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=te(t.name),n=_e({scope:"project",projectPath:a});return{role:t,projectPlugins:n,workspacePath:a}}),o.get("/roles/:id/scores",{schema:{tags:["Roles"],summary:"Get role quality scores",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:100,default:20}}}}},async(s,e)=>{let r=p.object({id:p.string().min(1)}).safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=L(r.data.id);if(!t)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=s.query.limit??20,n=fs(t.id,a),i=hs(t.id);return{scores:n,latestEma:i??null}}),o.patch("/roles/:id",{schema:{tags:["Roles"],summary:"Update a role",description:"Partially update a role's CAG prompt, learned rules, status, or preferences.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},learnedRules:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","inactive","retired"]},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=tn.safeParse(s.body);if(!t.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(t.error)});if(!L(r.data.id))return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let{allowedChannels:n,...i}=t.data,c={...i,updatedAt:Date.now()};if(n!==void 0&&(c.allowedChannels=n??void 0),Ce(r.data.id,c),t.data.cagPrompt!==void 0||t.data.learnedRules!==void 0){let d=L(r.data.id);if(d){let m=te(d.name);It(m)&&nt(m,d)}}let l=L(r.data.id);if(l&&(t.data.allowedTools!==void 0||t.data.disallowedTools!==void 0)){let d=te(l.name);It(d)&&ot(l.id,l.allowedTools,d)}return{role:l}}),o.delete("/roles/:id",{schema:{tags:["Roles"],summary:"Delete a role",description:"Delete a role and its workspace.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=L(r.data.id);if(!t)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});if(t.id===rs)return e.status(403).send({code:"FORBIDDEN",message:"System role 'chat-manager' cannot be deleted"});let a=te(t.name);if(It(a))try{Za(a,{recursive:!0,force:!0})}catch{}return st(r.data.id),{roleId:r.data.id,deleted:!0}}),o.post("/roles/:id/scan-directory",{schema:{tags:["Roles"],summary:"Scan directory for plugin/permission configuration",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=rn.safeParse(s.body);if(!t.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(t.error)});if(!L(r.data.id))return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=Is(t.data.path);return{path:t.data.path,enabledPlugins:n.enabledPlugins,mcpServers:n.mcpServers,allowedTools:n.allowedTools,disallowedTools:n.disallowedTools}}),o.get("/roles/:id/env-diff",{schema:{tags:["Roles"],summary:"Get role env diff",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=L(s.params.id);return r?{diffs:es(r.name,r.envVars),envFileExists:rt(r.name)!==null}:e.status(404).send({code:"NOT_FOUND",message:"Role not found"})}),o.post("/roles/:id/sync-to-env",{schema:{tags:["Roles"],summary:"Sync role env to .env file",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=L(s.params.id);return r?{success:!0,changed:ts(r.name,r.envVars)}:e.status(404).send({code:"NOT_FOUND",message:"Role not found"})}),o.post("/roles/:id/load-from-env",{schema:{tags:["Roles"],summary:"Load role env from .env file",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=L(s.params.id);if(!r)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let t=rt(r.name);if(!t)return e.status(400).send({code:"NOT_FOUND",message:".env file not found in role workspace"});let a={};for(let[n,i]of Object.entries(t))n.startsWith("ANTHROPIC_")||(a[n]=i);return Ce(r.id,{envVars:Object.keys(a).length>0?a:void 0,updatedAt:Date.now()}),{success:!0,updated:Object.keys(a).length}})}me();import{z as Hr}from"zod/v4";import{readdirSync as an,existsSync as nn}from"fs";import{join as kt,resolve as Kr,sep as Qr}from"path";import{homedir as on}from"os";var cn=20,dn=Hr.object({prefix:Hr.string()});function Yr(o){return o.startsWith("~/")?kt(on(),o.slice(2)):o}function zr(o){let s=Kr(o);for(let e of Mt){let r=Yr(e),t=Kr(r);if(s===t||s.startsWith(t+Qr))return!0}return!1}async function Xr(o){o.get("/fs/suggest-dirs",{schema:{tags:["FS"],summary:"Suggest directory completions",description:"Return directory suggestions matching a given path prefix.",querystring:{type:"object",required:["prefix"],properties:{prefix:{type:"string"}}}}},async(s,e)=>{let r=dn.safeParse(s.query);if(!r.success)return{suggestions:[]};let{prefix:t}=r.data;if(!t.startsWith("/")&&!t.startsWith("~/"))return{suggestions:[]};if(zr(t))return{suggestions:[]};let a=Yr(t),n,i;if(t.endsWith("/"))n=a,i="";else{let g=Math.max(a.lastIndexOf("/"),a.lastIndexOf(Qr));if(g<0)return{suggestions:[]};n=a.slice(0,g+1),i=a.slice(g+1)}if(!nn(n))return{suggestions:[]};let c;try{c=an(n,{withFileTypes:!0}).filter(g=>g.isDirectory()).map(g=>g.name)}catch{return{suggestions:[]}}let l=i.toLowerCase(),d=c.filter(g=>g.toLowerCase().startsWith(l)),I=(i.startsWith(".")?d:d.filter(g=>!g.startsWith("."))).filter(g=>!zr(kt(n,g)));return I.sort((g,A)=>g.localeCompare(A,void 0,{sensitivity:"base"})),{suggestions:I.slice(0,cn).map(g=>kt(n,g))}})}import{z as w}from"zod/v4";Ae();import{v4 as ln}from"uuid";var pn=w.object({roleId:w.string().min(1)}),un=w.object({roleId:w.string().min(1),prompt:w.string().min(1),topK:w.number().min(1).max(50).default(10)}),mn=w.object({limit:w.coerce.number().min(1).max(200).default(50),offset:w.coerce.number().min(0).default(0)});function Tt(o){return L(o)!==void 0}async function Zr(o){o.get("/memories/:roleId",{schema:{tags:["Memories"],summary:"List role memories",description:"List all memories for a specific role with pagination. Embeddings are stripped from the response.",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}},response:R.memoryList}},async(r,t)=>{let a=pn.safeParse(r.params);if(!a.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(a.error)});let n=a.data.roleId;if(!Tt(n))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let i=mn.safeParse(r.query),{limit:c,offset:l}=i.success?i.data:{limit:50,offset:0},m=ws(n,c,l).map(({embedding:b,...I})=>I);return{memories:m,count:m.length}}),o.post("/memories/query",{schema:{tags:["Memories"],summary:"Query role memories",description:"Query a role's memories using hybrid search (FTS5 + vector similarity) with Smallville-style scoring (recency, importance, relevance).",body:{type:"object",required:["roleId","prompt"],properties:{roleId:{type:"string",minLength:1,description:"The role whose memories to query"},prompt:{type:"string",minLength:1,description:"The search query"},topK:{type:"integer",minimum:1,maximum:50,default:10,description:"Number of results to return"}}},response:R.memoryQuery}},async(r,t)=>{let a=un.safeParse(r.body);if(!a.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(a.error)});let{roleId:n,prompt:i,topK:c}=a.data;if(!Tt(n))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let d=(await lt(n,i,{topK:c})).map(({embedding:m,...b})=>b);return{memories:d,count:d.length}});let s=w.object({roleId:w.string().min(1),content:w.string().min(1),type:w.enum(["event","thought","reflection"]).default("thought"),keywords:w.array(w.string()).default([]),importance:w.number().min(1).max(5).default(3),tier:w.enum(["working","episodic","semantic"]).default("episodic")});o.post("/memories",{schema:{tags:["Memories"],summary:"Create memory",description:"Create a new memory for a role. Embedding is auto-generated from content.",body:{type:"object",required:["roleId","content"],properties:{roleId:{type:"string",minLength:1},content:{type:"string",minLength:1},type:{type:"string",enum:["event","thought","reflection"],default:"thought"},keywords:{type:"array",items:{type:"string"},default:[]},importance:{type:"integer",minimum:1,maximum:5,default:3},tier:{type:"string",enum:["working","episodic","semantic"],default:"episodic"}}},response:R.memoryCreated}},async(r,t)=>{let a=s.safeParse(r.body);if(!a.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(a.error)});let{roleId:n,content:i,type:c,keywords:l,importance:d,tier:m}=a.data;if(!Tt(n))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let b;try{b=await it(i)}catch{}let I=`mem-${ln().slice(0,8)}`,y=Date.now();Ts({id:I,roleId:n,type:c,content:i,embedding:b,keywords:l,importance:d,sourceType:"manual",createdAt:y,lastAccessed:y,retrievedCount:0,tier:m??"episodic"});let g=Ee(I),{embedding:A,...V}=g;return t.status(201).send({memory:V})});let e=w.object({content:w.string().min(1).optional(),type:w.enum(["event","thought","reflection"]).optional(),keywords:w.array(w.string()).optional(),importance:w.number().min(1).max(5).optional()});o.patch("/memories/:id",{schema:{tags:["Memories"],summary:"Update memory",description:"Update a memory's content, type, keywords, or importance. Embedding is regenerated if content changes.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{content:{type:"string",minLength:1},type:{type:"string",enum:["event","thought","reflection"]},keywords:{type:"array",items:{type:"string"}},importance:{type:"integer",minimum:1,maximum:5}}},response:R.memoryUpdated}},async(r,t)=>{let{id:a}=r.params;if(!Ee(a))return t.status(404).send({code:"NOT_FOUND",message:"Memory not found"});let i=e.safeParse(r.body);if(!i.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(i.error)});let c=i.data,l,d=!0;if(c.content)try{l=await it(c.content)}catch{d=!1}let m=Ss(a,{content:c.content,embedding:l,keywords:c.keywords,importance:c.importance,type:c.type});return{memoryId:a,updated:m,embeddingUpdated:d}}),o.delete("/memories/:id",{schema:{tags:["Memories"],summary:"Delete memory",description:"Delete a memory by ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.memoryDeleted}},async(r,t)=>{let{id:a}=r.params;return Ee(a)?(Cs(a),{memoryId:a,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Memory not found"})})}import{query as hn}from"@anthropic-ai/claude-agent-sdk";import{v4 as ae}from"uuid";function gn(){try{return E().defaults.maxBudgetUsd}catch{return 5}}function St(o){return`# ChatManager \u2014 User Interface Agent
2
+ `),r=0;for(let t of e){let a=t.trim();if(!a||a.startsWith("#"))continue;a.startsWith("export ")&&(a=a.slice(7).trim());let n=a.indexOf("=");if(n===-1)continue;let i=a.slice(0,n).trim();if(!i)continue;let c=a.slice(n+1).trim();(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c=c.slice(1,-1)),c=c.replace(/\$\{(\w+)\}|\$(\w+)/g,(l,d,m)=>{let b=d??m;return process.env[b]??""}),(i.startsWith("ANTHROPIC_")||process.env[i]===void 0)&&(process.env[i]=c,r++)}return r}Se();Ae();ss();import{existsSync as Sr}from"fs";import wr from"path";import _a from"fastify";import Ea from"@fastify/cors";import Oa from"@fastify/static";import Fa from"@fastify/websocket";import Da from"@fastify/swagger";import xa from"@fastify/swagger-ui";import{timingSafeEqual as ja}from"crypto";function Ar(o,s){let e=_a({logger:!1});if(e.register(Da,{openapi:{info:{title:"Adam API",description:"Agent orchestration server built on Claude Agent SDK. Multi-agent system with parallel task execution, intelligent agent routing, self-evolving personas, and REST/WebSocket API.",version:Pe()},servers:[{url:"http://localhost:7100"}],tags:[{name:"Tasks",description:"Task lifecycle management"},{name:"Roles",description:"Role CRUD and workspace management"},{name:"Skills",description:"Skill CRUD and permissions"},{name:"Memories",description:"Agent memory search and retrieval"},{name:"Goals",description:"Goal-driven task management"},{name:"Strategies",description:"Thompson Sampling strategy engine"},{name:"Templates",description:"Task template CRUD and triggers"},{name:"Webhooks",description:"External system integration"},{name:"Config",description:"Runtime configuration management"},{name:"Evolution",description:"Agent evolution audit log"},{name:"Health",description:"Server health checks"}],components:{securitySchemes:{apiKey:{type:"apiKey",in:"header",name:"x-api-key",description:"API key for webhook endpoints"}}}}}),e.register(xa,{routePrefix:"/docs"}),e.register(Ea,{origin:!0}),e.register(Fa,{options:{maxPayload:1024*1024*16}}),s){let t=Buffer.from(s);e.addHook("onRequest",async(a,n)=>{let i=a.url;if(i==="/healthz"||i==="/readyz"||i.startsWith("/docs")||i.startsWith("/ui"))return;let c=a.headers["x-api-key"];if(c&&Cr(c,t))return;let l=a.query,d=l.api_key||l["x-api-key"];if(!(d&&Cr(d,t)))return n.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"})})}let r=wr.join(as,"web/dist");return Sr(r)&&(e.register(Oa,{root:r,prefix:"/ui/",wildcard:!0}),e.get("/ui",async(t,a)=>a.sendFile("index.html",r))),e.setErrorHandler((t,a,n)=>{if(t.validation){let c=t.validation.map(l=>{let d=l.instancePath||l.params?.missingProperty||"";return d?`${d}: ${l.message}`:l.message});return n.status(400).send({code:"VALIDATION_ERROR",message:c.join("; ")})}let i=t.statusCode??500;return n.status(i).send({code:"INTERNAL_ERROR",message:t.message})}),e.setNotFoundHandler((t,a)=>{let n=t.url.split("?")[0];return t.url.startsWith("/ui")&&Sr(r)&&!wr.extname(n)?a.sendFile("index.html",r):a.status(404).send({code:"NOT_FOUND",message:"Route not found"})}),e}function Cr(o,s){try{let e=Buffer.from(o);return e.length!==s.length?!1:ja(e,s)}catch{return!1}}import{z as u}from"zod/v4";import{v4 as Va}from"uuid";var Na=o=>({...o,nullable:!0}),S={type:"object",properties:{code:{type:"string"},message:{type:"string"}}},qa={type:"object",additionalProperties:!0,properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}},La={type:"object",additionalProperties:!0,properties:{type:{type:"string"},cron:{type:"string"},event:{type:"string"}}},Pr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},trigger:La,steps:{type:"array",items:qa},agentPreference:{type:"string"},config:{type:"object",additionalProperties:!0},tags:{type:"array",items:{type:"string"}},enabled:{type:"boolean"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Ma={type:"object",properties:{input:{type:"number"},output:{type:"number"}}},_r={type:"object",additionalProperties:!0,properties:{id:{type:"string"},parentId:{type:"string"},status:{type:"string"},prompt:{type:"string"},originalPrompt:{type:"string"},config:{type:"object",additionalProperties:!0},result:{type:"string"},error:{type:"string"},sdkSessionId:{type:"string"},roleId:{type:"string"},templateId:{type:"string"},createdAt:{type:"number"},startedAt:{type:"number"},completedAt:{type:"number"},costUsd:{type:"number"},tokenUsage:Ma,numTurns:{type:"number"},totalDurationMs:{type:"number"}}},Ba={type:"object",additionalProperties:!0,properties:{model:{type:"string"},effort:{type:"string"},maxTurns:{type:"number"}}},xe={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},source:{type:"string"},traits:{type:"array",items:{type:"string"}},background:{type:"string"},preferences:Ba,learnedRules:{type:"array",items:{type:"string"}},memoryStreamId:{type:"string"},status:{type:"string"},createdAt:{type:"number"},lastActiveAt:{type:"number"},taskCount:{type:"number"},performanceScore:{type:"number"},role:{type:"string"},toolProfile:{type:"array",items:{type:"string"}},evaluationCriteria:{type:"object",additionalProperties:{type:"number"}},strategyPoolId:{type:"string"}}},ht={type:"object",additionalProperties:!0,properties:{id:{type:"string"},roleId:{type:"string"},type:{type:"string"},content:{type:"string"},keywords:{type:"array",items:{type:"string"}},importance:{type:"number"},sourceType:{type:"string"},sourceTaskId:{type:"string"},evidence:{type:"array",items:{type:"string"}},createdAt:{type:"number"},lastAccessed:{type:"number"},retrievedCount:{type:"number"},score:{type:"number"}}},Ua={type:"object",additionalProperties:!0,properties:{id:{type:"string"},role:{type:"string"},taskType:{type:"string"},name:{type:"string"},promptTemplate:{type:"string"},alpha:{type:"number"},beta:{type:"number"},totalTrials:{type:"number"},avgReward:{type:"number"},toolProfile:{type:"array",items:{type:"string"}},createdAt:{type:"number"},updatedAt:{type:"number"}}},bt={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},role:{type:"string"},metricType:{type:"string"},targetValue:{type:"number"},currentValue:{type:"number"},deadline:{type:"number"},budgetUsd:{type:"number"},status:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Wa={type:"object",additionalProperties:!0,properties:{name:{type:"string"},displayName:{type:"string"},description:{type:"string"},tags:{type:"array",items:{type:"string"}},trigger:{type:"string"}}},R={templateCreated:{201:{type:"object",properties:{templateId:{type:"string"}}}},templateList:{200:{type:"object",properties:{templates:{type:"array",items:Pr}}}},templateDetail:{200:{type:"object",properties:{template:Pr}},404:S},templateUpdated:{200:{type:"object",properties:{templateId:{type:"string"}}},404:S},templateDeleted:{200:{type:"object",properties:{templateId:{type:"string"},deleted:{type:"boolean"}}},404:S},templateRun:{200:{type:"object",properties:{executionId:{type:"string"},status:{type:"string"}}},404:S},taskCreated:{201:{type:"object",properties:{taskId:{type:"string"}}},400:S},taskList:{200:{type:"object",properties:{tasks:{type:"array",items:_r}}}},taskDetail:{200:{type:"object",properties:{task:_r}},404:S},taskAction:{200:{type:"object",additionalProperties:!0,properties:{taskId:{type:"string"}}},400:S,404:S},approvalAction:{200:{type:"object",properties:{approvalId:{type:"string"},decision:{type:"string"}}},404:S},agentList:{200:{type:"object",properties:{roles:{type:"array",items:xe}}}},agentDetail:{200:{type:"object",properties:{agent:xe}},404:S},agentCreated:{201:{type:"object",properties:{agent:xe}}},agentUpdated:{200:{type:"object",properties:{agent:xe}},404:S},agentDeleted:{200:{type:"object",properties:{agentId:{type:"string"},deleted:{type:"boolean"}}},400:S,404:S},agentPersona:{200:{type:"object",properties:{persona:Na({type:"string"})}},404:S},memoryList:{200:{type:"object",properties:{memories:{type:"array",items:ht},count:{type:"number"}}},404:S},memoryQuery:{200:{type:"object",properties:{memories:{type:"array",items:ht},count:{type:"number"}}},404:S},memoryCreated:{201:{type:"object",properties:{memory:ht}},400:S,404:S},memoryUpdated:{200:{type:"object",properties:{memoryId:{type:"string"},updated:{type:"boolean"},embeddingUpdated:{type:"boolean"}}},400:S,404:S},memoryDeleted:{200:{type:"object",properties:{memoryId:{type:"string"},deleted:{type:"boolean"}}},404:S},strategyList:{200:{type:"object",properties:{strategies:{type:"array",items:Ua}}}},strategyProbabilities:{200:{type:"object",additionalProperties:!0,properties:{role:{type:"string"},taskType:{type:"string"},stats:{type:"object",additionalProperties:!0},probabilities:{type:"object",additionalProperties:{type:"number"}}}}},goalList:{200:{type:"object",properties:{goals:{type:"array",items:bt}}}},goalDetail:{200:{type:"object",properties:{goal:bt}},404:S},goalCreated:{201:{type:"object",properties:{goal:bt}},400:{...S,additionalProperties:!0,properties:{...S.properties,errors:{type:"array",items:{type:"string"}},warnings:{type:"array",items:{type:"string"}}}}},webhookTriggered:{202:{type:"object",properties:{code:{type:"string"},message:{type:"string"},executionId:{type:"string"},templateId:{type:"string"}}},401:S,404:S,409:S,500:S},webhookList:{200:{type:"object",properties:{webhooks:{type:"array",items:Wa},auth:{type:"string"}}}},configGet:{200:{type:"object",additionalProperties:!0,properties:{config:{type:"object",additionalProperties:{type:"object",additionalProperties:!0,properties:{value:{},mutable:{type:"boolean"}}}},mutable:{type:"array",items:{type:"string"}},restartRequired:{type:"array",items:{type:"string"}}}}},configPatch:{200:{type:"object",additionalProperties:!0,properties:{success:{type:"boolean"},updated:{type:"array",items:{type:"string"}},errors:{type:"array",items:{type:"string"}},message:{type:"string"}}}},healthz:{200:{type:"object",properties:{status:{type:"string"}}}},readyz:{200:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}},503:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}}}};var Er=u.union([u.object({type:u.literal("session"),sessionId:u.string()}),u.object({type:u.literal("channel"),channelId:u.string(),chatId:u.string().optional()})]),Ga=u.object({prompt:u.string().min(1,"prompt is required"),roleId:u.string().optional(),deliverTo:u.array(Er).optional(),reportTo:u.array(Er).optional(),config:u.object({allowedTools:u.array(u.string()).optional(),disallowedTools:u.array(u.string()).optional(),maxTurns:u.number().optional(),maxBudgetUsd:u.number().optional(),mcpServers:u.record(u.string(),u.unknown()).optional(),model:u.string().optional(),effort:u.enum(["low","medium","high","max"]).optional(),settingSources:u.array(u.string()).optional(),workspacePath:u.string().optional(),timeout:u.number().optional(),approvalRequired:u.array(u.string()).optional(),approvalTimeout:u.number().optional(),env:u.record(u.string(),u.string()).optional(),plugins:u.array(u.string()).optional()}).optional()}),re=u.object({id:u.string().uuid()}),$a=["pending","queued","running","paused","completed","failed","cancelled"],Ha=u.object({status:u.enum($a).optional(),roleId:u.string().optional(),limit:u.coerce.number().min(1).max(100).default(100),offset:u.coerce.number().min(0).default(0)});async function Or(o){let s=new ds;o.post("/tasks",{schema:{tags:["Tasks"],summary:"Create a task",description:"Create a new task with a prompt and optional agent/config overrides. The task enters 'pending' status and is picked up by the scheduler.",body:{type:"object",required:["prompt"],properties:{prompt:{type:"string",minLength:1,description:"Task prompt"},roleId:{type:"string",description:"Role to assign"},config:{type:"object",description:"Optional task configuration overrides",properties:{model:{type:"string"},maxTurns:{type:"integer"},maxBudgetUsd:{type:"number"},timeout:{type:"integer"},effort:{type:"string",enum:["low","medium","high","max"]}}}}},response:R.taskCreated}},async(a,n)=>{let i=Ga.safeParse(a.body);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let{prompt:c,roleId:l,config:d,deliverTo:m,reportTo:b}=i.data,I=zt(),y={timeout:d?.timeout??I.timeout,approvalRequired:d?.approvalRequired??I.approvalRequired,approvalTimeout:d?.approvalTimeout??I.approvalTimeout,allowedTools:d?.allowedTools??I.allowedTools,disallowedTools:d?.disallowedTools??I.disallowedTools,maxTurns:d?.maxTurns??I.maxTurns,maxBudgetUsd:d?.maxBudgetUsd??I.maxBudgetUsd,mcpServers:d?.mcpServers,model:d?.model||I.model||void 0,effort:d?.effort??I.effort,settingSources:d?.settingSources??I.settingSources,workspacePath:d?.workspacePath,env:d?.env??I.env,claudeCodePath:I.claudeCodePath,plugins:d?.plugins},g={id:Va(),status:"pending",prompt:c,roleId:l,config:y,deliverTo:m,reportTo:b,createdAt:Date.now()};return Ze(g),f.emit({type:"task_created",taskId:g.id}),n.status(201).send({taskId:g.id})}),o.get("/tasks",{schema:{tags:["Tasks"],summary:"List tasks",description:"List tasks with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["pending","queued","running","paused","completed","failed","cancelled"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}},response:R.taskList}},async(a,n)=>{let i=Ha.safeParse(a.query);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let{status:c,roleId:l,limit:d,offset:m}=i.data;return{tasks:W(c,d,m,l)}}),o.get("/tasks/:id",{schema:{tags:["Tasks"],summary:"Get task by ID",description:"Retrieve a single task by its UUID.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskDetail}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=F(i.data.id);return c?{task:c}:n.status(404).send({code:"NOT_FOUND",message:"Task not found"})}),o.post("/tasks/:id/cancel",{schema:{tags:["Tasks"],summary:"Cancel a task",description:"Cancel a running, queued, pending, or paused task. Returns 400 if the task is in a terminal state.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskAction}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=F(i.data.id);return c?c.status!=="running"&&c.status!=="queued"&&c.status!=="pending"&&c.status!=="paused"?n.status(400).send({code:"INVALID_STATE",message:`Cannot cancel task in status: ${c.status}`}):(s.cancelTask(c.id),{taskId:c.id,status:"cancelled"}):n.status(404).send({code:"NOT_FOUND",message:"Task not found"})});let e=u.object({taskIds:u.array(u.string()).min(1).max(500)});o.post("/tasks/batch-cancel",{schema:{tags:["Tasks"],summary:"Batch cancel tasks",description:"Cancel multiple tasks at once. Skips tasks that are already in terminal state. Returns count of cancelled tasks.",body:{type:"object",required:["taskIds"],properties:{taskIds:{type:"array",items:{type:"string"},minItems:1,maxItems:500}}}}},async(a,n)=>{let i=e.safeParse(a.body);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=new Set(["pending","queued","running","paused"]),l=0,d=[];for(let m of i.data.taskIds){let b=F(m);if(!b){d.push({taskId:m,reason:"not found"});continue}if(!c.has(b.status)){d.push({taskId:m,reason:`already ${b.status}`});continue}s.cancelTask(m),l++}return{cancelled:l,total:i.data.taskIds.length,errors:d.length>0?d:void 0}}),o.get("/tasks/:id/logs",{schema:{tags:["Tasks"],summary:"Get task step logs",description:"Returns execution step logs for a task (reasoning, tool calls, results).",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(a,n)=>{let i=F(a.params.id);if(!i)return n.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:c=50,offset:l=0}=a.query;return{logs:Je(i.id,c,l)}});let r=u.object({approvalId:u.string().uuid(),reason:u.string().optional()});o.post("/tasks/:id/approve",{schema:{tags:["Tasks"],summary:"Approve a pending approval",description:"Approve a tool-use approval request for a paused task. The skill agent resumes execution with the approved tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=r.safeParse(a.body);return c.success?F(i.data.id)?s.resolveApproval(c.data.approvalId,"allow",c.data.reason)?{approvalId:c.data.approvalId,decision:"allow"}:n.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):n.status(404).send({code:"NOT_FOUND",message:"Task not found"}):n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(c.error)})}),o.post("/tasks/:id/reject",{schema:{tags:["Tasks"],summary:"Reject a pending approval",description:"Reject a tool-use approval request for a paused task. The skill agent skips the denied tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=r.safeParse(a.body);return c.success?F(i.data.id)?s.resolveApproval(c.data.approvalId,"deny",c.data.reason)?{approvalId:c.data.approvalId,decision:"deny"}:n.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):n.status(404).send({code:"NOT_FOUND",message:"Task not found"}):n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(c.error)})});let t=u.object({planId:u.string(),decision:u.enum(["allow","deny"]),approvalType:u.enum(["once","permanent"]).optional(),reason:u.string().optional()});o.post("/tasks/:id/approve-plan",{schema:{tags:["Tasks"],summary:"Approve or deny an execution plan",description:"Respond to a plan approval request. Allow once (single task), allow permanent (create rule for similar tasks), or deny.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["planId","decision"],properties:{planId:{type:"string"},decision:{type:"string",enum:["allow","deny"]},approvalType:{type:"string",enum:["once","permanent"]},reason:{type:"string"}}}}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=t.safeParse(a.body);if(!c.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(c.error)});if(!F(i.data.id))return n.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{planId:d,decision:m,approvalType:b,reason:I}=c.data;return s.resolvePlanApproval(d,m,b,I)?{planId:d,decision:m,approvalType:b}:n.status(404).send({code:"NOT_FOUND",message:"Plan approval not found or already resolved"})}),o.get("/tasks/:id/plan",{schema:{tags:["Tasks"],summary:"Get execution plans for a task",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(a,n)=>{let i=re.safeParse(a.params);return i.success?F(i.data.id)?{plans:cs(i.data.id)}:n.status(404).send({code:"NOT_FOUND",message:"Task not found"}):n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)})}),o.get("/tasks/:id/delivery-log",{schema:{tags:["Tasks"],summary:"Get delivery log for a task",description:"Returns delivery log entries for a task, including channel and webhook delivery attempts.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50}}}}},async(a,n)=>{let i=re.safeParse(a.params);if(!i.success)return n.status(400).send({code:"VALIDATION_ERROR",message:u.prettifyError(i.error)});let c=F(i.data.id);if(!c)return n.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:l=50}=a.query;return{logs:os(c.id,l)}})}Se();Ae();async function Fr(o,s){o.get("/healthz",{schema:{tags:["Health"],summary:"Health check",description:"Basic liveness probe. Returns 200 if the server process is running.",response:R.healthz}},async(e,r)=>({status:"ok"})),o.get("/readyz",{schema:{tags:["Health"],summary:"Readiness check",description:"Readiness probe that checks database, roles, config, embedding model, and task hub. Returns 503 if any check fails.",response:R.readyz}},async(e,r)=>{let t={database:!1,manager:!1,config:!1};try{U().prepare("SELECT 1").get(),t.database=!0}catch{t.database=!1}t.manager=!0,t.config=!!s.server;try{let n=ge(void 0,1,0);t.agents=n.length>0}catch{t.agents=!1}return t.embedding=ls(),t.taskHub=!0,Object.values(t).every(n=>n)?{status:"ready",checks:t}:r.status(503).send({status:"not_ready",checks:t})}),o.get("/stats",{schema:{tags:["Health"],summary:"Runtime statistics",description:"Returns execution pool status, active/pending task counts, and cost summary."}},async(e,r)=>{let a=E().execution?.maxConcurrent??5,n=W("running"),i=W("pending"),c=Xt(ps());return{executionPool:{active:n.length,max:a,queued:i.length},totalCostToday:c}}),o.get("/version",{schema:{tags:["Health"],summary:"Server version",description:"Returns the server version from package.json.",response:{200:{type:"object",properties:{name:{type:"string"},version:{type:"string"}}}}}},async(e,r)=>({name:ns(),version:Pe()}))}import{timingSafeEqual as xr}from"crypto";import{z as jr}from"zod/v4";var vt=class{connections=new Map;eventBuffers=new Map;eventIndices=new Map;addConnection(s,e){this.connections.has(s)||this.connections.set(s,new Set),this.connections.get(s).add(e);let r=this.getBufferedEvents(s);for(let t of r)e.readyState===1&&e.send(JSON.stringify(t));e.on("close",()=>{this.removeConnection(s,e)})}removeConnection(s,e){let r=this.connections.get(s);r&&(r.delete(e),r.size===0&&this.connections.delete(s))}broadcast(s,e){this.addToBuffer(s,e);let r=this.connections.get(s);if(!r||r.size===0)return;let t=JSON.stringify(e);for(let a of r)a.readyState===1&&a.send(t)}addToBuffer(s,e){let r=this.eventBuffers.get(s);r||(r=[],this.eventBuffers.set(s,r)),r.push(e),r.length>100&&r.shift(),this.eventIndices.set(s,e.index)}getBufferedEvents(s){return this.eventBuffers.get(s)??[]}getNextIndex(s){let r=(this.eventIndices.get(s)??0)+1;return this.eventIndices.set(s,r),r}},Dr=new vt;var Ka=jr.object({id:jr.string().uuid()});async function Nr(o,s){o.get("/tasks/:id/stream",{websocket:!0},(e,r)=>{if(s&&!za(r,s)){e.close(4401,"Unauthorized");return}let t=Ka.safeParse(r.params);if(!t.success){e.close(1008,"Invalid task ID");return}let{id:a}=t.data;if(!F(a)){e.close(1008,"Task not found");return}Dr.addConnection(a,e)})}function za(o,s){let e=o.headers["x-api-key"];if(e)try{let a=Buffer.from(e),n=Buffer.from(s);if(a.length===n.length&&xr(a,n))return!0}catch{}let r=o.query,t=r.api_key||r["x-api-key"];if(t)try{let a=Buffer.from(t),n=Buffer.from(s);if(a.length===n.length&&xr(a,n))return!0}catch{}return!1}import{timingSafeEqual as qr}from"crypto";Y();var Qa=q("ws"),je=new Set;function Lr(o,s){o.get("/events",{websocket:!0},(e,r)=>{if(s&&!Ya(r,s)){e.close(4401,"Unauthorized");return}je.add(e),e.on("close",()=>{je.delete(e)}),e.on("error",t=>{Qa.error({error:t},"WebSocket error"),je.delete(e)})}),f.on("task_status_change",e=>{B(e)}),f.on("approval_request",e=>{B(e)}),f.on("stats_update",e=>{B(e)}),f.on("log_event",e=>{B(e)}),f.on("config_changed",e=>{B(e)}),f.on("plan_approval_request",e=>{(()=>{try{let t=ms(e.taskId);if(!t)return!1;let a=gs(t.sessionId);return a?a.source.type==="channel"&&!!a.source.channelId:!1}catch{return!1}})()||B(e)}),f.on("plan_approval_decision",e=>{B(e)}),f.on("task_created",e=>{B(e)}),f.on("execution_slot_change",e=>{B(e)}),f.on("execution_task_start",e=>{B(e)}),f.on("execution_task_end",e=>{B(e)}),f.on("delivery_status_change",e=>{B(e)})}function B(o){let s=JSON.stringify(o);for(let e of je)e.readyState===1&&e.send(s)}function Ya(o,s){let e=o.headers["x-api-key"];if(e)try{let a=Buffer.from(e),n=Buffer.from(s);if(a.length===n.length&&qr(a,n))return!0}catch{}let r=o.query,t=r.api_key||r["x-api-key"];if(t)try{let a=Buffer.from(t),n=Buffer.from(s);if(a.length===n.length&&qr(a,n))return!0}catch{}return!1}Se();function Xa(o){return{id:o.id,sdkSessionId:o.sdk_session_id??void 0,userTaskSessionId:o.user_task_session_id??void 0,workspacePath:o.workspace_path??void 0,toolsFingerprint:o.tools_fingerprint??void 0,createdAt:o.created_at,lastActiveAt:o.last_active_at??void 0}}function Rt(){let o=U(),s=o.prepare("SELECT * FROM server_state WHERE id = 1").get();if(s)return Xa(s);let e=Date.now();return o.prepare("INSERT INTO server_state (id, created_at) VALUES (1, ?)").run(e),{id:1,createdAt:e}}function fe(o){let s=U(),e=[],r=[];"sdkSessionId"in o&&(e.push("sdk_session_id = ?"),r.push(o.sdkSessionId??null)),"userTaskSessionId"in o&&(e.push("user_task_session_id = ?"),r.push(o.userTaskSessionId??null)),"workspacePath"in o&&(e.push("workspace_path = ?"),r.push(o.workspacePath??null)),"lastActiveAt"in o&&(e.push("last_active_at = ?"),r.push(o.lastActiveAt??null)),"toolsFingerprint"in o&&(e.push("tools_fingerprint = ?"),r.push(o.toolsFingerprint??null)),e.length!==0&&(Rt(),r.push(1),s.prepare(`UPDATE server_state SET ${e.join(", ")} WHERE id = ?`).run(...r))}function Ne(o){fe({sdkSessionId:o,lastActiveAt:Date.now()})}function Mr(){fe({sdkSessionId:void 0,lastActiveAt:Date.now()})}function Br(o){fe({workspacePath:o})}Ae();ss();import{z as p}from"zod/v4";import{v4 as Ur}from"uuid";ks();wa();import{rmSync as Za,existsSync as It}from"fs";var Wr=p.object({model:p.string().optional(),effort:p.enum(["low","medium","high","max"]).optional(),maxTurns:p.number().optional()}),Vr=p.object({path:p.string(),mode:p.enum(["ro","rw"]).default("rw"),inheritPlugins:p.boolean().optional(),inheritMcp:p.boolean().optional(),inheritPermissions:p.boolean().optional()}),Ja=p.string().max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/,"Env var key must match POSIX format: [A-Za-z_][A-Za-z0-9_]*").check(p.refine(o=>!o.startsWith("ANTHROPIC_"),"ANTHROPIC_* keys are managed globally in Settings")),Gr=p.record(Ja,p.string().max(4096)).optional().check(p.refine(o=>!o||Object.keys(o).length<=100,"Maximum 100 environment variables per role")),en=p.object({name:p.string().min(1,"name is required").regex(/^[\p{L}\p{N}_-]+$/u,"name must contain only letters, numbers, underscores, or hyphens"),cagPrompt:p.string().optional(),learnedRules:p.array(p.string()).optional(),allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),evaluationCriteria:p.record(p.string(),p.number()).optional(),executionMode:p.enum(["isolated","inline"]).optional(),model:p.string().optional(),maxBudgetUsd:p.number().optional(),approvalRequired:p.array(p.string()).optional(),preferences:Wr.optional(),additionalDirectories:p.array(Vr).optional(),allowedChannels:p.array(p.string()).optional(),inheritUserSettings:p.boolean().optional(),envVars:Gr}),tn=p.object({name:p.string().min(1).optional(),cagPrompt:p.string().optional(),learnedRules:p.array(p.string()).optional(),status:p.enum(["active","inactive","retired"]).optional(),allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),evaluationCriteria:p.record(p.string(),p.number()).optional(),executionMode:p.enum(["isolated","inline"]).optional(),model:p.string().optional(),maxBudgetUsd:p.number().optional(),approvalRequired:p.array(p.string()).optional(),preferences:Wr.optional(),additionalDirectories:p.array(Vr).optional(),permissionMode:p.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]).optional(),allowedBashPatterns:p.array(p.string()).optional(),deniedBashPatterns:p.array(p.string()).optional(),allowedChannels:p.array(p.string()).nullable().optional(),inheritUserSettings:p.boolean().optional(),envVars:Gr}),qe=p.object({id:p.string().min(1)}),sn=p.object({status:p.enum(["active","inactive","retired"]).optional(),limit:p.coerce.number().min(1).max(100).default(100),offset:p.coerce.number().min(0).default(0)}),rn=p.object({path:p.string().min(1)});async function $r(o){o.get("/roles",{schema:{tags:["Roles"],summary:"List all roles",description:"List all roles with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["active","inactive","retired"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(s,e)=>{let r=sn.safeParse(s.query);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let{status:t,limit:a,offset:n}=r.data;return{roles:ge(t,a,n).map(c=>({...c,workspacePath:te(c.name)}))}}),o.post("/roles",{schema:{tags:["Roles"],summary:"Create a role",description:"Create a new role with a name, CAG prompt, and optional preferences.",body:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(s,e)=>{let r=en.safeParse(s.body);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let{name:t,cagPrompt:a,learnedRules:n,allowedTools:i,disallowedTools:c,evaluationCriteria:l,executionMode:d,model:m,maxBudgetUsd:b,approvalRequired:I,preferences:y,additionalDirectories:g,allowedChannels:A,inheritUserSettings:V,envVars:ne}=r.data;if(tt(t))return e.status(409).send({code:"CONFLICT",message:`Role with name '${t}' already exists`});let H={id:`role-${Ur().slice(0,8)}`,name:t,cagPrompt:a??"",learnedRules:n??[],memoryStreamId:`mem-${Ur().slice(0,8)}`,status:"active",preferences:y??{},allowedTools:i,disallowedTools:c,evaluationCriteria:l,executionMode:d,model:m,maxBudgetUsd:b,approvalRequired:I,additionalDirectories:g,allowedChannels:A,inheritUserSettings:V,envVars:ne,createdAt:Date.now()};return et(H),at(H),e.status(201).send({role:H})}),o.get("/roles/:id",{schema:{tags:["Roles"],summary:"Get role by ID",description:"Retrieve a single role with its project-scope plugins.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=L(r.data.id);if(!t)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=te(t.name),n=_e({scope:"project",projectPath:a});return{role:t,projectPlugins:n,workspacePath:a}}),o.get("/roles/:id/scores",{schema:{tags:["Roles"],summary:"Get role quality scores",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:100,default:20}}}}},async(s,e)=>{let r=p.object({id:p.string().min(1)}).safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=L(r.data.id);if(!t)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=s.query.limit??20,n=fs(t.id,a),i=hs(t.id);return{scores:n,latestEma:i??null}}),o.patch("/roles/:id",{schema:{tags:["Roles"],summary:"Update a role",description:"Partially update a role's CAG prompt, learned rules, status, or preferences.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},learnedRules:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","inactive","retired"]},permissionMode:{type:"string",enum:["default","acceptEdits","dontAsk","bypassPermissions","plan","auto"]},allowedBashPatterns:{type:"array",items:{type:"string"}},deniedBashPatterns:{type:"array",items:{type:"string"}},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=tn.safeParse(s.body);if(!t.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(t.error)});if(!L(r.data.id))return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let{allowedChannels:n,...i}=t.data,c={...i,updatedAt:Date.now()};if(n!==void 0&&(c.allowedChannels=n??void 0),Ce(r.data.id,c),t.data.cagPrompt!==void 0||t.data.learnedRules!==void 0){let d=L(r.data.id);if(d){let m=te(d.name);It(m)&&nt(m,d)}}let l=L(r.data.id);if(l&&(t.data.allowedTools!==void 0||t.data.disallowedTools!==void 0)){let d=te(l.name);It(d)&&ot(l.id,l.allowedTools,d)}return{role:l}}),o.delete("/roles/:id",{schema:{tags:["Roles"],summary:"Delete a role",description:"Delete a role and its workspace.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=L(r.data.id);if(!t)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});if(t.id===rs)return e.status(403).send({code:"FORBIDDEN",message:"System role 'chat-manager' cannot be deleted"});let a=te(t.name);if(It(a))try{Za(a,{recursive:!0,force:!0})}catch{}return st(r.data.id),{roleId:r.data.id,deleted:!0}}),o.post("/roles/:id/scan-directory",{schema:{tags:["Roles"],summary:"Scan directory for plugin/permission configuration",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1}}}}},async(s,e)=>{let r=qe.safeParse(s.params);if(!r.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(r.error)});let t=rn.safeParse(s.body);if(!t.success)return e.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(t.error)});if(!L(r.data.id))return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=Is(t.data.path);return{path:t.data.path,enabledPlugins:n.enabledPlugins,mcpServers:n.mcpServers,allowedTools:n.allowedTools,disallowedTools:n.disallowedTools}}),o.get("/roles/:id/env-diff",{schema:{tags:["Roles"],summary:"Get role env diff",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=L(s.params.id);return r?{diffs:es(r.name,r.envVars),envFileExists:rt(r.name)!==null}:e.status(404).send({code:"NOT_FOUND",message:"Role not found"})}),o.post("/roles/:id/sync-to-env",{schema:{tags:["Roles"],summary:"Sync role env to .env file",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=L(s.params.id);return r?{success:!0,changed:ts(r.name,r.envVars)}:e.status(404).send({code:"NOT_FOUND",message:"Role not found"})}),o.post("/roles/:id/load-from-env",{schema:{tags:["Roles"],summary:"Load role env from .env file",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(s,e)=>{let r=L(s.params.id);if(!r)return e.status(404).send({code:"NOT_FOUND",message:"Role not found"});let t=rt(r.name);if(!t)return e.status(400).send({code:"NOT_FOUND",message:".env file not found in role workspace"});let a={};for(let[n,i]of Object.entries(t))n.startsWith("ANTHROPIC_")||(a[n]=i);return Ce(r.id,{envVars:Object.keys(a).length>0?a:void 0,updatedAt:Date.now()}),{success:!0,updated:Object.keys(a).length}})}me();import{z as Hr}from"zod/v4";import{readdirSync as an,existsSync as nn}from"fs";import{join as kt,resolve as Kr,sep as Qr}from"path";import{homedir as on}from"os";var cn=20,dn=Hr.object({prefix:Hr.string()});function Yr(o){return o.startsWith("~/")?kt(on(),o.slice(2)):o}function zr(o){let s=Kr(o);for(let e of Mt){let r=Yr(e),t=Kr(r);if(s===t||s.startsWith(t+Qr))return!0}return!1}async function Xr(o){o.get("/fs/suggest-dirs",{schema:{tags:["FS"],summary:"Suggest directory completions",description:"Return directory suggestions matching a given path prefix.",querystring:{type:"object",required:["prefix"],properties:{prefix:{type:"string"}}}}},async(s,e)=>{let r=dn.safeParse(s.query);if(!r.success)return{suggestions:[]};let{prefix:t}=r.data;if(!t.startsWith("/")&&!t.startsWith("~/"))return{suggestions:[]};if(zr(t))return{suggestions:[]};let a=Yr(t),n,i;if(t.endsWith("/"))n=a,i="";else{let g=Math.max(a.lastIndexOf("/"),a.lastIndexOf(Qr));if(g<0)return{suggestions:[]};n=a.slice(0,g+1),i=a.slice(g+1)}if(!nn(n))return{suggestions:[]};let c;try{c=an(n,{withFileTypes:!0}).filter(g=>g.isDirectory()).map(g=>g.name)}catch{return{suggestions:[]}}let l=i.toLowerCase(),d=c.filter(g=>g.toLowerCase().startsWith(l)),I=(i.startsWith(".")?d:d.filter(g=>!g.startsWith("."))).filter(g=>!zr(kt(n,g)));return I.sort((g,A)=>g.localeCompare(A,void 0,{sensitivity:"base"})),{suggestions:I.slice(0,cn).map(g=>kt(n,g))}})}import{z as w}from"zod/v4";Ae();import{v4 as ln}from"uuid";var pn=w.object({roleId:w.string().min(1)}),un=w.object({roleId:w.string().min(1),prompt:w.string().min(1),topK:w.number().min(1).max(50).default(10)}),mn=w.object({limit:w.coerce.number().min(1).max(200).default(50),offset:w.coerce.number().min(0).default(0)});function Tt(o){return L(o)!==void 0}async function Zr(o){o.get("/memories/:roleId",{schema:{tags:["Memories"],summary:"List role memories",description:"List all memories for a specific role with pagination. Embeddings are stripped from the response.",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}},response:R.memoryList}},async(r,t)=>{let a=pn.safeParse(r.params);if(!a.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(a.error)});let n=a.data.roleId;if(!Tt(n))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let i=mn.safeParse(r.query),{limit:c,offset:l}=i.success?i.data:{limit:50,offset:0},m=ws(n,c,l).map(({embedding:b,...I})=>I);return{memories:m,count:m.length}}),o.post("/memories/query",{schema:{tags:["Memories"],summary:"Query role memories",description:"Query a role's memories using hybrid search (FTS5 + vector similarity) with Smallville-style scoring (recency, importance, relevance).",body:{type:"object",required:["roleId","prompt"],properties:{roleId:{type:"string",minLength:1,description:"The role whose memories to query"},prompt:{type:"string",minLength:1,description:"The search query"},topK:{type:"integer",minimum:1,maximum:50,default:10,description:"Number of results to return"}}},response:R.memoryQuery}},async(r,t)=>{let a=un.safeParse(r.body);if(!a.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(a.error)});let{roleId:n,prompt:i,topK:c}=a.data;if(!Tt(n))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let d=(await lt(n,i,{topK:c})).map(({embedding:m,...b})=>b);return{memories:d,count:d.length}});let s=w.object({roleId:w.string().min(1),content:w.string().min(1),type:w.enum(["event","thought","reflection"]).default("thought"),keywords:w.array(w.string()).default([]),importance:w.number().min(1).max(5).default(3),tier:w.enum(["working","episodic","semantic"]).default("episodic")});o.post("/memories",{schema:{tags:["Memories"],summary:"Create memory",description:"Create a new memory for a role. Embedding is auto-generated from content.",body:{type:"object",required:["roleId","content"],properties:{roleId:{type:"string",minLength:1},content:{type:"string",minLength:1},type:{type:"string",enum:["event","thought","reflection"],default:"thought"},keywords:{type:"array",items:{type:"string"},default:[]},importance:{type:"integer",minimum:1,maximum:5,default:3},tier:{type:"string",enum:["working","episodic","semantic"],default:"episodic"}}},response:R.memoryCreated}},async(r,t)=>{let a=s.safeParse(r.body);if(!a.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(a.error)});let{roleId:n,content:i,type:c,keywords:l,importance:d,tier:m}=a.data;if(!Tt(n))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let b;try{b=await it(i)}catch{}let I=`mem-${ln().slice(0,8)}`,y=Date.now();Ts({id:I,roleId:n,type:c,content:i,embedding:b,keywords:l,importance:d,sourceType:"manual",createdAt:y,lastAccessed:y,retrievedCount:0,tier:m??"episodic"});let g=Ee(I),{embedding:A,...V}=g;return t.status(201).send({memory:V})});let e=w.object({content:w.string().min(1).optional(),type:w.enum(["event","thought","reflection"]).optional(),keywords:w.array(w.string()).optional(),importance:w.number().min(1).max(5).optional()});o.patch("/memories/:id",{schema:{tags:["Memories"],summary:"Update memory",description:"Update a memory's content, type, keywords, or importance. Embedding is regenerated if content changes.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{content:{type:"string",minLength:1},type:{type:"string",enum:["event","thought","reflection"]},keywords:{type:"array",items:{type:"string"}},importance:{type:"integer",minimum:1,maximum:5}}},response:R.memoryUpdated}},async(r,t)=>{let{id:a}=r.params;if(!Ee(a))return t.status(404).send({code:"NOT_FOUND",message:"Memory not found"});let i=e.safeParse(r.body);if(!i.success)return t.status(400).send({code:"VALIDATION_ERROR",message:w.prettifyError(i.error)});let c=i.data,l,d=!0;if(c.content)try{l=await it(c.content)}catch{d=!1}let m=Ss(a,{content:c.content,embedding:l,keywords:c.keywords,importance:c.importance,type:c.type});return{memoryId:a,updated:m,embeddingUpdated:d}}),o.delete("/memories/:id",{schema:{tags:["Memories"],summary:"Delete memory",description:"Delete a memory by ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.memoryDeleted}},async(r,t)=>{let{id:a}=r.params;return Ee(a)?(Cs(a),{memoryId:a,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Memory not found"})})}import{query as hn}from"@anthropic-ai/claude-agent-sdk";import{v4 as ae}from"uuid";function gn(){try{return E().defaults.maxBudgetUsd}catch{return 5}}function St(o){return`# ChatManager \u2014 User Interface Agent
3
3
 
4
4
  You are the primary interface between the user and the goal-driven autonomous system.
5
5
  You have access to a persistent conversation session and the adam-tools MCP server.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "adam-agent-server",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "Goal-driven AI agent orchestration server with Role+Skill model, real-time streaming, and multi-channel delivery",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,H as n,N as r,nt as i,w as a,y as o}from"./vendor-icons-CkI4-NxL.js";import{d as s,r as c,t as l}from"./vendor-react-DLRtONKt.js";import{r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./index-oA-kWqT5.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";import{n as h}from"./format-DvtQjPZn.js";var g=e(i(),1),_=l();function v(){let{id:e}=s(),[i,l]=(0,g.useState)(null),[v,b]=(0,g.useState)([]),[x,S]=(0,g.useState)([]),[C,w]=(0,g.useState)(null);if((0,g.useEffect)(()=>{e&&((async()=>{try{l((await u(`/channels/${e}`)).channel),w(null)}catch(e){w(e instanceof Error?e.message:`Failed to load channel`)}})(),u(`/delivery-rules`).then(t=>b(t.filter(t=>t.target.type===`channel`&&t.target.channelId===e))).catch(()=>b([])),u(`/delivery-rules`).then(async t=>{let n=t.filter(t=>t.target.type===`channel`&&t.target.channelId===e),r=[];for(let e of n.slice(0,3))try{let t=await u(`/delivery-rules/${e.id}/log`);r.push(...t.log??[])}catch{}r.sort((e,t)=>t.createdAt-e.createdAt),S(r.slice(0,20))}).catch(()=>S([])))},[e]),C)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{className:`text-center text-red-400`,children:C})]});if(!i)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{className:`text-center text-slate-500`,children:`Loading...`})]});let T=e=>e===`connected`?`success`:e===`connecting`?`warning`:e===`error`?`destructive`:`secondary`,E=e=>{switch(e){case`wechat`:return`WeChat`;case`telegram`:return`Telegram`;case`slack`:return`Slack`;case`discord`:return`Discord`;default:return e.charAt(0).toUpperCase()+e.slice(1)}},D={...i.config};for(let e of[`botToken`,`apiKey`,`secret`,`password`,`token`])e in D&&(D[e]=`********`);return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{children:(0,_.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,_.jsx)(d,{variant:T(i.status),children:i.status}),(0,_.jsx)(d,{variant:`outline`,children:E(i.platform)}),i.enabled?(0,_.jsx)(d,{variant:`success`,children:`enabled`}):(0,_.jsx)(d,{variant:`secondary`,children:`disabled`}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:i.id})]}),(0,_.jsx)(`h2`,{className:`text-lg font-semibold text-slate-200`,children:i.name})]})})}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,children:[(0,_.jsx)(y,{icon:n,label:`Created`,value:h(i.createdAt),mono:!0}),(0,_.jsx)(y,{icon:a,label:`Messages`,value:String(i.messageCount),mono:!0}),i.lastMessageAt&&(0,_.jsx)(y,{icon:n,label:`Last Message`,value:h(i.lastMessageAt),mono:!0}),i.linkedRoleId&&(0,_.jsx)(y,{icon:o,label:`Linked Role`,value:i.linkedRoleId.slice(0,8)+`...`,mono:!0})]}),(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Configuration`})}),(0,_.jsx)(`pre`,{className:`max-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-slate-800 p-3 font-mono text-xs text-slate-300`,children:JSON.stringify(D,null,2)})]}),v.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(r,{size:14}),` Delivery Rules (`,v.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:v.map(e=>(0,_.jsxs)(`div`,{className:`rounded-md border border-slate-700 bg-slate-800/50 p-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(d,{variant:`outline`,children:e.eventType}),e.enabled?(0,_.jsx)(d,{variant:`success`,children:`active`}):(0,_.jsx)(d,{variant:`secondary`,children:`disabled`}),(0,_.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[`max `,e.maxPerMinute,`/min`]})]}),(0,_.jsxs)(`p`,{className:`mt-1 text-xs text-slate-400 font-mono`,children:[`Rule: `,e.id]})]},e.id))})]}),x.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(a,{size:14}),` Delivery Log (`,x.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:x.slice(0,10).map(e=>(0,_.jsxs)(`div`,{className:`flex items-center justify-between rounded-md border border-slate-800 p-2`,children:[(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsx)(`span`,{className:`text-sm text-slate-300 font-mono`,children:e.taskId.slice(0,8)}),(0,_.jsx)(`span`,{className:`text-xs text-slate-500 ml-2`,children:h(e.createdAt)})]}),(0,_.jsx)(d,{variant:e.status===`delivered`?`default`:e.status===`failed`?`destructive`:`outline`,children:e.status})]},e.id))})]})]})}function y({icon:e,label:t,value:n,mono:r}){return(0,_.jsxs)(m,{className:`flex flex-col gap-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 text-slate-500`,children:[(0,_.jsx)(e,{size:12}),(0,_.jsx)(`span`,{className:`text-xs`,children:t})]}),(0,_.jsx)(`span`,{className:`text-sm text-slate-200 truncate ${r?`font-mono text-xs`:``}`,children:n})]})}export{v as ChannelDetail};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,H as n,N as r,nt as i,w as a,y as o}from"./vendor-icons-CkI4-NxL.js";import{d as s,r as c,t as l}from"./vendor-react-DLRtONKt.js";import{r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./index-rvaixveh.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";import{n as h}from"./format-DvtQjPZn.js";var g=e(i(),1),_=l();function v(){let{id:e}=s(),[i,l]=(0,g.useState)(null),[v,b]=(0,g.useState)([]),[x,S]=(0,g.useState)([]),[C,w]=(0,g.useState)(null);if((0,g.useEffect)(()=>{e&&((async()=>{try{l((await u(`/channels/${e}`)).channel),w(null)}catch(e){w(e instanceof Error?e.message:`Failed to load channel`)}})(),u(`/delivery-rules`).then(t=>b(t.filter(t=>t.target.type===`channel`&&t.target.channelId===e))).catch(()=>b([])),u(`/delivery-rules`).then(async t=>{let n=t.filter(t=>t.target.type===`channel`&&t.target.channelId===e),r=[];for(let e of n.slice(0,3))try{let t=await u(`/delivery-rules/${e.id}/log`);r.push(...t.log??[])}catch{}r.sort((e,t)=>t.createdAt-e.createdAt),S(r.slice(0,20))}).catch(()=>S([])))},[e]),C)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{className:`text-center text-red-400`,children:C})]});if(!i)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{className:`text-center text-slate-500`,children:`Loading...`})]});let T=e=>e===`connected`?`success`:e===`connecting`?`warning`:e===`error`?`destructive`:`secondary`,E=e=>{switch(e){case`wechat`:return`WeChat`;case`telegram`:return`Telegram`;case`slack`:return`Slack`;case`discord`:return`Discord`;default:return e.charAt(0).toUpperCase()+e.slice(1)}},D={...i.config};for(let e of[`botToken`,`apiKey`,`secret`,`password`,`token`])e in D&&(D[e]=`********`);return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/channels`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Channels`]}),(0,_.jsx)(m,{children:(0,_.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,_.jsx)(d,{variant:T(i.status),children:i.status}),(0,_.jsx)(d,{variant:`outline`,children:E(i.platform)}),i.enabled?(0,_.jsx)(d,{variant:`success`,children:`enabled`}):(0,_.jsx)(d,{variant:`secondary`,children:`disabled`}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:i.id})]}),(0,_.jsx)(`h2`,{className:`text-lg font-semibold text-slate-200`,children:i.name})]})})}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,children:[(0,_.jsx)(y,{icon:n,label:`Created`,value:h(i.createdAt),mono:!0}),(0,_.jsx)(y,{icon:a,label:`Messages`,value:String(i.messageCount),mono:!0}),i.lastMessageAt&&(0,_.jsx)(y,{icon:n,label:`Last Message`,value:h(i.lastMessageAt),mono:!0}),i.linkedRoleId&&(0,_.jsx)(y,{icon:o,label:`Linked Role`,value:i.linkedRoleId.slice(0,8)+`...`,mono:!0})]}),(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Configuration`})}),(0,_.jsx)(`pre`,{className:`max-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-slate-800 p-3 font-mono text-xs text-slate-300`,children:JSON.stringify(D,null,2)})]}),v.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(r,{size:14}),` Delivery Rules (`,v.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:v.map(e=>(0,_.jsxs)(`div`,{className:`rounded-md border border-slate-700 bg-slate-800/50 p-2`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,_.jsx)(d,{variant:`outline`,children:e.eventType}),e.enabled?(0,_.jsx)(d,{variant:`success`,children:`active`}):(0,_.jsx)(d,{variant:`secondary`,children:`disabled`}),(0,_.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[`max `,e.maxPerMinute,`/min`]})]}),(0,_.jsxs)(`p`,{className:`mt-1 text-xs text-slate-400 font-mono`,children:[`Rule: `,e.id]})]},e.id))})]}),x.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(a,{size:14}),` Delivery Log (`,x.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:x.slice(0,10).map(e=>(0,_.jsxs)(`div`,{className:`flex items-center justify-between rounded-md border border-slate-800 p-2`,children:[(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsx)(`span`,{className:`text-sm text-slate-300 font-mono`,children:e.taskId.slice(0,8)}),(0,_.jsx)(`span`,{className:`text-xs text-slate-500 ml-2`,children:h(e.createdAt)})]}),(0,_.jsx)(d,{variant:e.status===`delivered`?`default`:e.status===`failed`?`destructive`:`outline`,children:e.status})]},e.id))})]})]})}function y({icon:e,label:t,value:n,mono:r}){return(0,_.jsxs)(m,{className:`flex flex-col gap-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 text-slate-500`,children:[(0,_.jsx)(e,{size:12}),(0,_.jsx)(`span`,{className:`text-xs`,children:t})]}),(0,_.jsx)(`span`,{className:`text-sm text-slate-200 truncate ${r?`font-mono text-xs`:``}`,children:n})]})}export{v as ChannelDetail};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{S as t,b as n,g as r,nt as i,o as a,t as o,v as s,w as c,y as l}from"./vendor-icons-CkI4-NxL.js";import{t as u}from"./vendor-react-DLRtONKt.js";import{r as d}from"./dist-HyCSN_hp.js";import{f,t as p}from"./index-oA-kWqT5.js";import{n as m,r as h,t as g}from"./Card-4mOZntHG.js";import{t as _}from"./EmptyState-BlgMMAr-.js";var v=e(i(),1),y=u(),b=[`telegram`,`slack`,`discord`,`openclaw`,`wechat`,`whatsapp`],x={telegram:`{
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{S as t,b as n,g as r,nt as i,o as a,t as o,v as s,w as c,y as l}from"./vendor-icons-CkI4-NxL.js";import{t as u}from"./vendor-react-DLRtONKt.js";import{r as d}from"./dist-HyCSN_hp.js";import{f,t as p}from"./index-rvaixveh.js";import{n as m,r as h,t as g}from"./Card-4mOZntHG.js";import{t as _}from"./EmptyState-BlgMMAr-.js";var v=e(i(),1),y=u(),b=[`telegram`,`slack`,`discord`,`openclaw`,`wechat`,`whatsapp`],x={telegram:`{
2
2
  "botToken": ""
3
3
  }`,slack:`{
4
4
  "botToken": "",
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{T as t,d as n,et as r,m as i,nt as a,o,v as s}from"./vendor-icons-CkI4-NxL.js";import{t as c}from"./vendor-react-DLRtONKt.js";import{a as l,r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./vendor-state-B_-GdGNJ.js";import{f}from"./index-oA-kWqT5.js";import{a as p}from"./format-DvtQjPZn.js";var m=e(a(),1),h=d((e,t)=>({sessions:[],activeSessionId:null,messages:[],loading:!1,sending:!1,_chatWs:null,_chatWsReconnectDelay:1e3,fetchSessions:async()=>{try{e({sessions:(await u(`/chat/sessions`)).sessions})}catch{}},fetchMessages:async t=>{e({loading:!0});try{e({messages:(await u(`/chat/sessions/${t}`)).messages,loading:!1})}catch{e({messages:[],loading:!1})}},sendMessage:async n=>{if(t().sending)return null;e({sending:!0});try{let r=await u(`/chat/messages`,{method:`POST`,body:JSON.stringify({content:n,source:{type:`web`},sessionId:t().activeSessionId??void 0})});return e({activeSessionId:r.sessionId,sending:!1}),t().fetchSessions(),r}catch{return e({sending:!1}),null}},createSession:async()=>{try{let t=await u(`/chat/sessions`,{method:`POST`,body:JSON.stringify({source:{type:`web`}})});return e(e=>({sessions:[t.session,...e.sessions],activeSessionId:t.session.id,messages:[]})),t.session}catch{return null}},archiveSession:async t=>{try{await u(`/chat/sessions/${t}/archive`,{method:`POST`}),e(e=>({sessions:e.sessions.map(e=>e.id===t?{...e,status:`archived`}:e),activeSessionId:e.activeSessionId===t?null:e.activeSessionId,messages:e.activeSessionId===t?[]:e.messages}))}catch{}},restoreSession:async t=>{try{await u(`/chat/sessions/${t}/restore`,{method:`POST`}),e(e=>({sessions:e.sessions.map(e=>e.id===t?{...e,status:`active`}:e)}))}catch{}},deleteSession:async t=>{try{await u(`/chat/sessions/${t}`,{method:`DELETE`}),e(e=>({sessions:e.sessions.filter(e=>e.id!==t),activeSessionId:e.activeSessionId===t?null:e.activeSessionId,messages:e.activeSessionId===t?[]:e.messages}))}catch{}},setActiveSession:n=>{e({activeSessionId:n,messages:[]}),n&&t().fetchMessages(n)},connectChatStream:()=>{let n=t()._chatWs;if(n&&n.readyState<=1)return;let r=window.location.protocol===`https:`?`wss:`:`ws:`,i=localStorage.getItem(`adam_api_key`),a=new URL(`${r}//${window.location.host}/chat/stream`);i&&a.searchParams.set(`api_key`,i);let o=new WebSocket(a.toString());o.onopen=()=>{e({_chatWs:o,_chatWsReconnectDelay:1e3})},o.onclose=()=>{let n=t()._chatWsReconnectDelay;e({_chatWs:null,_chatWsReconnectDelay:Math.min(n*2,1e4)}),setTimeout(()=>{t().connectChatStream()},n)},o.onerror=()=>{o.close()},o.onmessage=n=>{try{let r=JSON.parse(n.data);if(r.type===`chat_message`&&r.message){let n=r.message,{activeSessionId:i,messages:a}=t();if(n.sessionId!==i||a.some(e=>e.id===n.id))return;e(e=>({messages:[...e.messages,n]}))}else r.type===`session_created`&&t().fetchSessions()}catch{}},e({_chatWs:o})},disconnectChatStream:()=>{let n=t()._chatWs;n&&(n.onclose=null,n.onerror=null,n.onmessage=null,n.close(),e({_chatWs:null}))}})),g=c();function _({message:e}){let t=e.role===`user`;return(0,g.jsx)(`div`,{className:l(`flex`,t?`justify-end`:`justify-start`),children:(0,g.jsxs)(`div`,{className:l(`max-w-[80%] rounded-lg px-3.5 py-2.5 text-sm leading-relaxed`,t?`bg-blue-600 text-white`:`border border-slate-700 bg-slate-800 text-slate-200`),children:[(0,g.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}),(0,g.jsx)(`div`,{className:l(`mt-1.5 text-[10px]`,t?`text-blue-200/60`:`text-slate-500`),children:p(typeof e.createdAt==`number`?e.createdAt:new Date(e.createdAt).getTime())})]})})}function v({onSend:e,disabled:t,placeholder:r=`Type a message...`}){let[i,a]=(0,m.useState)(``),o=(0,m.useRef)(null),s=()=>{let n=i.trim();!n||t||(e(n),a(``),o.current&&(o.current.style.height=`auto`))},c=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),s())},l=()=>{let e=o.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};return(0,g.jsxs)(`div`,{className:`flex items-end gap-2 border-t border-slate-800 bg-slate-950 px-4 py-3`,children:[(0,g.jsx)(`textarea`,{ref:o,value:i,onChange:e=>{a(e.target.value),l()},onKeyDown:c,placeholder:r,disabled:t,rows:1,className:`flex-1 resize-none rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50`}),(0,g.jsx)(f,{onClick:s,disabled:t||!i.trim(),size:`default`,"aria-label":`Send message`,children:(0,g.jsx)(n,{size:16})})]})}function y(e){let t=Math.floor((Date.now()-e)/1e3);if(t<60)return`just now`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function b({session:e,isActive:t,onSelect:n,onArchive:a,onRestore:s,onDelete:c}){let u=e.status===`archived`;return(0,g.jsxs)(`button`,{onClick:n,className:l(`group flex w-full flex-col gap-1 rounded-md px-2.5 py-2 text-left transition-colors`,t?`bg-slate-800 text-slate-100`:`text-slate-400 hover:bg-slate-800/50 hover:text-slate-300`,u&&`opacity-60`),children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsx)(`span`,{className:`truncate text-xs font-medium`,children:e.title??e.id.slice(0,8)}),(0,g.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100`,children:[u?(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),s()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),s())},className:`rounded p-0.5 text-slate-500 hover:text-emerald-400`,title:`Restore`,children:(0,g.jsx)(i,{size:12})}):(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),a()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),a())},className:`rounded p-0.5 text-slate-500 hover:text-amber-400`,title:`Archive`,children:(0,g.jsx)(r,{size:12})}),(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),c()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),c())},className:`rounded p-0.5 text-slate-500 hover:text-red-400`,title:`Delete`,children:(0,g.jsx)(o,{size:12})})]})]}),(0,g.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-slate-500`,children:[(0,g.jsxs)(`span`,{children:[e.messageCount,` turns`]}),(0,g.jsx)(`span`,{children:y(e.lastActiveAt)}),u&&(0,g.jsx)(`span`,{className:`rounded bg-slate-700 px-1 py-0.5 text-[9px]`,children:`archived`})]})]})}function x({sessions:e,activeSessionId:t,onSelectSession:n,onNewSession:r,onArchiveSession:i,onRestoreSession:a,onDeleteSession:o}){let c=e.filter(e=>e.status===`active`),l=e.filter(e=>e.status===`archived`);return(0,g.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-800 px-3 py-2.5`,children:[(0,g.jsx)(`span`,{className:`text-xs font-medium text-slate-400`,children:`Sessions`}),(0,g.jsx)(f,{variant:`ghost`,size:`sm`,onClick:r,children:(0,g.jsx)(s,{size:14})})]}),(0,g.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-1.5 py-1.5`,children:[c.length===0&&l.length===0&&(0,g.jsx)(`div`,{className:`px-2 py-4 text-center text-xs text-slate-500`,children:`No sessions yet`}),c.length>0&&(0,g.jsx)(`div`,{className:`space-y-0.5`,children:c.map(e=>(0,g.jsx)(b,{session:e,isActive:e.id===t,onSelect:()=>n(e.id),onArchive:()=>i(e.id),onRestore:()=>a(e.id),onDelete:()=>o(e.id)},e.id))}),l.length>0&&(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`mt-3 mb-1 px-2 text-[10px] font-medium uppercase tracking-wider text-slate-600`,children:`Archived`}),(0,g.jsx)(`div`,{className:`space-y-0.5`,children:l.map(e=>(0,g.jsx)(b,{session:e,isActive:e.id===t,onSelect:()=>n(e.id),onArchive:()=>i(e.id),onRestore:()=>a(e.id),onDelete:()=>o(e.id)},e.id))})]})]})]})}function S(){let e=h(e=>e.sessions),n=h(e=>e.activeSessionId),r=h(e=>e.messages),i=h(e=>e.sending),a=h(e=>e.fetchSessions),o=h(e=>e.sendMessage),s=h(e=>e.createSession),c=h(e=>e.archiveSession),l=h(e=>e.restoreSession),u=h(e=>e.deleteSession),d=h(e=>e.setActiveSession),f=h(e=>e.connectChatStream),p=h(e=>e.disconnectChatStream),y=(0,m.useRef)(null);return(0,m.useEffect)(()=>{a()},[a]),(0,m.useEffect)(()=>(f(),()=>p()),[f,p]),(0,m.useEffect)(()=>{y.current?.scrollIntoView?.({behavior:`smooth`})},[r]),(0,g.jsxs)(`div`,{className:`flex h-full overflow-hidden`,children:[(0,g.jsx)(`div`,{className:`hidden w-56 flex-shrink-0 border-r border-slate-800 bg-slate-950 lg:block`,children:(0,g.jsx)(x,{sessions:e,activeSessionId:n,onSelectSession:d,onNewSession:()=>void s(),onArchiveSession:e=>void c(e),onRestoreSession:e=>void l(e),onDeleteSession:e=>void u(e)})}),(0,g.jsxs)(`div`,{className:`flex flex-1 flex-col`,children:[(0,g.jsx)(`div`,{className:`flex-1 overflow-y-auto px-4 py-4`,children:r.length===0?(0,g.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 text-slate-500`,children:[(0,g.jsx)(`div`,{className:`rounded-full bg-slate-800 p-3`,children:(0,g.jsx)(t,{size:24})}),(0,g.jsx)(`div`,{className:`text-sm`,children:`Start a conversation with Adam`}),(0,g.jsx)(`div`,{className:`text-xs text-slate-600`,children:`Type a message below to begin`})]}):(0,g.jsxs)(`div`,{className:`mx-auto max-w-3xl space-y-3`,children:[r.map(e=>(0,g.jsx)(_,{message:e},e.id)),(0,g.jsx)(`div`,{ref:y})]})}),(0,g.jsx)(`div`,{className:`mx-auto w-full max-w-3xl`,children:(0,g.jsx)(v,{onSend:async e=>{await o(e)},disabled:i})})]})]})}export{S as Chat};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{T as t,d as n,et as r,m as i,nt as a,o,v as s}from"./vendor-icons-CkI4-NxL.js";import{t as c}from"./vendor-react-DLRtONKt.js";import{a as l,r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./vendor-state-B_-GdGNJ.js";import{f}from"./index-rvaixveh.js";import{a as p}from"./format-DvtQjPZn.js";var m=e(a(),1),h=d((e,t)=>({sessions:[],activeSessionId:null,messages:[],loading:!1,sending:!1,_chatWs:null,_chatWsReconnectDelay:1e3,fetchSessions:async()=>{try{e({sessions:(await u(`/chat/sessions`)).sessions})}catch{}},fetchMessages:async t=>{e({loading:!0});try{e({messages:(await u(`/chat/sessions/${t}`)).messages,loading:!1})}catch{e({messages:[],loading:!1})}},sendMessage:async n=>{if(t().sending)return null;e({sending:!0});try{let r=await u(`/chat/messages`,{method:`POST`,body:JSON.stringify({content:n,source:{type:`web`},sessionId:t().activeSessionId??void 0})});return e({activeSessionId:r.sessionId,sending:!1}),t().fetchSessions(),r}catch{return e({sending:!1}),null}},createSession:async()=>{try{let t=await u(`/chat/sessions`,{method:`POST`,body:JSON.stringify({source:{type:`web`}})});return e(e=>({sessions:[t.session,...e.sessions],activeSessionId:t.session.id,messages:[]})),t.session}catch{return null}},archiveSession:async t=>{try{await u(`/chat/sessions/${t}/archive`,{method:`POST`}),e(e=>({sessions:e.sessions.map(e=>e.id===t?{...e,status:`archived`}:e),activeSessionId:e.activeSessionId===t?null:e.activeSessionId,messages:e.activeSessionId===t?[]:e.messages}))}catch{}},restoreSession:async t=>{try{await u(`/chat/sessions/${t}/restore`,{method:`POST`}),e(e=>({sessions:e.sessions.map(e=>e.id===t?{...e,status:`active`}:e)}))}catch{}},deleteSession:async t=>{try{await u(`/chat/sessions/${t}`,{method:`DELETE`}),e(e=>({sessions:e.sessions.filter(e=>e.id!==t),activeSessionId:e.activeSessionId===t?null:e.activeSessionId,messages:e.activeSessionId===t?[]:e.messages}))}catch{}},setActiveSession:n=>{e({activeSessionId:n,messages:[]}),n&&t().fetchMessages(n)},connectChatStream:()=>{let n=t()._chatWs;if(n&&n.readyState<=1)return;let r=window.location.protocol===`https:`?`wss:`:`ws:`,i=localStorage.getItem(`adam_api_key`),a=new URL(`${r}//${window.location.host}/chat/stream`);i&&a.searchParams.set(`api_key`,i);let o=new WebSocket(a.toString());o.onopen=()=>{e({_chatWs:o,_chatWsReconnectDelay:1e3})},o.onclose=()=>{let n=t()._chatWsReconnectDelay;e({_chatWs:null,_chatWsReconnectDelay:Math.min(n*2,1e4)}),setTimeout(()=>{t().connectChatStream()},n)},o.onerror=()=>{o.close()},o.onmessage=n=>{try{let r=JSON.parse(n.data);if(r.type===`chat_message`&&r.message){let n=r.message,{activeSessionId:i,messages:a}=t();if(n.sessionId!==i||a.some(e=>e.id===n.id))return;e(e=>({messages:[...e.messages,n]}))}else r.type===`session_created`&&t().fetchSessions()}catch{}},e({_chatWs:o})},disconnectChatStream:()=>{let n=t()._chatWs;n&&(n.onclose=null,n.onerror=null,n.onmessage=null,n.close(),e({_chatWs:null}))}})),g=c();function _({message:e}){let t=e.role===`user`;return(0,g.jsx)(`div`,{className:l(`flex`,t?`justify-end`:`justify-start`),children:(0,g.jsxs)(`div`,{className:l(`max-w-[80%] rounded-lg px-3.5 py-2.5 text-sm leading-relaxed`,t?`bg-blue-600 text-white`:`border border-slate-700 bg-slate-800 text-slate-200`),children:[(0,g.jsx)(`div`,{className:`whitespace-pre-wrap break-words`,children:e.content}),(0,g.jsx)(`div`,{className:l(`mt-1.5 text-[10px]`,t?`text-blue-200/60`:`text-slate-500`),children:p(typeof e.createdAt==`number`?e.createdAt:new Date(e.createdAt).getTime())})]})})}function v({onSend:e,disabled:t,placeholder:r=`Type a message...`}){let[i,a]=(0,m.useState)(``),o=(0,m.useRef)(null),s=()=>{let n=i.trim();!n||t||(e(n),a(``),o.current&&(o.current.style.height=`auto`))},c=e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),s())},l=()=>{let e=o.current;e&&(e.style.height=`auto`,e.style.height=`${Math.min(e.scrollHeight,120)}px`)};return(0,g.jsxs)(`div`,{className:`flex items-end gap-2 border-t border-slate-800 bg-slate-950 px-4 py-3`,children:[(0,g.jsx)(`textarea`,{ref:o,value:i,onChange:e=>{a(e.target.value),l()},onKeyDown:c,placeholder:r,disabled:t,rows:1,className:`flex-1 resize-none rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50`}),(0,g.jsx)(f,{onClick:s,disabled:t||!i.trim(),size:`default`,"aria-label":`Send message`,children:(0,g.jsx)(n,{size:16})})]})}function y(e){let t=Math.floor((Date.now()-e)/1e3);if(t<60)return`just now`;let n=Math.floor(t/60);if(n<60)return`${n}m ago`;let r=Math.floor(n/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function b({session:e,isActive:t,onSelect:n,onArchive:a,onRestore:s,onDelete:c}){let u=e.status===`archived`;return(0,g.jsxs)(`button`,{onClick:n,className:l(`group flex w-full flex-col gap-1 rounded-md px-2.5 py-2 text-left transition-colors`,t?`bg-slate-800 text-slate-100`:`text-slate-400 hover:bg-slate-800/50 hover:text-slate-300`,u&&`opacity-60`),children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsx)(`span`,{className:`truncate text-xs font-medium`,children:e.title??e.id.slice(0,8)}),(0,g.jsxs)(`div`,{className:`flex gap-0.5 opacity-0 group-hover:opacity-100`,children:[u?(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),s()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),s())},className:`rounded p-0.5 text-slate-500 hover:text-emerald-400`,title:`Restore`,children:(0,g.jsx)(i,{size:12})}):(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),a()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),a())},className:`rounded p-0.5 text-slate-500 hover:text-amber-400`,title:`Archive`,children:(0,g.jsx)(r,{size:12})}),(0,g.jsx)(`span`,{role:`button`,tabIndex:0,onClick:e=>{e.stopPropagation(),c()},onKeyDown:e=>{e.key===`Enter`&&(e.stopPropagation(),c())},className:`rounded p-0.5 text-slate-500 hover:text-red-400`,title:`Delete`,children:(0,g.jsx)(o,{size:12})})]})]}),(0,g.jsxs)(`div`,{className:`flex items-center gap-2 text-[10px] text-slate-500`,children:[(0,g.jsxs)(`span`,{children:[e.messageCount,` turns`]}),(0,g.jsx)(`span`,{children:y(e.lastActiveAt)}),u&&(0,g.jsx)(`span`,{className:`rounded bg-slate-700 px-1 py-0.5 text-[9px]`,children:`archived`})]})]})}function x({sessions:e,activeSessionId:t,onSelectSession:n,onNewSession:r,onArchiveSession:i,onRestoreSession:a,onDeleteSession:o}){let c=e.filter(e=>e.status===`active`),l=e.filter(e=>e.status===`archived`);return(0,g.jsxs)(`div`,{className:`flex h-full flex-col`,children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between border-b border-slate-800 px-3 py-2.5`,children:[(0,g.jsx)(`span`,{className:`text-xs font-medium text-slate-400`,children:`Sessions`}),(0,g.jsx)(f,{variant:`ghost`,size:`sm`,onClick:r,children:(0,g.jsx)(s,{size:14})})]}),(0,g.jsxs)(`div`,{className:`flex-1 overflow-y-auto px-1.5 py-1.5`,children:[c.length===0&&l.length===0&&(0,g.jsx)(`div`,{className:`px-2 py-4 text-center text-xs text-slate-500`,children:`No sessions yet`}),c.length>0&&(0,g.jsx)(`div`,{className:`space-y-0.5`,children:c.map(e=>(0,g.jsx)(b,{session:e,isActive:e.id===t,onSelect:()=>n(e.id),onArchive:()=>i(e.id),onRestore:()=>a(e.id),onDelete:()=>o(e.id)},e.id))}),l.length>0&&(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`mt-3 mb-1 px-2 text-[10px] font-medium uppercase tracking-wider text-slate-600`,children:`Archived`}),(0,g.jsx)(`div`,{className:`space-y-0.5`,children:l.map(e=>(0,g.jsx)(b,{session:e,isActive:e.id===t,onSelect:()=>n(e.id),onArchive:()=>i(e.id),onRestore:()=>a(e.id),onDelete:()=>o(e.id)},e.id))})]})]})]})}function S(){let e=h(e=>e.sessions),n=h(e=>e.activeSessionId),r=h(e=>e.messages),i=h(e=>e.sending),a=h(e=>e.fetchSessions),o=h(e=>e.sendMessage),s=h(e=>e.createSession),c=h(e=>e.archiveSession),l=h(e=>e.restoreSession),u=h(e=>e.deleteSession),d=h(e=>e.setActiveSession),f=h(e=>e.connectChatStream),p=h(e=>e.disconnectChatStream),y=(0,m.useRef)(null);return(0,m.useEffect)(()=>{a()},[a]),(0,m.useEffect)(()=>(f(),()=>p()),[f,p]),(0,m.useEffect)(()=>{y.current?.scrollIntoView?.({behavior:`smooth`})},[r]),(0,g.jsxs)(`div`,{className:`flex h-full overflow-hidden`,children:[(0,g.jsx)(`div`,{className:`hidden w-56 flex-shrink-0 border-r border-slate-800 bg-slate-950 lg:block`,children:(0,g.jsx)(x,{sessions:e,activeSessionId:n,onSelectSession:d,onNewSession:()=>void s(),onArchiveSession:e=>void c(e),onRestoreSession:e=>void l(e),onDeleteSession:e=>void u(e)})}),(0,g.jsxs)(`div`,{className:`flex flex-1 flex-col`,children:[(0,g.jsx)(`div`,{className:`flex-1 overflow-y-auto px-4 py-4`,children:r.length===0?(0,g.jsxs)(`div`,{className:`flex h-full flex-col items-center justify-center gap-3 text-slate-500`,children:[(0,g.jsx)(`div`,{className:`rounded-full bg-slate-800 p-3`,children:(0,g.jsx)(t,{size:24})}),(0,g.jsx)(`div`,{className:`text-sm`,children:`Start a conversation with Adam`}),(0,g.jsx)(`div`,{className:`text-xs text-slate-600`,children:`Type a message below to begin`})]}):(0,g.jsxs)(`div`,{className:`mx-auto max-w-3xl space-y-3`,children:[r.map(e=>(0,g.jsx)(_,{message:e},e.id)),(0,g.jsx)(`div`,{ref:y})]})}),(0,g.jsx)(`div`,{className:`mx-auto w-full max-w-3xl`,children:(0,g.jsx)(v,{onSend:async e=>{await o(e)},disabled:i})})]})]})}export{S as Chat};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{G as t,K as n,V as r,W as i,c as a,k as o,nt as s,q as c,tt as l}from"./vendor-icons-CkI4-NxL.js";import{r as u,t as d}from"./vendor-react-DLRtONKt.js";import{C as f,n as p,t as m}from"./index-oA-kWqT5.js";import{n as h,r as g,t as _}from"./Card-4mOZntHG.js";import{a as v,o as y,t as b}from"./format-DvtQjPZn.js";import{a as x,i as S,n as C,o as w,r as T,t as E}from"./Table-BxbnOSbq.js";var D=e(s(),1),O=d();function k(){let e=f(e=>e.tasks),s=f(e=>e.goals),d=f(e=>e.stats),k=f(e=>e.readiness),j=f(e=>e.roles),M=f(e=>e.executionPool),N=f(e=>e.fetchTasks),P=f(e=>e.fetchGoals),F=f(e=>e.fetchRoles),I=f(e=>e.fetchExecutionPool);(0,D.useEffect)(()=>{N(),P(),F(),I();let e=setInterval(()=>{N(),I()},5e3);return()=>clearInterval(e)},[N,P,F,I]);let L=e.filter(e=>e.status===`running`).length,R=e.filter(e=>e.status===`completed`).length,z=e.filter(e=>e.status===`failed`).length,B=[...e].sort((e,t)=>t.createdAt-e.createdAt).slice(0,8);return(0,O.jsxs)(`div`,{className:`space-y-6`,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,O.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Dashboard`}),k&&(0,O.jsx)(`span`,{role:`status`,"aria-live":`polite`,children:(0,O.jsx)(m,{variant:k.status===`ready`?`success`:`destructive`,children:k.status===`ready`?`Server Ready`:`Not Ready`})})]}),(0,O.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,role:`region`,"aria-label":`Server statistics`,children:[(0,O.jsx)(A,{icon:o,label:`Active Tasks`,value:d.activeTasks||L,color:`text-blue-400`}),(()=>{let e=j.filter(e=>e.status===`active`).length,t=j.length,n=j.filter(e=>e.status===`probation`).length,r=j.filter(e=>e.status===`retired`).length,i=[n>0?`${n} probation`:``,r>0?`${r} retired`:``].filter(Boolean).join(` · `);return(0,O.jsx)(A,{icon:l,label:`Role Health`,value:i?`${e}/${t} | ${i}`:`${e}/${t}`,color:r>0?`text-red-400`:n>0?`text-amber-400`:`text-emerald-400`})})(),(0,O.jsx)(A,{icon:i,label:`Roles`,value:j.length,color:`text-emerald-400`}),(0,O.jsx)(A,{icon:t,label:`Cost Today`,value:b(d.totalCostToday),color:`text-purple-400`})]}),(0,O.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,role:`region`,"aria-label":`Additional statistics`,children:[(0,O.jsx)(A,{icon:n,label:`Completed`,value:R,color:`text-emerald-400`}),(0,O.jsx)(A,{icon:c,label:`Failed`,value:z,color:`text-red-400`}),(0,O.jsx)(A,{icon:a,label:`Goals`,value:s.length,color:`text-orange-400`}),(0,O.jsx)(A,{icon:r,label:`Execution Pool`,value:`${M.active}/${M.max} | ${M.queued} queued`,color:`text-blue-400`})]}),(0,O.jsx)(`div`,{className:`grid gap-4 lg:grid-cols-1`,children:(0,O.jsxs)(_,{children:[(0,O.jsx)(h,{children:(0,O.jsx)(g,{children:`System Checks`})}),k?(0,O.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:Object.entries(k.checks).map(([e,t])=>(0,O.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md bg-slate-800/30 px-3 py-2`,children:[(0,O.jsx)(`div`,{className:t?`h-2 w-2 rounded-full bg-emerald-500`:`h-2 w-2 rounded-full bg-red-500`}),(0,O.jsx)(`span`,{className:`text-xs capitalize text-slate-300`,children:e})]},e))}):(0,O.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Loading...`})]})}),(0,O.jsxs)(_,{padding:!1,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between px-4 pt-4`,children:[(0,O.jsx)(g,{children:`Recent Tasks`}),(0,O.jsx)(u,{to:`/work`,className:`text-xs text-blue-400 hover:text-blue-300`,children:`View all`})]}),(0,O.jsx)(`div`,{className:`mt-3`,children:(0,O.jsxs)(E,{children:[(0,O.jsx)(x,{children:(0,O.jsxs)(w,{children:[(0,O.jsx)(S,{children:`ID`}),(0,O.jsx)(S,{children:`Prompt`}),(0,O.jsx)(S,{children:`Status`}),(0,O.jsx)(S,{children:`Role`}),(0,O.jsx)(S,{children:`Created`})]})}),(0,O.jsxs)(C,{children:[B.map(e=>(0,O.jsxs)(w,{children:[(0,O.jsx)(T,{children:(0,O.jsx)(u,{to:`/tasks/${e.id}`,className:`font-mono text-xs text-blue-400 hover:text-blue-300`,children:e.id.slice(0,8)})}),(0,O.jsx)(T,{children:y(e.prompt,60)}),(0,O.jsx)(T,{children:(0,O.jsx)(m,{variant:p(e.status),children:e.status})}),(0,O.jsx)(T,{children:(0,O.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:e.roleId?e.roleId.slice(0,12):`—`})}),(0,O.jsx)(T,{className:`text-xs text-slate-500`,children:v(e.createdAt)})]},e.id)),B.length===0&&(0,O.jsx)(w,{children:(0,O.jsx)(T,{colSpan:5,className:`text-center text-slate-500`,children:`No tasks yet`})})]})]})})]})]})}function A({icon:e,label:t,value:n,color:r}){return(0,O.jsxs)(_,{className:`flex items-center gap-3`,children:[(0,O.jsx)(`div`,{className:`rounded-md bg-slate-800 p-2 ${r}`,children:(0,O.jsx)(e,{size:16})}),(0,O.jsxs)(`div`,{children:[(0,O.jsx)(`div`,{className:`text-lg font-semibold text-slate-100`,children:n}),(0,O.jsx)(`div`,{className:`text-xs text-slate-500`,children:t})]})]})}export{k as Dashboard};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{G as t,K as n,V as r,W as i,c as a,k as o,nt as s,q as c,tt as l}from"./vendor-icons-CkI4-NxL.js";import{r as u,t as d}from"./vendor-react-DLRtONKt.js";import{C as f,n as p,t as m}from"./index-rvaixveh.js";import{n as h,r as g,t as _}from"./Card-4mOZntHG.js";import{a as v,o as y,t as b}from"./format-DvtQjPZn.js";import{a as x,i as S,n as C,o as w,r as T,t as E}from"./Table-BxbnOSbq.js";var D=e(s(),1),O=d();function k(){let e=f(e=>e.tasks),s=f(e=>e.goals),d=f(e=>e.stats),k=f(e=>e.readiness),j=f(e=>e.roles),M=f(e=>e.executionPool),N=f(e=>e.fetchTasks),P=f(e=>e.fetchGoals),F=f(e=>e.fetchRoles),I=f(e=>e.fetchExecutionPool);(0,D.useEffect)(()=>{N(),P(),F(),I();let e=setInterval(()=>{N(),I()},5e3);return()=>clearInterval(e)},[N,P,F,I]);let L=e.filter(e=>e.status===`running`).length,R=e.filter(e=>e.status===`completed`).length,z=e.filter(e=>e.status===`failed`).length,B=[...e].sort((e,t)=>t.createdAt-e.createdAt).slice(0,8);return(0,O.jsxs)(`div`,{className:`space-y-6`,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,O.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Dashboard`}),k&&(0,O.jsx)(`span`,{role:`status`,"aria-live":`polite`,children:(0,O.jsx)(m,{variant:k.status===`ready`?`success`:`destructive`,children:k.status===`ready`?`Server Ready`:`Not Ready`})})]}),(0,O.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,role:`region`,"aria-label":`Server statistics`,children:[(0,O.jsx)(A,{icon:o,label:`Active Tasks`,value:d.activeTasks||L,color:`text-blue-400`}),(()=>{let e=j.filter(e=>e.status===`active`).length,t=j.length,n=j.filter(e=>e.status===`probation`).length,r=j.filter(e=>e.status===`retired`).length,i=[n>0?`${n} probation`:``,r>0?`${r} retired`:``].filter(Boolean).join(` · `);return(0,O.jsx)(A,{icon:l,label:`Role Health`,value:i?`${e}/${t} | ${i}`:`${e}/${t}`,color:r>0?`text-red-400`:n>0?`text-amber-400`:`text-emerald-400`})})(),(0,O.jsx)(A,{icon:i,label:`Roles`,value:j.length,color:`text-emerald-400`}),(0,O.jsx)(A,{icon:t,label:`Cost Today`,value:b(d.totalCostToday),color:`text-purple-400`})]}),(0,O.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,role:`region`,"aria-label":`Additional statistics`,children:[(0,O.jsx)(A,{icon:n,label:`Completed`,value:R,color:`text-emerald-400`}),(0,O.jsx)(A,{icon:c,label:`Failed`,value:z,color:`text-red-400`}),(0,O.jsx)(A,{icon:a,label:`Goals`,value:s.length,color:`text-orange-400`}),(0,O.jsx)(A,{icon:r,label:`Execution Pool`,value:`${M.active}/${M.max} | ${M.queued} queued`,color:`text-blue-400`})]}),(0,O.jsx)(`div`,{className:`grid gap-4 lg:grid-cols-1`,children:(0,O.jsxs)(_,{children:[(0,O.jsx)(h,{children:(0,O.jsx)(g,{children:`System Checks`})}),k?(0,O.jsx)(`div`,{className:`grid grid-cols-2 gap-2`,children:Object.entries(k.checks).map(([e,t])=>(0,O.jsxs)(`div`,{className:`flex items-center gap-2 rounded-md bg-slate-800/30 px-3 py-2`,children:[(0,O.jsx)(`div`,{className:t?`h-2 w-2 rounded-full bg-emerald-500`:`h-2 w-2 rounded-full bg-red-500`}),(0,O.jsx)(`span`,{className:`text-xs capitalize text-slate-300`,children:e})]},e))}):(0,O.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Loading...`})]})}),(0,O.jsxs)(_,{padding:!1,children:[(0,O.jsxs)(`div`,{className:`flex items-center justify-between px-4 pt-4`,children:[(0,O.jsx)(g,{children:`Recent Tasks`}),(0,O.jsx)(u,{to:`/work`,className:`text-xs text-blue-400 hover:text-blue-300`,children:`View all`})]}),(0,O.jsx)(`div`,{className:`mt-3`,children:(0,O.jsxs)(E,{children:[(0,O.jsx)(x,{children:(0,O.jsxs)(w,{children:[(0,O.jsx)(S,{children:`ID`}),(0,O.jsx)(S,{children:`Prompt`}),(0,O.jsx)(S,{children:`Status`}),(0,O.jsx)(S,{children:`Role`}),(0,O.jsx)(S,{children:`Created`})]})}),(0,O.jsxs)(C,{children:[B.map(e=>(0,O.jsxs)(w,{children:[(0,O.jsx)(T,{children:(0,O.jsx)(u,{to:`/tasks/${e.id}`,className:`font-mono text-xs text-blue-400 hover:text-blue-300`,children:e.id.slice(0,8)})}),(0,O.jsx)(T,{children:y(e.prompt,60)}),(0,O.jsx)(T,{children:(0,O.jsx)(m,{variant:p(e.status),children:e.status})}),(0,O.jsx)(T,{children:(0,O.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:e.roleId?e.roleId.slice(0,12):`—`})}),(0,O.jsx)(T,{className:`text-xs text-slate-500`,children:v(e.createdAt)})]},e.id)),B.length===0&&(0,O.jsx)(w,{children:(0,O.jsx)(T,{colSpan:5,className:`text-center text-slate-500`,children:`No tasks yet`})})]})]})})]})]})}function A({icon:e,label:t,value:n,color:r}){return(0,O.jsxs)(_,{className:`flex items-center gap-3`,children:[(0,O.jsx)(`div`,{className:`rounded-md bg-slate-800 p-2 ${r}`,children:(0,O.jsx)(e,{size:16})}),(0,O.jsxs)(`div`,{children:[(0,O.jsx)(`div`,{className:`text-lg font-semibold text-slate-100`,children:n}),(0,O.jsx)(`div`,{className:`text-xs text-slate-500`,children:t})]})]})}export{k as Dashboard};
@@ -0,0 +1 @@
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{L as t,R as n,a as r,nt as i,o as a,v as o}from"./vendor-icons-CkI4-NxL.js";import{t as s}from"./vendor-react-DLRtONKt.js";import{n as c,r as l}from"./dist-HyCSN_hp.js";import{f as u,w as d}from"./index-rvaixveh.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";var h=e(i(),1),g=s(),_=h.forwardRef(({className:e,type:t,...n},r)=>(0,g.jsx)(`input`,{type:t,className:c(`flex h-8 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-1 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:cursor-not-allowed disabled:opacity-50`,e),ref:r,...n}));_.displayName=`Input`;var v=/^[A-Za-z_][A-Za-z0-9_]*$/,y=/key|token|secret|password|credential/i;function b({envVars:e,onSave:i,mode:s,roleId:c,title:b=`Environment Variables`}){let[x,S]=(0,h.useState)([]),[C,w]=(0,h.useState)(!1),[T,E]=(0,h.useState)(new Set),[D,O]=(0,h.useState)([]),[k,A]=(0,h.useState)(!1);(0,h.useEffect)(()=>{S(Object.entries(e??{}).map(([e,t])=>({key:e,value:t,isNew:!1})))},[e]);let j=(0,h.useCallback)(async()=>{try{let e=await l(s===`global`?`/config/env-diff`:`/roles/${c}/env-diff`);O(s===`global`?e.diffs.filter(e=>e.configPath?.startsWith(`defaults.env.`)):e.diffs),A(e.envFileExists)}catch{}},[s,c]);(0,h.useEffect)(()=>{j()},[j]);let M=()=>{let t=Object.fromEntries(x.filter(e=>e.key.trim()).map(e=>[e.key,e.value]));return JSON.stringify(t)!==JSON.stringify(e)},N=()=>{S(e=>[...e,{key:``,value:``,isNew:!0}])},P=e=>{S(t=>t.filter((t,n)=>n!==e))},F=(e,t,n)=>{S(r=>r.map((r,i)=>i===e?{...r,[t]:n}:r))},I=e=>{E(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},L=()=>{let e=new Set;for(let t of x){let n=t.key.trim();if(n){if(!v.test(n))return`Invalid key format: "${n}"`;if(n.startsWith(`ANTHROPIC_`))return`ANTHROPIC_* keys are managed in the Anthropic section`;if(e.has(n))return`Duplicate key: "${n}"`;e.add(n)}}return e.size>100?`Maximum 100 environment variables`:null},R=async()=>{let e=L();if(e){d.error(e);return}w(!0);try{let e={};for(let t of x){let n=t.key.trim();n&&(e[n]=t.value)}s===`global`?await l(`/config/env`,{method:`PUT`,body:JSON.stringify(e)}):await l(`/roles/${c}`,{method:`PATCH`,body:JSON.stringify({envVars:e})}),d.success(`Environment variables saved`),i(),j()}catch(e){d.error(e instanceof Error?e.message:`Failed to save`)}finally{w(!1)}},z=async()=>{try{await l(s===`global`?`/config/sync-to-env`:`/roles/${c}/sync-to-env`,{method:`POST`}),d.success(`Synced DB to .env`),j()}catch(e){d.error(e instanceof Error?e.message:`Sync failed`)}},B=async()=>{try{await l(s===`global`?`/config/load-from-env`:`/roles/${c}/load-from-env`,{method:`POST`}),d.success(`Loaded .env to DB`),i(),j()}catch(e){d.error(e instanceof Error?e.message:`Load failed`)}};return(0,g.jsxs)(m,{children:[(0,g.jsxs)(f,{children:[(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsx)(p,{className:`text-sm`,children:b}),(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsxs)(u,{variant:`ghost`,size:`sm`,onClick:N,children:[(0,g.jsx)(o,{size:14,className:`mr-1`}),` Add`]}),M()&&(0,g.jsx)(u,{size:`sm`,onClick:()=>void R(),disabled:C,children:C?`Saving...`:`Save`})]})]}),s===`global`&&(0,g.jsx)(`p`,{className:`text-xs text-slate-500 mt-1`,children:`ANTHROPIC_* variables are managed in the Anthropic section above.`})]}),D.length>0&&k&&(0,g.jsx)(`div`,{className:`mx-4 mb-3 rounded border border-yellow-800 bg-yellow-950/50 p-3`,children:(0,g.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsx)(r,{size:14,className:`text-yellow-400`}),(0,g.jsxs)(`span`,{className:`text-xs text-yellow-400`,children:[`.env and DB differ on `,D.length,` key(s): `,D.map(e=>e.envKey).join(`, `)]})]}),(0,g.jsxs)(`div`,{className:`flex gap-2`,children:[(0,g.jsx)(u,{variant:`ghost`,size:`sm`,className:`text-xs`,onClick:()=>void z(),children:`DB → .env`}),(0,g.jsx)(u,{variant:`ghost`,size:`sm`,className:`text-xs`,onClick:()=>void B(),children:`.env → DB`})]})]})}),(0,g.jsxs)(`div`,{className:`px-4 pb-4 space-y-2`,children:[x.length===0&&(0,g.jsx)(`p`,{className:`text-xs text-slate-500 py-2`,children:`No environment variables configured.`}),x.map((e,r)=>{let i=y.test(e.key),o=T.has(e.key)||e.isNew;return(0,g.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,g.jsx)(_,{className:`w-48 font-mono text-xs`,placeholder:`KEY_NAME`,value:e.key,onChange:e=>F(r,`key`,e.target.value)}),(0,g.jsx)(`span`,{className:`text-slate-600`,children:`=`}),(0,g.jsxs)(`div`,{className:`relative flex-1`,children:[(0,g.jsx)(_,{className:`font-mono text-xs pr-8`,type:i&&!o?`password`:`text`,placeholder:`value`,value:e.value,onChange:e=>F(r,`value`,e.target.value)}),i&&(0,g.jsx)(`button`,{type:`button`,className:`absolute right-2 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300`,onClick:()=>I(e.key),children:o?(0,g.jsx)(n,{size:12}):(0,g.jsx)(t,{size:12})})]}),(0,g.jsx)(u,{variant:`ghost`,size:`sm`,className:`text-red-500 hover:text-red-300`,onClick:()=>P(r),children:(0,g.jsx)(a,{size:14})})]},r)})]})]})}export{b as t};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{F as t,h as n,nt as r}from"./vendor-icons-CkI4-NxL.js";import{t as i}from"./vendor-react-DLRtONKt.js";import{r as a}from"./dist-HyCSN_hp.js";import{C as o,f as s,t as c}from"./index-oA-kWqT5.js";import{t as l}from"./Card-4mOZntHG.js";import{a as u}from"./format-DvtQjPZn.js";import{t as d}from"./EmptyState-BlgMMAr-.js";var f=e(r(),1),p=i();function m(){let e=o(e=>e.roles),r=o(e=>e.fetchRoles),[i,m]=(0,f.useState)([]),[h,g]=(0,f.useState)(!0),[_,v]=(0,f.useState)(`all`);(0,f.useEffect)(()=>{r()},[r]);let y=(0,f.useCallback)(async()=>{g(!0);try{let e=new URLSearchParams({limit:`50`});_!==`all`&&e.set(`roleId`,_),m(await a(`/evolution-audit?${e}`))}catch{m([])}finally{g(!1)}},[_]);(0,f.useEffect)(()=>{y()},[y]);let b=t=>t?e.find(e=>e.id===t)?.name??t.slice(0,8):`System`;return(0,p.jsxs)(`div`,{className:`space-y-4`,children:[(0,p.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,p.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Evolution Audit`}),(0,p.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,p.jsxs)(`select`,{className:`rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:_,onChange:e=>v(e.target.value),children:[(0,p.jsx)(`option`,{value:`all`,children:`All roles`}),e.map(e=>(0,p.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,p.jsx)(s,{variant:`ghost`,size:`sm`,onClick:()=>void y(),children:(0,p.jsx)(n,{size:14})})]})]}),(0,p.jsx)(l,{children:h?(0,p.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,p.jsx)(`div`,{className:`h-6 w-6 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):i.length===0?(0,p.jsx)(d,{icon:(0,p.jsx)(t,{size:32}),title:`No evolution records`,description:`Evolution occurs when roles accumulate enough task experience`}):(0,p.jsxs)(`div`,{className:`space-y-4`,children:[(0,p.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[i.length,` records`]}),i.map(e=>(0,p.jsxs)(`div`,{className:`rounded border border-slate-800 p-3`,children:[(0,p.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,p.jsx)(c,{variant:`info`,children:b(e.roleId)}),(0,p.jsx)(`span`,{className:`text-xs text-slate-500`,children:u(e.timestamp)}),e.triggerTaskId&&(0,p.jsxs)(`span`,{className:`text-[10px] text-slate-600`,children:[`triggered by task `,e.triggerTaskId.slice(0,8)]})]}),e.diff.includes(`--- Diagnostic Report ---`)?(0,p.jsxs)(`div`,{className:`space-y-2`,children:[(0,p.jsxs)(`div`,{className:`rounded bg-slate-950 p-2`,children:[(0,p.jsx)(`p`,{className:`mb-1 text-[10px] font-medium text-slate-400`,children:`Diagnostic Report`}),(0,p.jsx)(`pre`,{className:`whitespace-pre-wrap font-mono text-xs text-slate-400`,children:e.diff.split(`--- Rules Diff ---`)[0]?.replace(`--- Diagnostic Report ---
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{F as t,h as n,nt as r}from"./vendor-icons-CkI4-NxL.js";import{t as i}from"./vendor-react-DLRtONKt.js";import{r as a}from"./dist-HyCSN_hp.js";import{C as o,f as s,t as c}from"./index-rvaixveh.js";import{t as l}from"./Card-4mOZntHG.js";import{a as u}from"./format-DvtQjPZn.js";import{t as d}from"./EmptyState-BlgMMAr-.js";var f=e(r(),1),p=i();function m(){let e=o(e=>e.roles),r=o(e=>e.fetchRoles),[i,m]=(0,f.useState)([]),[h,g]=(0,f.useState)(!0),[_,v]=(0,f.useState)(`all`);(0,f.useEffect)(()=>{r()},[r]);let y=(0,f.useCallback)(async()=>{g(!0);try{let e=new URLSearchParams({limit:`50`});_!==`all`&&e.set(`roleId`,_),m(await a(`/evolution-audit?${e}`))}catch{m([])}finally{g(!1)}},[_]);(0,f.useEffect)(()=>{y()},[y]);let b=t=>t?e.find(e=>e.id===t)?.name??t.slice(0,8):`System`;return(0,p.jsxs)(`div`,{className:`space-y-4`,children:[(0,p.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,p.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Evolution Audit`}),(0,p.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,p.jsxs)(`select`,{className:`rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:_,onChange:e=>v(e.target.value),children:[(0,p.jsx)(`option`,{value:`all`,children:`All roles`}),e.map(e=>(0,p.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,p.jsx)(s,{variant:`ghost`,size:`sm`,onClick:()=>void y(),children:(0,p.jsx)(n,{size:14})})]})]}),(0,p.jsx)(l,{children:h?(0,p.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,p.jsx)(`div`,{className:`h-6 w-6 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):i.length===0?(0,p.jsx)(d,{icon:(0,p.jsx)(t,{size:32}),title:`No evolution records`,description:`Evolution occurs when roles accumulate enough task experience`}):(0,p.jsxs)(`div`,{className:`space-y-4`,children:[(0,p.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[i.length,` records`]}),i.map(e=>(0,p.jsxs)(`div`,{className:`rounded border border-slate-800 p-3`,children:[(0,p.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[(0,p.jsx)(c,{variant:`info`,children:b(e.roleId)}),(0,p.jsx)(`span`,{className:`text-xs text-slate-500`,children:u(e.timestamp)}),e.triggerTaskId&&(0,p.jsxs)(`span`,{className:`text-[10px] text-slate-600`,children:[`triggered by task `,e.triggerTaskId.slice(0,8)]})]}),e.diff.includes(`--- Diagnostic Report ---`)?(0,p.jsxs)(`div`,{className:`space-y-2`,children:[(0,p.jsxs)(`div`,{className:`rounded bg-slate-950 p-2`,children:[(0,p.jsx)(`p`,{className:`mb-1 text-[10px] font-medium text-slate-400`,children:`Diagnostic Report`}),(0,p.jsx)(`pre`,{className:`whitespace-pre-wrap font-mono text-xs text-slate-400`,children:e.diff.split(`--- Rules Diff ---`)[0]?.replace(`--- Diagnostic Report ---
2
2
  `,``).trim()})]}),(0,p.jsxs)(`div`,{className:`rounded bg-slate-950 p-2`,children:[(0,p.jsx)(`p`,{className:`mb-1 text-[10px] font-medium text-slate-400`,children:`Rules Changes`}),(0,p.jsx)(`pre`,{className:`max-h-48 overflow-auto whitespace-pre-wrap font-mono text-xs`,children:(e.diff.split(`--- Rules Diff ---`)[1]??``).trim().split(`
3
3
  `).map((e,t)=>(0,p.jsxs)(`span`,{className:e.startsWith(`+`)?`text-green-400`:e.startsWith(`-`)?`text-red-400`:`text-slate-400`,children:[e,`
4
4
  `]},t))})]})]}):(0,p.jsx)(`pre`,{className:`max-h-48 overflow-auto whitespace-pre-wrap rounded bg-slate-950 p-2 font-mono text-xs`,children:e.diff.split(`
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,B as n,H as r,M as i,c as a,nt as o}from"./vendor-icons-CkI4-NxL.js";import{d as s,r as c,t as l}from"./vendor-react-DLRtONKt.js";import{r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./index-oA-kWqT5.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";import{n as h}from"./format-DvtQjPZn.js";var g=e(o(),1),_=l();function v(){let{id:e}=s(),[o,l]=(0,g.useState)(null),[v,b]=(0,g.useState)([]),[x,S]=(0,g.useState)(null);if((0,g.useEffect)(()=>{e&&(async()=>{try{let t=await u(`/goals/${e}`);l(t.goal),S(null);try{b((await u(`/strategies?role=${t.goal.roleId}`)).strategies??[])}catch{}}catch(e){S(e instanceof Error?e.message:`Failed to load goal`)}})()},[e]),x)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{className:`text-center text-red-400`,children:x})]});if(!o)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{className:`text-center text-slate-500`,children:`Loading...`})]});let C=o.targetValue>0?Math.min(100,o.currentValue/o.targetValue*100):0,w=o.deadline>0&&o.deadline<Date.now()&&o.status!==`completed`;return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{children:(0,_.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,_.jsx)(d,{variant:(e=>e===`completed`?`success`:e===`executing`||e===`evaluating`?`warning`:e===`failed`?`destructive`:`secondary`)(o.status),children:o.status}),(0,_.jsx)(d,{variant:`outline`,children:o.roleId}),(0,_.jsx)(d,{variant:`outline`,children:o.metricType}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:o.id})]}),(0,_.jsx)(`h2`,{className:`text-lg font-semibold text-slate-200`,children:o.name}),o.description&&(0,_.jsx)(`p`,{className:`text-sm text-slate-400 mt-1`,children:o.description})]})})}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,children:[(0,_.jsx)(y,{icon:a,label:`Progress`,value:`${o.currentValue} / ${o.targetValue}`}),(0,_.jsx)(y,{icon:r,label:w?`Overdue`:`Deadline`,value:h(o.deadline),mono:!0}),(0,_.jsx)(y,{icon:n,label:`Budget`,value:`$${o.budgetUsd.toFixed(2)}`}),(0,_.jsx)(y,{icon:i,label:`Created`,value:h(o.createdAt),mono:!0})]}),(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Progress`})}),(0,_.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,_.jsx)(`div`,{className:`flex-1 h-3 rounded-full bg-slate-700 overflow-hidden`,children:(0,_.jsx)(`div`,{className:`h-full rounded-full transition-all ${w?`bg-red-500`:`bg-blue-500`}`,style:{width:`${C}%`}})}),(0,_.jsxs)(`span`,{className:`text-sm text-slate-300 font-mono`,children:[C.toFixed(1),`%`]})]}),(0,_.jsxs)(`div`,{className:`mt-2 flex items-center justify-between text-xs text-slate-500`,children:[(0,_.jsxs)(`span`,{children:[o.currentValue,` current`]}),(0,_.jsxs)(`span`,{children:[o.targetValue,` target`]})]})]}),(o.deliverTo??[]).length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Delivery Targets`})}),(0,_.jsx)(`div`,{className:`space-y-1.5`,children:(o.deliverTo??[]).map((e,t)=>(0,_.jsx)(`div`,{className:`flex items-center gap-2 text-sm text-slate-300`,children:e.type===`channel`?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{variant:`outline`,children:`Channel`}),(0,_.jsx)(`span`,{className:`font-mono text-xs`,children:e.channelId.slice(0,8)}),e.chatId&&(0,_.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[`chat: `,e.chatId.slice(0,8)]})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{variant:`outline`,children:`Session`}),(0,_.jsx)(`span`,{className:`text-xs text-slate-400`,children:`Chat session`})]})},t))})]}),v.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(i,{size:14}),` Strategies (`,v.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:v.map(e=>(0,_.jsxs)(`div`,{className:`flex items-center justify-between text-sm border-b border-slate-800 pb-2`,children:[(0,_.jsxs)(`div`,{children:[(0,_.jsx)(`span`,{className:`text-slate-200`,children:e.name}),(0,_.jsx)(`span`,{className:`text-xs text-slate-500 ml-2`,children:e.taskType})]}),(0,_.jsxs)(d,{variant:`outline`,children:[e.trialCount,` trials`]})]},e.id))})]})]})}function y({icon:e,label:t,value:n,mono:r}){return(0,_.jsxs)(m,{className:`flex flex-col gap-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 text-slate-500`,children:[(0,_.jsx)(e,{size:12}),(0,_.jsx)(`span`,{className:`text-xs`,children:t})]}),(0,_.jsx)(`span`,{className:`text-sm text-slate-200 truncate ${r?`font-mono text-xs`:``}`,children:n})]})}export{v as GoalDetail};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{$ as t,B as n,H as r,M as i,c as a,nt as o}from"./vendor-icons-CkI4-NxL.js";import{d as s,r as c,t as l}from"./vendor-react-DLRtONKt.js";import{r as u}from"./dist-HyCSN_hp.js";import{t as d}from"./index-rvaixveh.js";import{n as f,r as p,t as m}from"./Card-4mOZntHG.js";import{n as h}from"./format-DvtQjPZn.js";var g=e(o(),1),_=l();function v(){let{id:e}=s(),[o,l]=(0,g.useState)(null),[v,b]=(0,g.useState)([]),[x,S]=(0,g.useState)(null);if((0,g.useEffect)(()=>{e&&(async()=>{try{let t=await u(`/goals/${e}`);l(t.goal),S(null);try{b((await u(`/strategies?role=${t.goal.roleId}`)).strategies??[])}catch{}}catch(e){S(e instanceof Error?e.message:`Failed to load goal`)}})()},[e]),x)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{className:`text-center text-red-400`,children:x})]});if(!o)return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{className:`text-center text-slate-500`,children:`Loading...`})]});let C=o.targetValue>0?Math.min(100,o.currentValue/o.targetValue*100):0,w=o.deadline>0&&o.deadline<Date.now()&&o.status!==`completed`;return(0,_.jsxs)(`div`,{className:`space-y-4`,children:[(0,_.jsxs)(c,{to:`/goals`,className:`flex items-center gap-1.5 text-sm text-slate-400 hover:text-slate-200`,children:[(0,_.jsx)(t,{size:14}),` Back to Goals`]}),(0,_.jsx)(m,{children:(0,_.jsx)(`div`,{className:`flex items-start justify-between gap-4`,children:(0,_.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,_.jsx)(d,{variant:(e=>e===`completed`?`success`:e===`executing`||e===`evaluating`?`warning`:e===`failed`?`destructive`:`secondary`)(o.status),children:o.status}),(0,_.jsx)(d,{variant:`outline`,children:o.roleId}),(0,_.jsx)(d,{variant:`outline`,children:o.metricType}),(0,_.jsx)(`span`,{className:`font-mono text-xs text-slate-500`,children:o.id})]}),(0,_.jsx)(`h2`,{className:`text-lg font-semibold text-slate-200`,children:o.name}),o.description&&(0,_.jsx)(`p`,{className:`text-sm text-slate-400 mt-1`,children:o.description})]})})}),(0,_.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 lg:grid-cols-4`,children:[(0,_.jsx)(y,{icon:a,label:`Progress`,value:`${o.currentValue} / ${o.targetValue}`}),(0,_.jsx)(y,{icon:r,label:w?`Overdue`:`Deadline`,value:h(o.deadline),mono:!0}),(0,_.jsx)(y,{icon:n,label:`Budget`,value:`$${o.budgetUsd.toFixed(2)}`}),(0,_.jsx)(y,{icon:i,label:`Created`,value:h(o.createdAt),mono:!0})]}),(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Progress`})}),(0,_.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,_.jsx)(`div`,{className:`flex-1 h-3 rounded-full bg-slate-700 overflow-hidden`,children:(0,_.jsx)(`div`,{className:`h-full rounded-full transition-all ${w?`bg-red-500`:`bg-blue-500`}`,style:{width:`${C}%`}})}),(0,_.jsxs)(`span`,{className:`text-sm text-slate-300 font-mono`,children:[C.toFixed(1),`%`]})]}),(0,_.jsxs)(`div`,{className:`mt-2 flex items-center justify-between text-xs text-slate-500`,children:[(0,_.jsxs)(`span`,{children:[o.currentValue,` current`]}),(0,_.jsxs)(`span`,{children:[o.targetValue,` target`]})]})]}),(o.deliverTo??[]).length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsx)(p,{children:`Delivery Targets`})}),(0,_.jsx)(`div`,{className:`space-y-1.5`,children:(o.deliverTo??[]).map((e,t)=>(0,_.jsx)(`div`,{className:`flex items-center gap-2 text-sm text-slate-300`,children:e.type===`channel`?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{variant:`outline`,children:`Channel`}),(0,_.jsx)(`span`,{className:`font-mono text-xs`,children:e.channelId.slice(0,8)}),e.chatId&&(0,_.jsxs)(`span`,{className:`text-xs text-slate-500`,children:[`chat: `,e.chatId.slice(0,8)]})]}):(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(d,{variant:`outline`,children:`Session`}),(0,_.jsx)(`span`,{className:`text-xs text-slate-400`,children:`Chat session`})]})},t))})]}),v.length>0&&(0,_.jsxs)(m,{children:[(0,_.jsx)(f,{children:(0,_.jsxs)(p,{className:`flex items-center gap-2`,children:[(0,_.jsx)(i,{size:14}),` Strategies (`,v.length,`)`]})}),(0,_.jsx)(`div`,{className:`space-y-2`,children:v.map(e=>(0,_.jsxs)(`div`,{className:`flex items-center justify-between text-sm border-b border-slate-800 pb-2`,children:[(0,_.jsxs)(`div`,{children:[(0,_.jsx)(`span`,{className:`text-slate-200`,children:e.name}),(0,_.jsx)(`span`,{className:`text-xs text-slate-500 ml-2`,children:e.taskType})]}),(0,_.jsxs)(d,{variant:`outline`,children:[e.trialCount,` trials`]})]},e.id))})]})]})}function y({icon:e,label:t,value:n,mono:r}){return(0,_.jsxs)(m,{className:`flex flex-col gap-1`,children:[(0,_.jsxs)(`div`,{className:`flex items-center gap-1.5 text-slate-500`,children:[(0,_.jsx)(e,{size:12}),(0,_.jsx)(`span`,{className:`text-xs`,children:t})]}),(0,_.jsx)(`span`,{className:`text-sm text-slate-200 truncate ${r?`font-mono text-xs`:``}`,children:n})]})}export{v as GoalDetail};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{C as t,S as n,c as r,h as i,nt as a,o,t as s,v as c,x as l}from"./vendor-icons-CkI4-NxL.js";import{t as u}from"./vendor-react-DLRtONKt.js";import{r as d}from"./dist-HyCSN_hp.js";import{C as f,a as p,c as m,d as h,f as g,i as _,l as v,n as ee,o as y,r as b,s as te,t as x,u as ne,w as S}from"./index-oA-kWqT5.js";import{n as C,r as w,t as T}from"./Card-4mOZntHG.js";import{n as E,t as D}from"./format-DvtQjPZn.js";import{t as O}from"./EmptyState-BlgMMAr-.js";var k=e(a(),1),A=u();function j({value:e,onChange:t,label:n=`Delivery Targets`}){let[r,i]=(0,k.useState)([]),[a,o]=(0,k.useState)(!1);(0,k.useEffect)(()=>{let e=!1;return Promise.all([d(`/channels`).catch(()=>({channels:[]})),d(`/chat/sessions`).catch(()=>({sessions:[]}))]).then(([t,n])=>{if(e)return;let r=new Map(t.channels.map(e=>[e.id,e])),a=[];for(let e of n.sessions)if(e.source.type===`channel`&&e.source.channelId&&e.source.chatId){let t=r.get(e.source.channelId);a.push({id:e.id,channelId:e.source.channelId,channelName:t?.name??e.source.channelId.slice(0,8),platform:t?.platform??`unknown`,chatId:e.source.chatId})}let o=new Set;i(a.filter(e=>{let t=`${e.channelId}:${e.chatId}`;return o.has(t)?!1:(o.add(t),!0)}))}),()=>{e=!0}},[]);let s=(t,n)=>e.some(e=>e.type===`channel`&&e.channelId===t&&e.chatId===n),c=(n,r)=>{s(n,r)?t(e.filter(e=>!(e.type===`channel`&&e.channelId===n&&e.chatId===r))):t([...e,{type:`channel`,channelId:n,chatId:r}])},l=e.filter(e=>e.type===`channel`).length;return(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(`label`,{className:`text-xs text-slate-400`,children:n}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(!a),className:`mt-1 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-left text-sm text-slate-200 hover:border-slate-600 focus:border-blue-500 focus:outline-none`,children:l===0?`Default (current session)`:`${l} channel${l>1?`s`:``} selected`}),a&&(0,A.jsxs)(`div`,{className:`absolute z-10 mt-1 w-full rounded-md border border-slate-700 bg-slate-800 py-1 shadow-lg`,children:[r.length===0?(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-slate-500`,children:`No active channel conversations. Start a chat on WeChat/Telegram first.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`px-3 py-1 text-xs text-slate-500`,children:`Channel conversations`}),r.map(e=>(0,A.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-700`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:s(e.channelId,e.chatId),onChange:()=>c(e.channelId,e.chatId),className:`rounded border-slate-600 bg-slate-700`}),(0,A.jsx)(`span`,{className:`truncate font-medium`,children:e.channelName}),(0,A.jsxs)(`span`,{className:`text-slate-500`,children:[`(`,e.platform,`)`]})]},`${e.channelId}:${e.chatId}`))]}),l>0&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>{t([]),o(!1)},className:`mt-1 w-full border-t border-slate-700 px-3 py-1 text-left text-xs text-red-400 hover:bg-slate-700`,children:`Clear all`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(!1),className:`w-full border-t border-slate-700 px-3 py-1 text-left text-xs text-slate-500 hover:bg-slate-700`,children:`Done`})]})]})}var M={active:`paused`,paused:`active`,completed:`active`,failed:`active`},N={active:(0,A.jsx)(t,{size:12}),paused:(0,A.jsx)(l,{size:12}),completed:(0,A.jsx)(i,{size:12}),failed:(0,A.jsx)(i,{size:12})};function P(){let e=f(e=>e.goals),t=f(e=>e.fetchGoals),a=f(e=>e.updateGoal),u=f(e=>e.deleteGoal),[P,F]=(0,k.useState)(!1),[I,L]=(0,k.useState)(``),[R,z]=(0,k.useState)(!1),[B,V]=(0,k.useState)(null),[H,U]=(0,k.useState)(null),[W,G]=(0,k.useState)(``),[K,q]=(0,k.useState)(``),[J,Y]=(0,k.useState)([]),[X,Z]=(0,k.useState)([]),[Q,re]=(0,k.useState)([]),[$,ie]=(0,k.useState)([]);(0,k.useEffect)(()=>{t();let e=setInterval(()=>void t(),1e4);return()=>clearInterval(e)},[t]);let ae=async()=>{if(I.trim()){z(!0),V(null);try{await d(`/goals`,{method:`POST`,body:JSON.stringify({input:I.trim(),deliverTo:Q.length>0?Q:void 0,reportTo:$.length>0?$:void 0})}),L(``),F(!1),t()}catch(e){V(e instanceof Error?e.message:`Failed to create goal`)}finally{z(!1)}}};return(0,A.jsxs)(`div`,{className:`space-y-4`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,A.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Goals`}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(g,{variant:`ghost`,size:`sm`,onClick:()=>void t(),children:(0,A.jsx)(i,{size:14})}),(0,A.jsxs)(g,{size:`sm`,onClick:()=>F(!P),children:[(0,A.jsx)(c,{size:14}),`New Goal`]})]})]}),P&&(0,A.jsxs)(T,{className:`space-y-3`,children:[(0,A.jsx)(`textarea`,{className:`w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none`,placeholder:`Describe your goal in natural language...`,rows:3,value:I,onChange:e=>L(e.target.value)}),(0,A.jsx)(j,{value:Q,onChange:re,label:`Deliver To (results)`}),(0,A.jsx)(j,{value:$,onChange:ie,label:`Report To (status)`}),B&&(0,A.jsx)(`p`,{className:`text-xs text-red-400`,children:B}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(g,{onClick:()=>void ae(),disabled:R||!I.trim(),children:R?`Creating...`:`Create`}),(0,A.jsx)(g,{variant:`ghost`,onClick:()=>F(!1),children:`Cancel`})]})]}),e.length===0?(0,A.jsx)(O,{icon:(0,A.jsx)(r,{size:32}),title:`No goals`,description:`Create a goal to start goal-driven task orchestration`}):(0,A.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:e.map(e=>{let t=e.targetValue>0?Math.min(100,Math.round(e.currentValue/e.targetValue*100)):0,r=new Date(e.deadline).getTime()<Date.now()&&e.status!==`completed`,i=H===e.id;return(0,A.jsxs)(T,{children:[(0,A.jsxs)(C,{children:[i?(0,A.jsx)(`input`,{className:`flex-1 rounded-md border border-slate-700 bg-slate-800 px-2 py-1 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:W,onChange:e=>G(e.target.value),autoFocus:!0}):(0,A.jsx)(w,{className:`text-slate-200 text-sm font-medium truncate max-w-[180px]`,children:e.name}),(0,A.jsx)(x,{variant:ee(e.status),children:e.status})]}),i?(0,A.jsx)(`textarea`,{className:`w-full rounded-md border border-slate-700 bg-slate-800 px-2 py-1 text-xs text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none mb-3`,placeholder:`Description...`,rows:2,value:K,onChange:e=>q(e.target.value)}):e.description?(0,A.jsx)(`p`,{className:`text-xs text-slate-400 mb-3 line-clamp-2`,children:e.description}):null,i&&(0,A.jsxs)(`div`,{className:`mb-3 space-y-2`,children:[(0,A.jsx)(j,{value:J,onChange:Y,label:`Deliver To (results)`}),(0,A.jsx)(j,{value:X,onChange:Z,label:`Report To (status)`})]}),(0,A.jsxs)(`div`,{className:`mb-3`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,A.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Progress`}),(0,A.jsxs)(`span`,{className:`font-mono text-xs text-slate-300`,children:[t,`%`]})]}),(0,A.jsx)(`div`,{className:`h-1.5 rounded-full bg-slate-800`,children:(0,A.jsx)(`div`,{className:`h-full rounded-full transition-all ${t>=100?`bg-emerald-500`:`bg-blue-500`}`,style:{width:`${t}%`}})}),(0,A.jsxs)(`div`,{className:`flex items-center justify-between mt-1`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-[10px] text-slate-500`,children:[e.currentValue,` / `,e.targetValue]}),(0,A.jsx)(`span`,{className:`font-mono text-[10px] text-slate-500`,children:e.metricType})]})]}),(0,A.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Role`}),(0,A.jsx)(x,{variant:`muted`,className:`text-[10px]`,children:e.roleId})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Budget`}),(0,A.jsx)(`span`,{className:`font-mono text-slate-300`,children:D(e.budgetUsd)})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500 ${r?`text-red-400`:``}`,children:`Deadline`}),(0,A.jsx)(`span`,{className:`text-slate-300 ${r?`text-red-400`:``}`,children:E(e.deadline)})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Created`}),(0,A.jsx)(`span`,{className:`text-slate-400`,children:E(e.createdAt)})]})]}),(0,A.jsx)(`div`,{className:`flex items-center gap-1 mt-3 pt-3 border-t border-slate-800`,children:i?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(g,{size:`sm`,variant:`ghost`,onClick:async()=>{try{await a(e.id,{name:W,description:K,deliverTo:J,reportTo:X}),U(null),S.success(`Goal updated`)}catch(e){S.error(e instanceof Error?e.message:`Failed to update`)}},children:`Save`}),(0,A.jsx)(g,{size:`sm`,variant:`ghost`,onClick:()=>U(null),children:(0,A.jsx)(s,{size:14})})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(g,{size:`sm`,variant:`ghost`,title:`Edit`,onClick:()=>{U(e.id),G(e.name),q(e.description??``),Y(e.deliverTo??[]),Z(e.reportTo??[])},children:(0,A.jsx)(n,{size:14})}),(0,A.jsxs)(g,{size:`sm`,variant:`ghost`,title:`Change to ${M[e.status]}`,onClick:async()=>{try{await a(e.id,{status:M[e.status]}),S.success(`Status changed to ${M[e.status]}`)}catch(e){S.error(e instanceof Error?e.message:`Failed to update status`)}},children:[N[e.status]??(0,A.jsx)(l,{size:12}),(0,A.jsx)(`span`,{className:`ml-1 text-xs`,children:M[e.status]})]}),(0,A.jsx)(`div`,{className:`ml-auto`,children:(0,A.jsxs)(b,{children:[(0,A.jsx)(h,{asChild:!0,children:(0,A.jsx)(g,{size:`sm`,variant:`ghost`,title:`Delete`,className:`text-red-400 hover:text-red-300`,children:(0,A.jsx)(o,{size:14})})}),(0,A.jsxs)(y,{children:[(0,A.jsxs)(v,{children:[(0,A.jsx)(ne,{children:`Delete goal`}),(0,A.jsxs)(te,{children:[`This will permanently delete "`,e.name,`". This action cannot be undone.`]})]}),(0,A.jsxs)(m,{children:[(0,A.jsx)(p,{children:`Cancel`}),(0,A.jsx)(_,{className:`bg-red-600 hover:bg-red-700`,onClick:async()=>{try{await u(e.id),S.success(`Goal deleted`)}catch(e){S.error(e instanceof Error?e.message:`Failed to delete`)}},children:`Delete`})]})]})]})})]})})]},e.id)})})]})}export{P as Goals,j as t};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{C as t,S as n,c as r,h as i,nt as a,o,t as s,v as c,x as l}from"./vendor-icons-CkI4-NxL.js";import{t as u}from"./vendor-react-DLRtONKt.js";import{r as d}from"./dist-HyCSN_hp.js";import{C as f,a as p,c as m,d as h,f as g,i as _,l as v,n as ee,o as y,r as b,s as te,t as x,u as ne,w as S}from"./index-rvaixveh.js";import{n as C,r as w,t as T}from"./Card-4mOZntHG.js";import{n as E,t as D}from"./format-DvtQjPZn.js";import{t as O}from"./EmptyState-BlgMMAr-.js";var k=e(a(),1),A=u();function j({value:e,onChange:t,label:n=`Delivery Targets`}){let[r,i]=(0,k.useState)([]),[a,o]=(0,k.useState)(!1);(0,k.useEffect)(()=>{let e=!1;return Promise.all([d(`/channels`).catch(()=>({channels:[]})),d(`/chat/sessions`).catch(()=>({sessions:[]}))]).then(([t,n])=>{if(e)return;let r=new Map(t.channels.map(e=>[e.id,e])),a=[];for(let e of n.sessions)if(e.source.type===`channel`&&e.source.channelId&&e.source.chatId){let t=r.get(e.source.channelId);a.push({id:e.id,channelId:e.source.channelId,channelName:t?.name??e.source.channelId.slice(0,8),platform:t?.platform??`unknown`,chatId:e.source.chatId})}let o=new Set;i(a.filter(e=>{let t=`${e.channelId}:${e.chatId}`;return o.has(t)?!1:(o.add(t),!0)}))}),()=>{e=!0}},[]);let s=(t,n)=>e.some(e=>e.type===`channel`&&e.channelId===t&&e.chatId===n),c=(n,r)=>{s(n,r)?t(e.filter(e=>!(e.type===`channel`&&e.channelId===n&&e.chatId===r))):t([...e,{type:`channel`,channelId:n,chatId:r}])},l=e.filter(e=>e.type===`channel`).length;return(0,A.jsxs)(`div`,{className:`relative`,children:[(0,A.jsx)(`label`,{className:`text-xs text-slate-400`,children:n}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(!a),className:`mt-1 w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-1.5 text-left text-sm text-slate-200 hover:border-slate-600 focus:border-blue-500 focus:outline-none`,children:l===0?`Default (current session)`:`${l} channel${l>1?`s`:``} selected`}),a&&(0,A.jsxs)(`div`,{className:`absolute z-10 mt-1 w-full rounded-md border border-slate-700 bg-slate-800 py-1 shadow-lg`,children:[r.length===0?(0,A.jsx)(`div`,{className:`px-3 py-2 text-xs text-slate-500`,children:`No active channel conversations. Start a chat on WeChat/Telegram first.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`px-3 py-1 text-xs text-slate-500`,children:`Channel conversations`}),r.map(e=>(0,A.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs text-slate-300 hover:bg-slate-700`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:s(e.channelId,e.chatId),onChange:()=>c(e.channelId,e.chatId),className:`rounded border-slate-600 bg-slate-700`}),(0,A.jsx)(`span`,{className:`truncate font-medium`,children:e.channelName}),(0,A.jsxs)(`span`,{className:`text-slate-500`,children:[`(`,e.platform,`)`]})]},`${e.channelId}:${e.chatId}`))]}),l>0&&(0,A.jsx)(`button`,{type:`button`,onClick:()=>{t([]),o(!1)},className:`mt-1 w-full border-t border-slate-700 px-3 py-1 text-left text-xs text-red-400 hover:bg-slate-700`,children:`Clear all`}),(0,A.jsx)(`button`,{type:`button`,onClick:()=>o(!1),className:`w-full border-t border-slate-700 px-3 py-1 text-left text-xs text-slate-500 hover:bg-slate-700`,children:`Done`})]})]})}var M={active:`paused`,paused:`active`,completed:`active`,failed:`active`},N={active:(0,A.jsx)(t,{size:12}),paused:(0,A.jsx)(l,{size:12}),completed:(0,A.jsx)(i,{size:12}),failed:(0,A.jsx)(i,{size:12})};function P(){let e=f(e=>e.goals),t=f(e=>e.fetchGoals),a=f(e=>e.updateGoal),u=f(e=>e.deleteGoal),[P,F]=(0,k.useState)(!1),[I,L]=(0,k.useState)(``),[R,z]=(0,k.useState)(!1),[B,V]=(0,k.useState)(null),[H,U]=(0,k.useState)(null),[W,G]=(0,k.useState)(``),[K,q]=(0,k.useState)(``),[J,Y]=(0,k.useState)([]),[X,Z]=(0,k.useState)([]),[Q,re]=(0,k.useState)([]),[$,ie]=(0,k.useState)([]);(0,k.useEffect)(()=>{t();let e=setInterval(()=>void t(),1e4);return()=>clearInterval(e)},[t]);let ae=async()=>{if(I.trim()){z(!0),V(null);try{await d(`/goals`,{method:`POST`,body:JSON.stringify({input:I.trim(),deliverTo:Q.length>0?Q:void 0,reportTo:$.length>0?$:void 0})}),L(``),F(!1),t()}catch(e){V(e instanceof Error?e.message:`Failed to create goal`)}finally{z(!1)}}};return(0,A.jsxs)(`div`,{className:`space-y-4`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,A.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Goals`}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(g,{variant:`ghost`,size:`sm`,onClick:()=>void t(),children:(0,A.jsx)(i,{size:14})}),(0,A.jsxs)(g,{size:`sm`,onClick:()=>F(!P),children:[(0,A.jsx)(c,{size:14}),`New Goal`]})]})]}),P&&(0,A.jsxs)(T,{className:`space-y-3`,children:[(0,A.jsx)(`textarea`,{className:`w-full rounded-md border border-slate-700 bg-slate-800 px-3 py-2 text-sm text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none`,placeholder:`Describe your goal in natural language...`,rows:3,value:I,onChange:e=>L(e.target.value)}),(0,A.jsx)(j,{value:Q,onChange:re,label:`Deliver To (results)`}),(0,A.jsx)(j,{value:$,onChange:ie,label:`Report To (status)`}),B&&(0,A.jsx)(`p`,{className:`text-xs text-red-400`,children:B}),(0,A.jsxs)(`div`,{className:`flex gap-2`,children:[(0,A.jsx)(g,{onClick:()=>void ae(),disabled:R||!I.trim(),children:R?`Creating...`:`Create`}),(0,A.jsx)(g,{variant:`ghost`,onClick:()=>F(!1),children:`Cancel`})]})]}),e.length===0?(0,A.jsx)(O,{icon:(0,A.jsx)(r,{size:32}),title:`No goals`,description:`Create a goal to start goal-driven task orchestration`}):(0,A.jsx)(`div`,{className:`grid gap-3 sm:grid-cols-2 lg:grid-cols-3`,children:e.map(e=>{let t=e.targetValue>0?Math.min(100,Math.round(e.currentValue/e.targetValue*100)):0,r=new Date(e.deadline).getTime()<Date.now()&&e.status!==`completed`,i=H===e.id;return(0,A.jsxs)(T,{children:[(0,A.jsxs)(C,{children:[i?(0,A.jsx)(`input`,{className:`flex-1 rounded-md border border-slate-700 bg-slate-800 px-2 py-1 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:W,onChange:e=>G(e.target.value),autoFocus:!0}):(0,A.jsx)(w,{className:`text-slate-200 text-sm font-medium truncate max-w-[180px]`,children:e.name}),(0,A.jsx)(x,{variant:ee(e.status),children:e.status})]}),i?(0,A.jsx)(`textarea`,{className:`w-full rounded-md border border-slate-700 bg-slate-800 px-2 py-1 text-xs text-slate-200 placeholder:text-slate-500 focus:border-blue-500 focus:outline-none mb-3`,placeholder:`Description...`,rows:2,value:K,onChange:e=>q(e.target.value)}):e.description?(0,A.jsx)(`p`,{className:`text-xs text-slate-400 mb-3 line-clamp-2`,children:e.description}):null,i&&(0,A.jsxs)(`div`,{className:`mb-3 space-y-2`,children:[(0,A.jsx)(j,{value:J,onChange:Y,label:`Deliver To (results)`}),(0,A.jsx)(j,{value:X,onChange:Z,label:`Report To (status)`})]}),(0,A.jsxs)(`div`,{className:`mb-3`,children:[(0,A.jsxs)(`div`,{className:`flex items-center justify-between mb-1`,children:[(0,A.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Progress`}),(0,A.jsxs)(`span`,{className:`font-mono text-xs text-slate-300`,children:[t,`%`]})]}),(0,A.jsx)(`div`,{className:`h-1.5 rounded-full bg-slate-800`,children:(0,A.jsx)(`div`,{className:`h-full rounded-full transition-all ${t>=100?`bg-emerald-500`:`bg-blue-500`}`,style:{width:`${t}%`}})}),(0,A.jsxs)(`div`,{className:`flex items-center justify-between mt-1`,children:[(0,A.jsxs)(`span`,{className:`font-mono text-[10px] text-slate-500`,children:[e.currentValue,` / `,e.targetValue]}),(0,A.jsx)(`span`,{className:`font-mono text-[10px] text-slate-500`,children:e.metricType})]})]}),(0,A.jsxs)(`div`,{className:`space-y-1.5 text-xs`,children:[(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Role`}),(0,A.jsx)(x,{variant:`muted`,className:`text-[10px]`,children:e.roleId})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Budget`}),(0,A.jsx)(`span`,{className:`font-mono text-slate-300`,children:D(e.budgetUsd)})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500 ${r?`text-red-400`:``}`,children:`Deadline`}),(0,A.jsx)(`span`,{className:`text-slate-300 ${r?`text-red-400`:``}`,children:E(e.deadline)})]}),(0,A.jsxs)(`div`,{className:`flex justify-between`,children:[(0,A.jsx)(`span`,{className:`text-slate-500`,children:`Created`}),(0,A.jsx)(`span`,{className:`text-slate-400`,children:E(e.createdAt)})]})]}),(0,A.jsx)(`div`,{className:`flex items-center gap-1 mt-3 pt-3 border-t border-slate-800`,children:i?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(g,{size:`sm`,variant:`ghost`,onClick:async()=>{try{await a(e.id,{name:W,description:K,deliverTo:J,reportTo:X}),U(null),S.success(`Goal updated`)}catch(e){S.error(e instanceof Error?e.message:`Failed to update`)}},children:`Save`}),(0,A.jsx)(g,{size:`sm`,variant:`ghost`,onClick:()=>U(null),children:(0,A.jsx)(s,{size:14})})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(g,{size:`sm`,variant:`ghost`,title:`Edit`,onClick:()=>{U(e.id),G(e.name),q(e.description??``),Y(e.deliverTo??[]),Z(e.reportTo??[])},children:(0,A.jsx)(n,{size:14})}),(0,A.jsxs)(g,{size:`sm`,variant:`ghost`,title:`Change to ${M[e.status]}`,onClick:async()=>{try{await a(e.id,{status:M[e.status]}),S.success(`Status changed to ${M[e.status]}`)}catch(e){S.error(e instanceof Error?e.message:`Failed to update status`)}},children:[N[e.status]??(0,A.jsx)(l,{size:12}),(0,A.jsx)(`span`,{className:`ml-1 text-xs`,children:M[e.status]})]}),(0,A.jsx)(`div`,{className:`ml-auto`,children:(0,A.jsxs)(b,{children:[(0,A.jsx)(h,{asChild:!0,children:(0,A.jsx)(g,{size:`sm`,variant:`ghost`,title:`Delete`,className:`text-red-400 hover:text-red-300`,children:(0,A.jsx)(o,{size:14})})}),(0,A.jsxs)(y,{children:[(0,A.jsxs)(v,{children:[(0,A.jsx)(ne,{children:`Delete goal`}),(0,A.jsxs)(te,{children:[`This will permanently delete "`,e.name,`". This action cannot be undone.`]})]}),(0,A.jsxs)(m,{children:[(0,A.jsx)(p,{children:`Cancel`}),(0,A.jsx)(_,{className:`bg-red-600 hover:bg-red-700`,onClick:async()=>{try{await u(e.id),S.success(`Goal deleted`)}catch(e){S.error(e instanceof Error?e.message:`Failed to delete`)}},children:`Delete`})]})]})]})})]})})]},e.id)})})]})}export{P as Goals,j as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{C as t,nt as n,o as r,s as i,x as a}from"./vendor-icons-CkI4-NxL.js";import{t as o}from"./vendor-react-DLRtONKt.js";import{C as s,f as c}from"./index-oA-kWqT5.js";import{t as l}from"./Card-4mOZntHG.js";import{t as u}from"./EmptyState-BlgMMAr-.js";var d=e(n(),1),f=o(),p={debug:`text-slate-500`,info:`text-blue-400`,warn:`text-amber-400`,error:`text-red-400`},m={adam:`text-purple-400`,manager:`text-cyan-400`,worker:`text-green-400`,scheduler:`text-orange-400`,api:`text-blue-400`,ws:`text-teal-400`,store:`text-yellow-400`,embedding:`text-pink-400`},h=[`adam`,`manager`,`worker`,`scheduler`,`api`,`ws`,`store`,`embedding`],g=[`debug`,`info`,`warn`,`error`];function _(){let e=s(e=>e.logs),n=(0,d.useRef)(null),[o,_]=(0,d.useState)(!0),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(null),C=(0,d.useMemo)(()=>e.filter(e=>!(y&&e.level!==y||x&&e.component!==x)),[e,y,x]);return(0,d.useEffect)(()=>{o&&n.current&&(n.current.scrollTop=n.current.scrollHeight)},[C,o]),(0,f.jsxs)(`div`,{className:`flex h-full flex-col gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,f.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Logs`}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>_(!o),title:o?`Pause auto-scroll`:`Resume auto-scroll`,children:o?(0,f.jsx)(t,{size:14}):(0,f.jsx)(a,{size:14})}),(0,f.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{s.setState({logs:[]})},title:`Clear logs`,children:(0,f.jsx)(r,{size:14})})]})]}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,f.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Level:`}),(0,f.jsxs)(`div`,{className:`flex gap-1`,children:[(0,f.jsx)(v,{active:y===null,onClick:()=>b(null),children:`All`}),g.map(e=>(0,f.jsx)(v,{active:y===e,onClick:()=>b(y===e?null:e),children:e},e))]})]}),(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,f.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Component:`}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[(0,f.jsx)(v,{active:x===null,onClick:()=>S(null),children:`All`}),h.map(e=>(0,f.jsx)(v,{active:x===e,onClick:()=>S(x===e?null:e),children:e},e))]})]})]}),(0,f.jsx)(l,{padding:!1,className:`flex-1 min-h-0`,children:C.length===0?(0,f.jsx)(u,{icon:(0,f.jsx)(i,{size:32}),title:`No log entries`,description:`Log events will appear here in real-time via WebSocket`}):(0,f.jsx)(`div`,{ref:n,className:`h-full max-h-[calc(100vh-280px)] overflow-y-auto p-3 font-mono text-xs leading-5`,children:C.map((e,t)=>{let n=new Date(e.timestamp).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3}),r=p[e.level]??`text-slate-400`,i=m[e.component]??`text-slate-400`;return(0,f.jsxs)(`div`,{className:`flex gap-2 hover:bg-slate-800/30 px-1 rounded`,children:[(0,f.jsx)(`span`,{className:`text-slate-600 shrink-0`,children:n}),(0,f.jsx)(`span`,{className:`w-12 shrink-0 uppercase ${r}`,children:e.level.padEnd(5)}),(0,f.jsxs)(`span`,{className:`w-20 shrink-0 ${i}`,children:[`[`,e.component,`]`]}),(0,f.jsx)(`span`,{className:`text-slate-300 break-all`,children:e.msg})]},t)})})}),(0,f.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-slate-500`,children:[(0,f.jsxs)(`span`,{children:[C.length,` entries `,C.length!==e.length&&`(${e.length} total)`]}),(0,f.jsx)(`span`,{children:o?`Auto-scrolling`:`Paused`})]})]})}function v({active:e,onClick:t,children:n}){return(0,f.jsx)(`button`,{onClick:t,className:`rounded px-2 py-0.5 text-xs transition-colors ${e?`bg-slate-700 text-slate-200`:`text-slate-500 hover:text-slate-300`}`,children:n})}export{_ as Logs};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{C as t,nt as n,o as r,s as i,x as a}from"./vendor-icons-CkI4-NxL.js";import{t as o}from"./vendor-react-DLRtONKt.js";import{C as s,f as c}from"./index-rvaixveh.js";import{t as l}from"./Card-4mOZntHG.js";import{t as u}from"./EmptyState-BlgMMAr-.js";var d=e(n(),1),f=o(),p={debug:`text-slate-500`,info:`text-blue-400`,warn:`text-amber-400`,error:`text-red-400`},m={adam:`text-purple-400`,manager:`text-cyan-400`,worker:`text-green-400`,scheduler:`text-orange-400`,api:`text-blue-400`,ws:`text-teal-400`,store:`text-yellow-400`,embedding:`text-pink-400`},h=[`adam`,`manager`,`worker`,`scheduler`,`api`,`ws`,`store`,`embedding`],g=[`debug`,`info`,`warn`,`error`];function _(){let e=s(e=>e.logs),n=(0,d.useRef)(null),[o,_]=(0,d.useState)(!0),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(null),C=(0,d.useMemo)(()=>e.filter(e=>!(y&&e.level!==y||x&&e.component!==x)),[e,y,x]);return(0,d.useEffect)(()=>{o&&n.current&&(n.current.scrollTop=n.current.scrollHeight)},[C,o]),(0,f.jsxs)(`div`,{className:`flex h-full flex-col gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,f.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Logs`}),(0,f.jsxs)(`div`,{className:`flex gap-2`,children:[(0,f.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>_(!o),title:o?`Pause auto-scroll`:`Resume auto-scroll`,children:o?(0,f.jsx)(t,{size:14}):(0,f.jsx)(a,{size:14})}),(0,f.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>{s.setState({logs:[]})},title:`Clear logs`,children:(0,f.jsx)(r,{size:14})})]})]}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-4`,children:[(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,f.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Level:`}),(0,f.jsxs)(`div`,{className:`flex gap-1`,children:[(0,f.jsx)(v,{active:y===null,onClick:()=>b(null),children:`All`}),g.map(e=>(0,f.jsx)(v,{active:y===e,onClick:()=>b(y===e?null:e),children:e},e))]})]}),(0,f.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,f.jsx)(`span`,{className:`text-xs text-slate-500`,children:`Component:`}),(0,f.jsxs)(`div`,{className:`flex flex-wrap gap-1`,children:[(0,f.jsx)(v,{active:x===null,onClick:()=>S(null),children:`All`}),h.map(e=>(0,f.jsx)(v,{active:x===e,onClick:()=>S(x===e?null:e),children:e},e))]})]})]}),(0,f.jsx)(l,{padding:!1,className:`flex-1 min-h-0`,children:C.length===0?(0,f.jsx)(u,{icon:(0,f.jsx)(i,{size:32}),title:`No log entries`,description:`Log events will appear here in real-time via WebSocket`}):(0,f.jsx)(`div`,{ref:n,className:`h-full max-h-[calc(100vh-280px)] overflow-y-auto p-3 font-mono text-xs leading-5`,children:C.map((e,t)=>{let n=new Date(e.timestamp).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,fractionalSecondDigits:3}),r=p[e.level]??`text-slate-400`,i=m[e.component]??`text-slate-400`;return(0,f.jsxs)(`div`,{className:`flex gap-2 hover:bg-slate-800/30 px-1 rounded`,children:[(0,f.jsx)(`span`,{className:`text-slate-600 shrink-0`,children:n}),(0,f.jsx)(`span`,{className:`w-12 shrink-0 uppercase ${r}`,children:e.level.padEnd(5)}),(0,f.jsxs)(`span`,{className:`w-20 shrink-0 ${i}`,children:[`[`,e.component,`]`]}),(0,f.jsx)(`span`,{className:`text-slate-300 break-all`,children:e.msg})]},t)})})}),(0,f.jsxs)(`div`,{className:`flex items-center justify-between text-xs text-slate-500`,children:[(0,f.jsxs)(`span`,{children:[C.length,` entries `,C.length!==e.length&&`(${e.length} total)`]}),(0,f.jsx)(`span`,{children:o?`Auto-scrolling`:`Paused`})]})]})}function v({active:e,onClick:t,children:n}){return(0,f.jsx)(`button`,{onClick:t,className:`rounded px-2 py-0.5 text-xs transition-colors ${e?`bg-slate-700 text-slate-200`:`text-slate-500 hover:text-slate-300`}`,children:n})}export{_ as Logs};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{Q as t,f as n,h as r,nt as i}from"./vendor-icons-CkI4-NxL.js";import{t as a}from"./vendor-react-DLRtONKt.js";import{r as o}from"./dist-HyCSN_hp.js";import{C as s,f as c,t as l}from"./index-oA-kWqT5.js";import{t as u}from"./Card-4mOZntHG.js";import{a as d}from"./format-DvtQjPZn.js";import{t as f}from"./EmptyState-BlgMMAr-.js";var p=e(i(),1),m=a();function h(){let e=s(e=>e.roles),i=s(e=>e.fetchRoles),[a,h]=(0,p.useState)(``),[g,_]=(0,p.useState)([]),[v,y]=(0,p.useState)(!1),[b,x]=(0,p.useState)(``),[S,C]=(0,p.useState)(!1),[w,T]=(0,p.useState)(`all`),[E,D]=(0,p.useState)(new Set);(0,p.useEffect)(()=>{i()},[i]),(0,p.useEffect)(()=>{!a&&e.length>0&&h(e[0].id)},[e,a]);let O=(0,p.useCallback)(async()=>{if(a){y(!0);try{_((await o(`/memories/${a}?limit=100`)).memories)}catch{_([])}finally{y(!1)}}},[a]);(0,p.useEffect)(()=>{a&&O()},[a,O]);let k=async()=>{if(!(!b.trim()||!a)){C(!0);try{_((await o(`/memories/query`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:a,prompt:b.trim(),topK:20})})).memories)}catch{_([])}finally{C(!1)}}},A=()=>{x(``),O()},j=g.filter(e=>w===`high`?e.importance>3:w===`medium`?e.importance===3:w===`low`?e.importance<3:!0),M=e=>e>=4?`text-red-400`:e===3?`text-yellow-400`:`text-slate-500`;return(0,m.jsxs)(`div`,{className:`space-y-4`,children:[(0,m.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,m.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Memories`}),(0,m.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>void O(),children:(0,m.jsx)(r,{size:14})})]}),(0,m.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,m.jsx)(`select`,{className:`rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:a,onChange:e=>h(e.target.value),children:e.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))}),(0,m.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,m.jsx)(`input`,{className:`w-64 rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 placeholder-slate-600 focus:border-blue-500 focus:outline-none`,value:b,onChange:e=>x(e.target.value),onKeyDown:e=>e.key===`Enter`&&void k(),placeholder:`Search memories...`}),(0,m.jsx)(c,{size:`sm`,variant:`ghost`,onClick:()=>void k(),disabled:S,children:(0,m.jsx)(n,{size:14})}),b&&(0,m.jsx)(c,{size:`sm`,variant:`ghost`,onClick:A,children:`Clear`})]}),(0,m.jsx)(`div`,{className:`flex gap-1`,children:[`all`,`high`,`medium`,`low`].map(e=>(0,m.jsx)(`button`,{className:`rounded px-2 py-1 text-xs transition-colors ${w===e?`bg-blue-600 text-white`:`bg-slate-800 text-slate-400 hover:bg-slate-700`}`,onClick:()=>T(e),children:e},e))})]}),(0,m.jsx)(u,{children:v||S?(0,m.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,m.jsx)(`div`,{className:`h-6 w-6 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):j.length===0?(0,m.jsx)(f,{icon:(0,m.jsx)(t,{size:32}),title:`No memories`,description:b?`No results for this query`:`This agent has no memories yet`}):(0,m.jsxs)(`div`,{className:`space-y-3`,children:[(0,m.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[j.length,` memories`]}),j.map(e=>(0,m.jsxs)(`div`,{className:`rounded border border-slate-800 p-3`,children:[(0,m.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-2`,children:[(0,m.jsx)(l,{variant:e.type===`reflection`?`info`:e.type===`thought`?`warning`:`muted`,children:e.type}),(0,m.jsx)(l,{variant:`muted`,children:e.sourceType}),(0,m.jsx)(`span`,{className:`text-xs font-medium ${M(e.importance)}`,children:`*`.repeat(e.importance)}),e.score!=null&&(0,m.jsxs)(`span`,{className:`text-[10px] text-slate-600`,children:[`score: `,e.score.toFixed(3)]})]}),(0,m.jsx)(`p`,{className:`whitespace-pre-wrap text-sm text-slate-300`,children:e.content}),(0,m.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1`,children:e.keywords.map(e=>(0,m.jsx)(`span`,{className:`rounded bg-slate-800 px-1.5 py-0.5 text-[10px] text-slate-500`,children:e},e))}),e.type===`reflection`&&e.evidence&&e.evidence.length>0&&(0,m.jsxs)(`div`,{className:`mt-2`,children:[(0,m.jsxs)(`button`,{className:`text-[10px] text-blue-400 hover:text-blue-300`,onClick:()=>D(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:[E.has(e.id)?`Hide`:`Show`,` evidence (`,e.evidence.length,` memories)`]}),E.has(e.id)&&(0,m.jsx)(`div`,{className:`mt-1.5 space-y-1 border-l-2 border-slate-800 pl-2`,children:e.evidence.map(e=>{let t=g.find(t=>t.id===e);return(0,m.jsx)(`div`,{className:`text-xs text-slate-500`,children:t?t.content.slice(0,120)+(t.content.length>120?`...`:``):(0,m.jsxs)(`span`,{className:`italic`,children:[`Memory `,e.slice(0,8),` (not in current view)`]})},e)})})]}),(0,m.jsxs)(`p`,{className:`mt-1.5 text-[10px] text-slate-600`,children:[d(e.createdAt),` | accessed `,e.retrievedCount,`x | last: `,d(e.lastAccessed)]})]},e.id))]})})]})}export{h as Memories};
1
+ import{r as e}from"./rolldown-runtime-Dw2cE7zH.js";import{Q as t,f as n,h as r,nt as i}from"./vendor-icons-CkI4-NxL.js";import{t as a}from"./vendor-react-DLRtONKt.js";import{r as o}from"./dist-HyCSN_hp.js";import{C as s,f as c,t as l}from"./index-rvaixveh.js";import{t as u}from"./Card-4mOZntHG.js";import{a as d}from"./format-DvtQjPZn.js";import{t as f}from"./EmptyState-BlgMMAr-.js";var p=e(i(),1),m=a();function h(){let e=s(e=>e.roles),i=s(e=>e.fetchRoles),[a,h]=(0,p.useState)(``),[g,_]=(0,p.useState)([]),[v,y]=(0,p.useState)(!1),[b,x]=(0,p.useState)(``),[S,C]=(0,p.useState)(!1),[w,T]=(0,p.useState)(`all`),[E,D]=(0,p.useState)(new Set);(0,p.useEffect)(()=>{i()},[i]),(0,p.useEffect)(()=>{!a&&e.length>0&&h(e[0].id)},[e,a]);let O=(0,p.useCallback)(async()=>{if(a){y(!0);try{_((await o(`/memories/${a}?limit=100`)).memories)}catch{_([])}finally{y(!1)}}},[a]);(0,p.useEffect)(()=>{a&&O()},[a,O]);let k=async()=>{if(!(!b.trim()||!a)){C(!0);try{_((await o(`/memories/query`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:a,prompt:b.trim(),topK:20})})).memories)}catch{_([])}finally{C(!1)}}},A=()=>{x(``),O()},j=g.filter(e=>w===`high`?e.importance>3:w===`medium`?e.importance===3:w===`low`?e.importance<3:!0),M=e=>e>=4?`text-red-400`:e===3?`text-yellow-400`:`text-slate-500`;return(0,m.jsxs)(`div`,{className:`space-y-4`,children:[(0,m.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,m.jsx)(`h1`,{className:`text-lg font-semibold text-slate-100`,children:`Memories`}),(0,m.jsx)(c,{variant:`ghost`,size:`sm`,onClick:()=>void O(),children:(0,m.jsx)(r,{size:14})})]}),(0,m.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,m.jsx)(`select`,{className:`rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 focus:border-blue-500 focus:outline-none`,value:a,onChange:e=>h(e.target.value),children:e.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))}),(0,m.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,m.jsx)(`input`,{className:`w-64 rounded border border-slate-700 bg-slate-900 px-2 py-1.5 text-sm text-slate-200 placeholder-slate-600 focus:border-blue-500 focus:outline-none`,value:b,onChange:e=>x(e.target.value),onKeyDown:e=>e.key===`Enter`&&void k(),placeholder:`Search memories...`}),(0,m.jsx)(c,{size:`sm`,variant:`ghost`,onClick:()=>void k(),disabled:S,children:(0,m.jsx)(n,{size:14})}),b&&(0,m.jsx)(c,{size:`sm`,variant:`ghost`,onClick:A,children:`Clear`})]}),(0,m.jsx)(`div`,{className:`flex gap-1`,children:[`all`,`high`,`medium`,`low`].map(e=>(0,m.jsx)(`button`,{className:`rounded px-2 py-1 text-xs transition-colors ${w===e?`bg-blue-600 text-white`:`bg-slate-800 text-slate-400 hover:bg-slate-700`}`,onClick:()=>T(e),children:e},e))})]}),(0,m.jsx)(u,{children:v||S?(0,m.jsx)(`div`,{className:`flex items-center justify-center py-8`,children:(0,m.jsx)(`div`,{className:`h-6 w-6 animate-spin rounded-full border-2 border-slate-700 border-t-blue-500`})}):j.length===0?(0,m.jsx)(f,{icon:(0,m.jsx)(t,{size:32}),title:`No memories`,description:b?`No results for this query`:`This agent has no memories yet`}):(0,m.jsxs)(`div`,{className:`space-y-3`,children:[(0,m.jsxs)(`p`,{className:`text-xs text-slate-500`,children:[j.length,` memories`]}),j.map(e=>(0,m.jsxs)(`div`,{className:`rounded border border-slate-800 p-3`,children:[(0,m.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-2`,children:[(0,m.jsx)(l,{variant:e.type===`reflection`?`info`:e.type===`thought`?`warning`:`muted`,children:e.type}),(0,m.jsx)(l,{variant:`muted`,children:e.sourceType}),(0,m.jsx)(`span`,{className:`text-xs font-medium ${M(e.importance)}`,children:`*`.repeat(e.importance)}),e.score!=null&&(0,m.jsxs)(`span`,{className:`text-[10px] text-slate-600`,children:[`score: `,e.score.toFixed(3)]})]}),(0,m.jsx)(`p`,{className:`whitespace-pre-wrap text-sm text-slate-300`,children:e.content}),(0,m.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1`,children:e.keywords.map(e=>(0,m.jsx)(`span`,{className:`rounded bg-slate-800 px-1.5 py-0.5 text-[10px] text-slate-500`,children:e},e))}),e.type===`reflection`&&e.evidence&&e.evidence.length>0&&(0,m.jsxs)(`div`,{className:`mt-2`,children:[(0,m.jsxs)(`button`,{className:`text-[10px] text-blue-400 hover:text-blue-300`,onClick:()=>D(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:[E.has(e.id)?`Hide`:`Show`,` evidence (`,e.evidence.length,` memories)`]}),E.has(e.id)&&(0,m.jsx)(`div`,{className:`mt-1.5 space-y-1 border-l-2 border-slate-800 pl-2`,children:e.evidence.map(e=>{let t=g.find(t=>t.id===e);return(0,m.jsx)(`div`,{className:`text-xs text-slate-500`,children:t?t.content.slice(0,120)+(t.content.length>120?`...`:``):(0,m.jsxs)(`span`,{className:`italic`,children:[`Memory `,e.slice(0,8),` (not in current view)`]})},e)})})]}),(0,m.jsxs)(`p`,{className:`mt-1.5 text-[10px] text-slate-600`,children:[d(e.createdAt),` | accessed `,e.retrievedCount,`x | last: `,d(e.lastAccessed)]})]},e.id))]})})]})}export{h as Memories};