@frumu/tandem-panel 0.4.5 → 0.4.6

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.
@@ -0,0 +1,558 @@
1
+ import{u as e,d as y,A as pt,y as ye,T as H,q as Je,R as gs,x as fs,k as qt,c as bs,e as ys}from"./preact-vendor-CErzQRjo.js";import{u as Q,a as jt,b as Ae,c as vs,Q as ws}from"./react-query-tfsRN0su.js";import{c as ne,o as Pt,d as dn,r as qr,e as un,f as Jt,g as ka,h as xs,W as Ns,U as ks,C as _s,X as Ss,T as Cs,j as Is,S as As,k as Ps,l as Ts,m as Ms,p as Rs,q as $s,t as qs,u as Es,v as Os,w as Ds,x as Fs,y as Us,z as js,R as Ls,A as Bs,B as Ks,P as Ws,D as Js,E as Qs,F as Hs,G as Gs,H as zs,I as Vs,J as Ys,K as Xs,L as Zs,N as ei,O as ti,V as ai,Y as ni,Z as ri,_ as si,$ as ii,a0 as oi,a1 as li,a2 as ci,a3 as di,a4 as ui,a5 as mi,a6 as pi,a7 as hi,a8 as gi,a9 as fi,aa as bi,ab as yi,ac as vi,ad as wi,ae as xi,af as Ni,ag as ki,ah as _i,ai as Si,aj as Ci,ak as Ii,al as Ai,am as Pi,an as Ti,ao as Mi,ap as Ri,aq as $i,ar as qi,as as Ei,at as Oi}from"./vendor-B5SLbWPm.js";import{m as xe,A as ot,u as Er}from"./motion-1UTHZOUD.js";import{g as Or,p as Di}from"./markdown-CscybTAD.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const l of s)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function n(s){const l={};return s.integrity&&(l.integrity=s.integrity),s.referrerPolicy&&(l.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?l.credentials="include":s.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(s){if(s.ep)return;s.ep=!0;const l=n(s);fetch(s.href,l)}})();class Fi extends Error{constructor(t,n,r,s){super(`Tandem API Validation Error [${n}] at ${t}: ${r.length} issues found.`),this.endpoint=t,this.status=n,this.issues=r,this.rawSnippet=s,this.name="TandemValidationError"}}const ar=ne().or(Pt({id:ne().optional(),runID:ne().optional(),runId:ne().optional(),run_id:ne().optional(),sessionID:ne().optional(),sessionId:ne().optional(),session_id:ne().optional(),missionID:ne().optional(),missionId:ne().optional(),mission_id:ne().optional(),instanceID:ne().optional(),instanceId:ne().optional(),instance_id:ne().optional()})).transform(a=>typeof a=="string"?a:a.id||a.runID||a.runId||a.run_id||a.sessionID||a.sessionId||a.session_id||a.missionID||a.missionId||a.mission_id||a.instanceID||a.instanceId||a.instance_id);dn().transform(a=>a);qr(ne(),dn()).transform(a=>a);const Ui=Pt({ready:un().optional(),phase:ne().optional(),workspace_root:ne().optional(),workspaceRoot:ne().optional()}).passthrough().transform(a=>({...a,workspaceRoot:a.workspace_root??a.workspaceRoot})),tn=Pt({id:ne(),title:ne(),created_at_ms:Jt().optional(),createdAtMs:Jt().optional(),directory:ne().optional(),workspace_root:ne().optional(),workspaceRoot:ne().optional(),archived:un().optional()}).passthrough().transform(a=>({...a,createdAtMs:a.created_at_ms??a.createdAtMs??0,workspaceRoot:a.workspace_root??a.workspaceRoot})),nr=Pt({sessions:ka(tn).optional().default([]),count:Jt().optional().default(0)}).passthrough(),ji=Pt({active:Pt({runID:ne().optional(),runId:ne().optional(),run_id:ne().optional(),attachEventStream:ne().optional()}).passthrough().nullable().optional()}).passthrough().transform(a=>a.active?{active:{...a.active,runId:a.active.runId||a.active.runID||a.active.run_id}}:{active:null}),Dr=Pt({ok:un().optional(),runID:ne().optional(),runId:ne().optional(),run_id:ne().optional(),status:ne().optional()}).passthrough().transform(a=>({...a,runId:a.runId||a.runID||a.run_id})),Fr=Pt({id:ne().optional(),runID:ne().optional(),runId:ne().optional(),run_id:ne().optional(),routine_id:ne().optional(),automation_id:ne().optional(),status:ne().optional(),started_at_ms:Jt().optional(),finished_at_ms:Jt().optional()}).passthrough().transform(a=>({...a,runId:a.runId||a.runID||a.run_id,routineId:a.routine_id,automationId:a.automation_id,startedAtMs:a.started_at_ms,finishedAtMs:a.finished_at_ms})),rr=Pt({ok:un().default(!0),rev:Jt().optional()}).passthrough(),Ur=Pt({key:ne(),value:dn(),rev:Jt().optional(),updated_at_ms:Jt().optional(),updated_by:ne().optional()}).passthrough().transform(a=>({...a,updatedAtMs:a.updated_at_ms,updatedBy:a.updated_by})),Li=Pt({items:ka(Ur).optional().default([]),count:Jt().optional().default(0)}).passthrough(),Bi=Pt({id:ne().optional(),text:ne().optional(),content:ne().optional(),user_id:ne().optional(),userID:ne().optional(),source_type:ne().optional(),sourceType:ne().optional(),tags:ka(ne()).optional(),source:ne().optional(),session_id:ne().optional(),sessionID:ne().optional(),run_id:ne().optional(),runID:ne().optional()}).passthrough().transform(a=>({...a,text:a.text||a.content,content:a.content||a.text,userId:a.userID||a.user_id,sourceType:a.sourceType||a.source_type,sessionId:a.session_id||a.sessionID,runId:a.run_id||a.runID})),Ki=Pt({items:ka(Bi).optional().default([]),count:Jt().optional().default(0)}).passthrough(),Wi=Pt({id:ne(),text:ne().optional(),content:ne().optional(),score:Jt().optional(),source_type:ne().optional(),sourceType:ne().optional(),run_id:ne().optional(),runID:ne().optional(),tags:ka(ne()).optional()}).passthrough().transform(a=>({...a,text:a.text||a.content,content:a.content||a.text,sourceType:a.sourceType||a.source_type,runId:a.runID||a.run_id})),Ji=Pt({results:ka(Wi).optional().default([]),count:Jt().optional().default(0)}).passthrough(),Qi=Pt({type:ne(),properties:qr(ne(),dn()).optional().default({}),sessionID:ne().optional(),session_id:ne().optional(),sessionId:ne().optional(),runID:ne().optional(),run_id:ne().optional(),runId:ne().optional(),timestamp:ne().optional()}).passthrough().transform(a=>({...a,properties:a.properties,sessionId:a.sessionId||a.sessionID||a.session_id,runId:a.runId||a.runID||a.run_id}));function Ct(a,t,n,r){const s=a.safeParse(t);if(!s.success){const l=JSON.stringify(t).substring(0,200);throw new Fi(n,r,s.error.issues,l)}return s.data}function Hi(a){const t=a.trim();if(!t||t===": keep-alive"||t.startsWith(":"))return null;try{const n=JSON.parse(t),r=Qi.safeParse(n);return r.success?r.data:null}catch{return null}}async function*fa(a,t,n){const r=n?.connectTimeoutMs??3e4,s=new AbortController,l=setTimeout(()=>s.abort(),r),d=n?.signal?Gi([s.signal,n.signal]):s.signal;let u;try{u=await fetch(a,{headers:{Accept:"text/event-stream",Authorization:`Bearer ${t}`,"Cache-Control":"no-cache"},signal:d})}finally{clearTimeout(l)}if(!u.ok){const b=await u.text().catch(()=>"");throw new Error(`SSE connect failed (${u.status} ${u.statusText}): ${b}`)}if(!u.body)throw new Error("SSE response has no body");const p=new TextDecoder,k=u.body.getReader();let q="";try{for(;;){const{done:b,value:w}=await k.read();if(b)break;q+=p.decode(w,{stream:!0});const M=q.split(`
2
+ `);q=M.pop()??"";let E="";for(const K of M)if(K.startsWith("data:"))E+=K.slice(5).trimStart();else if(K===""&&E){const B=Hi(E);B&&(yield B),E=""}}}finally{k.releaseLock()}}function Gi(a){const t=new AbortController;for(const n of a){if(n.aborted){t.abort(n.reason);break}n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}const Ft=a=>typeof a=="string"&&a.trim().length>0?a:null,zi=a=>{try{const t=ar.parse(a);if(t)return t}catch{const t=a.run||null;if(t)try{const n=ar.parse(t);if(n)return n}catch{}}throw new Error("Run ID missing in engine response")};class Vi{constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.timeoutMs=t.timeoutMs??2e4;const n=this._request.bind(this);this.sessions=new eo(this.baseUrl,this.token,this.timeoutMs,n),this.permissions=new to(n),this.questions=new ao(n),this.providers=new no(n),this.identity=new ro(n),this.channels=new so(n),this.mcp=new io(n,this._requestText.bind(this));const r=()=>this.token;this.routines=new ho(this.baseUrl,r,n),this.automations=new fo(this.baseUrl,r,n),this.automationsV2=new bo(this.baseUrl,r,n),this.workflowPlans=new go(n),this.memory=new oo(n),this.skills=new lo(n),this.packs=new co(n),this.capabilities=new uo(n),this.resources=new mo(this.baseUrl,r,n),this.browser=new Yi(n),this.workflows=new Xi(this.baseUrl,r,n),this.bugMonitor=new Zi(n),this.coder=new po(n),this.agentTeams=new yo(n),this.missions=new vo(n)}setToken(t){this.token=t,this.sessions.setToken(t)}async health(){const t=await this._request("/global/health");return Ct(Ui,t,"/global/health",200)}async listToolIds(){return this._request("/tool/ids")}async listTools(){const t=await this._request("/tool");return Array.isArray(t)?t:[]}async executeTool(t,n){return this._request("/tool/execute",{method:"POST",body:JSON.stringify({tool:t,args:n??{}})})}stream(t,n,r){const s=new URLSearchParams({sessionID:t});n&&s.set("runID",n);const l=`${this.baseUrl}/event?${s.toString()}`;return fa(l,this.token,r)}globalStream(t){const n=`${this.baseUrl}/global/event`;return fa(n,this.token,t)}async runEvents(t,n){const r=new URLSearchParams;n?.sinceSeq!==void 0&&r.set("since_seq",String(n.sinceSeq)),n?.tail!==void 0&&r.set("tail",String(n.tail));const s=r.toString()?`?${r.toString()}`:"",l=await this._request(`/run/${encodeURIComponent(t)}/events${s}`);return Array.isArray(l)?l:[]}async _request(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let l;try{l=await fetch(`${this.baseUrl}${t}`,{...n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(l.status!==204){if(!l.ok){const d=await l.text().catch(()=>"");throw new Error(`Request failed (${l.status} ${l.statusText}): ${d}`)}return l.json()}}async _requestText(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let l;try{l=await fetch(`${this.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(!l.ok){const d=await l.text().catch(()=>"");throw new Error(`Request failed (${l.status} ${l.statusText}): ${d}`)}return l.text()}}class Yi{constructor(t){this.req=t}async status(){return this.req("/browser/status")}async install(){return this.req("/browser/install",{method:"POST"})}async smokeTest(t){return this.req("/browser/smoke-test",{method:"POST",body:JSON.stringify(t??{})})}}class Xi{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){const n=await this.req("/workflows")??{},r=Array.isArray(n.workflows)?n.workflows:[];return{workflows:r,count:typeof n.count=="number"?n.count:r.length}}async get(t){return(await this.req(`/workflows/${encodeURIComponent(t)}`)).workflow??{}}async validate(t){return this.req("/workflows/validate",{method:"POST",body:JSON.stringify(t??{})})}async simulate(t){return this.req("/workflows/simulate",{method:"POST",body:JSON.stringify(t)})}events(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId,s=t?.run_id??t?.runId;r&&n.set("workflow_id",r),s&&n.set("run_id",s);const l=n.toString()?`?${n.toString()}`:"";return fa(`${this.baseUrl}/workflows/events${l}`,this.getToken(),{signal:t?.signal})}async listRuns(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r),t?.limit!==void 0&&n.set("limit",String(t.limit));const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflows/runs${s}`)??{},u=Array.isArray(d.runs)?d.runs:[];return{runs:u,count:typeof d.count=="number"?d.count:u.length}}async getRun(t){return(await this.req(`/workflows/runs/${encodeURIComponent(t)}`)).run??{}}async run(t,n){return this.req(`/workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}async listHooks(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r);const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflow-hooks${s}`)??{},u=Array.isArray(d.hooks)?d.hooks:[];return{hooks:u,count:typeof d.count=="number"?d.count:u.length}}async patchHook(t,n){return this.req(`/workflow-hooks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}}class Zi{constructor(t){this.req=t}async getConfig(){return this.req("/config/bug-monitor")}async patchConfig(t){return this.req("/config/bug-monitor",{method:"PATCH",body:JSON.stringify(t)})}async getStatus(){return this.req("/bug-monitor/status")}async recomputeStatus(){return this.req("/bug-monitor/status/recompute",{method:"POST"})}async pause(){return this.req("/bug-monitor/pause",{method:"POST"})}async resume(){return this.req("/bug-monitor/resume",{method:"POST"})}async debug(){return this.req("/bug-monitor/debug")}async listIncidents(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/incidents${n}`)}async getIncident(t){return(await this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}`)).incident??{}}async replayIncident(t,n){return this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}/replay`,{method:"POST",body:JSON.stringify(n??{})})}async listDrafts(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/drafts${n}`)}async listPosts(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/posts${n}`)}async getDraft(t){return(await this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}`)).draft??{}}async approveDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async denyDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n})})}async report(t){return this.req("/bug-monitor/report",{method:"POST",body:JSON.stringify(t)})}async createTriageRun(t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-run`,{method:"POST"})}async createTriageSummary(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/issue-draft`,{method:"POST",body:JSON.stringify(n??{})})}async publishDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/publish`,{method:"POST",body:JSON.stringify(n??{})})}async recheckMatch(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/recheck-match`,{method:"POST",body:JSON.stringify(n??{})})}}class eo{constructor(t,n,r,s){this.baseUrl=t,this.token=n,this.timeoutMs=r,this.req=s}setToken(t){this.token=t}async create(t={}){const n={title:t.title??"Tandem SDK Session",directory:t.directory??"."};return t.permissions&&(n.permission=t.permissions),t.model&&t.provider&&(n.model={providerID:t.provider,modelID:t.model},n.provider=t.provider),(await this.req("/session",{method:"POST",body:JSON.stringify(n)})).id}async list(t={}){const n=new URLSearchParams;t.q&&n.set("q",t.q),t.page!==void 0&&n.set("page",String(t.page)),t.pageSize!==void 0&&n.set("page_size",String(t.pageSize)),t.archived!==void 0&&n.set("archived",String(t.archived)),t.scope&&n.set("scope",t.scope),t.workspace&&n.set("workspace",t.workspace);const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/session${r}`);return Ct(nr,s,"/session",200)}async get(t){const n=await this.req(`/session/${encodeURIComponent(t)}`);return Ct(tn,n,`/session/${t}`,200)}async update(t,n){const r=await this.req(`/session/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Ct(tn,r,`/session/${t}`,200)}async archive(t){return this.update(t,{archived:!0})}async delete(t){await this.req(`/session/${encodeURIComponent(t)}`,{method:"DELETE"})}async messages(t){return this.req(`/session/${encodeURIComponent(t)}/message`)}async todos(t){const n=await this.req(`/session/${encodeURIComponent(t)}/todo`);return Array.isArray(n)?n:n.todos??[]}async activeRun(t){const n=await this.req(`/session/${encodeURIComponent(t)}/run`);return Ct(ji,n,`/session/${t}/run`,200)}async promptAsync(t,n,r,s){return this.promptAsyncParts(t,[{type:"text",text:n}],r,s)}async promptAsyncParts(t,n,r,s){const l={parts:n};r?.provider&&r?.model&&(l.model={providerID:r.provider,modelID:r.model}),s?.toolMode&&(l.toolMode=s.toolMode),s?.toolAllowlist?.length&&(l.toolAllowlist=s.toolAllowlist),s?.contextMode&&(l.contextMode=s.contextMode);const d=`/session/${encodeURIComponent(t)}/prompt_async?return=run`,u=new AbortController,p=setTimeout(()=>u.abort(),this.timeoutMs);let k;try{k=await fetch(`${this.baseUrl}${d}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(l),signal:u.signal})}finally{clearTimeout(p)}if(k.status===409){const w=(await k.json().catch(()=>({}))).activeRun,M=Ft(w?.runID)||Ft(w?.runId)||Ft(w?.run_id);if(M)return{runId:M}}if(!k.ok){const b=await k.text().catch(()=>"");throw new Error(`promptAsyncParts failed (${k.status}): ${b}`)}const q=await k.json();return{runId:zi(q)}}async promptSync(t,n){const r={parts:[{type:"text",text:n}]},s=await this.req(`/session/${encodeURIComponent(t)}/prompt_sync`,{method:"POST",body:JSON.stringify(r)});return Ft(s.reply)||Ft(s.text)||Ft(s.output)||""}async abort(t){return this.req(`/session/${encodeURIComponent(t)}/abort`,{method:"POST",body:JSON.stringify({})})}async cancel(t){return this.req(`/session/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})})}async cancelRun(t,n){return this.req(`/session/${encodeURIComponent(t)}/run/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})})}async fork(t){const n=await this.req(`/session/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify({})});return Ct(tn,n,`/session/${t}/fork`,200)}async diff(t){return this.req(`/session/${encodeURIComponent(t)}/diff`)}async revert(t){return this.req(`/session/${encodeURIComponent(t)}/revert`,{method:"POST",body:JSON.stringify({})})}async unrevert(t){return this.req(`/session/${encodeURIComponent(t)}/unrevert`,{method:"POST",body:JSON.stringify({})})}async children(t){const n=await this.req(`/session/${encodeURIComponent(t)}/children`);return Ct(nr,n,`/session/${t}/children`,200).sessions}async summarize(t){return this.req(`/session/${encodeURIComponent(t)}/summarize`,{method:"POST",body:JSON.stringify({})})}async attach(t,n){return this.req(`/session/${encodeURIComponent(t)}/attach`,{method:"POST",body:JSON.stringify({target_workspace:n})})}}class to{constructor(t){this.req=t}async list(){return this.req("/permission")}async reply(t,n){const r=await this.req(`/permission/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({reply:n})});if(!r.ok)throw new Error(`Permission reply rejected: ${r.error??t}`);return{ok:!0}}}class ao{constructor(t){this.req=t}async list(){const t=await this.req("/question");return Array.isArray(t)?{questions:t}:t}async reply(t,n){return this.req(`/question/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({answer:n})})}async reject(t){return this.req(`/question/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({})})}}class no{constructor(t){this.req=t}async catalog(){return this.req("/provider")}async config(){return this.req("/config/providers")}async setDefaults(t,n){await this.req("/config",{method:"PATCH",body:JSON.stringify({default_provider:t,providers:{[t]:{default_model:n}}})})}async setApiKey(t,n){await this.req(`/auth/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({apiKey:n})})}async authStatus(){return this.req("/provider/auth")}}class ro{constructor(t){this.req=t}async get(){return this.req("/config/identity")}async patch(t){return this.req("/config/identity",{method:"PATCH",body:JSON.stringify(t)})}}class so{constructor(t){this.req=t}async config(){return this.req("/channels/config")}async status(){return this.req("/channels/status")}async put(t,n){return this.req(`/channels/${t}`,{method:"PUT",body:JSON.stringify(n)})}async delete(t){return this.req(`/channels/${t}`,{method:"DELETE"})}async verify(t,n={}){return this.req(`/channels/${t}/verify`,{method:"POST",body:JSON.stringify(n)})}}class io{constructor(t,n){this.req=t,this.reqText=n}async list(){return this.req("/mcp")}async listTools(){return this.req("/mcp/tools")}async listResources(){const t=await this.req("/mcp/resources");return Array.isArray(t)?t:[]}async add(t){return this.req("/mcp",{method:"POST",body:JSON.stringify(t)})}async connect(t){return this.req(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})}async disconnect(t){return this.req(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})}async refresh(t){return this.req(`/mcp/${encodeURIComponent(t)}/refresh`,{method:"POST"})}async setEnabled(t,n){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:n})})}async delete(t){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})}async auth(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"POST",body:JSON.stringify(n??{})})}async deleteAuth(t){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"DELETE"})}async authCallback(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth/callback`,{method:"POST",body:JSON.stringify(n)})}async authenticate(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth/authenticate`,{method:"POST",body:JSON.stringify(n??{})})}async catalogToml(t){if(!this.reqText)throw new Error("Text request helper unavailable");return this.reqText(`/mcp/catalog/${encodeURIComponent(t)}/toml`)}}class oo{constructor(t){this.req=t}async put(t){return this.req("/memory/put",{method:"POST",body:JSON.stringify(t)})}async search(t){const n=await this.req("/memory/search",{method:"POST",body:JSON.stringify(t)});return Ct(Ji,n,"/memory/search",200)}async list(t){const n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset)),t?.userId&&n.set("user_id",t.userId);const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/memory${r}`);return Ct(Ki,s,"/memory",200)}async delete(t){return this.req(`/memory/${encodeURIComponent(t)}`,{method:"DELETE"})}async promote(t){return this.req("/memory/promote",{method:"POST",body:JSON.stringify(t)})}async demote(t){const n={id:t.id,run_id:t.runId};return this.req("/memory/demote",{method:"POST",body:JSON.stringify(n)})}async audit(t){const n=new URLSearchParams;t?.run_id&&n.set("run_id",t.run_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/memory/audit${r}`);return Array.isArray(s)?{entries:s,count:s.length}:s}}class lo{constructor(t){this.req=t}async list(t){const n=t?`?location=${encodeURIComponent(t)}`:"",r=await this.req(`/skills${n}`);return Array.isArray(r)?{skills:r,count:r.length}:r}async get(t){return this.req(`/skills/${encodeURIComponent(t)}`)}async import(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath,location:t.location,namespace:t.namespace,conflict_policy:t.conflict_policy??t.conflictPolicy};return this.req("/skills/import",{method:"POST",body:JSON.stringify(n)})}async preview(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath,location:t.location,namespace:t.namespace,conflict_policy:t.conflict_policy??t.conflictPolicy};return this.req("/skills/import/preview",{method:"POST",body:JSON.stringify(n)})}async templates(){const t=await this.req("/skills/templates");return Array.isArray(t)?{templates:t,count:t.length}:t}async catalog(){const t=await this.req("/skills/catalog"),n=Array.isArray(t)?t:[];return{skills:n,count:n.length}}async validate(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath};return this.req("/skills/validate",{method:"POST",body:JSON.stringify(n)})}async match(t){const n={goal:t.goal,max_matches:t.max_matches??t.maxMatches,threshold:t.threshold};return this.req("/skills/router/match",{method:"POST",body:JSON.stringify(n)})}async evalBenchmark(t){const n={threshold:t.threshold,cases:t.cases.map(r=>({prompt:r.prompt,expected_skill:r.expected_skill??r.expectedSkill}))};return this.req("/skills/evals/benchmark",{method:"POST",body:JSON.stringify(n)})}async evalTriggers(t){const n={skill_name:t.skill_name??t.skillName,prompts:t.prompts,threshold:t.threshold};return this.req("/skills/evals/triggers",{method:"POST",body:JSON.stringify(n)})}async compile(t){const n={skill_name:t.skill_name??t.skillName,goal:t.goal,threshold:t.threshold,max_matches:t.max_matches??t.maxMatches,schedule:t.schedule};return this.req("/skills/compile",{method:"POST",body:JSON.stringify(n)})}async generate(t){return this.req("/skills/generate",{method:"POST",body:JSON.stringify(t)})}async generateInstall(t){const n={prompt:t.prompt,threshold:t.threshold,location:t.location,conflict_policy:t.conflictPolicy,artifacts:t.artifacts?{"SKILL.md":t.artifacts["SKILL.md"],"workflow.yaml":t.artifacts["workflow.yaml"],"automation.example.yaml":t.artifacts["automation.example.yaml"]}:void 0};return this.req("/skills/generate/install",{method:"POST",body:JSON.stringify(n)})}}class co{constructor(t){this.req=t}async list(){return this.req("/packs")}async inspect(t){return this.req(`/packs/${encodeURIComponent(t)}`)}async install(t){return this.req("/packs/install",{method:"POST",body:JSON.stringify(t)})}async installFromAttachment(t){return this.req("/packs/install_from_attachment",{method:"POST",body:JSON.stringify(t)})}async uninstall(t){return this.req("/packs/uninstall",{method:"POST",body:JSON.stringify(t)})}async export(t){return this.req("/packs/export",{method:"POST",body:JSON.stringify(t)})}async detect(t){return this.req("/packs/detect",{method:"POST",body:JSON.stringify(t)})}async updates(t){const r=await this.req(`/packs/${encodeURIComponent(t)}/updates`)||{},s=Array.isArray(r.updates)?r.updates:[];return{pack_id:Ft(r.pack_id)??void 0,name:Ft(r.name)??void 0,current_version:Ft(r.current_version)??void 0,updates:s}}async update(t,n){const r=await this.req(`/packs/${encodeURIComponent(t)}/update`,{method:"POST",body:JSON.stringify(n??{})});return{updated:!!r.updated,pack_id:Ft(r.pack_id)??void 0,name:Ft(r.name)??void 0,current_version:Ft(r.current_version)??void 0,target_version:Ft(r.target_version)??void 0,reason:Ft(r.reason)??void 0}}}class uo{constructor(t){this.req=t}async getBindings(){return(await this.req("/capabilities/bindings")).bindings}async setBindings(t){return this.req("/capabilities/bindings",{method:"PUT",body:JSON.stringify(t)})}async discovery(){return this.req("/capabilities/discovery")}async resolve(t){return this.req("/capabilities/resolve",{method:"POST",body:JSON.stringify(t)})}async readiness(t){return this.req("/capabilities/readiness",{method:"POST",body:JSON.stringify(t)})}}class mo{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(t){const n=new URLSearchParams;t?.prefix&&n.set("prefix",t.prefix),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/resource${r}`);return Ct(Li,s,"/resource",200)}async write(t){return this.req("/resource",{method:"PUT",body:JSON.stringify(t)})}async get(t){const n=await this.req(`/resource/${encodeURIComponent(t)}`);return Ct(Ur,n,`/resource/${t}`,200)}async putKey(t,n,r){const s=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({value:n,...r??{}})});return Ct(rr,s,`/resource/${t}`,200)}async patchKey(t,n){const r=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Ct(rr,r,`/resource/${t}`,200)}async delete(t,n){return this.req("/resource",{method:"DELETE",body:JSON.stringify({key:t,...n})})}async deleteKey(t){return this.req(`/resource/${encodeURIComponent(t)}`,{method:"DELETE"})}events(t){const n=new URLSearchParams;t?.sinceSeq!==void 0&&n.set("since_seq",String(t.sinceSeq)),t?.tail!==void 0&&n.set("tail",String(t.tail));const r=n.toString()?`?${n.toString()}`:"";return fa(`${this.baseUrl}/resource/events${r}`,this.getToken())}}class po{constructor(t){this.req=t}async createRun(t){return this.req("/coder/runs",{method:"POST",body:JSON.stringify(t)})}async listRuns(t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit));const r=t?.workflow_mode??t?.workflowMode,s=t?.repo_slug??t?.repoSlug;r&&n.set("workflow_mode",r),s&&n.set("repo_slug",s);const l=n.toString()?`?${n.toString()}`:"",u=await this.req(`/coder/runs${l}`)??{},p=Array.isArray(u.runs)?u.runs:[];return{runs:p,count:typeof u.count=="number"?u.count:p.length}}async getRun(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}`)??{};return{...r,coderRun:r.coder_run??void 0,coder_run:r.coder_run??void 0,run:r.run??void 0}}async executeNext(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-next`,{method:"POST",body:JSON.stringify(n??{})})}async executeAll(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-all`,{method:"POST",body:JSON.stringify(n??{})})}async createFollowOnRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/follow-on-run`,{method:"POST",body:JSON.stringify(n)})}async approveRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async cancelRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n})})}async listArtifacts(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/artifacts`)??{},s=Array.isArray(r.artifacts)?r.artifacts:[];return{...r,artifacts:s,count:typeof r.count=="number"?r.count:s.length}}async getMemoryHits(t,n){const r=new URLSearchParams;n?.query&&r.set("q",n.query),n?.limit!==void 0&&r.set("limit",String(n.limit));const s=r.toString()?`?${r.toString()}`:"",d=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-hits${s}`)??{},u=Array.isArray(d.hits)?d.hits:[];return{...d,hits:u,count:typeof d.count=="number"?d.count:u.length}}async createTriageInspectionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-inspection-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageReproductionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-reproduction-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewEvidence(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-evidence`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixValidationReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-validation-report`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrDraft(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-draft`,{method:"POST",body:JSON.stringify(n??{})})}async submitPr(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-submit`,{method:"POST",body:JSON.stringify(n??{})})}async createMergeReadinessReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-readiness-report`,{method:"POST",body:JSON.stringify(n)})}async createMergeRecommendationSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-recommendation-summary`,{method:"POST",body:JSON.stringify(n)})}async listMemoryCandidates(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`)??{},s=Array.isArray(r.candidates)?r.candidates:[];return{...r,candidates:s,count:typeof r.count=="number"?r.count:s.length}}async createMemoryCandidate(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`,{method:"POST",body:JSON.stringify(n)})}async promoteMemoryCandidate(t,n,r){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates/${encodeURIComponent(n)}/promote`,{method:"POST",body:JSON.stringify(r??{})})}}class ho{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){return this.req("/routines")}async create(t){const n={...t};return"prompt"in n&&!("entrypoint"in n)&&(n.entrypoint=n.prompt),this.req("/routines",{method:"POST",body:JSON.stringify(n)})}async update(t,n){return this.req(`/routines/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){await this.req(`/routines/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const n=await this.req(`/routines/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return Ct(Dr,n,`/routines/${t}/run_now`,200)}async listRuns(t){const n=new URLSearchParams;t?.routine_id&&n.set("routine_id",t.routine_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return this.req(`/routines/runs${r}`)}async getRunsForRoutine(t,n=25){return this.req(`/routines/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){const n=await this.req(`/routines/runs/${encodeURIComponent(t)}`);return Ct(Fr,n,`/routines/runs/${t}`,200)}async listArtifacts(t){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/routines/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.routine_id??t?.routineId;r&&n.set("routine_id",r);const s=n.toString()?`?${n.toString()}`:"";return fa(`${this.baseUrl}/routines/events${s}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class go{constructor(t){this.req=t}async preview(t){return this.req("/workflow-plans/preview",{method:"POST",body:JSON.stringify({prompt:t.prompt,schedule:t.schedule,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,workspace_root:t.workspace_root??t.workspaceRoot,operator_preferences:t.operator_preferences??t.operatorPreferences})})}async apply(t){return this.req("/workflow-plans/apply",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId,plan:t.plan,creator_id:t.creator_id??t.creatorId,pack_builder_export:t.pack_builder_export??t.packBuilderExport})})}async chatStart(t){return this.req("/workflow-plans/chat/start",{method:"POST",body:JSON.stringify({prompt:t.prompt,schedule:t.schedule,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,workspace_root:t.workspace_root??t.workspaceRoot,operator_preferences:t.operator_preferences??t.operatorPreferences})})}async get(t){return this.req(`/workflow-plans/${encodeURIComponent(t)}`)}async chatMessage(t){return this.req("/workflow-plans/chat/message",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId,message:t.message})})}async chatReset(t){return this.req("/workflow-plans/chat/reset",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId})})}}class fo{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){return this.req("/automations")}async create(t){return this.req("/automations",{method:"POST",body:JSON.stringify(t)})}async update(t,n){return this.req(`/automations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){await this.req(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const n=await this.req(`/automations/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return Ct(Dr,n,`/automations/${t}/run_now`,200)}async listRuns(t){const n=new URLSearchParams;t?.automation_id&&n.set("automation_id",t.automation_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return this.req(`/automations/runs${r}`)}async getRunsForAutomation(t,n=25){return this.req(`/automations/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){const n=await this.req(`/automations/runs/${encodeURIComponent(t)}`);return Ct(Fr,n,`/automations/runs/${t}`,200)}async listArtifacts(t){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/automations/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const l=n.toString()?`?${n.toString()}`:"";return fa(`${this.baseUrl}/automations/events${l}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class bo{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async create(t){return this.req("/automations/v2",{method:"POST",body:JSON.stringify(t)})}async list(){return this.req("/automations/v2")}async get(t){return this.req(`/automations/v2/${encodeURIComponent(t)}`)}async update(t,n){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})})}async pause(t,n){return this.req(`/automations/v2/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resume(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({})})}async listRuns(t,n=50){return this.req(`/automations/v2/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}`)}async pauseRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async cancelRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n??""})})}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const l=n.toString()?`?${n.toString()}`:"";return fa(`${this.baseUrl}/automations/v2/events${l}`,this.getToken(),{signal:t?.signal})}}class yo{constructor(t){this.req=t}async listTemplates(){return this.req("/agent-team/templates")}async createTemplate(t){return this.req("/agent-team/templates",{method:"POST",body:JSON.stringify(t)})}async updateTemplate(t,n){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async deleteTemplate(t){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"DELETE"})}async composeStandup(t){return this.req("/agent-standup/compose",{method:"POST",body:JSON.stringify({name:t.name,workspace_root:t.workspaceRoot,schedule:t.schedule,participant_template_ids:t.participantTemplateIds,report_path_template:t.reportPathTemplate})})}async listInstances(t){const n=new URLSearchParams;t?.missionID&&n.set("missionID",t.missionID),t?.parentInstanceID&&n.set("parentInstanceID",t.parentInstanceID),t?.status&&n.set("status",t.status);const r=n.toString()?`?${n.toString()}`:"";return this.req(`/agent-team/instances${r}`)}async listMissions(){return this.req("/agent-team/missions")}async listApprovals(){return this.req("/agent-team/approvals")}async spawn(t){return this.req("/agent-team/spawn",{method:"POST",body:JSON.stringify(t)})}async approveSpawn(t,n){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denySpawn(t,n){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}}class vo{constructor(t){this.req=t}async list(){return this.req("/mission")}async create(t){return this.req("/mission",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.req(`/mission/${encodeURIComponent(t)}`)}async applyEvent(t,n){return this.req(`/mission/${encodeURIComponent(t)}/event`,{method:"POST",body:JSON.stringify({event:n})})}}const rn="charcoal_fire",xa=[{id:"charcoal_fire",name:"Charcoal & Fire",description:"Deep charcoal surfaces with solar-yellow power accents and crimson security cues.",cssVars:{"--color-background":"#121212","--color-surface":"#141414","--color-surface-elevated":"#1a1a1a","--color-border":"rgba(245, 245, 245, 0.10)","--color-border-subtle":"rgba(245, 245, 245, 0.06)","--color-primary":"#F59E0B","--color-primary-hover":"#D97706","--color-primary-muted":"#B45309","--color-secondary":"#EF4444","--color-secondary-hover":"#DC2626","--color-success":"#10B981","--color-warning":"#F59E0B","--color-error":"#EF4444","--color-text":"#F5F5F5","--color-text-muted":"rgba(245, 245, 245, 0.70)","--color-text-subtle":"rgba(245, 245, 245, 0.50)","--color-glass":"rgba(255, 255, 255, 0.03)","--color-glass-border":"rgba(255, 255, 255, 0.08)","--font-sans":'"Manrope", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(245, 158, 11, 0.16)","--tcp-glow-b":"rgba(239, 68, 68, 0.12)"}},{id:"electric_blue",name:"Electric Blue",description:"The original Tandem look: electric-blue primary with purple secondary.",cssVars:{"--color-background":"#0a0a0f","--color-surface":"#12121a","--color-surface-elevated":"#1a1a24","--color-border":"#2a2a3a","--color-border-subtle":"#1f1f2e","--color-primary":"#3b82f6","--color-primary-hover":"#2563eb","--color-primary-muted":"#1d4ed8","--color-secondary":"#8b5cf6","--color-secondary-hover":"#7c3aed","--color-success":"#10b981","--color-warning":"#f59e0b","--color-error":"#ef4444","--color-text":"#f8fafc","--color-text-muted":"#94a3b8","--color-text-subtle":"#64748b","--color-glass":"rgba(18, 18, 26, 0.8)","--color-glass-border":"rgba(255, 255, 255, 0.1)","--font-sans":'"Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(59, 130, 246, 0.16)","--tcp-glow-b":"rgba(139, 92, 246, 0.12)"}},{id:"emerald_night",name:"Emerald Night",description:"Dark glass with emerald primary and cyan secondary highlights.",cssVars:{"--color-background":"#0b1010","--color-surface":"#0f1616","--color-surface-elevated":"#142020","--color-border":"rgba(226, 232, 240, 0.12)","--color-border-subtle":"rgba(226, 232, 240, 0.08)","--color-primary":"#10B981","--color-primary-hover":"#059669","--color-primary-muted":"#047857","--color-secondary":"#22D3EE","--color-secondary-hover":"#06B6D4","--color-success":"#22C55E","--color-warning":"#F59E0B","--color-error":"#EF4444","--color-text":"#F1F5F9","--color-text-muted":"rgba(241, 245, 249, 0.72)","--color-text-subtle":"rgba(241, 245, 249, 0.52)","--color-glass":"rgba(15, 22, 22, 0.75)","--color-glass-border":"rgba(255, 255, 255, 0.10)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(16, 185, 129, 0.16)","--tcp-glow-b":"rgba(34, 211, 238, 0.12)"}},{id:"hello_bunny",name:"Hello Bunny",description:"Soft pink glass with berry accents and a cozy, playful vibe.",cssVars:{"--color-background":"#140A12","--color-surface":"#1C0E1A","--color-surface-elevated":"#251022","--color-border":"rgba(255, 228, 242, 0.12)","--color-border-subtle":"rgba(255, 228, 242, 0.08)","--color-primary":"#FB7185","--color-primary-hover":"#F43F5E","--color-primary-muted":"#E11D48","--color-secondary":"#C084FC","--color-secondary-hover":"#A855F7","--color-success":"#34D399","--color-warning":"#FBBF24","--color-error":"#FB7185","--color-text":"#FFEAF4","--color-text-muted":"rgba(255, 234, 244, 0.74)","--color-text-subtle":"rgba(255, 234, 244, 0.52)","--color-glass":"rgba(255, 255, 255, 0.04)","--color-glass-border":"rgba(255, 228, 242, 0.10)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(251, 113, 133, 0.16)","--tcp-glow-b":"rgba(192, 132, 252, 0.12)"}},{id:"porcelain",name:"Porcelain",description:"Plain, bright whites with soft pastel accents and glassy structure.",cssVars:{"--color-background":"#F8FAFC","--color-surface":"#FFFFFF","--color-surface-elevated":"#F1F5F9","--color-border":"rgba(15, 23, 42, 0.12)","--color-border-subtle":"rgba(15, 23, 42, 0.08)","--color-primary":"#6366F1","--color-primary-hover":"#4F46E5","--color-primary-muted":"#4338CA","--color-secondary":"#F472B6","--color-secondary-hover":"#EC4899","--color-success":"#10B981","--color-warning":"#F59E0B","--color-error":"#EF4444","--color-text":"#0F172A","--color-text-muted":"rgba(15, 23, 42, 0.70)","--color-text-subtle":"rgba(15, 23, 42, 0.50)","--color-glass":"rgba(255, 255, 255, 0.72)","--color-glass-border":"rgba(15, 23, 42, 0.10)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(99, 102, 241, 0.13)","--tcp-glow-b":"rgba(244, 114, 182, 0.11)"}},{id:"neon_riot",name:"Neon Riot",description:"Electric cyan and magenta over deep space surfaces.",cssVars:{"--color-background":"#050014","--color-surface":"#0B0720","--color-surface-elevated":"#140A3A","--color-border":"rgba(248, 250, 252, 0.16)","--color-border-subtle":"rgba(248, 250, 252, 0.10)","--color-primary":"#00E5FF","--color-primary-hover":"#00B8D4","--color-primary-muted":"#00838F","--color-secondary":"#FF3DF5","--color-secondary-hover":"#D500F9","--color-success":"#22C55E","--color-warning":"#FBBF24","--color-error":"#FB7185","--color-text":"#F8FAFC","--color-text-muted":"rgba(248, 250, 252, 0.72)","--color-text-subtle":"rgba(248, 250, 252, 0.52)","--color-glass":"rgba(5, 0, 20, 0.55)","--color-glass-border":"rgba(255, 255, 255, 0.14)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(0, 229, 255, 0.20)","--tcp-glow-b":"rgba(255, 61, 245, 0.14)"}},{id:"cosmic_glass",name:"Cosmic Glass",description:"Transparent nebula glass panels with deep-space glow.",cssVars:{"--color-background":"#03020F","--color-surface":"rgba(9, 6, 28, 0.72)","--color-surface-elevated":"rgba(18, 12, 40, 0.82)","--color-border":"rgba(120, 105, 255, 0.22)","--color-border-subtle":"rgba(120, 105, 255, 0.12)","--color-primary":"#7C5CFF","--color-primary-hover":"#6A40FF","--color-primary-muted":"#4C2ED8","--color-secondary":"#FF7AD9","--color-secondary-hover":"#FF4FC3","--color-success":"#3BE4C0","--color-warning":"#F9D86B","--color-error":"#FF5C7A","--color-text":"#F3F0FF","--color-text-muted":"rgba(243, 240, 255, 0.74)","--color-text-subtle":"rgba(243, 240, 255, 0.52)","--color-glass":"rgba(14, 10, 40, 0.48)","--color-glass-border":"rgba(255, 255, 255, 0.16)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(124, 92, 255, 0.20)","--tcp-glow-b":"rgba(255, 122, 217, 0.14)"}},{id:"pink_pony",name:"Pink Pony",description:"Candy pinks and dreamy pastels with brighter glass accents.",cssVars:{"--color-background":"#240818","--color-surface":"rgba(56, 12, 38, 0.94)","--color-surface-elevated":"rgba(72, 16, 48, 0.96)","--color-border":"rgba(255, 184, 217, 0.36)","--color-border-subtle":"rgba(255, 184, 217, 0.22)","--color-primary":"#FF5FB1","--color-primary-hover":"#FF3B9A","--color-primary-muted":"#D91E7D","--color-secondary":"#FFB8E6","--color-secondary-hover":"#FF98D8","--color-success":"#58E5C1","--color-warning":"#FFD166","--color-error":"#FF5C8A","--color-text":"#FFF7FC","--color-text-muted":"rgba(255, 247, 252, 0.86)","--color-text-subtle":"rgba(255, 247, 252, 0.68)","--color-glass":"rgba(74, 17, 50, 0.78)","--color-glass-border":"rgba(255, 220, 238, 0.30)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(255, 95, 177, 0.20)","--tcp-glow-b":"rgba(255, 184, 230, 0.14)"}},{id:"zen_dusk",name:"Zen Dusk",description:"Muted green dusk tones for calmer long-session work.",cssVars:{"--color-background":"#0B1110","--color-surface":"#101716","--color-surface-elevated":"#141D1C","--color-border":"rgba(226, 232, 240, 0.12)","--color-border-subtle":"rgba(226, 232, 240, 0.06)","--color-primary":"#7CC8A4","--color-primary-hover":"#6AB690","--color-primary-muted":"#559B7B","--color-secondary":"#9FB8B0","--color-secondary-hover":"#8AA59C","--color-success":"#5EC79B","--color-warning":"#E6C17B","--color-error":"#E38B8B","--color-text":"#E6EFEA","--color-text-muted":"rgba(230, 239, 234, 0.72)","--color-text-subtle":"rgba(230, 239, 234, 0.50)","--color-glass":"rgba(20, 28, 26, 0.72)","--color-glass-border":"rgba(255, 255, 255, 0.08)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(124, 200, 164, 0.16)","--tcp-glow-b":"rgba(159, 184, 176, 0.12)"}}],Zt={duration:{normal:.22},easing:{standard:[.22,1,.36,1]},spring:{gentle:{type:"spring",stiffness:220,damping:26,mass:.9},snappy:{type:"spring",stiffness:320,damping:30,mass:.82},drawer:{type:"spring",stiffness:340,damping:34,mass:.82}}};function Fn(a){let t=String(a||"").trim()||rn;return t==="web_control"&&(t=rn),xa.find(n=>n.id===t)||xa[0]}function wo(a){const t=Fn(a).id,n=xa.findIndex(r=>r.id===t);return n<0?rn:xa[(n+1)%xa.length].id}function jr(a,t=typeof document<"u"?document.documentElement:null){const n=Fn(a);if(!t)return n;for(const[r,s]of Object.entries(n.cssVars))s!=null&&t.style.setProperty(r,s);return t.dataset.theme=n.id,t.style.colorScheme=n.id==="porcelain"?"light":"dark",n}function Lr(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const Br="tandem.themeId";function xo(){try{const a=localStorage.getItem(Br);return Fn(a).id}catch{return rn}}function No(a){return jr(a)}function ko(a){const t=jr(a);try{localStorage.setItem(Br,t.id)}catch{}return t}function ja(){const[a,t]=y(()=>Lr());return ye(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>t(n.matches);return r(),typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>n.removeEventListener("change",r)):(n.addListener(r),()=>n.removeListener(r))},[]),a}function _o(a,t,n){return Math.min(n,Math.max(t,a))}function sn({className:a="",children:t}){return e("div",{className:`tcp-glow-layer ${a}`.trim(),children:t})}function La({className:a="",children:t}){const n=ja();return e(xe.div,{className:a,initial:n?!1:{opacity:0,y:14},animate:n?void 0:{opacity:1,y:0},exit:n?void 0:{opacity:0,y:-10},transition:n?void 0:{duration:Zt.duration.normal,ease:Zt.easing.standard},children:t})}function So({className:a="",children:t}){const n=ja();return e(xe.div,{className:a,initial:n?!1:"hidden",animate:n?void 0:"show",variants:n?void 0:{hidden:{},show:{transition:{staggerChildren:.06,delayChildren:.02}}},children:t})}function Kr({className:a="",children:t,as:n="div"}){const r=ja(),s=n==="section"?xe.section:n==="article"?xe.article:xe.div;return e(s,{className:a,variants:r?void 0:{hidden:{opacity:0,y:12,scale:.985},show:{opacity:1,y:0,scale:1,transition:{duration:Zt.duration.normal,ease:Zt.easing.standard}}},initial:r?!1:"hidden",animate:r?void 0:"show",children:t})}function Co({value:a,format:t=r=>String(r),className:n=""}){const r=ja(),[s,l]=y(()=>Number(a||0)),d=pt(Number(a||0));return ye(()=>{const u=Number(a||0);if(!Number.isFinite(u)){l(0),d.current=0;return}if(r){l(u),d.current=u;return}const p=d.current,k=u-p;if(!k){l(u),d.current=u;return}const q=performance.now();let b=0;const w=M=>{const E=_o((M-q)/420,0,1),K=1-Math.pow(1-E,3),B=p+k*K;l(B),E<1?b=window.requestAnimationFrame(w):d.current=u};return b=window.requestAnimationFrame(w),()=>window.cancelAnimationFrame(b)},[r,a]),e("span",{className:n,children:t(Number.isFinite(s)?s:0)})}function Ht({tone:a="ok",text:t,className:n=""}){return e("span",{className:`tcp-status-pulse ${a} ${n}`.trim(),children:[e("span",{className:"tcp-status-pulse-dot","aria-hidden":"true"}),t?e("span",{children:t}):null]})}function Gt({className:a="",children:t}){return e("div",{className:`tcp-toolbar ${a}`.trim(),children:t})}function Ra({className:a="",title:t,children:n,...r}){return e("button",{type:"button",title:t,className:`tcp-icon-btn ${a}`.trim(),...r,children:n})}function Ie({tone:a="info",className:t="",children:n}){return e("span",{className:`${a==="ok"?"tcp-badge-ok":a==="warn"?"tcp-badge-warn":a==="err"?"tcp-badge-err":a==="ghost"?"tcp-badge tcp-badge-ghost":"tcp-badge-info"} ${t}`.trim(),children:n})}function yn({active:a=!1,className:t="",children:n,...r}){return e("button",{type:"button",className:`tcp-filter-chip ${a?"active":""} ${t}`.trim(),...r,children:n})}function Ze({title:a,subtitle:t,actions:n,className:r="",children:s}){return e(Kr,{as:"section",className:`tcp-panel-card ${r}`.trim(),children:[a||t||n?e("div",{className:"tcp-panel-card-head",children:[e("div",{className:"min-w-0",children:[a?e("h3",{className:"tcp-title",children:a}):null,t?e("p",{className:"tcp-subtle mt-1",children:t}):null]}),n?e("div",{className:"shrink-0",children:n}):null]}):null,s]})}function Io({text:a,title:t="Nothing here yet",action:n,className:r=""}){return e("div",{className:`tcp-empty-state ${r}`.trim(),children:[e("div",{className:"tcp-empty-state-orb"}),e("div",{className:"relative z-10",children:[e("div",{className:"tcp-empty-state-title",children:t}),e("p",{className:"tcp-subtle mt-1",children:a}),n?e("div",{className:"mt-3",children:n}):null]})]})}function Ao({eyebrow:a,title:t,subtitle:n,badges:r,actions:s,className:l=""}){return e(Kr,{className:`tcp-page-header ${l}`.trim(),children:[e(sn,{className:"tcp-page-header-glow"}),e("div",{className:"relative z-10 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between",children:[e("div",{className:"min-w-0",children:[a?e("div",{className:"tcp-page-eyebrow",children:a}):null,e("h1",{className:"tcp-page-title",children:t}),n?e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:n}):null,r?e("div",{className:"mt-3 flex flex-wrap gap-2",children:r}):null]}),s?e(Gt,{className:"justify-start lg:justify-end",children:s}):null]})]})}function Ea({className:a="",mainClassName:t="",asideClassName:n="",main:r,aside:s}){return e("div",{className:`tcp-split-view ${a}`.trim(),children:[e("div",{className:`min-w-0 ${t}`.trim(),children:r}),s?e("div",{className:`min-w-0 ${n}`.trim(),children:s}):null]})}function on({open:a,title:t,onClose:n,children:r}){const s=ja();return e(ot,{children:a?e(xe.div,{className:"tcp-drawer-root",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-drawer-backdrop","aria-label":"Close",onClick:n}),e(xe.aside,{className:"tcp-drawer-panel",initial:s?!1:{x:"100%"},animate:s?void 0:{x:0},exit:s?void 0:{x:"100%"},transition:s?void 0:Zt.spring.drawer,children:[e("div",{className:"tcp-drawer-head",children:[e("div",{className:"min-w-0",children:t?e("h3",{className:"tcp-title",children:t}):null}),e(Ra,{title:"Close drawer",onClick:n,children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})]}):null})}function Po({loginMutation:a,savedToken:t,onCheckEngine:n,controlPanelName:r}){const[s,l]=y(t),[d,u]=y(!0),[p,k]=y(""),[q,b]=y(!1);return e("main",{className:"relative min-h-screen overflow-hidden px-5 py-8",children:[e(sn,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("div",{className:"relative z-10 mx-auto grid min-h-[calc(100vh-4rem)] w-full max-w-6xl items-center gap-6 lg:grid-cols-[1.05fr_0.95fr]",children:[e("section",{className:"grid gap-4",children:[e("div",{className:"tcp-page-eyebrow",children:"Tandem Control"}),e("h1",{className:"tcp-page-title max-w-3xl",children:"Sign in to continue."}),e("p",{className:"tcp-subtle max-w-2xl text-base",children:"Enter your engine token to access chat, orchestrator, automations, memory, live feed, and settings."})]}),e(Ze,{title:r,subtitle:"Authenticate against your Tandem engine to continue.",children:e("form",{className:"grid gap-3",onSubmit:w=>{if(w.preventDefault(),!s.trim()){b(!1),k("Token is required.");return}a.mutate({token:s.trim(),remember:d})},children:[e("label",{className:"text-sm tcp-subtle",children:"Engine token"}),e("input",{className:"tcp-input",type:"password",value:s,onInput:w=>l(w.target.value),placeholder:"tk_...",autoComplete:"off"}),e("label",{className:"inline-flex items-center gap-2 text-xs tcp-subtle",children:[e("input",{type:"checkbox",className:"h-4 w-4 accent-slate-400",checked:d,onChange:w=>u(w.target.checked)}),"Remember token on this browser"]}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{disabled:a.isPending,type:"submit",className:"tcp-btn-primary w-full",children:[e("i",{"data-lucide":"key-round"}),"Sign in"]}),e("button",{type:"button",className:"tcp-btn w-full",onClick:async()=>{try{const w=await n();b(!0),k(w)}catch(w){b(!1),k(w instanceof Error?w.message:String(w))}},children:[e("i",{"data-lucide":"activity"}),"Check engine"]})]}),e("div",{className:`min-h-[1.2rem] text-sm ${q?"text-lime-300":"text-rose-300"}`,children:a.error?.message||p}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e("div",{className:"font-medium",children:"Readiness"}),e(Ht,{tone:q?"ok":"warn",text:q?"Engine reachable":"Waiting"})]}),e("p",{className:"tcp-subtle text-xs",children:"Connectivity checks are non-destructive and help verify the local panel can reach the engine before authentication."})]})]})})]})]})}function To(a){ye(()=>{const t=n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="k"&&(n.preventDefault(),a())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[a])}function Mo({open:a,onClose:t,actions:n}){const[r,s]=y("");ye(()=>{a||s("")},[a]),ye(()=>{if(!a)return;const d=u=>{u.key==="Escape"&&t()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[a,t]);const l=H(()=>{const d=r.trim().toLowerCase();return d?n.filter(u=>`${u.label} ${u.group}`.toLowerCase().includes(d)):n},[n,r]);return e(ot,{children:a?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:e(xe.div,{className:"tcp-doc-dialog w-[min(44rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},transition:{duration:.16,ease:"easeOut"},onClick:d=>d.stopPropagation(),children:[e("div",{className:"tcp-doc-header",children:[e("h3",{className:"tcp-doc-title",children:"Command Palette"}),e("kbd",{className:"tcp-subtle text-xs",children:"Ctrl/Cmd + K"})]}),e("div",{className:"p-3",children:[e("input",{autoFocus:!0,value:r,onInput:d=>s(d.target.value),placeholder:"Jump to route or action",className:"tcp-input"}),e("div",{className:"mt-3 grid max-h-[50vh] gap-2 overflow-auto",children:[l.map(d=>e("button",{type:"button",className:"tcp-btn w-full justify-between",onClick:()=>{d.onSelect(),t()},children:[e("span",{className:"inline-flex items-center gap-1.5",children:[e("i",{"data-lucide":"list"}),e("span",{children:d.label})]}),e("span",{className:"tcp-subtle text-xs",children:d.group})]},d.id)),l.length?null:e("p",{className:"tcp-subtle px-1 py-2",children:"No matching action."})]})]})]})}):null})}const Wr=[["dashboard","Dashboard","home"],["chat","Chat","message-square"],["automations","Automations","bot"],["agents","Agents","users"],["orchestrator","Orchestrator","sparkles"],["memory","Memory","database"],["feed","Live Feed","radio"],["settings","Settings","settings"],["packs","Packs","package"],["teams","Teams","users"],["channels","Channels","message-circle"],["mcp","MCP","link"],["bug-monitor","Bug Monitor","bug-play"],["files","Files","folder-open"],["packs-detail","Packs","package"],["teams-detail","Teams","users"]],Ro=Wr.filter(([a])=>["dashboard","chat","automations","agents","orchestrator","memory","feed","settings"].includes(a)),Jr={openai:{label:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",placeholder:"sk-proj-..."},anthropic:{label:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",placeholder:"sk-ant-..."},google:{label:"Google",keyUrl:"https://aistudio.google.com/app/apikey",placeholder:"AIza..."},groq:{label:"Groq",keyUrl:"https://console.groq.com/keys",placeholder:"gsk_..."},mistral:{label:"Mistral",keyUrl:"https://console.mistral.ai/api-keys/",placeholder:"..."},together:{label:"Together",keyUrl:"https://api.together.xyz/settings/api-keys",placeholder:"..."},cohere:{label:"Cohere",keyUrl:"https://dashboard.cohere.com/api-keys",placeholder:"..."},openrouter:{label:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",placeholder:"sk-or-v1-..."},azure:{label:"Azure OpenAI",keyUrl:"https://portal.azure.com/",placeholder:"..."},bedrock:{label:"Bedrock",keyUrl:"https://console.aws.amazon.com/bedrock/",placeholder:"..."},vertex:{label:"Vertex",keyUrl:"https://console.cloud.google.com/vertex-ai",placeholder:"..."},copilot:{label:"GitHub Copilot",keyUrl:"https://github.com/settings/tokens",placeholder:"ghp_..."},ollama:{label:"Ollama",keyUrl:"",placeholder:"No key required"}},Qr=Wr,$o=Ro,qo=new Map([["packs","automations"],["teams","automations"],["swarm","orchestrator"],["failure-reporter","bug-monitor"]]),Eo=new Set(Qr.map(([a])=>a));function Un(a,t="dashboard"){const n=qo.get(String(a||"").trim());return n||(Eo.has(a)?a:t)}function sr(a="dashboard"){const t=(window.location.hash||`#/${a}`).replace(/^#\//,"");return Un(t.split("?")[0].split("/")[0].trim(),a)}function Oo(a){window.location.hash=`#/${a}`}function Do(){const[a,t]=y(()=>sr());ye(()=>{const r=()=>t(sr());return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]);const n=Je(r=>{const s=Un(r);if(window.location.hash!==`#/${s}`){Oo(s);return}t(s)},[]);return{route:a,navigate:n}}const Hr=gs({toast:()=>{}});function Fo({children:a}){const[t,n]=y([]),r=Je((l,d)=>{const u=Math.random().toString(36).slice(2);n(p=>[...p,{id:u,kind:l,text:d}].slice(-4)),window.setTimeout(()=>{n(p=>p.filter(k=>k.id!==u))},3500)},[]),s=H(()=>({toast:r}),[r]);return e(Hr.Provider,{value:s,children:[a,e("div",{className:"toasts","aria-live":"polite","aria-atomic":"true",children:e(ot,{children:t.map(l=>e(xe.div,{initial:{opacity:0,y:-8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-6,scale:.98},transition:{duration:.16,ease:"easeOut"},className:`toast toast-${l.kind}`,children:l.text},l.id))})})]})}function Uo(){return fs(Hr)}function Xt({title:a,subtitle:t,children:n,actions:r,className:s}){return e(Ze,{title:a,subtitle:t,actions:r,className:s||"",children:n})}function qe({text:a,title:t,action:n}){return e(Io,{text:a,title:t,action:n})}function _t(a){return JSON.stringify(a,null,2)}function vn(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function jo(a){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(Number(a||0))}function Lo(a){const{api:t,client:n,navigate:r,providerStatus:s}=a,[l,d]=y(""),u=new Set(["workflow","bug_monitor_triage"]),p=Q({queryKey:["dashboard","health"],queryFn:()=>t("/api/system/health"),refetchInterval:15e3}),k=Q({queryKey:["dashboard","sessions"],queryFn:()=>n.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),q=Q({queryKey:["dashboard","routines"],queryFn:()=>n.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),b=Q({queryKey:["dashboard","swarm"],queryFn:()=>t("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),w=Q({queryKey:["dashboard","workflow-context-runs"],queryFn:()=>t("/api/engine/context/runs?limit=12").catch(()=>({runs:[]})),refetchInterval:6e3}),M=Q({queryKey:["dashboard","workflow-context-run",l],enabled:!!l,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(l)}`).catch(()=>({run:null}))}),E=Q({queryKey:["dashboard","workflow-context-blackboard",l],enabled:!!l,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(l)}/blackboard`).catch(()=>({blackboard:null}))}),K=vn(k.data,"sessions"),B=vn(q.data,"routines"),se=vn(w.data,"runs").filter(S=>u.has(String(S?.run_type||"").trim().toLowerCase())),G=!!(p.data?.engine?.ready||p.data?.engine?.healthy),ge=String(b.data?.status||"unknown"),N=["planning","awaiting_approval","running","executing"].includes(ge.toLowerCase()),W=se.filter(S=>["queued","planning","running","awaiting_approval"].includes(String(S?.status||"").trim().toLowerCase())),J=H(()=>[{label:"Recent sessions",value:K.length,tone:"info",helper:"Latest active conversation surfaces"},{label:"Automations",value:B.length,tone:"ok",helper:"Configured routines and schedules"},{label:"Swarm status",value:N?1:0,tone:N?"warn":"ghost",helper:ge},{label:"Provider ready",value:s.ready?1:0,tone:s.ready?"ok":"warn",helper:s.ready?s.defaultModel:"Needs setup"},{label:"Workflow contexts",label:"Context runs",value:se.length,tone:W.length?"warn":"info",helper:W.length?`${W.length} active`:"Workflow + triage visibility"}],[W.length,s.defaultModel,s.ready,B.length,K.length,N,ge,se.length]);return e(La,{className:"grid gap-4",children:[e(Ze,{className:"overflow-hidden",children:[e("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Overview"}),e("h1",{className:"tcp-page-title",children:"Command center"}),e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:"A higher-signal home screen with animated state, quick entry points, and a clearer read on what the system is doing right now."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e(Ie,{tone:G?"ok":"warn",children:G?"Engine healthy":"Engine checking"}),e(Ie,{tone:s.ready?"ok":"warn",children:s.ready?s.defaultProvider:"Provider setup required"}),N?e(Ht,{tone:"live",text:`Swarm ${ge}`}):e(Ie,{tone:"ghost",children:["Swarm ",ge]})]})]}),e("div",{className:"grid gap-3",children:e(Gt,{className:"justify-start",children:[e("button",{className:"tcp-btn-primary w-full sm:w-auto",onClick:()=>r("chat"),children:[e("i",{"data-lucide":"message-square"}),"Chat session"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"sparkles"}),"Plan work"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Automations"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("settings"),children:[e("i",{"data-lucide":"settings"}),"Configure runtime"]})]})})]}),e("div",{className:"mt-5",children:[e("div",{className:"dashboard-kpis",children:J.map(S=>e("div",{children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("span",{className:"dashboard-kpi-label",children:S.label}),e(Ie,{tone:S.tone,children:S.helper})]}),e("strong",{children:e(Co,{value:S.value,format:jo})})]},S.label))}),e("div",{className:"mt-4 dashboard-bars",children:[e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Engine readiness"}),e("span",{className:"dashboard-bar-count",children:G?"100%":"45%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:"dashboard-bar-fill completed",style:{width:G?"100%":"45%"}})})]}),e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Provider confidence"}),e("span",{className:"dashboard-bar-count",children:s.ready?"100%":"30%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${s.ready?"running":"queued"}`,style:{width:s.ready?"100%":"30%"}})})]}),e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Automation activity"}),e("span",{className:"dashboard-bar-count",children:[B.length," routines"]})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${B.length?"scheduled":"manual"}`,style:{width:`${Math.min(100,Math.max(12,B.length*12))}%`}})})]})]})]})]}),e(Ea,{main:e(Ze,{title:"Recent sessions",subtitle:"Latest conversations, ready to reopen.",children:e("div",{className:"grid gap-2",children:K.length?K.map(S=>e("button",{className:"tcp-list-item text-left",onClick:()=>r("chat"),children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"messages-square"}),String(S.title||S.id||"Session")]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(S.id||S.session_id||"")})]},String(S.id||S.session_id||Math.random()))):e(qe,{text:"Start a conversation to populate recent sessions here."})})}),aside:e("div",{className:"grid gap-4",children:[e(Ze,{title:"Context visibility",subtitle:"Recent workflow and failure-triage context runs with their current projection state.",children:[e(Gt,{className:"mb-3",children:[e(Ie,{tone:W.length?"warn":"info",children:[se.length," recent"]}),e("button",{className:"tcp-btn",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]})]}),e("div",{className:"grid gap-2",children:se.length?se.slice(0,5).map(S=>e("button",{className:"tcp-list-item text-left",onClick:()=>d(String(S?.run_id||"").trim()),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:String(S?.objective||S?.run_id||"Context run")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e(Ie,{tone:"ghost",children:String(S?.run_type||"context")}),e(Ie,{tone:["failed","cancelled"].includes(String(S?.status||"").toLowerCase())?"err":["running","queued","planning"].includes(String(S?.status||"").toLowerCase())?"warn":"ok",children:String(S?.status||"unknown")})]})]}),e("div",{className:"tcp-subtle text-xs",children:String(S?.run_id||"")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Array.isArray(S?.tasks)?S.tasks.length:0," tasks ·"," ",Array.isArray(S?.steps)?S.steps.length:0," steps"]})]},String(S?.run_id||Math.random()))):e(qe,{text:"Workflow and failure-triage context runs will appear here once they execute."})})]}),e(Ze,{title:"Automation snapshot",subtitle:"Schedules and run-ready routines.",children:[e(Gt,{className:"mb-3",children:[e(Ie,{tone:"info",children:[B.length," loaded"]}),e("button",{className:"tcp-btn",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Manage"]})]}),e("div",{className:"grid gap-2",children:B.length?B.slice(0,4).map(S=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:String(S.name||S.id||"Routine")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(S.schedule||S.status||"manual")})]},String(S.id||S.routine_id||Math.random()))):e(qe,{text:"No routines are configured yet."})})]}),e(Ze,{title:"Health notes",subtitle:"Direct links for the next likely action.",children:e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"activity"}),"Engine endpoint"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(p.data?.engineUrl||"Unavailable")})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"radio"}),"Swarm"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:["Status: ",ge]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"database"}),"Memory & feed"]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>r("memory"),children:"Open memory"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>r("feed"),children:"Open live feed"})]})]})]})})]})}),e(on,{open:!!l,onClose:()=>d(""),title:l||"Workflow context run",children:l?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(M.data?.run?.objective||l)}),e(Ie,{tone:"info",children:String(M.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["type: ",String(M.data?.run?.run_type||"workflow")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium mb-2",children:"Projected blackboard"}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(E.data?.blackboard?.tasks)?E.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(E.data?.blackboard?.artifacts)?E.data.blackboard.artifacts.length:0]})]}),e("pre",{className:"tcp-code",children:_t({run:M.data?.run||null,blackboard:E.data?.blackboard||null})})]}):null})]})}const Bo={Activity:Ei,Archive:qi,ArrowLeftToLine:$i,ArrowUpCircle:Ri,BadgeCheck:Mi,Binary:Ti,Bug:Pi,BugPlay:Ai,Bot:Ii,BookOpen:Ci,Check:Si,ClipboardList:_i,Clock:ki,Clock3:Ni,Copy:xi,CopyPlus:wi,ExternalLink:vi,Cpu:yi,Database:bi,Download:fi,FileUp:gi,Filter:hi,FilterX:pi,FlaskConical:mi,FolderOpen:ui,History:di,Home:ci,Info:li,KeyRound:oi,Link:ii,LoaderCircle:si,List:ri,LogOut:ni,MessageCircle:ai,MessageSquare:ti,MessagesSquare:ei,Menu:Zs,MonitorCog:Xs,Paperclip:Ys,Package:Vs,PaintBucket:zs,Pencil:Gs,Play:Hs,PlugZap:Qs,Plus:Js,Pause:Ws,Radio:Ks,RefreshCw:Bs,RotateCw:Ls,Save:js,Search:Us,Send:Fs,Settings:Ds,Settings2:Os,ShieldAlert:Es,ShieldCheck:qs,SlidersHorizontal:$s,Sparkles:Rs,Siren:Ms,Share2:Ts,Shield:Ps,Square:As,Trash2:Is,TriangleAlert:Cs,X:Ss,XCircle:_s,Users:ks,Workflow:Ns},Mn=new Set;let Rn=0;function Ko(){Rn=0;const a=[...Mn];Mn.clear();for(const t of a)xs({icons:Bo,attrs:{width:"16",height:"16","stroke-width":"1.8"},...t?{root:t}:{}})}function zt(a){Mn.add(a||null),!Rn&&(Rn=window.requestAnimationFrame(Ko))}Or.setOptions({gfm:!0,breaks:!0});function Na(a){const t=String(a||""),n=Or.parse(t,{async:!1});return Di.sanitize(n)}const $n="tcp.chat.session";function Gr(a){return String(a?.id||a?.session_id||a?.sessionID||"").trim()}function Wo(a){const t=String(a?.title||a?.name||"").trim();if(t)return t;const n=Gr(a);return n?`Session ${n.slice(0,8)}`:"Session"}function Jo(a){return Array.isArray(a)?a:Array.isArray(a?.sessions)?a.sessions:[]}function Qo(a){return String(a?.title||"").trim().toLowerCase().startsWith("__provider_test__")}function ir(a){return Jo(a).filter(t=>!Qo(t)).map(t=>({id:Gr(t),title:Wo(t),raw:t})).filter(t=>!!t.id)}async function Ho(a,t){try{const n=await a.sessions.list({pageSize:50}),r=ir(n);if(r.length>0)return r}catch{}try{const n=await t("/api/engine/session?page_size=50",{method:"GET"});return ir(n)}catch{return[]}}function or(){try{return localStorage.getItem($n)||""}catch{return""}}function Go(a){try{a?localStorage.setItem($n,a):localStorage.removeItem($n)}catch{}}function zo(a){return Array.isArray(a)?a.map(n=>n?typeof n=="string"?n:typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:"":"").filter(Boolean).join(`
3
+ `).trim():""}function Vo(a){return String(a?.info?.role||a?.role||a?.message_role||a?.type||a?.author||"assistant").trim().toLowerCase()}function Yo(a){const t=zo(a?.parts);if(t)return t;const n=[a?.content,a?.text,a?.message,a?.delta,a?.body].map(s=>typeof s=="string"?s:"").find(s=>s.trim().length>0);if(n)return n.trim();const r=a?.content;if(Array.isArray(r)){const s=r.map(l=>l?typeof l=="string"?l:typeof l?.text=="string"?l.text:typeof l?.content=="string"?l.content:"":"").filter(Boolean);if(s.length)return s.join(`
4
+ `).trim()}return""}function Xo(a,t){return a==="assistant"?t||"Assistant":a==="user"?"User":a==="system"?"System":a||"Assistant"}function Zo(a,t,n){const r=Vo(a),s=Yo(a),l=r==="assistant"||r==="system";return{id:String(a?.id||a?.messageID||a?.message_id||a?.event_id||`${r}-${t}`).trim()||`${r}-${t}`,role:r,displayRole:Xo(r,n),text:s,markdown:l}}function zr(a,t){return(Array.isArray(a)?a:Array.isArray(a?.messages)?a.messages:[]).map((r,s)=>Zo(r,s,t))}const lr=new Set(["tool.called","tool_call.started","session.tool_call"]),cr=new Set(["tool.result","tool_call.completed","tool_call.failed","session.tool_result"]),el=new Set(["run.complete","run.completed","session.run.finished","session.run.completed"]),tl=new Set(["run.failed","session.run.failed","run.cancelled","run.canceled","session.run.cancelled","session.run.canceled"]);function Vr(a){return String(a||"").trim().replace(/\s+/g," ").replace(/[<>]/g,"")}function ya(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return Vr(t.tool||t.name||t.toolName||t.tool_id||t.toolID||n.tool||n.name||n.toolName||"")}function Pa(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return String(t.callID||t.toolCallID||t.tool_call_id||t.id||n.callID||n.toolCallID||n.tool_call_id||n.id||"").trim()}function wn(a,t=""){const n=a?.properties||{};return String(a?.runId||a?.runID||a?.run_id||n.runID||n.runId||n.run_id||n.run?.id||t).trim()}function za(a){if(!a)return null;const t=a.request||a.approval||a.permission||{},n=String(a.id||a.requestID||a.requestId||a.approvalID||t.id||t.requestID||"").trim();return n?{id:n,tool:Vr(a.tool||t.tool||t.name||"tool")||"tool",permission:String(a.permission||t.permission||"").trim(),pattern:String(a.pattern||t.pattern||"").trim(),sessionId:String(a.sessionId||a.sessionID||a.session_id||t.sessionId||t.sessionID||"").trim(),status:String(a.status||t.status||"").trim().toLowerCase()}:null}function dr(a){const t=String(a||"").trim().toLowerCase();return t?t.includes("approved")||t.includes("rejected")||t.includes("denied")||t.includes("resolved")||t.includes("expired")||t.includes("cancel")||t.includes("complete")||t.includes("done")||t.includes("timeout")?!1:t.includes("pending")||t.includes("request")||t.includes("ask")||t.includes("await")||t.includes("open")||t.includes("queue")||t.includes("new")||t.includes("progress")||t==="unknown":!0}function al(a,t){const n=t&&typeof t=="object"?t:{},r=String(a||"").trim()||"pack.event",s=String(n.path||"").trim(),l=String(n.attachment_id||n.attachmentId||"").trim(),d=String(n.connector||"").trim(),u=String(n.channel_id||n.channelId||"").trim(),p=String(n.sender_id||n.senderId||"").trim(),k=String(n.name||"").trim(),q=String(n.version||"").trim(),b=String(n.error||"").trim(),w=[];k&&w.push(k),q&&w.push(q),s&&w.push(s),d&&w.push(d),u&&w.push(`channel=${u}`),p&&w.push(`sender=${p}`);const M=w.join(" · ");return{id:`${r}:${l||s||k||"event"}`,type:r,path:s,attachmentId:l,connector:d,channelId:u,senderId:p,error:b,summary:M||r,at:Date.now()}}const Oa=new Map;function Yr(a,t){return`${t?"cred":"anon"}:${a}`}function nl(a,t=!0){const n=Yr(a,t),r=Oa.get(n);if(r&&!r.closed)return r;const s=new EventSource(a,{withCredentials:t}),l={source:s,listeners:new Set,errorListeners:new Set,refs:0,closed:!1};return s.onmessage=d=>{for(const u of[...l.listeners])try{u(d)}catch{}},s.onerror=d=>{for(const u of[...l.errorListeners])try{u(d)}catch{}s.readyState===EventSource.CLOSED&&(l.closed=!0,Oa.delete(n))},Oa.set(n,l),l}function jn(a,t,n={}){const r=n.withCredentials!==!1,s=Yr(a,r),l=nl(a,r);return l.refs+=1,l.listeners.add(t),typeof n.onError=="function"&&l.errorListeners.add(n.onError),()=>{const d=Oa.get(s);d&&(d.listeners.delete(t),typeof n.onError=="function"&&d.errorListeners.delete(n.onError),d.refs=Math.max(0,d.refs-1),d.refs===0&&(d.closed=!0,d.source.close(),Oa.delete(s)))}}const rl="control-panel",Xr="tandem_control_panel_chat_auto_approve_tools",sl="tandem.automations.plannerSeed",il={md:"text/markdown",txt:"text/plain",csv:"text/csv",json:"application/json",pdf:"application/pdf",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function ur(a=""){const t=String(a).toLowerCase().split(".").pop()||"";return il[t]||"application/octet-stream"}function ol(a="",t=""){if(!a||!t)return t||"";const n=String(a).replace(/[\\/]+$/,""),r=String(t).replace(/^[\\/]+/,"");return`${n}/${r}`}function ll(a){const t=Number(a||0);return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function xn(a,t){return!a||!t?!0:String(a).trim()===String(t).trim()}function cl(a){const t=String(a||"").trim();return t!=="server.connected"&&t!=="engine.lifecycle.ready"}function dl(a){return a==="completed"?"chat-tool-chip-ok":a==="failed"?"chat-tool-chip-failed":"chat-tool-chip-running"}function ul(){try{return localStorage.getItem(Xr)==="1"}catch{return!1}}function ml(a){try{localStorage.setItem(Xr,a?"1":"0")}catch{}}function pl(a){try{const t=String(a?.prompt||a?.goal||"").trim();if(!t)return;sessionStorage.setItem(sl,JSON.stringify({prompt:t,plan_source:String(a?.plan_source||"chat_setup").trim()||"chat_setup"}))}catch{}}function ua(a){return a instanceof Error?a.message:String(a)}function hl(a){return a.decision==="pass_through"?null:a.intent_kind==="provider_setup"?{title:"Provider setup",body:`Configure ${a.slots.provider_ids[0]||"a provider"} in Settings.`,cta:"Open Settings",actionType:"open_provider_setup",payload:a.proposed_action.payload||{}}:a.intent_kind==="integration_setup"?{title:"Tool connection",body:`Connect ${a.slots.integration_targets[0]||"the matching tool"} through MCP.`,cta:"Open MCP",actionType:"open_mcp_setup",payload:a.proposed_action.payload||{}}:a.intent_kind==="automation_create"?{title:"Automation setup",body:a.slots.goal||"Create an automation from this request.",cta:"Open Automations",actionType:"open_automations",payload:a.proposed_action.payload||{}}:{title:"Setup help",body:a.clarifier?.question||"Choose a setup path.",cta:"Open Settings",actionType:"open_provider_setup",payload:a.proposed_action.payload||{},clarifier:a.clarifier||void 0}}function gl({client:a,api:t,toast:n,providerStatus:r,identity:s,navigate:l}){const d=jt(),u=!!Er(),p=pt(null),k=pt(null),q=pt(null),b=pt(null),w=pt(null),M=pt(!0),E=pt(null),K=pt(null),[B,se]=y([]),[G,ge]=y(!1),[N,W]=y(or()),[J,S]=y([]),[fe,f]=y(!1),[D,de]=y(""),[$e,Y]=y([]),[U,ie]=y([]),[oe,Ue]=y(!1),[_e,P]=y(""),[te,ve]=y(!1),[Se,V]=y([]),[Ne,me]=y(new Set),[Ee,F]=y([]),[De,le]=y(new Set),[ae,nt]=y([]),[et,Ge]=y(new Set),[Xe,ct]=y(ul()),[bt,dt]=y(!1),[Te,ze]=y([]),[rt,tt]=y(null),[Ve,st]=y(null),yt=H(()=>B.find(L=>L.id===N)?.title||"Chat",[N,B]);ye(()=>(M.current=!0,()=>{M.current=!1,w.current?.abort(),E.current&&window.clearTimeout(E.current),K.current&&window.clearTimeout(K.current)}),[]),ye(()=>{const g=p.current;g&&zt(g)},[B,$e,U,ae,Se,Ee,J,G,te,_e]),ye(()=>{Go(N)},[N]),ye(()=>{const g=k.current;g&&(g.style.height="0px",g.style.height=`${Math.min(g.scrollHeight,180)}px`)},[D]),ye(()=>{const g=b.current;g&&(g.scrollTop=g.scrollHeight)},[J,_e,te]);const pe=Je(async()=>{const g=await Ho(a,t);M.current&&(se(g),W(L=>{if(L&&g.some(j=>j.id===L))return L;const A=or();return A&&g.some(j=>j.id===A)?A:g[0]?.id||""}))},[t,a]),Ce=Je(async()=>{const g=String(r.defaultProvider||"").trim(),L=String(r.defaultModel||"").trim();if(g&&L)return{providerID:g,modelID:L};try{const A=await a.providers.config(),j=String(A?.default||"").trim(),O=String(A?.providers?.[j]?.defaultModel||"").trim();if(j&&O)return{providerID:j,modelID:O}}catch{}return null},[a.providers,r.defaultModel,r.defaultProvider]),at=Je(async()=>{const g=await Ce(),L={title:`Chat ${new Date().toLocaleTimeString()}`};g&&(L.provider=g.providerID,L.model=g.modelID);const A=await a.sessions.create(L),j=String(A||"").trim();if(!j)throw new Error("Failed to create session.");return W(j),await pe(),j},[a.sessions,pe,Ce]),ce=Je(g=>{const L=zr(g,s.botName||"Assistant");S(L)},[s.botName]),Le=Je(async()=>{if(!N){S([]);return}f(!0);try{const g=await a.sessions.messages(N).catch(()=>({messages:[]}));if(!M.current)return;ce(g)}finally{M.current&&f(!1)}},[a.sessions,ce,N]),ut=Je(()=>{V([]),me(new Set)},[]),v=Je(()=>{F([]),le(new Set)},[]),C=Je((g,L,A="")=>{const j=String(g||"").trim();if(!j)return;let O=!0;A&&(me(re=>{if(re.has(A))return O=!1,re;const Oe=new Set(re);return Oe.add(A),Oe.size>1e3?new Set([A]):Oe}),!O)||V(re=>[{id:`${j}:${L}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:j,status:L,at:Date.now()},...re].slice(0,80))},[]),z=Je((g,L)=>{const A=al(g,L);if(!String(A.type).toLowerCase().startsWith("pack."))return;let O=!0;le(re=>{if(re.has(A.id))return O=!1,re;const Oe=new Set(re);return Oe.add(A.id),Oe.size>400?new Set([A.id]):Oe}),O&&F(re=>[A,...re].slice(0,80))},[]),m=Je(g=>{dr(g?.status||"")&&nt(L=>{const A=L.findIndex(j=>j.id===g.id);if(A>=0){const j=[...L];return j[A]={...j[A],...g},j}return[g,...L]})},[]),X=Je(g=>{nt(L=>L.filter(A=>A.id!==g))},[]),we=Je(async()=>{const g=await a.permissions.list().catch(()=>({requests:[]})),A=(Array.isArray(g?.requests)?g.requests:[]).map(j=>za(j)).filter(j=>!!j).filter(j=>xn(j.sessionId,N)).filter(j=>dr(j.status));M.current&&nt(A.slice(0,80))},[a.permissions,N]),T=Je(async(g,L,A=!1)=>{if(!(!g||et.has(g))){Ge(O=>{const re=new Set(O);return re.add(g),re});try{await a.permissions.reply(g,L),X(g),A||n("ok",`Permission ${L==="deny"?"denied":"approved"} (${g}).`)}catch(O){A||n("err",ua(O))}finally{Ge(O=>{const re=new Set(O);return re.delete(g),re}),we()}}},[a.permissions,et,we,X,n]),I=Je(async()=>{if(!(!Xe||bt||ae.length===0)){dt(!0);try{for(const g of[...ae])await T(g.id,"always",!0)}finally{M.current&&dt(!1)}}},[Xe,bt,ae,T]),lt=Je(g=>(Array.isArray(g)?g:Array.isArray(g?.tools)?g.tools:[]).map(A=>{if(typeof A=="string")return A;const j=A||{};return String(j.name||j.id||j.tool||"").trim()}).filter(Boolean),[]),ht=Je(async()=>{try{const g=await a.listTools?.().catch(()=>null);let L=lt(g||[]);if(!L.length){const A=await t("/api/engine/tool",{method:"GET"}).catch(()=>[]);L=lt(A||[])}if(M.current){const A=[...new Set(L)].sort((j,O)=>j.localeCompare(O));ze(A)}}catch{M.current&&ze([])}},[t,a,lt]),Tt=Je(g=>new Promise((L,A)=>{const j=`${Date.now()}-${Math.random().toString(16).slice(2)}`;ie(re=>[...re,{id:j,name:g.name,progress:0,error:""}]);const O=new XMLHttpRequest;O.open("POST",`/api/files/upload?dir=${encodeURIComponent(rl)}`),O.withCredentials=!0,O.responseType="json",O.setRequestHeader("x-file-name",encodeURIComponent(g.name)),O.upload.onprogress=re=>{if(!re.lengthComputable)return;const Oe=re.loaded/re.total*100;ie(We=>We.map(i=>i.id===j?{...i,progress:Oe}:i))},O.onerror=()=>{ie(re=>re.map(Oe=>Oe.id===j?{...Oe,error:"Network error"}:Oe)),window.setTimeout(()=>{ie(re=>re.filter(Oe=>Oe.id!==j))},1200),A(new Error(`Upload failed: ${g.name}`))},O.onload=()=>{const re=O.response||{};if(O.status<200||O.status>=300||re?.ok===!1){const Oe=String(re?.error||`Upload failed (${O.status})`);ie(We=>We.map(i=>i.id===j?{...i,error:Oe}:i)),window.setTimeout(()=>{ie(We=>We.filter(i=>i.id!==j))},1600),A(new Error(Oe));return}ie(Oe=>Oe.filter(We=>We.id!==j)),L(re)},O.send(g)}),[]),Bt=Je(async g=>{const L=[...g||[]];if(!L.length)return;let A=0;for(const j of L)try{const O=await Tt(j);Y(re=>[{name:String(O?.name||j.name),path:String(O?.path||j.name),size:Number(O?.size||j.size||0),mime:j.type||ur(String(O?.name||j.name)),url:String(O?.absPath||ol(O?.root,O?.path)||O?.path||j.name)},...re]),A+=1}catch(O){n("err",ua(O))}A>0&&n("ok",`Uploaded ${A} file${A===1?"":"s"}.`)},[n,Tt]),ea=Je(async g=>{if(await a.sessions.delete(g),se(L=>L.filter(A=>A.id!==g)),tt(null),n("ok","Session deleted."),N===g){const L=B.find(A=>A.id!==g)?.id||"";if(L)W(L);else{const A=await at();W(A)}}},[a.sessions,at,N,B,n]),wt=Je((g,L)=>{const A=String(g||"").trim();if(!A)return;const j=L>0?`
5
+
6
+ ${L} attachment${L===1?"":"s"}`:"";S(O=>[...O,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",displayRole:"User",text:`${A}${j}`,markdown:!1}])},[]),Kt=Je(async()=>{if(oe)return;const g=D.trim(),L=[...$e],A=g||(L.length?"Please analyze the attached file(s).":"");if(A){try{const j=await t("/api/engine/setup/understand",{method:"POST",body:JSON.stringify({surface:"control_panel_chat",session_id:N||void 0,text:A,channel:null,trigger:{source:"direct_message",is_direct_message:!0,was_explicitly_mentioned:!1,is_reply_to_bot:!1},scope:{kind:"direct",id:N||"control-panel-chat"}})});if(j.decision!=="pass_through"){const O=hl(j);if(O){st(O),de("");return}}}catch{}de(""),Ue(!0),wt(A,L.length);try{let j=N;if(j||(j=await at()),!j)throw new Error("No active session.");const O=await Ce();if(!O)throw new Error("No default provider/model configured. Set it in Settings before sending chat.");const re=L.map(ke=>({type:"file",mime:ke.mime||ur(ke.name||ke.path),filename:ke.name||ke.path||"attachment",url:ke.url||ke.path}));re.push({type:"text",text:A});const Oe=async()=>{const ke=await fetch(`/api/engine/session/${encodeURIComponent(j)}/run`,{method:"GET",credentials:"include"});if(!ke.ok)return"";const Z=await ke.json().catch(()=>({}));return Z?.active?.runID||Z?.active?.runId||Z?.active?.run_id||""},We=async()=>{const ke=await Oe().catch(()=>"");ke&&await fetch(`/api/engine/session/${encodeURIComponent(j)}/run/${encodeURIComponent(ke)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent(j)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{});for(let Z=0;Z<50;Z+=1){if(!await Oe().catch(()=>""))return!0;await new Promise(Re=>window.setTimeout(Re,200))}return!1},i=async()=>fetch(`/api/engine/session/${encodeURIComponent(j)}/prompt_async?return=run`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({parts:re,model:{providerID:O.providerID,modelID:O.modelID}})});let c=await i(),_="";if(c.status===409){if(!await We())throw new Error("Session has a stuck active run. Cancel it and retry.");if(c=await i(),c.ok){const Z=await c.json().catch(()=>({}));_=Z?.runID||Z?.runId||Z?.run_id||""}else{if(c.status===409)throw new Error("Session is still busy with another run. Retry in a moment.");{const Z=await c.text().catch(()=>"");throw new Error(`prompt_async retry failed (${c.status}): ${Z}`)}}}else if(c.ok){const ke=await c.json().catch(()=>({}));_=ke?.runID||ke?.runId||ke?.run_id||""}else{const ke=await c.text().catch(()=>"");throw new Error(`prompt_async failed (${c.status}): ${ke}`)}if(!_)throw new Error("No run ID returned from engine.");L.length&&Y([]),P(""),ve(!0);const $=new AbortController;w.current?.abort(),w.current=$;let ue=!1,Qe=!1,gt="";const Mt=3e4,Et=18e4,xt=async(ke,Z)=>{const ft=Date.now();for(;Date.now()-ft<Z;){const Re=await Oe().catch(()=>ke);if(await Le(),!Re||Re!==ke)return!0;await new Promise(Fe=>window.setTimeout(Fe,350))}return!1},Rt=()=>{E.current&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{Qe=!0,gt="no-events-timeout",$.abort("no-events-timeout")},Mt)};Rt(),K.current&&window.clearTimeout(K.current),K.current=window.setTimeout(()=>{Qe=!0,gt="max-stream-window",$.abort("max-stream-window")},Et);try{for await(const ke of a.stream(j,_,{signal:$.signal})){const Z=ke;if(cl(Z.type)&&Rt(),Z.type==="approval.requested"||Z.type==="permission.request"||Z.type==="permission.asked"){const Re=za(Z.properties||{});Re&&xn(Re.sessionId,j)?(m(Re),I()):we()}if(Z.type==="approval.resolved"||Z.type==="permission.resolved"||Z.type==="permission.replied"){const Re=za(Z.properties||{});Re?.id&&X(Re.id),we()}String(Z.type||"").toLowerCase().startsWith("pack.")&&z(Z.type,Z.properties||{});const ft=wn(Z);if(!(ft&&ft!==_)){if(Z.type==="session.response"){const Re=String(Z.properties?.delta||"");if(!Re)continue;ue=!0,ve(!1),P(Fe=>`${Fe}${Re}`)}if(lr.has(Z.type)){const Re=ya(Z.properties)||"tool",Fe=Pa(Z.properties);C(Re,"started",`${Fe||ft||_}:${Re}:started`)}if(cr.has(Z.type)){const Re=ya(Z.properties)||"tool",Fe=Pa(Z.properties),Nt=String(Z.properties?.status||Z.properties?.state||"").toLowerCase(),Lt=Z.type==="tool_call.failed"||Nt.includes("fail")||Nt.includes("error")||!!Z.properties?.error;C(Re,Lt?"failed":"completed",`${Fe||ft||_}:${Re}:${Lt?"failed":"completed"}`)}if(Z.type==="message.part.updated"){const Re=Z.properties?.part||{},Fe=String(Re.type||"").trim().toLowerCase().replace(/_/g,"-"),Nt=ya(Re)||ya(Z.properties),Lt=Pa(Re),mt=Re?.state,It=String((mt&&typeof mt=="object"?mt.status:mt)||Re.status||"").trim().toLowerCase(),oa=!!Re.error||!!(mt&&typeof mt=="object"&&mt.error)||It.includes("fail")||It.includes("error")||It.includes("deny")||It.includes("reject")||It.includes("cancel"),_a=!!Re.result||!!Re.output||!!(mt&&typeof mt=="object"&&(mt.output||mt.result))||It.includes("done")||It.includes("complete")||It.includes("success");if(Nt&&(Fe==="tool"||Fe==="tool-invocation")){const da=oa?"failed":_a?"completed":"started";C(Nt,da,`${Lt||ft||_}:${Nt}:${da}`)}Nt&&Fe==="tool-result"&&C(Nt,oa?"failed":"completed",`${Lt||ft||_}:${Nt}:${oa?"failed":"completed"}`)}if(tl.has(Z.type))throw new Error(String(Z.properties?.error||"Run failed."));if((Z.type==="session.updated"||Z.type==="session.status")&&String(Z.properties?.status||"").toLowerCase()==="idle"||el.has(Z.type))break}}}catch(ke){const Z=String(ke?.message||ke||"").toLowerCase();if(!(Qe||Z.includes("abort")||Z.includes("terminated")||Z.includes("networkerror")))throw ke}finally{E.current&&window.clearTimeout(E.current),K.current&&window.clearTimeout(K.current)}if(Qe){const ke=await xt(_,45e3);if(await Le(),!ke)throw new Error("Run stream timed out and the run is still active. Check logs and retry.")}if(ue||ve(!0),await Le(),await new Promise(ke=>window.setTimeout(ke,180)),await Le(),await new Promise(ke=>window.setTimeout(ke,220)),await Le(),!ue&&await Oe().catch(()=>"")===_)if(await xt(_,3e4))await Le();else throw new Error(`Run ${_} is still active without a final response (${gt||"stream-ended"}).`);P(""),ve(!1),await pe(),await d.invalidateQueries({queryKey:["chat"]}).catch(()=>{})}catch(j){const O=ua(j),re=O.includes("no-events-timeout")||O.includes("max-stream-window")||O.includes("AbortError")||O.toLowerCase().includes("terminated")?"Run stream timed out before events were received. Check engine/provider logs and retry.":O;n("err",re),await Le()}finally{M.current&&(Ue(!1),ve(!1))}}},[t,wt,I,a,at,D,d,z,C,Le,we,pe,X,Ce,N,oe,n,$e,m]);ye(()=>{pe(),ht();const g=async()=>{const A=await at().catch(()=>"");A&&W(A),ge(!1)};window.addEventListener("tcp:new-chat",g);const L=window.setInterval(()=>{pe()},8e3);return()=>{window.removeEventListener("tcp:new-chat",g),window.clearInterval(L)}},[at,ht,pe]),ye(()=>{N&&(w.current?.abort(),ge(!1),ut(),v(),we(),Le())},[Le,we,v,ut,N]),ye(()=>{N||S([])},[N]),ye(()=>{!N&&B.length===0&&at().catch(()=>{})},[at,N,B.length]),ye(()=>{ml(Xe),Xe&&I()},[Xe,I]),ye(()=>{const g=window.setInterval(()=>{N&&we()},2500);return()=>window.clearInterval(g)},[we,N]),ye(()=>{const g=jn("/api/global/event",L=>{let A=null;try{A=JSON.parse(String(L.data||"{}"))}catch{return}const j=String(A?.type||"").trim();if(!j)return;const O=A?.properties||{},re=za(O);if(re&&xn(re.sessionId,N)&&((j==="approval.requested"||j==="permission.request"||j==="permission.asked")&&m(re),(j==="approval.resolved"||j==="permission.resolved"||j==="permission.replied")&&X(re.id)),j.toLowerCase().startsWith("pack.")&&z(j,O),lr.has(j)){const Oe=ya(O)||"tool",We=Pa(O),i=wn(A,"global");C(Oe,"started",`${We||i}:${Oe}:started`)}if(cr.has(j)){const Oe=ya(O)||"tool",We=Pa(O),i=wn(A,"global"),c=String(O?.status||O?.state||"").toLowerCase(),_=j==="tool_call.failed"||c.includes("fail")||!!O?.error;C(Oe,_?"failed":"completed",`${We||i}:${Oe}:${_?"failed":"completed"}`)}},{withCredentials:!0});return()=>g()},[z,C,X,N,m]);const ia=$e.length;return e("div",{ref:p,className:"chat-layout chat-layout-fill min-w-0 min-h-0 h-full flex-1",children:[e(xe.aside,{className:`chat-sessions-panel ${G?"open":""}`,initial:!1,animate:u?{x:G?0:"-104%"}:{x:G?0:"-104%",transition:{duration:.18,ease:"easeOut"}},children:[e("div",{className:"chat-sessions-header",children:[e("h3",{className:"chat-sessions-title",children:[e("i",{"data-lucide":"history"}),"Sessions"]}),e("div",{className:"flex items-center gap-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{at().catch(g=>n("err",ua(g))),ge(!1)},children:[e("i",{"data-lucide":"plus"}),"New"]}),e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{pe()},children:e("i",{"data-lucide":"refresh-cw"})})]})]}),e("div",{className:"chat-session-list",children:[e(ot,{children:B.map(g=>e(xe.div,{className:"chat-session-row",initial:u?!1:{opacity:0,y:6},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-6},children:[e("button",{type:"button",className:`chat-session-btn ${g.id===N?"active":""}`,title:g.id,onClick:()=>{W(g.id),ge(!1)},children:e("span",{className:"block truncate",children:g.title})}),e("button",{type:"button",className:"chat-session-del",title:"Delete session",onClick:()=>tt({id:g.id,title:g.title}),children:e("i",{"data-lucide":"trash-2"})})]},g.id))}),B.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No sessions yet."})]})]}),e(ot,{children:G?e(xe.button,{type:"button",className:"chat-scrim open","aria-label":"Close sessions",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>ge(!1)}):null}),e("div",{className:"chat-workspace min-h-0 min-w-0",children:[e("section",{className:"chat-main-shell flex min-h-0 min-w-0 flex-col overflow-hidden",children:[e("header",{className:"chat-main-header shrink-0",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Sessions",onClick:()=>ge(g=>!g),children:e("i",{"data-lucide":"history"})}),e("div",{className:"chat-main-dot"}),e("h3",{className:"tcp-title chat-main-title",children:yt}),Te.length?e("span",{className:"chat-main-tools",children:[Te.length," tools"]}):null]}),Ve?e("div",{className:"mx-3 mb-2 rounded-xl border border-amber-500/30 bg-amber-500/8 p-3",children:[e("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"tcp-title text-sm",children:Ve.title}),e("div",{className:"tcp-subtle text-sm",children:Ve.body})]}),e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>st(null),children:"Dismiss"})]}),Ve.clarifier?e("div",{className:"mb-2 flex flex-wrap gap-2",children:Ve.clarifier.options.map(g=>e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>st({title:g.id==="provider_setup"?"Provider setup":g.id==="integration_setup"?"Tool connection":"Automation setup",body:g.id==="provider_setup"?"Open Settings to configure a provider.":g.id==="integration_setup"?"Open MCP to connect the tool you need.":"Open Automations to build the workflow.",cta:g.id==="provider_setup"?"Open Settings":g.id==="integration_setup"?"Open MCP":"Open Automations",actionType:g.id==="provider_setup"?"open_provider_setup":g.id==="integration_setup"?"open_mcp_setup":"open_automations",payload:Ve.payload}),children:g.label},g.id))}):null,e("button",{type:"button",className:"tcp-btn",onClick:()=>{Ve.actionType==="open_provider_setup"?l("settings"):Ve.actionType==="open_mcp_setup"?l("mcp"):Ve.actionType==="open_automations"&&(pl(Ve.payload),l("automations"))},children:Ve.cta})]}):null,e("div",{ref:b,className:"chat-messages mb-2 min-h-0 min-w-0 flex-1 space-y-2 overflow-auto p-3",children:[fe&&!J.length?e("p",{className:"chat-rail-empty",children:"Loading messages..."}):null,!fe&&!J.length&&!te&&!_e?e("p",{className:"chat-rail-empty",children:"No messages yet. Send a prompt to start."}):null,e(ot,{initial:!1,children:J.map(g=>{const L=g.role==="assistant"||g.role==="system",A=L?"assistant":"user";return e(xe.article,{className:`chat-msg ${A}`,initial:u?!1:{opacity:0,y:4},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-4},children:[e("div",{className:"chat-msg-role",children:L?e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:g.displayRole})]}):g.displayRole}),g.markdown?e("div",{className:"tcp-markdown tcp-markdown-ai",dangerouslySetInnerHTML:{__html:Na(g.text||"")}}):e("pre",{className:"chat-msg-pre",children:g.text})]},g.id)})}),te||_e?e("article",{className:"chat-msg assistant",children:[e("div",{className:"chat-msg-role",children:e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:s.botName||"Assistant"})]})}),te&&!_e?e("div",{className:"tcp-thinking","aria-live":"polite",children:[e("span",{children:"Thinking"}),e("i",{}),e("i",{}),e("i",{})]}):null,_e?e("pre",{className:"chat-msg-pre",children:_e}):null]}):null]}),e("div",{className:"chat-composer shrink-0",children:[e("div",{className:`chat-attach-row mb-2 ${ia?"":"hidden"}`,children:[e("span",{className:"tcp-subtle",children:[ia," attached"]}),e("div",{className:"chat-files-line",children:$e.map((g,L)=>e("span",{className:"chat-file-pill min-w-0",children:[e("span",{className:"chat-file-pill-name",title:g.path,children:g.path}),e("span",{className:"chat-file-pill-size",children:ll(g.size)}),e("button",{type:"button",className:"chat-file-pill-btn chat-file-pill-btn-danger",title:"Remove from list",onClick:()=>Y(A=>A.filter((j,O)=>O!==L)),children:e("i",{"data-lucide":"x"})})]},`${g.path}-${L}`))})]}),U.length?e("div",{className:"mb-2 grid gap-1.5",children:U.map(g=>{const L=Math.max(0,Math.min(100,Number(g.progress||0)));return e("div",{className:"chat-upload-card",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2 text-xs",children:[e("span",{className:"chat-upload-name truncate",children:g.name}),e("span",{className:g.error?"chat-upload-meta-error":"chat-upload-meta",children:g.error||`${L.toFixed(0)}%`})]}),e("div",{className:"chat-upload-bar",children:e("div",{className:"chat-upload-bar-fill",style:{width:`${L}%`}})})]},g.id)})}):null,e("div",{className:"chat-input-wrap",children:[e("input",{ref:q,type:"file",className:"hidden",multiple:!0,onChange:g=>{Bt(g.target.files),g.target.value=""}}),e("button",{type:"button",className:"chat-icon-btn chat-icon-btn-inner",title:"Attach files",onClick:()=>q.current?.click(),children:e("i",{"data-lucide":"paperclip"})}),e("textarea",{ref:k,rows:1,value:D,className:"tcp-input chat-input-with-clip chat-input-modern resize-none",placeholder:"Ask anything... (Enter to send, Shift+Enter newline)",onInput:g=>de(g.target.value),onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),Kt())}}),e("button",{type:"button",className:"chat-send-btn",title:"Send",disabled:oe,onClick:()=>{Kt()},children:e("i",{"data-lucide":"send"})})]})]})]}),e("aside",{className:"chat-right-rail hidden min-h-0 flex-col gap-3 overflow-hidden xl:flex",children:[e("section",{className:"min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tools"}),e("span",{className:"chat-rail-count",children:Te.length})]}),e("div",{className:"chat-tools-list",children:Te.length?Te.slice(0,32).map(g=>e("button",{type:"button",className:"chat-tool-pill",title:`Insert ${g}`,onClick:()=>{de(L=>L.trim()?`${L} ${g}`:g),k.current?.focus()},children:g},g)):e("p",{className:"chat-rail-empty",children:"No tools loaded."})})]}),e("section",{className:"min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Approvals"}),e("span",{className:"chat-rail-count",children:ae.length})]}),e("div",{className:"mb-2 flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",disabled:!ae.length||bt,onClick:async()=>{const g=ae.map(A=>A.id).filter(Boolean);if(!g.length)return;for(const A of g)await T(A,"once",!0);await we();const L=g.filter(A=>ae.some(j=>String(j.id||"").trim()===A)).length;L>0?n("warn",`${L} request${L===1?"":"s"} still pending (likely stale/expired).`):n("ok",`Approved ${g.length} pending request${g.length===1?"":"s"}.`)},children:"Approve all"}),e("label",{className:"chat-auto-approve-label",children:[e("input",{type:"checkbox",className:"chat-auto-approve-checkbox",checked:Xe,onChange:g=>ct(g.target.checked)}),"Auto"]})]}),e("div",{className:"chat-tools-activity",children:ae.length?ae.slice(0,20).map(g=>{const L=et.has(g.id),A=[g.permission,g.pattern].filter(Boolean).join(" ");return e("article",{className:"chat-pack-event-card",children:[e("div",{className:"chat-pack-event-title truncate",title:g.id,children:g.tool}),e("div",{className:"chat-pack-event-summary mt-0.5",children:A||g.id}),e("div",{className:"mt-1 flex gap-1",children:[e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:L,onClick:()=>{T(g.id,"once")},children:"Allow"}),e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:L,onClick:()=>{T(g.id,"always")},children:"Always"}),e("button",{className:"tcp-btn-danger h-6 px-1.5 text-[10px]",disabled:L,onClick:()=>{T(g.id,"deny")},children:"Deny"})]})]},g.id)}):e("p",{className:"chat-rail-empty",children:"No pending approvals."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Pack Events"}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:"chat-rail-count",children:Ee.length}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:()=>{v()},children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]})]}),e("div",{className:"chat-tools-activity",children:Ee.length?Ee.slice(0,20).map(g=>e(xe.article,{className:"chat-pack-event-card",initial:u?!1:{opacity:0,y:6},animate:u?void 0:{opacity:1,y:0},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"chat-pack-event-title truncate",title:g.type,children:g.type}),e("span",{className:"chat-pack-event-time",children:new Date(g.at).toLocaleTimeString()})]}),e("div",{className:"chat-pack-event-summary mt-0.5",children:g.summary}),g.error?e("div",{className:"chat-pack-event-error mt-1",children:g.error}):null,e("div",{className:"mt-1 flex flex-wrap gap-1",children:[e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:()=>l("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Packs"]}),g.path?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const L=await t("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:g.path,source:{kind:"control_panel_chat",event:"pack.detected"}})});n("ok",`Installed ${L?.installed?.name||"pack"} ${L?.installed?.version||""}`.trim())}catch(L){n("err",`Install failed: ${ua(L)}`)}},children:[e("i",{"data-lucide":"download"}),"Install path"]}):null,g.path&&g.attachmentId?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const L=await t("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:g.attachmentId,path:g.path,connector:g.connector||void 0,channel_id:g.channelId||void 0,sender_id:g.senderId||void 0})});n("ok",`Installed ${L?.installed?.name||"pack"} ${L?.installed?.version||""}`.trim())}catch(L){n("err",`Install failed: ${ua(L)}`)}},children:[e("i",{"data-lucide":"paperclip"}),"Install attach"]}):null]})]},`${g.id}-${g.at}`)):e("p",{className:"chat-rail-empty",children:"No pack events yet."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tool Activity"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:ut,children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]}),e("div",{className:"chat-tools-activity",children:Se.length?Se.slice(0,24).map(g=>e("div",{className:`chat-tool-chip ${dl(g.status)}`,children:[g.tool,": ",g.status]},g.id)):e("p",{className:"chat-rail-empty",children:"No tool events yet."})})]})]})]}),e(ot,{children:rt?e(xe.div,{className:"tcp-confirm-overlay",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>tt(null),children:e(xe.div,{className:"tcp-confirm-dialog",initial:u?!1:{opacity:0,y:8,scale:.98},animate:u?void 0:{opacity:1,y:0,scale:1},exit:u?void 0:{opacity:0,y:6,scale:.98},onClick:g=>g.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Delete session"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:rt.title})," and all its messages."]}),e("div",{className:"tcp-confirm-actions",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>tt(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{type:"button",className:"tcp-btn-danger",onClick:()=>{ea(rt.id).catch(g=>n("err",ua(g)))},children:[e("i",{"data-lucide":"trash-2"}),"Delete session"]})]})]})}):null})]})}function Zr(a){const t=String(a||"").trim().toLowerCase();return t==="assigned"?"assigned":t==="validated"?"validated":t==="in_progress"||t==="running"?"in_progress":t==="done"||t==="completed"?"done":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"failed":t==="blocked"?"blocked":t==="runnable"||t==="ready"?"runnable":t==="created"?"created":"pending"}function fl(a){const t={};for(const n of Array.isArray(a)?a:[]){const r=String(n?.step_id||n?.payload?.task_id||"").trim();if(!r)continue;const s=n?.payload&&typeof n.payload=="object"?n.payload:{},l=t[r]||{assignedRole:"",errorMessage:"",runtimeDetail:"",runtimeStatus:"",sessionId:""};t[r]={assignedRole:String(s?.assigned_agent||s?.agent_id||l.assignedRole||""),errorMessage:String(s?.error||l.errorMessage||""),runtimeDetail:String(s?.why_next_step||l.runtimeDetail||""),runtimeStatus:String(s?.step_status||l.runtimeStatus||""),sessionId:String(s?.session_id||l.sessionId||"")}}return t}function bl(a,t){const n=Zr(a?.status);return{id:String(a?.id||""),title:String(a?.payload?.title||a?.task_type||a?.id||"Untitled task"),description:String(a?.payload?.description||""),dependencies:Array.isArray(a?.depends_on_task_ids)?a.depends_on_task_ids.map(r=>String(r||"")).filter(Boolean):[],state:n,retry_count:Number(a?.attempt||a?.retry_count||0),error_message:n==="failed"||n==="blocked"?String(a?.last_error||t?.errorMessage||""):"",runtime_status:String(t?.runtimeStatus||""),runtime_detail:String(t?.runtimeDetail||""),assigned_role:String(a?.assigned_agent||a?.lease_owner||t?.assignedRole||""),workflow_id:String(a?.workflow_id||""),session_id:String(t?.sessionId||"")}}function yl(a,t){const n=Zr(a?.stepStatus||a?.status);return{id:String(a?.taskId||a?.step_id||""),title:String(a?.title||a?.step_id||"Untitled step"),description:String(a?.description||""),dependencies:Array.isArray(a?.dependsOn)?a.dependsOn.map(r=>String(r||"")).filter(Boolean):[],state:n,retry_count:Number(a?.retry_count||0),error_message:n==="failed"||n==="blocked"?String(a?.error_message||t?.errorMessage||""):"",runtime_status:String(a?.runtime_status||t?.runtimeStatus||""),runtime_detail:String(a?.runtime_detail||t?.runtimeDetail||""),assigned_role:String(a?.assignedAgent||t?.assignedRole||""),workflow_id:String(a?.workflowId||""),session_id:String(a?.sessionId||a?.session_id||t?.sessionId||"")}}function es(a){const t=fl(a?.events),n=Array.isArray(a?.run?.tasks)?a.run.tasks:[],r=n.length?n:Array.isArray(a?.blackboard?.tasks)?a.blackboard.tasks:[],s=Array.isArray(a?.tasks)?a.tasks:[],l=r.map(b=>bl(b,t[String(b?.id||"").trim()])).filter(b=>b.id),d=s.map(b=>yl(b,t[String(b?.taskId||b?.step_id||"").trim()])).filter(b=>b.id),u=new Map;for(const b of l)u.set(b.id,b);for(const b of d){if(!u.has(b.id)){u.set(b.id,b);continue}const w=u.get(b.id);w&&u.set(b.id,{...w,session_id:w.session_id||b.session_id,runtime_status:w.runtime_status||b.runtime_status,runtime_detail:w.runtime_detail||b.runtime_detail,assigned_role:w.assigned_role||b.assigned_role,error_message:w.error_message||b.error_message})}const p=[...u.values()],k=String(a?.run?.current_step_id||"").trim()||p.find(b=>b.state==="in_progress"||b.state==="assigned")?.id||"",q=l.length?d.length?"hybrid":(n.length,"blackboard"):d.length?"context_steps":"empty";return{currentTaskId:k,taskSource:q,tasks:p}}const vl={created:"Created",pending:"Pending",runnable:"Runnable",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"};function wl(a){return a==="done"||a==="validated"?"tcp-badge-ok":a==="failed"?"tcp-badge-err":a==="in_progress"||a==="runnable"||a==="assigned"?"tcp-badge-warn":"tcp-badge-info"}function xl(a){return a==="in_progress"||a==="assigned"?e("i",{"data-lucide":"loader-circle",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null}function mr({task:a,isCurrent:t,isSelected:n,workflowSummary:r,onTaskSelect:s,onRetryTask:l}){const[d,u]=y(!1),p=a.state==="failed"||a.state==="blocked"?String(a.error_message||"").trim():"";return e("div",{className:`cursor-pointer rounded-lg border p-2 ${n?"border-cyan-400/70 bg-cyan-950/20":t?"border-amber-400/70":"border-slate-700/60 bg-slate-900/20"}`,onClick:()=>s?.(a),children:[e("div",{className:"mb-1 flex items-start justify-between gap-2",children:[e("div",{className:"line-clamp-6 text-xs font-medium leading-snug",title:a.title,children:a.title}),e("span",{className:`${wl(a.state)} inline-flex shrink-0 items-center gap-1`,children:[xl(a.state),e("span",{children:vl[a.state]})]})]}),a.description?e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:a.description}):null,a.assigned_role||a.gate?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[a.assigned_role?e("span",{className:"rounded border border-cyan-600/50 bg-cyan-950/30 px-1.5 py-0.5",children:["role: ",a.assigned_role]}):null,a.gate?e("span",{className:"rounded border border-amber-600/50 bg-amber-950/30 px-1.5 py-0.5",children:["gate: ",a.gate]}):null]}):null,r&&r.runs>0?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[e("span",{className:"rounded border border-indigo-600/50 bg-indigo-950/30 px-1.5 py-0.5",children:["workflow runs: ",r.runs]}),r.failed>0?e("span",{className:"rounded border border-rose-600/50 bg-rose-950/30 px-1.5 py-0.5 text-rose-200",children:["workflow failed: ",r.failed]}):null]}):null,p?e("div",{className:"mt-1 text-xs text-rose-300",children:[e("div",{className:d?"whitespace-pre-wrap break-words":"line-clamp-2",children:p}),p.length>130?e("button",{className:"tcp-btn mt-1 h-6 px-2 text-[11px]",onClick:()=>u(k=>!k),children:d?"Less":"More"}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-1",children:[a.dependencies.slice(0,2).map(k=>e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["<-"," ",k]},k)),a.dependencies.length>2?e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["+",a.dependencies.length-2," more"]}):null]}),e("div",{className:"mt-2 tcp-subtle text-[10px]",children:"Details"}),a.state==="failed"&&l?e("button",{className:"tcp-btn mt-2 h-7 px-2 text-xs",onClick:k=>{k.stopPropagation(),l(a)},children:"Retry Task"}):null]})}function ts({tasks:a,currentTaskId:t,selectedTaskId:n,workflowSummaryByTaskId:r,onTaskSelect:s,onRetryTask:l}){const[d,u]=y("runnable"),p=H(()=>{const b={created:[],pending:[],runnable:[],assigned:[],in_progress:[],blocked:[],done:[],failed:[],validated:[]};for(const K of a)b[K.state].push(K);const w=new Set([...b.done,...b.validated].map(K=>K.id)),M=[...b.runnable],E=[];for(const K of[...b.created,...b.pending])K.dependencies.length===0||K.dependencies.every(se=>w.has(se))?M.push(K):E.push(K);return{runnable:M,waiting:E,assigned:b.assigned,in_progress:b.in_progress,blocked:b.blocked,done:[...b.done,...b.validated],failed:b.failed}},[a]),k=[{key:"runnable",label:"Ready",tasks:p.runnable},{key:"waiting",label:"Waiting on deps",tasks:p.waiting},{key:"assigned",label:"Assigned",tasks:p.assigned},{key:"in_progress",label:"In Progress",tasks:p.in_progress},{key:"blocked",label:"Blocked",tasks:p.blocked},{key:"done",label:"Done",tasks:p.done},{key:"failed",label:"Failed",tasks:p.failed}],q=H(()=>{const b=k.find(w=>w.tasks.some(M=>M.id===t));return b?b.key:k.find(w=>w.tasks.length>0)?.key||"runnable"},[k,t]);return ye(()=>{u(b=>k.some(w=>w.key===b)?b:q)},[k,q]),a.length?e(qt,{children:[e("div",{className:"grid gap-3 xl:hidden",children:[e("div",{className:"flex gap-2 overflow-x-auto pb-1",children:k.map(b=>{const w=b.key===d;return e("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[11px] font-medium ${w?"border-amber-400/60 bg-amber-400/10 text-amber-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>u(b.key),children:[b.label," (",b.tasks.length,")"]},b.key)})}),k.filter(b=>b.key===d).map(b=>e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-2",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:b.label}),e("div",{className:"tcp-subtle text-xs",children:b.tasks.length})]}),e("div",{className:"grid gap-2",children:[b.tasks.map(w=>e(mr,{task:w,isCurrent:w.id===t,isSelected:w.id===n,workflowSummary:r?.[w.id],onTaskSelect:s,onRetryTask:l},w.id)),b.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},b.key))]}),e("div",{className:"hidden gap-3 xl:grid xl:grid-cols-3",children:k.map(b=>e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-2",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:b.label}),e("div",{className:"tcp-subtle text-xs",children:b.tasks.length})]}),e("div",{className:"grid gap-2",children:[b.tasks.map(w=>e(mr,{task:w,isCurrent:w.id===t,isSelected:w.id===n,workflowSummary:r?.[w.id],onTaskSelect:s,onRetryTask:l},w.id)),b.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},b.key))})]}):e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-4",children:"No tasks yet."})}function ga(a,t,n={}){ye(()=>{if(!(!n.enabled||!a))return jn(a,t,{withCredentials:n.withCredentials})},[t,n.enabled,n.withCredentials,a])}const Nl=`{
7
+ "id": "agentic-design",
8
+ "label": "Agentic Design",
9
+ "description": "Design a multi-agent workflow with explicit orchestration, gates, and operator controls.",
10
+ "blueprint":
11
+ {
12
+ "mission_id": "mission_agentic_design",
13
+ "title": "Agentic system design mission",
14
+ "goal": "Design a multi-agent workflow for a target operation, including orchestration, handoffs, models, tools, and safeguards.",
15
+ "success_criteria":
16
+ [
17
+ "Agent roles and responsibilities are clearly defined",
18
+ "Handoffs, gates, and dependencies are explicit",
19
+ "The design includes observability, stop controls, and repair flow",
20
+ ],
21
+ "shared_context": "This is a design mission, not code generation. Optimize for robust orchestration, role clarity, bounded autonomy, and human trust. Make model/tool choices explicit where they matter.",
22
+ "workspace_root": "",
23
+ "orchestrator_template_id": "",
24
+ "phases":
25
+ [
26
+ { "phase_id": "architecture", "title": "Architecture", "execution_mode": "soft" },
27
+ { "phase_id": "governance", "title": "Governance", "execution_mode": "barrier" },
28
+ ],
29
+ "milestones":
30
+ [
31
+ {
32
+ "milestone_id": "design-basis-ready",
33
+ "title": "Design basis ready",
34
+ "phase_id": "architecture",
35
+ "required_stage_ids": ["role-design", "flow-design"],
36
+ },
37
+ ],
38
+ "team":
39
+ {
40
+ "allowed_template_ids": [],
41
+ "default_model_policy": null,
42
+ "allowed_mcp_servers": [],
43
+ "max_parallel_agents": 4,
44
+ "mission_budget": {},
45
+ "orchestrator_only_tool_calls": false,
46
+ },
47
+ "workstreams":
48
+ [
49
+ {
50
+ "workstream_id": "role-design",
51
+ "title": "Role and agent design",
52
+ "objective": "Define the orchestrator and worker roles with clear responsibilities and escalation boundaries.",
53
+ "role": "architect",
54
+ "prompt": "Design the agent roles for this system. Define the orchestrator, specialized workers, reviewers, testers, and approval actors. Be explicit about what each role owns, when it should escalate, and what outputs it produces.",
55
+ "priority": 1,
56
+ "phase_id": "architecture",
57
+ "lane": "roles",
58
+ "milestone": "design-basis-ready",
59
+ "depends_on": [],
60
+ "input_refs": [],
61
+ "tool_allowlist_override": [],
62
+ "mcp_servers_override": [],
63
+ "output_contract":
64
+ {
65
+ "kind": "report_markdown",
66
+ "summary_guidance": "Agent roster, role boundaries, escalation points, and expected outputs.",
67
+ },
68
+ },
69
+ {
70
+ "workstream_id": "flow-design",
71
+ "title": "Flow and handoff design",
72
+ "objective": "Design the mission graph, dependencies, handoffs, and artifact contracts.",
73
+ "role": "analyst",
74
+ "prompt": "Design the multi-agent workflow graph. Specify phases, dependencies, artifact contracts, fan-out and fan-in points, and where review or approval gates should exist. Make the handoffs explicit and operationally understandable.",
75
+ "priority": 1,
76
+ "phase_id": "architecture",
77
+ "lane": "flow",
78
+ "milestone": "design-basis-ready",
79
+ "depends_on": [],
80
+ "input_refs": [],
81
+ "tool_allowlist_override": [],
82
+ "mcp_servers_override": [],
83
+ "output_contract":
84
+ {
85
+ "kind": "report_markdown",
86
+ "summary_guidance": "Mission graph, dependencies, handoffs, and output contracts.",
87
+ },
88
+ },
89
+ {
90
+ "workstream_id": "governance-design",
91
+ "title": "Governance and safety design",
92
+ "objective": "Define runtime controls, observability, kill switches, and repair mechanisms.",
93
+ "role": "coordinator",
94
+ "prompt": "Design the governance layer for the system. Specify approval gates, model and tool boundaries, logging, token or budget guardrails, kill switch semantics, pause and resume behavior, and step-level repair expectations.",
95
+ "priority": 1,
96
+ "phase_id": "governance",
97
+ "lane": "governance",
98
+ "depends_on": ["role-design", "flow-design"],
99
+ "input_refs": [],
100
+ "tool_allowlist_override": [],
101
+ "mcp_servers_override": [],
102
+ "output_contract":
103
+ {
104
+ "kind": "plan_markdown",
105
+ "summary_guidance": "Safety model, review points, observability, recovery, and operator controls.",
106
+ },
107
+ },
108
+ ],
109
+ "review_stages":
110
+ [
111
+ {
112
+ "stage_id": "design-approval",
113
+ "stage_kind": "approval",
114
+ "title": "Agentic design review",
115
+ "target_ids": ["governance-design"],
116
+ "role": "approver",
117
+ "prompt": "Review the complete agentic design for coherence. Reject designs with unclear role boundaries, missing observability, or unbounded autonomy.",
118
+ "checklist":
119
+ [
120
+ "Role boundaries are clear",
121
+ "Handoffs and gates are explicit",
122
+ "Safety and repair paths are credible",
123
+ ],
124
+ "priority": 1,
125
+ "phase_id": "governance",
126
+ "lane": "approval",
127
+ "tool_allowlist_override": [],
128
+ "mcp_servers_override": [],
129
+ "gate":
130
+ {
131
+ "required": true,
132
+ "decisions": ["approve", "rework", "cancel"],
133
+ "rework_targets": ["governance-design"],
134
+ "instructions": "Use rework if the design lacks control boundaries, clear outputs, or repairability.",
135
+ },
136
+ },
137
+ ],
138
+ "metadata": null,
139
+ },
140
+ }
141
+ `,kl=`{
142
+ "id": "ai-opportunity",
143
+ "label": "AI Opportunities",
144
+ "description": "Map workflow pain points to realistic AI, copilot, and agentic opportunities.",
145
+ "blueprint":
146
+ {
147
+ "mission_id": "mission_ai_opportunity",
148
+ "title": "AI opportunity assessment",
149
+ "goal": "Identify the highest-value AI opportunities in the target business process and produce a prioritized implementation brief.",
150
+ "success_criteria":
151
+ [
152
+ "Workflow bottlenecks and repetitive work are identified",
153
+ "AI opportunities are ranked by value, feasibility, and risk",
154
+ "Final brief recommends concrete next pilots",
155
+ ],
156
+ "shared_context": "Audience is operators and product leadership. Focus on realistic AI leverage, not hype. Separate automation, copilots, and fully agentic opportunities. Flag data, tooling, and approval constraints explicitly.",
157
+ "workspace_root": "",
158
+ "orchestrator_template_id": "",
159
+ "phases":
160
+ [
161
+ { "phase_id": "discovery", "title": "Discovery", "execution_mode": "soft" },
162
+ { "phase_id": "recommendation", "title": "Recommendation", "execution_mode": "barrier" },
163
+ ],
164
+ "milestones":
165
+ [
166
+ {
167
+ "milestone_id": "opportunity-map-ready",
168
+ "title": "Opportunity map ready",
169
+ "phase_id": "discovery",
170
+ "required_stage_ids": ["workflow-analysis", "capability-map"],
171
+ },
172
+ ],
173
+ "team":
174
+ {
175
+ "allowed_template_ids": [],
176
+ "default_model_policy": null,
177
+ "allowed_mcp_servers": [],
178
+ "max_parallel_agents": 4,
179
+ "mission_budget": {},
180
+ "orchestrator_only_tool_calls": false,
181
+ },
182
+ "workstreams":
183
+ [
184
+ {
185
+ "workstream_id": "workflow-analysis",
186
+ "title": "Workflow analysis",
187
+ "objective": "Break down the current workflow, identify friction, handoffs, delays, and repeated manual work.",
188
+ "role": "analyst",
189
+ "prompt": "Act as an AI workflow analyst. Map the current workflow step by step, identify where humans are spending time, where handoffs fail, where decisions bottleneck, and where information must be gathered, transformed, or checked. Produce a workflow analysis memo that distinguishes repetitive work, judgment-heavy work, and coordination-heavy work.",
190
+ "priority": 1,
191
+ "phase_id": "discovery",
192
+ "lane": "workflow",
193
+ "milestone": "opportunity-map-ready",
194
+ "depends_on": [],
195
+ "input_refs": [],
196
+ "tool_allowlist_override": [],
197
+ "mcp_servers_override": [],
198
+ "output_contract":
199
+ {
200
+ "kind": "report_markdown",
201
+ "summary_guidance": "Workflow steps, bottlenecks, repeated work, approval points, and observed failure modes.",
202
+ },
203
+ },
204
+ {
205
+ "workstream_id": "capability-map",
206
+ "title": "AI capability map",
207
+ "objective": "Match workflow problems to realistic AI patterns such as extraction, triage, drafting, routing, review, and autonomous follow-through.",
208
+ "role": "strategist",
209
+ "prompt": "Act as an agentic systems strategist. Review the workflow analysis context and map each major problem to practical AI patterns. Distinguish simple automation, LLM copilots, tool-using agents, and multi-agent orchestration. Be explicit about prerequisites, risks, and where human approval is still required.",
210
+ "priority": 2,
211
+ "phase_id": "discovery",
212
+ "lane": "capability",
213
+ "milestone": "opportunity-map-ready",
214
+ "depends_on": [],
215
+ "input_refs": [],
216
+ "tool_allowlist_override": [],
217
+ "mcp_servers_override": [],
218
+ "output_contract":
219
+ {
220
+ "kind": "report_markdown",
221
+ "summary_guidance": "Problem-to-capability map with candidate AI patterns, prerequisites, and operational risks.",
222
+ },
223
+ },
224
+ {
225
+ "workstream_id": "opportunity-brief",
226
+ "title": "Opportunity brief",
227
+ "objective": "Synthesize the findings into a prioritized AI opportunity brief with clear next pilots.",
228
+ "role": "analyst",
229
+ "prompt": "Synthesize the workflow analysis and capability map into an executive-ready AI opportunity brief. Rank candidates by expected value, implementation complexity, operator trust requirements, and data/tool prerequisites. Recommend the best near-term pilots and explain why weaker options were not prioritized.",
230
+ "priority": 1,
231
+ "phase_id": "recommendation",
232
+ "lane": "synthesis",
233
+ "depends_on": ["workflow-analysis", "capability-map"],
234
+ "input_refs": [],
235
+ "tool_allowlist_override": [],
236
+ "mcp_servers_override": [],
237
+ "output_contract":
238
+ {
239
+ "kind": "brief_markdown",
240
+ "summary_guidance": "Ranked AI opportunities, reasoning, operational implications, and recommended pilots.",
241
+ },
242
+ },
243
+ ],
244
+ "review_stages":
245
+ [
246
+ {
247
+ "stage_id": "opportunity-review",
248
+ "stage_kind": "review",
249
+ "title": "Feasibility and trust review",
250
+ "target_ids": ["opportunity-brief"],
251
+ "role": "reviewer",
252
+ "prompt": "Review the opportunity brief for realism. Reject vague AI claims, hidden implementation assumptions, and missing trust or approval considerations. The brief should make clear what can be automated, what needs a copilot, and what still requires strong human judgment.",
253
+ "checklist":
254
+ [
255
+ "Opportunities are realistically scoped",
256
+ "Human approval needs are explicit",
257
+ "Recommended pilots are specific and actionable",
258
+ ],
259
+ "priority": 1,
260
+ "phase_id": "recommendation",
261
+ "lane": "review",
262
+ "tool_allowlist_override": [],
263
+ "mcp_servers_override": [],
264
+ },
265
+ ],
266
+ "metadata": null,
267
+ },
268
+ }
269
+ `,_l=`{
270
+ "id": "automation-rollout",
271
+ "label": "Rollout",
272
+ "description": "Plan rollout, enablement, controls, and measurement for an automation initiative.",
273
+ "blueprint":
274
+ {
275
+ "mission_id": "mission_automation_rollout",
276
+ "title": "Automation rollout mission",
277
+ "goal": "Plan the rollout of an AI or agentic automation initiative across process, tooling, operating model, and measurement.",
278
+ "success_criteria":
279
+ [
280
+ "Rollout plan includes sequencing, owners, risks, and readiness needs",
281
+ "Metrics and operator controls are explicit",
282
+ "Human change-management needs are addressed",
283
+ ],
284
+ "shared_context": "Optimize for actual operational rollout. Include enablement, communications, governance, training, and success measurement. Avoid purely technical plans.",
285
+ "workspace_root": "",
286
+ "orchestrator_template_id": "",
287
+ "phases":
288
+ [
289
+ { "phase_id": "readiness", "title": "Readiness", "execution_mode": "soft" },
290
+ { "phase_id": "launch", "title": "Launch", "execution_mode": "barrier" },
291
+ ],
292
+ "milestones": [],
293
+ "team":
294
+ {
295
+ "allowed_template_ids": [],
296
+ "default_model_policy": null,
297
+ "allowed_mcp_servers": [],
298
+ "max_parallel_agents": 4,
299
+ "mission_budget": {},
300
+ "orchestrator_only_tool_calls": false,
301
+ },
302
+ "workstreams":
303
+ [
304
+ {
305
+ "workstream_id": "process-readiness",
306
+ "title": "Process readiness",
307
+ "objective": "Define the target operating process, roles, and readiness gaps.",
308
+ "role": "operator",
309
+ "prompt": "Plan the operating-process changes required to adopt the automation. Identify role changes, review points, ownership, runbooks, and readiness blockers.",
310
+ "priority": 1,
311
+ "phase_id": "readiness",
312
+ "lane": "operations",
313
+ "depends_on": [],
314
+ "input_refs": [],
315
+ "tool_allowlist_override": [],
316
+ "mcp_servers_override": [],
317
+ "output_contract":
318
+ {
319
+ "kind": "plan_markdown",
320
+ "summary_guidance": "Operating model changes, ownership, readiness blockers, and process notes.",
321
+ },
322
+ },
323
+ {
324
+ "workstream_id": "platform-readiness",
325
+ "title": "Platform and tooling readiness",
326
+ "objective": "Define the tooling, integration, data, and observability requirements for launch.",
327
+ "role": "planner",
328
+ "prompt": "Plan the platform requirements for rollout: integrations, tools, permissions, logs, metrics, data dependencies, guardrails, and monitoring expectations.",
329
+ "priority": 1,
330
+ "phase_id": "readiness",
331
+ "lane": "platform",
332
+ "depends_on": [],
333
+ "input_refs": [],
334
+ "tool_allowlist_override": [],
335
+ "mcp_servers_override": [],
336
+ "output_contract":
337
+ {
338
+ "kind": "plan_markdown",
339
+ "summary_guidance": "Tooling, integrations, observability, and launch prerequisites.",
340
+ },
341
+ },
342
+ {
343
+ "workstream_id": "launch-plan",
344
+ "title": "Rollout and adoption plan",
345
+ "objective": "Create the rollout sequence, communications, operator enablement, and measurement plan.",
346
+ "role": "coordinator",
347
+ "prompt": "Using the readiness work, create a rollout plan with phases, launch criteria, internal communications, operator training, fallback plans, and success metrics. Make the rollout sequence explicit.",
348
+ "priority": 2,
349
+ "phase_id": "launch",
350
+ "lane": "rollout",
351
+ "depends_on": ["process-readiness", "platform-readiness"],
352
+ "input_refs": [],
353
+ "tool_allowlist_override": [],
354
+ "mcp_servers_override": [],
355
+ "output_contract":
356
+ {
357
+ "kind": "plan_markdown",
358
+ "summary_guidance": "Rollout sequencing, enablement, communications, fallback, and success metrics.",
359
+ },
360
+ },
361
+ ],
362
+ "review_stages":
363
+ [
364
+ {
365
+ "stage_id": "launch-gate",
366
+ "stage_kind": "approval",
367
+ "title": "Launch readiness gate",
368
+ "target_ids": ["launch-plan"],
369
+ "role": "approver",
370
+ "prompt": "Review the rollout plan for operational readiness. Confirm that controls, training, communications, fallback, and measurement are credible before launch.",
371
+ "checklist":
372
+ [
373
+ "Launch prerequisites are explicit",
374
+ "Operator enablement is covered",
375
+ "Fallback and measurement are defined",
376
+ ],
377
+ "priority": 1,
378
+ "phase_id": "launch",
379
+ "lane": "approval",
380
+ "tool_allowlist_override": [],
381
+ "mcp_servers_override": [],
382
+ "gate":
383
+ {
384
+ "required": true,
385
+ "decisions": ["approve", "rework", "cancel"],
386
+ "rework_targets": ["launch-plan"],
387
+ "instructions": "Use rework if the rollout plan lacks readiness criteria, operator enablement, or fallback handling.",
388
+ },
389
+ },
390
+ ],
391
+ "metadata": null,
392
+ },
393
+ }
394
+ `,Sl=`{
395
+ "id": "workflow-audit",
396
+ "label": "Workflow Audit",
397
+ "description": "Audit an existing workflow and design a safer, observable automation model.",
398
+ "blueprint":
399
+ {
400
+ "mission_id": "mission_workflow_audit",
401
+ "title": "Workflow automation audit",
402
+ "goal": "Audit an existing workflow and produce a concrete automation design with failure points, control points, and implementation recommendations.",
403
+ "success_criteria":
404
+ [
405
+ "Current-state workflow is documented",
406
+ "Automation candidates include controls and failure handling",
407
+ "A practical implementation plan is produced",
408
+ ],
409
+ "shared_context": "Focus on operational reliability. Make human approvals, logging needs, repair loops, and recovery paths explicit. Favor concrete workflow shapes over abstract transformation language.",
410
+ "workspace_root": "",
411
+ "orchestrator_template_id": "",
412
+ "phases":
413
+ [
414
+ { "phase_id": "audit", "title": "Audit", "execution_mode": "soft" },
415
+ { "phase_id": "design", "title": "Design", "execution_mode": "barrier" },
416
+ ],
417
+ "milestones":
418
+ [
419
+ {
420
+ "milestone_id": "audit-complete",
421
+ "title": "Audit complete",
422
+ "phase_id": "audit",
423
+ "required_stage_ids": ["current-state", "failure-analysis"],
424
+ },
425
+ ],
426
+ "team":
427
+ {
428
+ "allowed_template_ids": [],
429
+ "default_model_policy": null,
430
+ "allowed_mcp_servers": [],
431
+ "max_parallel_agents": 4,
432
+ "mission_budget": {},
433
+ "orchestrator_only_tool_calls": false,
434
+ },
435
+ "workstreams":
436
+ [
437
+ {
438
+ "workstream_id": "current-state",
439
+ "title": "Current-state workflow",
440
+ "objective": "Document the current workflow, actors, triggers, tools, and handoffs.",
441
+ "role": "operator",
442
+ "prompt": "Act as an operations architect. Document the workflow as it exists today: triggers, inputs, outputs, handoffs, approvals, tools, data dependencies, and places where work stalls or gets retried.",
443
+ "priority": 1,
444
+ "phase_id": "audit",
445
+ "lane": "mapping",
446
+ "milestone": "audit-complete",
447
+ "depends_on": [],
448
+ "input_refs": [],
449
+ "tool_allowlist_override": [],
450
+ "mcp_servers_override": [],
451
+ "output_contract":
452
+ {
453
+ "kind": "report_markdown",
454
+ "summary_guidance": "Current-state workflow map, actors, tools, handoffs, and bottlenecks.",
455
+ },
456
+ },
457
+ {
458
+ "workstream_id": "failure-analysis",
459
+ "title": "Failure and control analysis",
460
+ "objective": "Identify where workflow automation can fail, what needs approval, and what must be observable.",
461
+ "role": "reviewer",
462
+ "prompt": "Act as a workflow reliability reviewer. Inspect the current-state map and identify failure modes, ambiguous steps, risky autonomous actions, missing approvals, recovery gaps, and required logging or metrics.",
463
+ "priority": 1,
464
+ "phase_id": "audit",
465
+ "lane": "controls",
466
+ "milestone": "audit-complete",
467
+ "depends_on": [],
468
+ "input_refs": [],
469
+ "tool_allowlist_override": [],
470
+ "mcp_servers_override": [],
471
+ "output_contract":
472
+ {
473
+ "kind": "brief_markdown",
474
+ "summary_guidance": "Failure modes, control points, approval needs, logging, and recovery requirements.",
475
+ },
476
+ },
477
+ {
478
+ "workstream_id": "automation-design",
479
+ "title": "Automation design",
480
+ "objective": "Turn the audit into a practical automation architecture and rollout plan.",
481
+ "role": "planner",
482
+ "prompt": "Design the target workflow automation. Specify which steps remain human, which become deterministic automation, which should use agents, and where review gates, kill switches, repair loops, and observability are required. Produce a rollout plan that can be implemented incrementally.",
483
+ "priority": 2,
484
+ "phase_id": "design",
485
+ "lane": "design",
486
+ "depends_on": ["current-state", "failure-analysis"],
487
+ "input_refs": [],
488
+ "tool_allowlist_override": [],
489
+ "mcp_servers_override": [],
490
+ "output_contract":
491
+ {
492
+ "kind": "plan_markdown",
493
+ "summary_guidance": "Target workflow design, control model, observability plan, and incremental rollout steps.",
494
+ },
495
+ },
496
+ ],
497
+ "review_stages":
498
+ [
499
+ {
500
+ "stage_id": "automation-review",
501
+ "stage_kind": "approval",
502
+ "title": "Automation readiness review",
503
+ "target_ids": ["automation-design"],
504
+ "role": "approver",
505
+ "prompt": "Review the automation design for realism, controllability, operator trust, and failure recovery. Reject designs that automate too aggressively without approvals or observability.",
506
+ "checklist":
507
+ [
508
+ "Control points are explicit",
509
+ "Failure recovery is defined",
510
+ "Rollout is incremental and realistic",
511
+ ],
512
+ "priority": 1,
513
+ "phase_id": "design",
514
+ "lane": "approval",
515
+ "tool_allowlist_override": [],
516
+ "mcp_servers_override": [],
517
+ "gate":
518
+ {
519
+ "required": true,
520
+ "decisions": ["approve", "rework", "cancel"],
521
+ "rework_targets": ["automation-design"],
522
+ "instructions": "Approve only when the automation design is safe, observable, and realistically deployable.",
523
+ },
524
+ },
525
+ ],
526
+ "metadata": null,
527
+ },
528
+ }
529
+ `;function Cl(a){return Array.isArray(a?.servers)?a.servers.map(t=>{const n=String(t?.name||"").trim();return n?{name:n,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(Boolean):a&&typeof a=="object"?Object.entries(a).map(([t,n])=>{const r=String(t||"").trim();return r?{name:r,connected:!!n?.connected,enabled:n?.enabled!==!1}:null}).filter(Boolean):[]}function na(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function Nn(a){const t=String(a.provider||"").trim(),n=String(a.model||"").trim();return!t||!n?null:{default_model:{provider_id:t,model_id:n}}}function kn(a){const t=a?.default_model||a?.defaultModel||{};return{provider:String(t?.provider_id||t?.providerId||"").trim(),model:String(t?.model_id||t?.modelId||"").trim()}}function pr(a,t,n){const r={type:"run_once"};return a==="cron"?{type:"cron",cron_expression:String(n||"").trim(),timezone:"UTC",misfire_policy:r}:a==="interval"?{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(t||"3600"),10)||3600),timezone:"UTC",misfire_policy:r}:{type:"manual",timezone:"UTC",misfire_policy:r}}function ha(a){return{mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,title:"",goal:"",success_criteria:[],shared_context:"",workspace_root:a,orchestrator_template_id:"",phases:[{phase_id:"phase_1",title:"Phase 1",description:"",execution_mode:"soft"}],milestones:[],team:{allowed_template_ids:[],default_model_policy:null,allowed_mcp_servers:[],max_parallel_agents:4,mission_budget:{},orchestrator_only_tool_calls:!1},workstreams:[{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:"Workstream 1",objective:"",role:"worker",prompt:"",priority:1,phase_id:"phase_1",lane:"lane_1",milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}],review_stages:[],metadata:null}}function Va(a){return Function(`"use strict"; return (${a});`)()}const Il=[Va(kl),Va(Sl),Va(Nl),Va(_l)];function as(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Al(a){const t=[];String(a.title||"").trim()||t.push("Mission title is required."),String(a.goal||"").trim()||t.push("Mission goal is required.");const n=as(a.workspace_root);return n&&t.push(n),(!Array.isArray(a.workstreams)||a.workstreams.length===0)&&t.push("At least one workstream is required."),t}function Pl(a,t){const n=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},r=n.mission_blueprint||n.missionBlueprint||n.mission_blueprint_v1;if(!r||typeof r!="object")return null;const s=r;return{...ha(t),...s,workspace_root:String(s.workspace_root||t||"").trim(),phases:Array.isArray(s.phases)&&s.phases.length?s.phases:ha(t).phases,milestones:Array.isArray(s.milestones)?s.milestones:[],workstreams:Array.isArray(s.workstreams)?s.workstreams:[],review_stages:Array.isArray(s.review_stages)?s.review_stages:[]}}function ra({title:a,subtitle:t,icon:n,children:r}){return e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-3",children:[e("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-100",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:a})]}),t?e("div",{className:"tcp-subtle mt-1 text-xs",children:t}):null]}),e("div",{className:"grid gap-3",children:r})]})}function Ye({label:a,value:t,onInput:n,placeholder:r,type:s="text"}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("input",{type:s,value:t,placeholder:r,onInput:l=>n(l.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function Ta({label:a,value:t,onInput:n,placeholder:r,rows:s=5}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("textarea",{rows:s,value:t,placeholder:r,onInput:l=>n(l.target.value),className:"min-h-[108px] w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function Tl({active:a,label:t,icon:n,onClick:r}){return e("button",{className:`tcp-btn h-8 px-3 text-xs ${a?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:r,type:"button",children:e("span",{className:"inline-flex items-center gap-2",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:t})]})})}function kt({children:a}){return e("div",{className:"tcp-subtle -mt-1 text-xs",children:a})}function Ml({text:a}){return e("div",{className:"tcp-subtle rounded-lg border border-slate-800 bg-slate-950/50 p-3 text-xs",children:a})}function Rl({value:a,error:t,open:n,browseDir:r,search:s,parentDir:l,currentDir:d,directories:u,onOpen:p,onClose:k,onClear:q,onSearchChange:b,onBrowseParent:w,onBrowseDirectory:M,onSelectDirectory:E}){const K=String(s||"").trim().toLowerCase();return e(qt,{children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Workspace root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:p,children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:`tcp-input text-sm ${t?"border-red-500/70 text-red-100":""}`,value:a,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:q,disabled:!a,children:[e("i",{"data-lucide":"x"}),"Clear"]})]})]}),n?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:k}),e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",d||r||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:w,disabled:!l,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:E,disabled:!d,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:k,children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:s,onInput:B=>b(B.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:u.length?u.map(B=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>M(String(B?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(B?.name||B?.path||"")})]})},String(B?.path||B?.name))):e(Ml,{text:K?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null]})}function _n({providerLabel:a,modelLabel:t,draft:n,providers:r,onChange:s,inheritLabel:l="Inherit team default"}){const d=r.find(u=>u.id===n.provider)?.models||[];return e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"cpu"}),e("span",{children:a})]}),e("select",{value:n.provider,onInput:u=>{const p=u.target.value,k=r.find(q=>q.id===p)?.models||[];s({provider:p,model:k[0]||""})},className:"tcp-select h-10 w-full",children:[e("option",{value:"",children:l}),r.map(u=>e("option",{value:u.id,children:[u.id,u.configured===!1?" (not configured)":""]},u.id))]})]}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"sparkles"}),e("span",{children:t})]}),e("select",{value:n.model,onInput:u=>s({...n,model:u.target.value}),className:"tcp-select h-10 w-full",disabled:!n.provider,children:[e("option",{value:"",children:n.provider?"Select a model":l}),d.map(u=>e("option",{value:u,children:u},u))]})]})]})}function $l({client:a,api:t,toast:n,defaultProvider:r,defaultModel:s,editingAutomation:l=null,onShowAutomations:d,onShowRuns:u,onClearEditing:p}){const k=jt(),q=pt(null),[b,w]=y("mission"),[M,E]=y("manual"),[K,B]=y("3600"),[se,G]=y(""),[ge,N]=y(!0),[W,J]=y(""),[S,fe]=y(""),[f,D]=y(null),[de,$e]=y(""),[Y,U]=y(ha("")),[ie,oe]=y({provider:r,model:s}),[Ue,_e]=y({}),[P,te]=y({}),[ve,Se]=y(!1),[V,Ne]=y(!1),[me,Ee]=y(""),[F,De]=y(""),le=Q({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),ae=Q({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),nt=Q({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),et=Q({queryKey:["tool","ids"],queryFn:()=>a.listToolIds().catch(()=>[]),refetchInterval:3e4}),Ge=Q({queryKey:["agent-team","templates"],queryFn:async()=>{const m=await a.agentTeams.listTemplates().catch(()=>({templates:[]}));return Array.isArray(m?.templates)?m.templates:[]},refetchInterval:3e4}),Xe=Q({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),ct=Q({queryKey:["advanced-mission-builder","workspace-browser",me],enabled:V&&!!me,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(me)}`,{method:"GET"})});ye(()=>{const m=String(Xe.data?.workspaceRoot||Xe.data?.workspace_root||"").trim();m&&($e(m),U(X=>X.workspace_root?X:{...ha(m),workspace_root:m}))},[Xe.data]),ye(()=>{const m=de||String(Xe.data?.workspaceRoot||Xe.data?.workspace_root||"").trim();if(!l){U(ha(m)),D(null),J(""),N(!0),E("manual"),B("3600"),G(""),oe({provider:r,model:s}),_e({}),te({});return}const X=Pl(l,m);if(!X)return;U(X),oe(kn(X.team.default_model_policy));const we={};for(const ht of X.workstreams)we[ht.workstream_id]=kn(ht.model_override);_e(we);const T={};for(const ht of X.review_stages)T[ht.stage_id]=kn(ht.model_override);te(T);const I=l?.schedule||{},lt=String(I?.type||"").trim().toLowerCase();lt==="cron"?(E("cron"),G(String(I?.cron_expression||"").trim())):lt==="interval"?(E("interval"),B(String(I?.interval_seconds||3600))):(E("manual"),G(""),B("3600")),N(!1),D(null),J("")},[l?.automation_id,de,r,s,Xe.data]);const bt=H(()=>{const m=Array.isArray(le.data?.all)?le.data.all:[],X=ae.data?.providers||{},we=m.map(T=>({id:String(T?.id||"").trim(),models:Object.keys(T?.models||{}),configured:!!X[String(T?.id||"").trim()]})).filter(T=>T.id).sort((T,I)=>T.id.localeCompare(I.id));return r&&!we.some(T=>T.id===r)&&we.unshift({id:r,models:s?[s]:[],configured:!0}),we},[s,r,le.data,ae.data]),dt=H(()=>Cl(nt.data),[nt.data]),Te=H(()=>(Array.isArray(et.data)?et.data:[]).map(m=>String(m||"").trim()).filter(Boolean).sort(),[et.data]),ze=H(()=>(Array.isArray(Ge.data)?Ge.data:[]).map(m=>({template_id:String(m?.template_id||m?.templateId||"").trim(),role:String(m?.role||"").trim()})).filter(m=>m.template_id),[Ge.data]),rt=Array.isArray(ct.data?.directories)?ct.data.directories:[],tt=String(ct.data?.parent||"").trim(),Ve=String(ct.data?.dir||me||"").trim(),st=H(()=>{const m=String(F||"").trim().toLowerCase();return m?rt.filter(X=>String(X?.name||X?.path||"").trim().toLowerCase().includes(m)):rt},[F,rt]),yt=as(Y.workspace_root||de);ye(()=>{try{q.current?zt(q.current):zt()}catch{}},[b,ve,f,S,Y,ie,Ue,P]);const pe=H(()=>({...Y,workspace_root:Y.workspace_root||de,team:{...Y.team,default_model_policy:Nn(ie)},workstreams:Y.workstreams.map(m=>({...m,model_override:Nn(Ue[m.workstream_id]||{provider:"",model:""})})),review_stages:Y.review_stages.map(m=>({...m,model_override:Nn(P[m.stage_id]||{provider:"",model:""})}))}),[Y,de,ie,Ue,P]),Ce=H(()=>Al(pe),[pe]),at=H(()=>[...pe.workstreams.map(m=>m.workstream_id),...pe.review_stages.map(m=>m.stage_id)],[pe]);function ce(m){U(X=>({...X,...m})),D(null)}function Le(){U(m=>({...m,workstreams:[...m.workstreams,{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:`Workstream ${m.workstreams.length+1}`,objective:"",role:"worker",prompt:"",priority:m.workstreams.length+1,phase_id:m.phases[0]?.phase_id||"",lane:`lane_${m.workstreams.length+1}`,milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}]})),D(null)}function ut(){U(m=>({...m,review_stages:[...m.review_stages,{stage_id:`review_${crypto.randomUUID().slice(0,8)}`,stage_kind:"approval",title:`Gate ${m.review_stages.length+1}`,target_ids:[],role:"reviewer",prompt:"",checklist:[],priority:m.review_stages.length+1,phase_id:m.phases[0]?.phase_id||"",lane:"review",milestone:"",tool_allowlist_override:[],mcp_servers_override:[],gate:{required:!0,decisions:["approve","rework","cancel"],rework_targets:[],instructions:""}}]})),D(null)}function v(m){const X=Il.find(T=>T.id===m);if(!X)return;const we={...ha(Y.workspace_root||de),...X.blueprint,mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,workspace_root:Y.workspace_root||de};U(we),D(null),J(""),w("mission"),oe({provider:r,model:s}),_e({}),te({}),n("info",`Loaded ${X.label}. Review the prompts and adapt them to your mission.`)}async function C(){if(Ce.length){const m=Ce.join(" ");J(m),n("err",m),w("mission");return}fe("preview"),J("");try{const m=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:pe,schedule:pr(M,K,se)})});D(m),w("compile")}catch(m){const X=m instanceof Error?m.message:String(m||""),we=X==="mission blueprint validation failed"&&Ce.length?Ce.join(" "):X;J(we),n("err",we)}finally{fe("")}}async function z(){if(Ce.length){const m=Ce.join(" ");J(m),n("err",m),w("mission");return}fe("apply"),J("");try{const m=pr(M,K,se);if(l?.automation_id){const T=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:pe,schedule:m})});await a.automationsV2.update(l.automation_id,{name:T?.automation?.name,description:T?.automation?.description||null,schedule:T?.automation?.schedule,agents:T?.automation?.agents,flow:T?.automation?.flow,execution:T?.automation?.execution,workspace_root:T?.automation?.workspace_root,metadata:T?.automation?.metadata}),await Promise.all([k.invalidateQueries({queryKey:["automations"]}),k.invalidateQueries({queryKey:["automations","v2","list"]})]),n("ok","Advanced mission updated."),p?.(),d();return}const X=await t("/api/engine/mission-builder/apply",{method:"POST",body:JSON.stringify({blueprint:pe,creator_id:"control-panel",schedule:m})});await Promise.all([k.invalidateQueries({queryKey:["automations"]}),k.invalidateQueries({queryKey:["automations","v2","list"]})]);const we=String(X?.automation?.automation_id||"").trim();ge&&we?(await a.automationsV2.runNow(we),n("ok","Advanced mission created and started."),u()):(n("ok","Advanced mission created."),d()),U(ha(de)),D(null),N(!0)}catch(m){const X=m instanceof Error?m.message:String(m||""),we=X==="mission blueprint validation failed"&&Ce.length?Ce.join(" "):X;J(we),n("err",we)}finally{fe("")}}return e("div",{ref:q,className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-3",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Mission Builder"}),e("div",{className:"tcp-subtle text-xs",children:"Build one coordinated swarm mission with shared context, per-lane roles, explicit handoffs, and a compiled preview before launch."}),e("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>Se(!0),children:[e("i",{"data-lucide":"book-open"}),"How this works"]}),e("span",{className:"tcp-subtle text-xs",children:"Start from example:"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>v("ai-opportunity"),children:[e("i",{"data-lucide":"sparkles"}),"AI Opportunities"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>v("workflow-audit"),children:[e("i",{"data-lucide":"workflow"}),"Workflow Audit"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>v("agentic-design"),children:[e("i",{"data-lucide":"bot"}),"Agentic Design"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>v("automation-rollout"),children:[e("i",{"data-lucide":"arrow-up-circle"}),"Rollout"]})]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[["mission","clipboard-list"],["team","users"],["workstreams","workflow"],["review","shield-check"],["compile","binary"]].map(([m,X])=>e(Tl,{active:b===m,label:m==="workstreams"?"workstreams":m,icon:X,onClick:()=>w(m)},m))})]}),W?e("div",{className:"rounded-xl border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-200",children:W}):null,l?e("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:["Editing advanced mission:"," ",e("strong",{children:String(l?.name||l?.automation_id||"")})]}):null,ve?e("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-slate-950/80 p-4 backdrop-blur-sm",children:e("div",{className:"max-h-[90vh] w-full max-w-4xl overflow-y-auto rounded-2xl border border-slate-700 bg-slate-950 p-5 shadow-2xl",children:[e("div",{className:"mb-4 flex items-start justify-between gap-4",children:[e("div",{children:[e("div",{className:"text-lg font-semibold text-slate-100",children:"How the Advanced Swarm Builder Works"}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Think of this as a mission compiler: one shared goal, many scoped workstreams, explicit handoffs, and optional review gates."})]}),e("button",{className:"tcp-btn h-9 px-3 text-sm",onClick:()=>Se(!1),children:"Close"})]}),e("div",{className:"grid gap-4 lg:grid-cols-2",children:[e(ra,{title:"What goes where",subtitle:"Use the right field for the right level of instruction.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"Mission goal:"})," the one shared outcome for the whole operation."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Success criteria:"})," concrete checks for whether the mission is done well."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Shared context:"})," facts, constraints, tone, audience, deadlines, approved sources."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream objective:"})," the local assignment for that lane."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream prompt:"})," the operating instructions for how that lane should work."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Output contract:"})," the artifact that downstream work expects to receive."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Review / gate prompt:"})," what a reviewer or approver must check before promotion."]})]})}),e(ra,{title:"How to get good results",subtitle:"The builder works best when each stage is explicit.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:"Keep the mission goal outcome-based, not a long checklist."}),e("div",{children:"Make success criteria measurable."}),e("div",{children:"Give each workstream one clear responsibility."}),e("div",{children:"Use dependencies only for real handoffs."}),e("div",{children:"Define outputs as concrete artifacts, not vague intentions."}),e("div",{children:"Use review gates for quality and promotion, not for every step."}),e("div",{children:"Prefer prompts that say what evidence, format, and audience the step should target."})]})}),e(ra,{title:"Prompt pattern",subtitle:"A reliable starting scaffold for most workstreams.",children:e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3 text-xs text-slate-300",children:[e("div",{children:e("strong",{className:"text-slate-100",children:"Mission goal"})}),e("div",{className:"mt-1",children:"Produce a coordinated launch plan for Product X for the next 30 days."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Shared context"})}),e("div",{className:"mt-1",children:"Audience is SMB owners. Tone is clear and practical. Use approved workspace and MCP sources only. Avoid speculative claims."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream objective"})}),e("div",{className:"mt-1",children:"Analyze the target workflow and identify the 3 highest-value AI opportunities for a near-term pilot."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream prompt"})}),e("div",{className:"mt-1",children:"Act as an AI workflow strategist. Map the current process, identify repeated manual work, decision bottlenecks, and coordination pain, then recommend realistic AI patterns with evidence and operational caveats."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Output contract"})}),e("div",{className:"mt-1",children:"A markdown memo with sections: workflow summary, AI opportunities, feasibility constraints, risks, and recommended pilots."})]})}),e(ra,{title:"Starter examples",subtitle:"Use these when you do not want to begin from a blank blueprint.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"AI Opportunities:"})," workflow analysis and capability mapping feeding a ranked pilot brief."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workflow Audit:"})," current-state mapping and failure analysis feeding an automation design review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Agentic Design:"})," role design and flow design feeding governance and safety review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Rollout:"})," process readiness and platform readiness feeding a launch plan and approval gate."]})]})})]})]})}):null,b==="mission"?e(ra,{title:"Mission",subtitle:"Global brief, success criteria, and schedule.",icon:"clipboard-list",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(Ye,{label:"Mission title",value:Y.title,onInput:m=>ce({title:m})}),e(Ye,{label:"Mission ID",value:Y.mission_id,onInput:m=>ce({mission_id:m})})]}),e(kt,{children:"Use a short title a human operator would recognize later in the automation list."}),e(Rl,{value:Y.workspace_root,error:yt,open:V,browseDir:me,search:F,parentDir:tt,currentDir:Ve,directories:st,onOpen:()=>{const m=String(Y.workspace_root||de||"/").trim();Ee(m||"/"),De(""),Ne(!0)},onClose:()=>{Ne(!1),De("")},onClear:()=>ce({workspace_root:""}),onSearchChange:De,onBrowseParent:()=>{tt&&Ee(tt)},onBrowseDirectory:m=>Ee(m),onSelectDirectory:()=>{Ve&&(ce({workspace_root:Ve}),Ne(!1),De(""),n("ok",`Workspace selected: ${Ve}`))}}),e(kt,{children:"This is the shared working directory the mission can use for files and artifacts."}),yt?e("div",{className:"text-xs text-red-300",children:yt}):null,e(Ta,{label:"Mission goal",value:Y.goal,onInput:m=>ce({goal:m}),placeholder:"Describe the shared objective all participants are working toward."}),e(kt,{children:"Write the one shared outcome for the whole swarm, not a list of steps."}),e(Ta,{label:"Shared context",value:Y.shared_context||"",onInput:m=>ce({shared_context:m}),placeholder:"Shared constraints, references, context, and operator guidance."}),e(kt,{children:"Put the facts every lane should inherit here: audience, constraints, tone, deadlines, approved sources, and things to avoid."}),e(Ye,{label:"Success criteria",value:Y.success_criteria.join(", "),onInput:m=>ce({success_criteria:na(m)}),placeholder:"comma-separated"}),e(kt,{children:"These should be measurable checks like “brief includes 5 competitors” or “plan contains owner, timeline, and risks”."}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Schedule"}),e("select",{value:M,onInput:m=>E(m.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"manual",children:"Manual"}),e("option",{value:"interval",children:"Interval"}),e("option",{value:"cron",children:"Cron"})]})]}),M==="interval"?e(Ye,{label:"Interval seconds",value:K,onInput:B}):null,M==="cron"?e(Ye,{label:"Cron expression",value:se,onInput:G}):null]})]}):null,b==="team"?e(ra,{title:"Team",subtitle:"Templates, default model, concurrency, and mission limits.",icon:"users",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Orchestrator template"}),e("select",{value:Y.orchestrator_template_id||"",onInput:m=>ce({orchestrator_template_id:m.target.value}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"",children:"None"}),ze.map(m=>e("option",{value:m.template_id,children:[m.template_id," (",m.role||"role",")"]},m.template_id))]})]}),e(Ye,{label:"Allowed templates",value:(Y.team.allowed_template_ids||[]).join(", "),onInput:m=>ce({team:{...Y.team,allowed_template_ids:na(m)}}),placeholder:"comma-separated"})]}),e(kt,{children:"The orchestrator keeps the mission coherent. Allowed templates restrict which reusable agent profiles lanes are permitted to use."}),e(_n,{providerLabel:"Default model provider",modelLabel:"Default model",draft:ie,providers:bt,inheritLabel:"No team default",onChange:oe}),e("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-4",children:[e(Ye,{label:"Max parallel agents",value:String(Y.team.max_parallel_agents||4),onInput:m=>ce({team:{...Y.team,max_parallel_agents:Math.max(1,Number.parseInt(String(m||"4"),10)||4)}}),type:"number"}),e(Ye,{label:"Token ceiling",value:String(Y.team.mission_budget?.max_total_tokens||""),onInput:m=>ce({team:{...Y.team,mission_budget:{...Y.team.mission_budget||{},max_total_tokens:m?Number(m):void 0}}}),type:"number"}),e(Ye,{label:"Cost ceiling USD",value:String(Y.team.mission_budget?.max_total_cost_usd||""),onInput:m=>ce({team:{...Y.team,mission_budget:{...Y.team.mission_budget||{},max_total_cost_usd:m?Number(m):void 0}}}),type:"number"}),e(Ye,{label:"Tool-call ceiling",value:String(Y.team.mission_budget?.max_total_tool_calls||""),onInput:m=>ce({team:{...Y.team,mission_budget:{...Y.team.mission_budget||{},max_total_tool_calls:m?Number(m):void 0}}}),type:"number"})]}),e(Ye,{label:"Allowed MCP servers",value:(Y.team.allowed_mcp_servers||[]).join(", "),onInput:m=>ce({team:{...Y.team,allowed_mcp_servers:na(m)}}),placeholder:dt.map(m=>m.name).join(", ")}),e(kt,{children:"Team defaults apply everywhere unless a workstream or review stage overrides its own tool or MCP scope."})]}):null,b==="workstreams"?e(ra,{title:"Workstreams",subtitle:"Scoped sub-objectives, dependencies, tools, MCP, and output contracts.",icon:"workflow",children:[e(kt,{children:"A workstream is one scoped lane of work. Give it one responsibility, one artifact to produce, and only the dependencies it truly needs."}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:Le,children:[e("i",{"data-lucide":"plus"}),"Add workstream"]})}),pe.workstreams.map((m,X)=>{const we=Ue[m.workstream_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:m.title||`Workstream ${X+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>ce({workstreams:pe.workstreams.filter(T=>T.workstream_id!==m.workstream_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(Ye,{label:"Title",value:m.title,onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,title:T}:I)})}),e(Ye,{label:"Role",value:m.role,onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,role:T}:I)})})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(Ye,{label:"Phase",value:m.phase_id||"",onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,phase_id:T}:I)})}),e(Ye,{label:"Lane",value:m.lane||"",onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,lane:T}:I)})}),e(Ye,{label:"Priority",value:String(m.priority||0),onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,priority:Number(T)||0}:I)}),type:"number"})]}),e(kt,{children:"`Phase` says when this lane belongs in the mission. `Lane` groups related work. `Priority` decides ordering among runnable work in the same open phase."}),e(Ta,{label:"Objective",value:m.objective,onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,objective:T}:I)}),rows:3}),e(kt,{children:"Objective is the local assignment. Keep it crisp: what this lane must accomplish."}),e(Ta,{label:"Prompt",value:m.prompt,onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,prompt:T}:I)}),rows:5}),e(kt,{children:"Prompt is how the lane should operate: role, evidence standard, audience, format, and what good work looks like."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(Ye,{label:"Depends on",value:m.depends_on.join(", "),onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,depends_on:na(T)}:I)}),placeholder:"comma-separated stage ids"}),e(Ye,{label:"Output contract kind",value:m.output_contract.kind,onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,output_contract:{...I.output_contract,kind:T}}:I)})})]}),e(kt,{children:"`Depends on` should list upstream stage IDs that must finish first. `Output contract kind` names the artifact downstream lanes expect."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(Ye,{label:"Tool allowlist override",value:(m.tool_allowlist_override||[]).join(", "),onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,tool_allowlist_override:na(T)}:I)}),placeholder:Te.join(", ")}),e(Ye,{label:"MCP servers override",value:(m.mcp_servers_override||[]).join(", "),onInput:T=>ce({workstreams:pe.workstreams.map(I=>I.workstream_id===m.workstream_id?{...I,mcp_servers_override:na(T)}:I)}),placeholder:dt.map(T=>T.name).join(", ")})]}),e(kt,{children:"Leave tool and MCP overrides empty to inherit team defaults. Override only when this lane needs a narrower or different scope."}),e(_n,{providerLabel:"Model provider",modelLabel:"Model",draft:we,providers:bt,onChange:T=>_e(I=>({...I,[m.workstream_id]:T}))})]},m.workstream_id)})]}):null,b==="review"?e(ra,{title:"Review & Gates",subtitle:"Reviewer, tester, and approval stages.",icon:"shield-check",children:[e(kt,{children:"Use review stages to check quality or readiness before later work is promoted. Approval stages are the right place for human checkpoints."}),e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:ut,children:[e("i",{"data-lucide":"plus"}),"Add review stage"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>ce({phases:[...pe.phases,{phase_id:`phase_${pe.phases.length+1}`,title:`Phase ${pe.phases.length+1}`,description:"",execution_mode:"soft"}]}),children:[e("i",{"data-lucide":"copy-plus"}),"Add phase"]})]}),e("div",{className:"grid gap-2",children:pe.phases.map((m,X)=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:e("div",{className:"grid gap-3 md:grid-cols-4",children:[e(Ye,{label:"Phase ID",value:m.phase_id,onInput:we=>ce({phases:pe.phases.map((T,I)=>I===X?{...T,phase_id:we}:T)})}),e(Ye,{label:"Title",value:m.title,onInput:we=>ce({phases:pe.phases.map((T,I)=>I===X?{...T,title:we}:T)})}),e(Ye,{label:"Description",value:m.description||"",onInput:we=>ce({phases:pe.phases.map((T,I)=>I===X?{...T,description:we}:T)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Execution mode"}),e("select",{value:m.execution_mode||"soft",onInput:we=>ce({phases:pe.phases.map((T,I)=>I===X?{...T,execution_mode:we.target.value}:T)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"soft",children:"soft"}),e("option",{value:"barrier",children:"barrier"})]})]})]})},m.phase_id))}),e(kt,{children:"`soft` phases prefer the current open phase first. `barrier` phases hold later phases closed until earlier required work is complete."}),pe.review_stages.map((m,X)=>{const we=P[m.stage_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:m.title||`Review stage ${X+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>ce({review_stages:pe.review_stages.filter(T=>T.stage_id!==m.stage_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(Ye,{label:"Title",value:m.title,onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,title:T}:I)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Stage kind"}),e("select",{value:m.stage_kind,onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,stage_kind:T.target.value}:I)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"review",children:"review"}),e("option",{value:"test",children:"test"}),e("option",{value:"approval",children:"approval"})]})]})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(Ye,{label:"Targets",value:m.target_ids.join(", "),onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,target_ids:na(T)}:I)}),placeholder:at.join(", ")}),e(Ye,{label:"Phase",value:m.phase_id||"",onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,phase_id:T}:I)})}),e(Ye,{label:"Lane",value:m.lane||"",onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,lane:T}:I)})})]}),e(kt,{children:"Targets are the stages this review or gate is checking. Put the review in the phase where that checkpoint should happen."}),e(Ta,{label:"Prompt",value:m.prompt,onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,prompt:T}:I)}),rows:4}),e(kt,{children:"Use the prompt to define what must be checked and what should trigger approve, rework, or fail."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(Ye,{label:"Checklist",value:(m.checklist||[]).join(", "),onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,checklist:na(T)}:I)}),placeholder:"comma-separated"}),e(Ye,{label:"MCP servers override",value:(m.mcp_servers_override||[]).join(", "),onInput:T=>ce({review_stages:pe.review_stages.map(I=>I.stage_id===m.stage_id?{...I,mcp_servers_override:na(T)}:I)}),placeholder:dt.map(T=>T.name).join(", ")})]}),e(kt,{children:"Checklist items should be concrete pass/fail checks, not broad wishes."}),e(_n,{providerLabel:"Model provider",modelLabel:"Model",draft:we,providers:bt,onChange:T=>te(I=>({...I,[m.stage_id]:T}))})]},m.stage_id)})]}):null,b==="compile"?e(ra,{title:"Compile & Run",subtitle:"Validate the mission graph before launch.",icon:"binary",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",disabled:S==="preview",onClick:()=>{C()},children:[e("i",{"data-lucide":"refresh-cw"}),S==="preview"?"Compiling...":"Compile preview"]}),e("button",{className:"tcp-btn-primary h-8 px-3 text-xs",disabled:S==="apply",onClick:()=>{z()},children:[e("i",{"data-lucide":l?"save":"arrow-up-circle"}),S==="apply"?"Saving...":l?"Save automation":ge?"Create and run":"Create draft"]}),l?null:e("label",{className:"ml-2 inline-flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:ge,onChange:m=>N(m.target.checked)}),"Run immediately after create"]}),l&&p?e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>p(),children:"Cancel edit"}):null]}),f?e(qt,{children:[e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Validation"}),Array.isArray(f?.validation)&&f.validation.length?e("div",{className:"grid gap-2",children:f.validation.map((m,X)=>e("div",{className:`rounded-lg border px-3 py-2 text-xs ${String(m?.severity||"").toLowerCase()==="warning"?"border-amber-500/40 bg-amber-500/10 text-amber-200":"border-slate-700 bg-slate-950/60 text-slate-200"}`,children:[e("div",{className:"font-medium",children:String(m?.code||m?.severity||"validation")}),e("div",{className:"mt-1",children:String(m?.message||"")})]},`${m?.code||"message"}-${X}`))}):e("div",{className:"tcp-subtle text-xs",children:"No validation warnings."})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Compiled automation"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:[e("div",{children:["name: ",String(f?.automation?.name||"—")]}),e("div",{children:["nodes:"," ",Array.isArray(f?.automation?.flow?.nodes)?f.automation.flow.nodes.length:0]}),e("div",{children:["agents:"," ",Array.isArray(f?.automation?.agents)?f.automation.agents.length:0]}),e("div",{children:["max parallel:"," ",String(f?.automation?.execution?.max_parallel_agents??"—")]})]})]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Node preview"}),e("div",{className:"grid gap-2",children:(Array.isArray(f?.node_previews)?f.node_previews:[]).map(m=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/70 p-3 text-xs text-slate-300",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-slate-100",children:String(m?.title||m?.node_id||"node")}),e("span",{className:"tcp-subtle",children:String(m?.node_id||"")}),e("span",{className:"tcp-subtle",children:["phase: ",String(m?.phase_id||"—")]}),e("span",{className:"tcp-subtle",children:["lane: ",String(m?.lane||"—")]}),e("span",{className:"tcp-subtle",children:["priority: ",String(m?.priority??"—")]})]}),e("div",{className:"mt-1",children:["depends on:"," ",Array.isArray(m?.depends_on)&&m.depends_on.length?m.depends_on.join(", "):"none"]}),e("div",{className:"mt-1",children:["tools:"," ",Array.isArray(m?.tool_allowlist)&&m.tool_allowlist.length?m.tool_allowlist.join(", "):"default"]}),e("div",{className:"mt-1",children:["MCP:"," ",Array.isArray(m?.mcp_servers)&&m.mcp_servers.length?m.mcp_servers.join(", "):"default"]})]},String(m?.node_id||"")))})]})]}):e("div",{className:"tcp-subtle text-xs",children:"Compile the mission to inspect validation, compiled nodes, and execution shape."})]}):null]})}const ln=[{label:"Every hour",desc:"Good for monitoring & alerts",icon:"⏰",cron:"",intervalSeconds:3600},{label:"Every morning",desc:"Daily digest at 9 AM",icon:"☀️",cron:"0 9 * * *"},{label:"Every evening",desc:"End-of-day summary at 6 PM",icon:"🌙",cron:"0 18 * * *"},{label:"Daily at midnight",desc:"Nightly data processing",icon:"🔄",cron:"0 0 * * *"},{label:"Weekly Monday",desc:"Weekly reports & reviews",icon:"📋",cron:"0 9 * * 1"},{label:"Manual only",desc:"Run whenever you want",icon:"🎯",cron:""}],Ln=[{id:"single",label:"Single Agent",icon:"🤖",desc:"One focused AI handles the whole task",bestFor:"Simple, well-defined tasks"},{id:"team",label:"Agent Team",icon:"👥",desc:"Multiple specialized AIs collaborate with a planner and workers",bestFor:"Complex multi-step tasks (recommended)"},{id:"swarm",label:"Swarm",icon:"🐝",desc:"A swarm of AIs work in parallel on sub-tasks",bestFor:"Large-scale parallel work"}],hr=["Check my email every morning and send me a summary of what's important","Monitor GitHub issues and post daily standup updates to Slack","Summarize my calendar each Sunday and plan the upcoming week","Watch for price changes on competitor products and alert me","Generate a weekly report from our Notion workspace"],gr="tandem.automations.plannerSeed";function sa(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function ns(a){return Array.isArray(a?.servers)?a.servers.map(t=>{const n=String(t?.name||"").trim();return n?{name:n,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):a&&typeof a=="object"?Object.entries(a).map(([t,n])=>{const r=String(t||"").trim();if(!r)return null;const s=n&&typeof n=="object"?n:{};return{name:r,connected:!!s.connected,enabled:s.enabled!==!1}}).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):[]}function ql(a){const t=String(a.cron||"").trim();if(t)return{cron:{expression:t}};const n=ln.find(r=>r.label===a.schedulePreset);return n?.intervalSeconds?{interval_seconds:{seconds:n.intervalSeconds}}:n?.cron?{cron:{expression:n.cron}}:{type:"manual"}}function El(a){const t=String(a?.cron?.expression||a?.cron_expression||"").trim();if(t)return t;const n=Number(a?.interval_seconds?.seconds);return Number.isFinite(n)&&n>0?n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`:"manual"}function rs(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function $a(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function an(a,t){const n=String(a||"").trim(),r=String(t||"").trim();return!n&&!r?"":n?r?"":"Planner model is required when a planner provider is set.":"Planner model provider is required when a planner model is set."}function Sn(a,t){const n=String(a||"").trim(),r=String(t||"").trim();return!n&&!r?"":n?r?"":"Model is required when a provider is set.":"Model provider is required when a model is set."}function Ol(a){let t;const n=String(a.roleModelsJson||"").trim();if(n)try{const u=JSON.parse(n);u&&typeof u=="object"&&!Array.isArray(u)&&(t=u)}catch{t=void 0}const r=String(a.plannerModelProvider||"").trim(),s=String(a.plannerModelId||"").trim();r&&s&&(t={...t||{}},t.planner={provider_id:r,model_id:s});const l=a.mode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxAgents||"4"),10)||4)):1,d={execution_mode:a.mode,max_parallel_agents:l};return String(a.modelProvider||"").trim()&&(d.model_provider=String(a.modelProvider).trim()),String(a.modelId||"").trim()&&(d.model_id=String(a.modelId).trim()),t&&Object.keys(t).length&&(d.role_models=t),d}function Dl(a){const t=String(a||"").trim();if(!t)return"";try{const n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?"Role model overrides must be a JSON object.":""}catch{return"Role model overrides must be valid JSON."}}function ss(a){const t=String(a?.type||"").trim().toLowerCase(),n=String(a?.cron?.expression||a?.cron_expression||a?.cron||"").trim(),r=Number(a?.interval_seconds?.seconds||a?.interval_seconds||a?.intervalSeconds||3600),s=Number.isFinite(r)&&r>0?Math.round(r):3600;return{scheduleKind:t==="manual"?"manual":n?"cron":"interval",cronExpression:n,intervalSeconds:s}}function Fl(a){let t="",n=!1;for(const r of String(a||"").trim())/^[a-z0-9]$/i.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="_",n=!0);return t.replace(/^_+|_+$/g,"")||"mcp"}function Ba(a){const t=new Set,n=[];for(const r of a){const s=String(r||"").trim();!s||t.has(s)||(t.add(s),n.push(s))}return n}function Ya(a,t){const n=new Set,r=[];for(const s of[t,...a]){const l=String(s||"").trim();!l||n.has(l)||(n.add(l),r.push(l))}return r}function Bn(a){return Ba(String(a||"").split(/[\n,]/g).map(t=>String(t||"").trim()).filter(Boolean))}function Ul(a){return Ba(a).join(`
530
+ `)}function jl(a,t,n){return t==="all"?["*"]:Ba([...Bn(n),...a.map(r=>`mcp.${Fl(r)}.*`)])}function Ll(a){const t=a?.metadata?.operator_preferences||a?.metadata?.operatorPreferences;if(t&&typeof t=="object")return t;const n=Array.isArray(a?.agents)?a.agents[0]:null,r=n?.model_policy?.default_model||n?.modelPolicy?.defaultModel||null,s=n?.model_policy?.role_models||n?.modelPolicy?.roleModels||null,l={};return(r?.provider_id||r?.providerId)&&(l.model_provider=r.provider_id||r.providerId),(r?.model_id||r?.modelId)&&(l.model_id=r.model_id||r.modelId),s&&typeof s=="object"&&(l.role_models=s),(a?.execution?.max_parallel_agents||a?.execution?.maxParallelAgents)&&(l.max_parallel_agents=a.execution.max_parallel_agents||a.execution.maxParallelAgents),l}function Bl(a){const t=Ba((Array.isArray(a?.agents)?a.agents.flatMap(r=>Array.isArray(r?.tool_policy?.allowlist)?r.tool_policy.allowlist:[]):[]).map(r=>String(r||"").trim()).filter(Boolean));if(!t.length||t.includes("*"))return{toolAccessMode:"all",customToolsText:""};const n=t.filter(r=>!r.startsWith("mcp."));return{toolAccessMode:"custom",customToolsText:Ul(n)}}function Kl(a){const t=String(a?.automation_id||a?.automationId||a?.id||"").trim();if(!t)return null;const n=ss(a?.schedule),r=Ll(a),s=r?.role_models?.planner||r?.roleModels?.planner||{},l=Number(r?.max_parallel_agents??r?.maxParallelAgents??a?.execution?.max_parallel_agents??a?.execution?.maxParallelAgents??1),d=String(r?.execution_mode||r?.executionMode||"").trim(),u=Array.isArray(a?.metadata?.allowed_mcp_servers)?a.metadata.allowed_mcp_servers:Array.isArray(a?.agents?.[0]?.mcp_policy?.allowed_servers)?a.agents[0].mcp_policy.allowed_servers:[],p=Bl(a),k=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map((q,b)=>({nodeId:String(q?.node_id||q?.nodeId||q?.id||`node-${b}`).trim(),title:String(q?.title||q?.name||q?.objective||q?.node_id||q?.id||"Workflow step").trim(),objective:String(q?.objective||"").trim(),agentId:String(q?.agent_id||q?.agentId||"").trim()})):[];return{automationId:t,name:String(a?.name||t).trim(),description:String(a?.description||"").trim(),scheduleKind:n.scheduleKind,cronExpression:n.cronExpression,intervalSeconds:String(n.intervalSeconds),workspaceRoot:String(a?.workspace_root||a?.workspaceRoot||a?.metadata?.workspace_root||"").trim(),executionMode:d==="single"||d==="swarm"||d==="team"?d:l>1?"swarm":"team",maxParallelAgents:String(Number.isFinite(l)&&l>0?Math.round(l):1),modelProvider:String(r?.model_provider||r?.modelProvider||"").trim(),modelId:String(r?.model_id||r?.modelId||"").trim(),plannerModelProvider:String(s?.provider_id||s?.providerId||"").trim(),plannerModelId:String(s?.model_id||s?.modelId||"").trim(),toolAccessMode:p.toolAccessMode,customToolsText:p.customToolsText,selectedMcpServers:u.map(q=>String(q||"").trim()).filter(Boolean),nodes:k}}function Wl(a){const t=a?.metadata&&typeof a.metadata=="object"?a.metadata:{};return String(t.builder_kind||t.builderKind||a?.builder_kind||"").trim().toLowerCase()==="mission_blueprint"?!0:!!(t.mission_blueprint||t.missionBlueprint||t.mission_blueprint_v1||t.mission)}function Jl(a){const t={type:"run_once"};return a.scheduleKind==="manual"?{type:"manual",timezone:"UTC",misfire_policy:t}:a.scheduleKind==="cron"?{type:"cron",cron_expression:String(a.cronExpression||"").trim(),timezone:"UTC",misfire_policy:t}:{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(a.intervalSeconds||"3600"),10)||3600),timezone:"UTC",misfire_policy:t}}function Ql(a){return String(a?.metadata?.feature||"").trim()==="agent_standup"}function Hl(a){const t={execution_mode:a.executionMode,max_parallel_agents:a.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxParallelAgents||"4"),10)||4)):1},n=String(a.modelProvider||"").trim(),r=String(a.modelId||"").trim();n&&(t.model_provider=n),r&&(t.model_id=r);const s=String(a.plannerModelProvider||"").trim(),l=String(a.plannerModelId||"").trim();return s&&l&&(t.role_models={planner:{provider_id:s,model_id:l}}),t.tool_access_mode=a.toolAccessMode,a.toolAccessMode==="custom"&&(t.tool_allowlist=Bn(a.customToolsText)),t}function Gl(a){const t={};return a.model_provider&&a.model_id&&(t.default_model={provider_id:a.model_provider,model_id:a.model_id}),a.role_models&&typeof a.role_models=="object"&&(t.role_models=a.role_models),Object.keys(t).length?t:null}function la(a){const t=String(a||"").trim().toLowerCase();return["queued","running","in_progress","executing","pending_approval","awaiting_approval"].includes(t)}function fr(a){const t=Number(a?.started_at_ms||a?.fired_at_ms||a?.created_at_ms||0);if(!Number.isFinite(t)||t<=0)return"time unavailable";const n=Date.now()-t,r=Math.max(0,Math.floor(n/1e3));return r<60?`${r}s`:r<3600?`${Math.floor(r/60)}m`:`${Math.floor(r/3600)}h`}function zl(a,t){const n=[],r=String(a?.status||"").trim().toLowerCase();return(r==="pending_approval"||r==="awaiting_approval")&&n.push("Run is waiting for approval before external actions."),r==="blocked_policy"&&n.push("Run was blocked by policy. Check tool allowlist and integration permissions."),(r==="failed"||r==="error")&&n.push("Run failed. Inspect detail/error fields for root cause."),(r==="completed"||r==="done")&&!t.length&&n.push("Run completed but produced no artifacts. Verify output target and tool actions."),a?.requires_approval===!0&&n.push("Automation policy requires human approval. Disable it for fully automated runs."),n}function br(a){const t=a?.properties||{};return String(a?.run_id||a?.runId||a?.runID||t?.run_id||t?.runId||t?.runID||t?.run?.id||"").trim()}function Yt(a){return String(a?.type||a?.event_type||a?.event||"").trim()}function wa(a){const t=a?.properties||{},n=a?.timestamp_ms||a?.timestampMs||t?.timestamp_ms||t?.timestampMs||t?.firedAtMs||Date.now(),r=Number(n);return Number.isFinite(r)?r:Date.now()}function cn(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?Date.now():t<1e12?t*1e3:t}function Fa(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function yr(a){const t=Fa(a);return t?new Date(t).toLocaleTimeString():"time unavailable"}function qn(a,t=28){const n=String(a||"").trim();if(!n)return"";if(n.length<=t)return n;const r=Math.max(8,Math.floor((t-1)/2)),s=Math.max(6,t-r-1);return`${n.slice(0,r)}…${n.slice(-s)}`}function Vl(a,t){const n=(Array.isArray(a)?a:[]).map(s=>({id:`event:${String(s?.seq||"")}:${String(s?.event_type||s?.eventType||"")}`,family:"event",type:String(s?.event_type||s?.eventType||"context_event"),detail:String(s?.payload?.reason||s?.payload?.detail||s?.payload?.error||s?.payload?.status||s?.status||"").trim(),at:Fa(s?.created_at_ms||s?.timestamp_ms||s?.timestampMs)||Number(s?.seq||0),raw:s})),r=(Array.isArray(t)?t:[]).map(s=>({id:`patch:${String(s?.seq||"")}:${String(s?.op||"")}`,family:"patch",type:String(s?.op||"blackboard_patch"),detail:String(s?.payload?.status||s?.payload?.task_id||s?.payload?.artifact_id||s?.payload?.title||"").trim(),at:Fa(s?.created_at_ms||s?.timestamp_ms)||Number(s?.seq||0),raw:s}));return[...n,...r].sort((s,l)=>Number(l.at||0)-Number(s.at||0))}function Da(a,t=88){const n=String(a||"").replace(/\s+/g," ").trim();return n?n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n:""}function pa(a){return String(a?.mission_snapshot?.objective||a?.mission?.objective||a?.objective||a?.name||"").replace(/\s+/g," ").trim()}function Cn(a){const t=String(a?.name||"").trim();if(t)return t;const n=pa(a);if(n)return Da(n,96);const r=String(a?.automation_id||a?.routine_id||"").trim();return r||"Run"}function ma(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"":new Date(cn(t)).toLocaleString()}function is(a){const t=Array.isArray(a?.active_session_ids)?a.active_session_ids:Array.isArray(a?.activeSessionIds)?a.activeSessionIds:[],n=[String(a?.latest_session_id||"").trim(),String(a?.latestSessionId||"").trim()].filter(Boolean),r=Object.values(a?.checkpoint?.node_outputs||a?.checkpoint?.nodeOutputs||{}).map(s=>{const l=s?.content||{};return String(l?.session_id||l?.sessionId||"").trim()}).filter(Boolean);return Array.from(new Set([...n,...t.map(s=>String(s||"").trim()).filter(Boolean),...r].filter(Boolean)))}function Yl(a){const t=a?.checkpoint?.node_outputs||a?.checkpoint?.nodeOutputs||{};return Object.entries(t).map(([n,r])=>({nodeId:n,value:r}))}function Xl(a){const t=String(a?.summary||"").trim(),n=a?.content||{},r=String(n?.text||n?.raw_text||"").trim();return[t,r].filter(Boolean).join(`
531
+ `).trim()}function Kn(a){return(Array.isArray(a?.parts)?a.parts:[]).map(r=>{const s=String(r?.type||"").trim();if(s==="text"||s==="reasoning")return String(r?.text||"").trim();if(s==="tool"){const l=String(r?.tool||"tool").trim(),d=String(r?.error||"").trim(),u=r?.result?_t(r.result):"";return[`tool: ${l}`,d?`error: ${d}`:"",u].filter(Boolean).join(`
532
+ `)}return String(r?.text||"").trim()}).filter(Boolean).join(`
533
+
534
+ `).trim()}function Zl(a){const t=String(a?.info?.role||"").trim().toLowerCase();if(t==="user")return"user";if(t==="assistant")return"assistant";const n=Kn(a).toLowerCase();return n.includes("engine_error")||n.includes("error")?"error":"system"}function ec(a){return Array.isArray(a?.parts)?a.parts:[]}function tc(a){return cn(a?.info?.time?.created||a?.info?.created_at_ms||a?.created_at_ms||0)}function ac(a,t){return String(a?.info?.id||a?.id||`message-${t}`).trim()||`message-${t}`}function Ma(a){const t=String(a||"").trim();return t?`session ${qn(t,18)}`:"session"}function En(a){const t=String(a||"").trim();return t?t.startsWith("node-")?t:`node-${t}`:""}function vr(a){const t=String(a||"").trim();if(!t)return"";for(const n of[/node id:\s*([a-z0-9._-]+)/i,/step[_\s]id:\s*([a-z0-9._-]+)/i,/task[_\s]id:\s*(?:node-)?([a-z0-9._-]+)/i]){const r=t.match(n);if(r?.[1])return En(r[1])}return""}function nc(a,t,n){const r=new Set(Array.isArray(t?.completed_nodes)?t.completed_nodes.map(String):[]),s=new Set(Array.isArray(t?.pending_nodes)?t.pending_nodes.map(String):[]),l=String(a||"").trim();if(r.has(l))return"done";const d=t?.node_outputs?.[l]||t?.nodeOutputs?.[l],u=String(d?.error||d?.content?.error||d?.content?.message||d?.content?.status_message||"").trim().toLowerCase();return u&&(u.includes("failed")||u.includes("error"))?"failed":(s.has(l),n.length?"pending":"runnable")}function rc(a,t=""){const n=Array.isArray(a?.automation_snapshot?.flow?.nodes)?a.automation_snapshot.flow.nodes:[];if(!n.length)return{currentTaskId:"",taskSource:"empty",tasks:[]};const r=a?.checkpoint||{},s=new Set(Array.isArray(r?.completed_nodes)?r.completed_nodes.map(String):[]),l=n.map(u=>{const p=String(u?.node_id||"").trim(),k=`node-${p}`,q=Array.isArray(u?.depends_on)?u.depends_on.map(K=>`node-${String(K||"").trim()}`).filter(Boolean):[],b=q.every(K=>s.has(K.replace(/^node-/,""))),w=nc(p,r,b?[]:q),M=r?.node_outputs?.[p]||r?.nodeOutputs?.[p]||{},E=t===k&&String(a?.status||"").trim().toLowerCase()==="running"?"in_progress":w==="pending"&&b?"runnable":w;return{id:k,title:String(u?.objective||p||"Workflow node"),description:u?.agent_id?`agent: ${u.agent_id}`:"",dependencies:q,state:E,retry_count:Number(r?.node_attempts?.[p]||r?.nodeAttempts?.[p]||0),error_message:String(M?.error||M?.content?.error||""),runtime_status:String(M?.content?.status||""),runtime_detail:String(M?.summary||M?.content?.message||""),assigned_role:String(u?.agent_id||""),workflow_id:String(a?.automation_id||""),session_id:String(M?.content?.session_id||M?.content?.sessionId||"")}});return{currentTaskId:t||l.find(u=>u.state==="in_progress"||u.state==="assigned")?.id||l.find(u=>u.state==="runnable")?.id||"",taskSource:"checkpoint",tasks:l}}function sc(a,t,n){const r=String(a?.status||"").trim().toLowerCase();if(!["running","pausing","paused"].includes(r))return"";for(let l=n.length-1;l>=0;l-=1){const d=n[l]?.event?.properties||n[l]?.event||{},u=En(String(d?.task_id||d?.step_id||d?.node_id||"").trim());if(u)return u;const p=vr(String(d?.message||d?.detail||d?.reason||""));if(p)return p}for(let l=t.length-1;l>=0;l-=1){const d=vr(Kn(t[l]?.message));if(d)return d}const s=Array.isArray(a?.checkpoint?.pending_nodes)?a.checkpoint.pending_nodes:[];return s.length?En(String(s[0]||"")):""}function nn(a){const t=a?.properties||a||{};return String(t?.reason||t?.detail||t?.error?.message||t?.error||t?.message||t?.status||"").trim()}function os(a){const t=String(a?.detail||"").trim();return t?t.includes("BASH_COMMAND_MISSING")?"This workflow failed because the agent called the `bash` tool without providing a shell command. The tool was available, but the request payload was missing its required `command` field.":t.includes("WEBFETCH_URL_MISSING")?"This workflow failed because a web fetch tool call was made without a URL.":t.includes("No such file or directory")?"This workflow failed because the agent tried to read a path that does not exist from the configured workspace root.":t:""}function ic(a,t,n){const r=[],s=(l,d,u,p,k)=>{u.trim()&&(r.some(q=>q.key===l)||r.push({key:l,title:d,reason:u,source:p,at:k}))};if((a?.requires_approval===!0||String(a?.status||"").trim()==="pending_approval")&&s("approval-required","Approval required",String(a?.approval_reason||"Manual approval required before external side effects.").trim(),"policy"),String(a?.denial_reason||"").trim()&&s("denied","Run denied",String(a.denial_reason).trim(),"run"),String(a?.paused_reason||"").trim()&&s("paused","Run paused",String(a.paused_reason).trim(),"run"),String(a?.detail||"").trim()){const l=String(a.detail).trim();(l.toLowerCase().includes("tool")||l.toLowerCase().includes("bash_command_missing")||l.toLowerCase().includes("command_missing")||l.toLowerCase().includes("permission")||l.toLowerCase().includes("approval")||l.toLowerCase().includes("mcp")||l.toLowerCase().includes("auth")||l.toLowerCase().includes("failed after"))&&s("detail","Failure reason",os(a),"run")}is(a).length||s("missing-session","No linked session transcript","This run does not expose a linked session transcript, so only telemetry/history are available.","run");for(const l of Yl(a)){const d=Xl(l.value);if(!d)continue;const u=d.toLowerCase();(u.includes("could not complete")||u.includes("invalid attachment")||u.includes("timed out")||u.includes("blocked")||u.includes("no email delivery tool")||u.includes("auth was not approved"))&&s(`node-output-${l.nodeId}`,`Node issue: ${l.nodeId}`,Da(d,360),l.nodeId,Number(l.value?.created_at_ms||l.value?.createdAtMs||0))}return[...t,...n].forEach(l=>{const d=String(Yt(l?.event||l)||"").trim(),u=nn(l?.event||l),p=Number(l?.at||wa(l?.event||l)||0);(d==="permission.asked"||d==="approval.required"||d==="routine.approval_required")&&s(`event-${d}`,"Permission or approval required",u||d,"permission",p),d==="mcp.auth.required"&&s(`event-${d}`,"MCP auth required",u||"An MCP connector requires authorization.","mcp",p),(d==="session.error"||d==="run.failed"||d==="routine.run.failed")&&s(`event-${d}`,"Execution failure",u||d,"session",p),u.toLowerCase().includes("no further tool calls")&&s("tool-mode","Tool policy blocked progress",u,"policy",p),u.toLowerCase().includes("timed out")&&s(`timeout-${d||p}`,"Timeout",u,"session",p)}),r.sort((l,d)=>(d.at||0)-(l.at||0))}function oc({value:a,onChange:t,routedSkill:n,routingConfidence:r,validationBadge:s,generatedSkill:l,advancedMode:d,customSkillName:u,customSkillDescription:p,customWorkflowKind:k,onToggleAdvancedMode:q,onChangeCustomSkillName:b,onChangeCustomSkillDescription:w,onChangeCustomWorkflowKind:M,showArtifactPreview:E,onToggleArtifactPreview:K,artifactPreviewKey:B,onSelectArtifactPreviewKey:se,onGenerateSkill:G,onInstallGeneratedSkill:ge,isGeneratingSkill:N,isInstallingSkill:W,installStatus:J,topMatches:S,isMatching:fe}){const f=Object.keys(l?.artifacts||{});return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Describe what you want the AI to do — in plain English. No technical knowledge needed."}),e("textarea",{className:"tcp-input min-h-[120px] text-base",placeholder:`e.g. "${hr[0]}"`,value:a,onInput:D=>t(D.target.value),autoFocus:!0}),e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500",children:"Need inspiration? Try one of these:"}),e("div",{className:"flex flex-wrap gap-2",children:hr.slice(1).map(D=>e("button",{className:"tcp-btn truncate text-left text-xs",style:{maxWidth:"280px"},onClick:()=>t(D),children:D},D))})]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Reusable Flows"}),e("span",{className:"text-slate-500",children:fe?"Analyzing…":"Ready"})]}),n?e("p",{className:"mt-1",children:["Reusable flow match: ",e("strong",{children:n})," ",r?`(${r})`:"",s?e("span",{className:`ml-2 ${s==="validated"?"tcp-badge-ok":"tcp-badge-warn"}`,children:s==="validated"?"Validated":"Not validated"}):null]}):e("p",{className:"mt-1 text-slate-400",children:"No reusable flow selected. Tandem will create and run a workflow plan in the engine."}),S.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:S.slice(0,3).map((D,de)=>e("span",{className:"tcp-badge-info",children:[String(D?.skill_name||"unknown")," ",typeof D?.confidence=="number"?`${Math.round(D.confidence*100)}%`:""]},`${String(D?.skill_name||"match")}-${de}`))}):null]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Optional: Reusable Skill Export"}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:q,children:d?"Hide Export Options":"Show Export Options"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:G,disabled:!a.trim()||N,children:N?"Generating…":"Generate Reusable Skill Draft"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:ge,disabled:!l?.artifacts||W,children:W?"Installing…":"Save Reusable Skill"})]})]}),e("p",{className:"mt-1 text-slate-400",children:"This is a secondary prompt-based export path. It does not power the default automation flow, and it does not automatically track planner-chat revisions to the workflow plan."}),e("div",{className:"mt-2 rounded-lg border border-slate-800/70 bg-slate-950/30 px-3 py-2 text-xs text-slate-400",children:"Recommended flow: review and finalize the workflow plan first, then generate or regenerate the reusable skill draft if you want a reusable export from the current prompt."}),d?e("div",{className:"mt-2 grid gap-2",children:[e("input",{className:"tcp-input text-xs",placeholder:"skill-name",value:u,onInput:D=>b(D.target.value)}),e("input",{className:"tcp-input text-xs",placeholder:"Short skill description",value:p,onInput:D=>w(D.target.value)}),e("select",{className:"tcp-input text-xs",value:k,onInput:D=>M(D.target.value),children:[e("option",{value:"pack_builder_recipe",children:"pack_builder_recipe"}),e("option",{value:"automation_v2_dag",children:"automation_v2_dag"})]})]}):null,l?e("div",{className:"mt-2 grid gap-1",children:[e("p",{children:["Optional scaffold status:"," ",e("strong",{children:String(l?.status||"generated")})]}),e("p",{className:"text-amber-200",children:"This draft was generated from the prompt and export options. If you revise the workflow plan later in review, regenerate this draft before saving it."}),e("p",{children:["Suggested skill:"," ",e("strong",{children:String(l?.router?.skill_name||"new optional skill")})]}),e("p",{className:"text-slate-400",children:["Artifacts:"," ",f.join(", ")||"SKILL.md, workflow.yaml, automation.example.yaml"]}),e("div",{className:"mt-1 flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:K,children:E?"Hide Raw":"Show Raw"}),E?e("select",{className:"tcp-input h-7 text-xs",value:B,onInput:D=>se(D.target.value),children:Object.keys(l?.artifacts||{}).map(D=>e("option",{value:D,children:D},D))}):null]}),E?e("textarea",{className:"tcp-input min-h-[140px] font-mono text-[11px]",readOnly:!0,value:String(l?.artifacts?.[B]||"")}):null]}):e("p",{className:"mt-1 text-slate-400",children:"Generate a reusable skill draft from this prompt if you want to save it for later reuse."}),J?e("p",{className:"mt-2 text-slate-300",children:J}):null]})]})}function lc({selected:a,onSelect:t,customCron:n,onCustomCron:r}){return e("div",{className:"grid gap-3",children:[e("p",{className:"text-sm text-slate-400",children:"When should this automation run?"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:ln.map(s=>e("button",{onClick:()=>t(s),className:`tcp-list-item flex flex-col items-start gap-1 text-left transition-all ${a===s.label?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("div",{className:"flex items-center gap-2 font-medium",children:[e("span",{children:s.icon}),e("span",{children:s.label})]}),e("span",{className:"tcp-subtle text-xs",children:s.desc}),s.cron?e("code",{className:"rounded bg-slate-800/60 px-1.5 py-0.5 text-xs text-slate-400",children:s.cron}):null]},s.label))}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-500",children:"Custom cron expression (advanced)"}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"e.g. 30 8 * * 1-5 (8:30am weekdays)",value:n,onInput:s=>r(s.target.value)})]})]})}function cc({selected:a,onSelect:t,maxAgents:n,onMaxAgents:r,workspaceRoot:s,onWorkspaceRootChange:l,providerOptions:d,providerId:u,modelId:p,plannerProviderId:k,plannerModelId:q,onProviderChange:b,onModelChange:w,onPlannerProviderChange:M,onPlannerModelChange:E,roleModelsJson:K,onRoleModelsChange:B,roleModelsError:se,toolAccessMode:G,customToolsText:ge,onToolAccessModeChange:N,onCustomToolsTextChange:W,mcpServers:J,selectedMcpServers:S,onToggleMcpServer:fe,onOpenMcpSettings:f,workspaceRootError:D,plannerModelError:de,workspaceBrowserOpen:$e,workspaceBrowserDir:Y,workspaceBrowserSearch:U,onWorkspaceBrowserSearchChange:ie,onOpenWorkspaceBrowser:oe,onCloseWorkspaceBrowser:Ue,onBrowseWorkspaceParent:_e,onBrowseWorkspaceDirectory:P,onSelectWorkspaceDirectory:te,workspaceBrowserParentDir:ve,workspaceCurrentBrowseDir:Se,filteredWorkspaceDirectories:V}){const Ne=d.find(F=>F.id===u)?.models||[],me=d.find(F=>F.id===k)?.models||[],Ee=String(U||"").trim().toLowerCase();return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"How should the AI handle this task? (You can always change this later.)"}),e("div",{className:"grid gap-3",children:Ln.map(F=>e("button",{onClick:()=>t(F.id),className:`tcp-list-item flex items-start gap-4 text-left transition-all ${a===F.id?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("span",{className:"mt-0.5 text-2xl",children:F.icon}),e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-semibold",children:F.label}),F.id==="team"?e("span",{className:"rounded-full bg-amber-500/20 px-2 py-0.5 text-xs text-amber-300",children:"Recommended"}):null]}),e("span",{className:"text-sm text-slate-300",children:F.desc}),e("span",{className:"tcp-subtle text-xs",children:["Best for: ",F.bestFor]})]}),e("div",{className:"ml-auto mt-1 h-4 w-4 shrink-0 rounded-full border-2 border-slate-600 transition-all data-[checked]:border-amber-400 data-[checked]:bg-amber-400/30","data-checked":a===F.id?!0:void 0})]},F.id))}),a==="swarm"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Max parallel agents"}),e("input",{type:"number",min:"2",max:"16",className:"tcp-input w-24",value:n,onInput:F=>r(F.target.value)})]}):null,e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Execution Directory"}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn",type:"button",onClick:oe,children:"Browse"}),e("input",{className:`tcp-input text-sm ${D?"border-red-500/70 text-red-100":""}`,value:s,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>l(""),disabled:!s,children:"Clear"})]}),e("div",{className:"text-xs text-slate-500",children:"Tandem will run this automation from this workspace directory."}),D?e("div",{className:"text-xs text-red-300",children:D}):null]})]}),e(ot,{children:$e?e(xe.div,{className:"fixed inset-0 z-50 flex items-center justify-center p-4",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:Ue}),e(xe.div,{className:"tcp-confirm-dialog max-w-2xl",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",Se||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:_e,disabled:!ve,children:"Up"}),e("button",{className:"tcp-btn-primary",type:"button",onClick:te,disabled:!Se,children:"Select This Folder"}),e("button",{className:"tcp-btn",type:"button",onClick:Ue,children:"Close"})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:U,onInput:F=>ie(F.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:V.length?V.map(F=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>P(String(F?.path||"")),children:String(F?.name||F?.path||"")},String(F?.path||F?.name))):e(qe,{text:Ee?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Provider"}),e("select",{className:"tcp-input text-sm",value:u,onInput:F=>b(F.target.value),children:[e("option",{value:"",children:"Use workspace default"}),d.map(F=>e("option",{value:F.id,children:F.id},F.id))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("input",{className:"tcp-input text-sm",value:p,list:u?`models-${u}`:void 0,onInput:F=>w(F.target.value),placeholder:"Use workspace default model"}),u?e("datalist",{id:`models-${u}`,children:Ne.map(F=>e("option",{value:F},F))}):null]})]}),e("div",{className:"grid gap-2 rounded-lg border border-slate-800/70 bg-slate-950/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Planner fallback model"}),e("div",{className:"text-xs text-slate-400",children:"Optional. Use this only if you want planning chat to try broader engine-side revisions beyond the built-in deterministic edits."}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner provider"}),e("select",{className:"tcp-input text-sm",value:k,onInput:F=>M(F.target.value),children:[e("option",{value:"",children:"Disabled"}),d.map(F=>e("option",{value:F.id,children:F.id},`planner-${F.id}`))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("input",{className:"tcp-input text-sm",value:q,list:k?`planner-models-${k}`:void 0,onInput:F=>E(F.target.value),placeholder:"Disabled unless provider and model are set"}),k?e("datalist",{id:`planner-models-${k}`,children:me.map(F=>e("option",{value:F},F))}):null]})]}),de?e("div",{className:"text-xs text-red-300",children:de}):null]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Role model overrides (advanced JSON)"}),e("textarea",{className:`tcp-input min-h-[72px] font-mono text-xs ${se?"border-red-500/70 text-red-100":""}`,value:K,onInput:F=>B(F.target.value),placeholder:'{"planner":{"provider_id":"openai","model_id":"gpt-5"},"worker":{"provider_id":"anthropic","model_id":"claude-sonnet-4"}}'}),se?e("div",{className:"text-xs text-red-300",children:se}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${G==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>N("all"),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access. Use this for autonomous coding and file operations."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${G==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>N("custom"),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still come from the selected servers below."})]})]}),G==="custom"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Allowed built-in tools"}),e("textarea",{className:"tcp-input min-h-[96px] font-mono text-xs",value:ge,onInput:F=>W(F.target.value),placeholder:`read
535
+ write
536
+ edit
537
+ bash
538
+ ls
539
+ glob
540
+ websearch`}),e("div",{className:"text-xs text-slate-500",children:"Enter one tool per line or comma-separated. Example: `read`, `write`, `edit`, `bash`, `ls`, `glob`, `websearch`."})]}):e("div",{className:"text-xs text-slate-500",children:"All built-in tools are allowed. MCP tools are additionally controlled by the server selection below."})]}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"MCP Servers"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:f,children:"Add MCP Server"})]}),J.length?e("div",{className:"flex flex-wrap gap-2",children:J.map(F=>{const De=S.includes(F.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${De?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>fe(F.name),children:[F.name," ",F.connected?"• connected":"• disconnected"]},F.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet. Add one to allow external tools in this automation."})]})]})}function dc({wizard:a,onToggleExportPackDraft:t,onSubmit:n,isPending:r,planPreview:s,isPreviewing:l,planningConversation:d,planningChangeSummary:u,onSendPlanningMessage:p,isSendingPlanningMessage:k,onResetPlanningChat:q,isResettingPlanningChat:b,plannerError:w,plannerDiagnostics:M,generatedSkill:E,installStatus:K}){const[B,se]=y(""),[G,ge]=y(!1),[N,W]=y(!1),[J,S]=y({}),fe=a.cron?a.cron:ln.find(le=>le.label===a.schedulePreset)?.intervalSeconds?`Every ${ln.find(le=>le.label===a.schedulePreset).intervalSeconds/3600}h`:a.schedulePreset||"Manual",f=s&&typeof s=="object"?s.operator_preferences||s.operatorPreferences||{}:{},D=String(f?.execution_mode||a.mode||"team").trim(),de=Ln.find(le=>le.id===D),$e=Number(f?.max_parallel_agents??f?.maxParallelAgents??(D==="swarm"?a.maxAgents:1)),Y=!!s,U=String(Y?f?.model_provider||f?.modelProvider||"":a.modelProvider||"").trim(),ie=String(Y?f?.model_id||f?.modelId||"":a.modelId||"").trim(),oe=f&&typeof f=="object"&&(f?.role_models?.planner||f?.roleModels?.planner),Ue=String(Y?oe?.provider_id||oe?.providerId||"":a.plannerModelProvider||"").trim(),_e=String(Y?oe?.model_id||oe?.modelId||"":a.plannerModelId||"").trim(),P=!!(Ue&&_e||U&&ie),te=String(s?.workspace_root||s?.workspaceRoot||a.workspaceRoot||"").trim(),ve=Array.isArray(s?.allowed_mcp_servers||s?.allowedMcpServers)?s?.allowed_mcp_servers||s?.allowedMcpServers||[]:a.selectedMcpServers,Se=String(Y?f?.tool_access_mode||f?.toolAccessMode||"all":a.toolAccessMode||"all").trim(),V=Y?Ba((f?.tool_allowlist||f?.toolAllowlist||[]).map(le=>String(le||"").trim())):Bn(a.customToolsText),Ne=s?.schedule?rs(s.schedule):fe,me=String(s?.title||"").trim(),Ee=String(M?.fallback_reason||M?.fallbackReason||"").trim(),F=String(M?.detail||"").trim(),De=le=>S(ae=>({...ae,[le]:!ae[le]}));return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Review your automation before deploying."}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/40 p-4 grid gap-3",children:[me?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Plan Title"}),e("span",{className:"text-sm font-semibold text-slate-100",children:me})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Goal"}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>ge(le=>!le),children:[e("span",{className:"text-sm text-slate-100 italic",children:G?"Hide goal":"View goal"}),e("span",{className:"tcp-subtle text-xs",children:G?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${G?"":"max-h-28 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:Na(a.goal||"")}})})]})]}),e("div",{className:"grid grid-cols-2 gap-3",children:[e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Schedule"}),e("span",{className:"text-sm font-medium text-slate-200",children:Ne})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Execution Mode"}),e("span",{className:"text-sm font-medium text-slate-200",children:[de?.icon," ",de?.label||D,Number.isFinite($e)&&$e>1?` · ${$e} agents`:""]})]})]}),Y||U||ie?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Model Override"}),e("span",{className:"text-sm font-medium text-slate-200",children:U||ie?`${U||"default provider"} / ${ie||"default model"}`:"Workspace default"})]}):null,Y||Ue||_e?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Planner Model"}),e("span",{className:"text-sm font-medium text-slate-200",children:Ue||_e?`${Ue||"default provider"} / ${_e||"default model"}`:U||ie?`Using model override: ${U||"default provider"} / ${ie||"default model"}`:"Workspace default"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Broader Planner Revisions"}),e("span",{className:"text-sm font-medium text-slate-200",children:P?"Enabled. Tandem will use the planner model if set, otherwise it falls back to the selected model override.":"Disabled unless a planner model, model override, or workspace default model is configured"})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workspace Root"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:te||"engine workspace root"})]}),Y||ve.length?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"MCP Servers"}),ve.length?e("div",{className:"flex flex-wrap gap-1",children:ve.map(le=>e("span",{className:"tcp-badge-info",children:le},le))}):e("span",{className:"text-sm font-medium text-slate-400",children:"None"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Tool Access"}),Se==="custom"?V.length?e("div",{className:"flex flex-wrap gap-1",children:V.map(le=>e("span",{className:"tcp-badge-info",children:le},le))}):e("span",{className:"text-sm font-medium text-slate-400",children:"Custom allowlist"}):e("span",{className:"text-sm font-medium text-slate-200",children:"All tools"})]}),a.routedSkill?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Reusable Flow Match"}),e("span",{className:"text-sm font-medium text-slate-200",children:[a.routedSkill,a.routingConfidence?` (${a.routingConfidence})`:""]})]}):null,a.cron?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Cron"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:a.cron})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workflow Plan"}),l?e("span",{className:"text-sm text-slate-300",children:"Planning workflow…"}):s?e("div",{className:"grid gap-1 text-sm text-slate-300",children:[e("span",{children:["Confidence: ",e("strong",{children:String(s?.confidence||"unknown")})]}),e("span",{children:["Execution target:"," ",e("strong",{children:String(s?.execution_target||"automation_v2")})]}),me?e("span",{children:["Title: ",e("strong",{children:me})]}):null,e("span",{children:["Steps:"," ",e("strong",{children:Array.isArray(s?.steps)?s.steps.length:0})]}),Array.isArray(s?.steps)&&s.steps.length?e("div",{className:"mt-1 grid gap-1",children:s.steps.map((le,ae)=>(()=>{const nt=String(le?.step_id||le?.stepId||`step-${ae+1}`),et=!!J[nt];return e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>De(nt),children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-xs font-medium text-slate-200",children:[nt,le?.kind?e("span",{className:"ml-2 text-[11px] uppercase tracking-wide text-slate-500",children:String(le.kind)}):null]}),typeof le?.objective=="string"&&le.objective.trim()?e("div",{className:"mt-1 line-clamp-2 text-xs text-slate-400",children:le.objective}):null]}),e("span",{className:"tcp-subtle shrink-0 text-xs",children:et?"Hide":"Details"})]}),et&&typeof le?.objective=="string"&&le.objective.trim()?e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:"tcp-markdown tcp-markdown-ai text-sm",dangerouslySetInnerHTML:{__html:Na(le.objective||"")}})}):null]},`${nt}-${ae}`)})())}):null,typeof s?.description=="string"&&s.description.trim()?e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>W(le=>!le),children:[e("span",{className:"text-sm text-slate-200",children:"Plan description"}),e("span",{className:"tcp-subtle text-xs",children:N?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${N?"":"max-h-24 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:Na(String(s.description||""))}})})]}):null]}):e("span",{className:"text-sm text-slate-400",children:"Workflow preview has not been generated yet."})]})]}),w?e("div",{className:"rounded-xl border border-red-500/40 bg-red-950/30 p-3 text-sm text-red-200",children:w}):null,Ee?e("div",{className:"rounded-xl border border-amber-500/40 bg-amber-950/30 p-3 text-sm text-amber-100",children:[e("div",{className:"font-medium text-amber-200",children:"Planner fallback"}),e("div",{className:"mt-1",children:["Reason: ",e("code",{className:"text-xs",children:Ee})]}),F?e("div",{className:"mt-2 text-xs text-amber-200/90 whitespace-pre-wrap",children:F}):null]}):null,u.length?e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-emerald-300",children:"Latest Plan Changes"}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:u.map((le,ae)=>e("span",{className:"tcp-badge-ok",children:le},`${le}-${ae}`))})]}):null,s?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/40 p-4 grid gap-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Planning Chat"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:b||!s?.plan_id,onClick:q,children:b?"Resetting…":"Reset Plan"})]}),e("div",{className:"rounded-lg border border-amber-500/30 bg-amber-950/20 px-3 py-2 text-xs text-amber-200",children:P?"With a planner model or model override configured, planning chat can attempt broader natural-language workflow rewrites across the allowed fixed step ids. Deterministic edits still act as the safety net for schedule, workspace root, title, MCP servers, execution mode, model overrides, safe workflow shapes, small workflow-step changes, and terminal output-style changes. Custom step types are still not supported in this slice.":"Planning chat is currently limited to deterministic edits like schedule, workspace root, title, MCP servers, execution mode, model overrides, switching between safe workflow shapes, small workflow-step changes like adding or removing input collection, analysis, or notifications, and terminal output-style changes like JSON, markdown, summary, URLs, or citations. Broader workflow rewrites require a planner model or model override, and custom step types are still not supported in this slice."}),e("div",{className:"max-h-56 overflow-auto rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:Array.isArray(d?.messages)&&d.messages.length?e("div",{className:"grid gap-3",children:d.messages.map((le,ae)=>e("div",{className:"grid gap-1",children:[e("span",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:String(le?.role||"assistant")}),e("div",{className:"text-sm text-slate-200",children:String(le?.text||"").trim()})]},`${le?.created_at_ms||ae}-${ae}`))}):e("div",{className:"text-sm text-slate-400",children:"Add planning notes here to revise the workflow before creating it."})}),e("textarea",{className:"tcp-input min-h-[84px] text-sm",value:B,onInput:le=>se(le.target.value),placeholder:'Example: "Make this weekly, run it from /srv/acme/app, and remove notifications."'}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn-primary",disabled:k||!B.trim()||!s?.plan_id,onClick:()=>{const le=B.trim();le&&(p(le),se(""))},children:k?"Updating plan…":"Update Plan"})})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:e("label",{className:"flex items-start gap-3 rounded-lg border border-slate-700/50 bg-slate-900/30 p-3 text-sm text-slate-300",children:[e("input",{type:"checkbox",className:"mt-0.5",checked:a.exportPackDraft,onChange:t}),e("span",{className:"grid gap-1",children:[e("span",{className:"font-medium text-slate-200",children:"Also export a reusable pack draft"}),e("span",{className:"text-xs text-slate-400",children:"After creating the automation, Tandem will also create a Pack Builder draft so this workflow can be saved and reused later."})]})]})}),E||K?e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Reusable Skill Export"}),e("div",{className:"mt-1 grid gap-1",children:[E?e(qt,{children:[e("span",{children:["Draft status:"," ",e("strong",{className:"text-slate-300",children:String(E?.status||"generated")})]}),e("span",{className:"text-amber-200",children:"This draft is prompt-based and may be stale if you changed the workflow plan in planning chat. Regenerate it from Step 1 before saving if you want it to reflect the latest plan direction."})]}):null,K?e("span",{children:K}):null]})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:["💡 Tandem will save this automation and schedule a"," ",e("strong",{className:"text-slate-300",children:de?.label||D})," that runs"," ",e("strong",{className:"text-slate-300",children:Ne}),". You can pause, edit or delete it anytime."]}),e("button",{className:"tcp-btn-primary",disabled:r||l||!a.goal.trim()||!s,onClick:n,children:r?"Creating automation…":"🚀 Create Automation"})]})}function uc({client:a,api:t,toast:n,navigate:r,defaultProvider:s,defaultModel:l}){const d=jt(),[u,p]=y(1),[k,q]=y("automations_page"),[b,w]=y([]),[M,E]=y(null),[K,B]=y(null),[se,G]=y([]),[ge,N]=y(""),[W,J]=y(null),[S,fe]=y(!1),[f,D]=y(""),[de,$e]=y(""),[Y,U]=y(""),[ie,oe]=y(null),[Ue,_e]=y(!1),[P,te]=y("SKILL.md"),[ve,Se]=y(""),[V,Ne]=y({goal:"",workspaceRoot:"",schedulePreset:"Every morning",cron:"",mode:"team",maxAgents:"4",routedSkill:"",routingConfidence:"",modelProvider:String(s||""),modelId:String(l||""),plannerModelProvider:"",plannerModelId:"",roleModelsJson:"",toolAccessMode:"all",customToolsText:"",selectedMcpServers:[],exportPackDraft:!1,advancedMode:!1,customSkillName:"",customSkillDescription:"",customWorkflowKind:"pack_builder_recipe"}),me=Q({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),Ee=Q({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),F=Q({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),De=Q({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),le=Q({queryKey:["automations","workspace-browser",f],enabled:S&&!!f,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(f)}`,{method:"GET"})}),ae=H(()=>(Array.isArray(me.data?.all)?me.data.all:[]).map(C=>({id:String(C?.id||"").trim(),models:Object.keys(C?.models||{})})).filter(C=>!!C.id).sort((C,z)=>C.id.localeCompare(z.id)),[me.data]),nt=H(()=>ns(F.data),[F.data]),et=Array.isArray(le.data?.directories)?le.data.directories:[],Ge=String(le.data?.parent||"").trim(),Xe=String(le.data?.dir||f||"").trim(),ct=String(de||"").trim().toLowerCase(),bt=H(()=>ct?et.filter(v=>String(v?.name||v?.path||"").trim().toLowerCase().includes(ct)):et,[et,ct]);ye(()=>{const v=String(Ee.data?.default||s||"").trim();if(!v)return;const C=ae.find(m=>m.id===v)?.models||[],z=String(Ee.data?.providers?.[v]?.default_model||l||C[0]||"").trim();Ne(m=>m.modelProvider&&m.modelId?m:{...m,modelProvider:m.modelProvider||v,modelId:m.modelId||z})},[l,s,ae,Ee.data]),ye(()=>{const v=String(De.data?.workspaceRoot||De.data?.workspace_root||"").trim();v&&Ne(C=>String(C.workspaceRoot||"").trim()?C:{...C,workspaceRoot:v})},[De.data]);const dt=Ae({mutationFn:async v=>!v.trim()||!a?.skills?.match?null:a.skills.match({goal:v,maxMatches:3,threshold:.35}),onError:()=>{}}),Te=Ae({mutationFn:async()=>{if(!a?.workflowPlans?.chatStart)throw new Error("This control panel build is missing workflow planner client support. Rebuild the control panel against the local tandem client package.");return await a.workflowPlans.chatStart({prompt:V.goal,schedule:ql(V),plan_source:k,allowed_mcp_servers:V.selectedMcpServers,workspace_root:V.workspaceRoot,operator_preferences:Ol(V)})||null},onSuccess:v=>{E(v?.plan||null),B(v?.conversation||null),G([]),N(""),J(v?.planner_diagnostics||v?.plannerDiagnostics||null)},onError:v=>{E(null),B(null),G([]),N(v instanceof Error?v.message:String(v)),J(null)}}),ze=Ae({mutationFn:async v=>!a?.workflowPlans?.chatMessage||!M?.plan_id?null:a.workflowPlans.chatMessage({plan_id:M.plan_id,message:v}),onSuccess:v=>{E(v?.plan||null),B(v?.conversation||null),G(Array.isArray(v?.change_summary)?v.change_summary.map(C=>String(C||"").trim()).filter(Boolean):[]),N(typeof v?.clarifier?.question=="string"?String(v.clarifier.question):""),J(v?.planner_diagnostics||v?.plannerDiagnostics||null)},onError:v=>{const C=v instanceof Error?v.message:String(v);N(C),n("err",C)}}),rt=Ae({mutationFn:async()=>!a?.workflowPlans?.chatReset||!M?.plan_id?null:a.workflowPlans.chatReset({plan_id:M.plan_id}),onSuccess:v=>{E(v?.plan||null),B(v?.conversation||null),G([]),N(""),J(v?.planner_diagnostics||v?.plannerDiagnostics||null)},onError:v=>{const C=v instanceof Error?v.message:String(v);N(C),n("err",C)}}),tt=Ae({mutationFn:async v=>{if(!a?.skills?.get||!a?.skills?.validate)return null;const z=(await a.skills.get(v))?.content;return z?a.skills.validate({content:z}):null},onSuccess:v=>{if(!v){U("");return}U(v.invalid>0?"not_validated":"validated")},onError:()=>U("not_validated")}),Ve=Ae({mutationFn:async()=>{if(!a?.skills?.generate||!V.goal.trim())return null;const v=V.advancedMode?[V.goal.trim(),V.customSkillName?`Skill name: ${V.customSkillName}`:"",V.customSkillDescription?`Description: ${V.customSkillDescription}`:"",`Workflow kind: ${V.customWorkflowKind}`].filter(Boolean).join(`
541
+ `):V.goal;return a.skills.generate({prompt:v})},onSuccess:v=>{oe(v);const C=Object.keys(v?.artifacts||{})[0];te(C||"SKILL.md"),_e(!1),Se("")},onError:()=>{oe(null),_e(!1),Se("Optional skill generation failed.")}}),st=Ae({mutationFn:async()=>{if(!a?.skills?.generateInstall)return null;const v=ie?.artifacts;if(!v||!v["SKILL.md"])throw new Error("No generated artifacts available to install.");return a.skills.generateInstall({location:"project",conflictPolicy:"rename",artifacts:{"SKILL.md":v["SKILL.md"],"workflow.yaml":v["workflow.yaml"],"automation.example.yaml":v["automation.example.yaml"]}})},onSuccess:v=>{const C=v?.skill?.name;Se(C?`Installed optional skill as '${String(C)}' in project skills.`:"Installed optional skill in project skills."),d.invalidateQueries({queryKey:["automations"]})},onError:v=>Se(`Install failed: ${v instanceof Error?v.message:String(v)}`)}),yt=Ae({mutationFn:async()=>{if(!V.goal.trim())throw new Error("Please describe your goal first.");const v=M||await Te.mutateAsync().catch(z=>{throw z instanceof Error?z:new Error(String(z))}),C=v?.plan||v;if(!C)throw new Error("Workflow plan preview failed.");return a.workflowPlans.apply({plan:C,creator_id:"control-panel",...V.exportPackDraft?{pack_builder_export:{enabled:!0,auto_apply:!1}}:{}})},onSuccess:async v=>{v?.pack_builder_export?.status==="preview_pending"?n("ok","🎉 Automation created and reusable pack draft exported. Check Pack Builder to continue."):n("ok","🎉 Automation created! Check 'My Automations' to see it running."),await Promise.all([d.invalidateQueries({queryKey:["automations"]}),d.invalidateQueries({queryKey:["mcp"]})]),Ne({goal:"",workspaceRoot:String(De.data?.workspaceRoot||De.data?.workspace_root||"").trim(),schedulePreset:"Every morning",cron:"",mode:"team",maxAgents:"4",routedSkill:"",routingConfidence:"",modelProvider:String(s||""),modelId:String(l||""),plannerModelProvider:"",plannerModelId:"",roleModelsJson:"",toolAccessMode:"all",customToolsText:"",selectedMcpServers:[],exportPackDraft:!1,advancedMode:!1,customSkillName:"",customSkillDescription:"",customWorkflowKind:"pack_builder_recipe"}),w([]),q("automations_page"),E(null),B(null),G([]),N(""),U(""),oe(null),_e(!1),te("SKILL.md"),Se(""),p(1)},onError:v=>{const C=v instanceof Error?v.message:String(v);N(C),n("err",C)}}),pe=$a(V.workspaceRoot),Ce=an(V.plannerModelProvider,V.plannerModelId),at=Dl(V.roleModelsJson),ce=u===1?V.goal.trim().length>8:u===2?!!V.schedulePreset||!!V.cron.trim():u===3?!!V.mode&&!pe&&!Ce&&!at:!0,Le=["What?","When?","How?","Review"],ut=async()=>{if(u===1){const C=await dt.mutateAsync(V.goal);C&&C.decision==="match"&&C.skill_name?(tt.mutateAsync(String(C.skill_name)),Ne(m=>({...m,routedSkill:String(C.skill_name),routingConfidence:typeof C.confidence=="number"?`${Math.round(C.confidence*100)}%`:""}))):(U(""),Ne(m=>({...m,routedSkill:"",routingConfidence:""})));const z=Array.isArray(C?.top_matches)?C.top_matches:[];w(z)}const v=u+1;if(v===4){N(""),E(null),B(null),G([]);try{await Te.mutateAsync()}catch{return}}p(v)};return ye(()=>{if(u===1)try{const v=sessionStorage.getItem(gr);if(!v)return;sessionStorage.removeItem(gr);const C=JSON.parse(v),z=String(C?.prompt||"").trim();if(!z)return;const m=String(C?.plan_source||"chat_setup").trim()||"chat_setup";q(m),Ne(X=>({...X,goal:z}))}catch{}},[u]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex items-center gap-2",children:Le.map((v,C)=>{const z=C+1,m=z===u,X=z<u;return e("div",{className:"flex-1",children:[e("button",{className:`mb-1 flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium transition-all ${m?"bg-amber-500/20 text-amber-300":X?"text-slate-400":"text-slate-600"}`,onClick:()=>X&&p(z),children:[e("span",{className:`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${m?"bg-amber-500 text-black":X?"bg-slate-600 text-white":"bg-slate-800 text-slate-500"}`,children:X?"✓":z}),v]}),e("div",{className:"h-0.5 w-full rounded-full bg-slate-800",children:e("div",{className:"h-full rounded-full bg-amber-500 transition-all",style:{width:X?"100%":m?"50%":"0%"}})})]},v)})}),e(ot,{mode:"wait",children:e(xe.div,{initial:{opacity:0,x:16},animate:{opacity:1,x:0},exit:{opacity:0,x:-16},transition:{duration:.18},children:u===1?e(oc,{value:V.goal,onChange:v=>Ne(C=>({...C,goal:v})),routedSkill:V.routedSkill,routingConfidence:V.routingConfidence,validationBadge:Y,generatedSkill:ie,advancedMode:V.advancedMode,customSkillName:V.customSkillName,customSkillDescription:V.customSkillDescription,customWorkflowKind:V.customWorkflowKind,onToggleAdvancedMode:()=>Ne(v=>({...v,advancedMode:!v.advancedMode})),onChangeCustomSkillName:v=>Ne(C=>({...C,customSkillName:v})),onChangeCustomSkillDescription:v=>Ne(C=>({...C,customSkillDescription:v})),onChangeCustomWorkflowKind:v=>Ne(C=>({...C,customWorkflowKind:v})),showArtifactPreview:Ue,onToggleArtifactPreview:()=>_e(v=>!v),artifactPreviewKey:P,onSelectArtifactPreviewKey:v=>te(v),onGenerateSkill:()=>{Ve.mutateAsync()},onInstallGeneratedSkill:()=>{st.mutateAsync()},isGeneratingSkill:Ve.isPending,isInstallingSkill:st.isPending,installStatus:ve,topMatches:b,isMatching:dt.isPending}):u===2?e(lc,{selected:V.schedulePreset,onSelect:v=>Ne(C=>({...C,schedulePreset:v.label,cron:v.cron})),customCron:V.cron,onCustomCron:v=>Ne(C=>({...C,cron:v,schedulePreset:""}))}):u===3?e(cc,{selected:V.mode,onSelect:v=>Ne(C=>({...C,mode:v})),maxAgents:V.maxAgents,onMaxAgents:v=>Ne(C=>({...C,maxAgents:v})),workspaceRoot:V.workspaceRoot,onWorkspaceRootChange:v=>Ne(C=>({...C,workspaceRoot:v})),providerOptions:ae,providerId:V.modelProvider,modelId:V.modelId,plannerProviderId:V.plannerModelProvider,plannerModelId:V.plannerModelId,onProviderChange:v=>Ne(C=>({...C,modelProvider:v,modelId:v===C.modelProvider?C.modelId:""})),onModelChange:v=>Ne(C=>({...C,modelId:v})),onPlannerProviderChange:v=>Ne(C=>({...C,plannerModelProvider:v,plannerModelId:v===C.plannerModelProvider?C.plannerModelId:""})),onPlannerModelChange:v=>Ne(C=>({...C,plannerModelId:v})),roleModelsJson:V.roleModelsJson,onRoleModelsChange:v=>Ne(C=>({...C,roleModelsJson:v})),roleModelsError:at,toolAccessMode:V.toolAccessMode,customToolsText:V.customToolsText,onToolAccessModeChange:v=>Ne(C=>({...C,toolAccessMode:v})),onCustomToolsTextChange:v=>Ne(C=>({...C,customToolsText:v})),mcpServers:nt,selectedMcpServers:V.selectedMcpServers,onToggleMcpServer:v=>Ne(C=>({...C,selectedMcpServers:C.selectedMcpServers.includes(v)?C.selectedMcpServers.filter(z=>z!==v):[...C.selectedMcpServers,v]})),onOpenMcpSettings:()=>r("mcp"),workspaceRootError:pe,plannerModelError:Ce,workspaceBrowserOpen:S,workspaceBrowserDir:f,workspaceBrowserSearch:de,onWorkspaceBrowserSearchChange:$e,onOpenWorkspaceBrowser:()=>{const v=String(V.workspaceRoot||De.data?.workspaceRoot||De.data?.workspace_root||"/").trim();D(v||"/"),$e(""),fe(!0)},onCloseWorkspaceBrowser:()=>{fe(!1),$e("")},onBrowseWorkspaceParent:()=>{Ge&&D(Ge)},onBrowseWorkspaceDirectory:v=>D(v),onSelectWorkspaceDirectory:()=>{Xe&&(Ne(v=>({...v,workspaceRoot:Xe})),fe(!1),$e(""),n("ok",`Workspace selected: ${Xe}`))},workspaceBrowserParentDir:Ge,workspaceCurrentBrowseDir:Xe,filteredWorkspaceDirectories:bt}):e(dc,{wizard:V,onToggleExportPackDraft:()=>Ne(v=>({...v,exportPackDraft:!v.exportPackDraft})),onSubmit:()=>yt.mutate(),isPending:yt.isPending,planPreview:M,isPreviewing:Te.isPending,planningConversation:K,planningChangeSummary:se,onSendPlanningMessage:v=>{ze.mutateAsync(v)},isSendingPlanningMessage:ze.isPending,onResetPlanningChat:()=>{rt.mutateAsync()},isResettingPlanningChat:rt.isPending,plannerError:ge,plannerDiagnostics:W,generatedSkill:ie,installStatus:ve})},u)}),u<4?e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn",disabled:u===1||Te.isPending,onClick:()=>p(v=>v-1),children:"← Back"}),e("button",{className:"tcp-btn-primary",disabled:!ce||Te.isPending,onClick:()=>{ut()},children:Te.isPending?"Generating Plan...":"Next →"})]}):null]})}function wr({client:a,toast:t,navigate:n,viewMode:r,selectedRunId:s,onSelectRunId:l,onOpenRunningView:d,onOpenAdvancedEdit:u}){const p=jt(),k=pt(null),[q,b]=y(null),[w,M]=y(null),[E,K]=y("all"),[B,se]=y([]),[G,ge]=y(""),[N,W]=y("all"),[J,S]=y(""),[fe,f]=y([]),D=pt(null),de=pt(null),[$e,Y]=y(!0),[U,ie]=y(null),oe=s.startsWith("automation-v2-run-"),Ue=Q({queryKey:["automations","list"],queryFn:()=>a?.automations?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),_e=Q({queryKey:["automations","v2","list"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),P=H(()=>{const i=sa(_e.data,"automations"),c=new Map;for(const _ of i){const $=String(_?.automation_id||_?.automationId||_?.id||"").trim();$&&(c.has($)||c.set($,_))}return Array.from(c.values())},[_e.data]),te=H(()=>P.map(i=>String(i?.automation_id||i?.automationId||i?.id||"").trim()).filter(Boolean),[P]),ve=Q({queryKey:["providers","catalog","workflow-edit"],queryFn:()=>a?.providers?.catalog?.().catch(()=>({providers:[]}))??Promise.resolve({providers:[]}),refetchInterval:3e4}),Se=Q({queryKey:["mcp","servers","workflow-edit"],queryFn:()=>a?.mcp?.list?.().catch(()=>({servers:[]}))??Promise.resolve({servers:[]}),refetchInterval:15e3}),V=Q({queryKey:["automations","runs"],queryFn:()=>a?.automations?.listRuns?.({limit:20}).catch(()=>({runs:[]}))??Promise.resolve({runs:[]}),refetchInterval:9e3}),Ne=Q({queryKey:["automations","v2","runs",te],enabled:!!a?.automationsV2?.listRuns,queryFn:async()=>te.length?{runs:(await Promise.all(te.map(async c=>{const _=await a?.automationsV2?.listRuns?.(c,12).catch(()=>({runs:[]}));return Array.isArray(_?.runs)?_.runs:[]}))).flat()}:{runs:[]},refetchInterval:9e3}),me=Q({queryKey:["automations","run",s],enabled:!!s,queryFn:()=>(oe?a?.automationsV2?.getRun?.(s):a?.automations?.getRun?.(s))?.catch(()=>({run:null}))??Promise.resolve({run:null}),refetchInterval:s?5e3:!1}),Ee=Q({queryKey:["automations","run","artifacts",s],enabled:!!s&&!oe,queryFn:()=>a?.automations?.listArtifacts?.(s).catch(()=>({artifacts:[]})),refetchInterval:s?8e3:!1}),F=H(()=>is(me.data?.run),[me.data]),De=vs({queries:F.map(i=>({queryKey:["automations","run","session",s,i,"messages"],enabled:!!s&&!!i,queryFn:()=>a?.sessions?.messages?.(i).catch(()=>[])??Promise.resolve([]),refetchInterval:s&&i&&la(me.data?.run?.status)?4e3:!1}))}),le=String(me.data?.run?.automation_id||me.data?.run?.routine_id||"").trim(),ae=String(me.data?.contextRunID||(oe&&s?`automation-v2-${s}`:"")).trim(),nt=Q({queryKey:["automations","history",le],enabled:!!le&&!oe,queryFn:()=>a?.automations?.history?.(le,80).catch(()=>({events:[]})),refetchInterval:s?1e4:!1}),et=Q({queryKey:["automations","run","events",s],enabled:!!s&&!!a?.runEvents,queryFn:()=>a.runEvents(s,{tail:400}).catch(()=>[]),refetchInterval:s&&la(me.data?.run?.status)?5e3:!1}),Ge=Q({queryKey:["automations","run","context",ae],enabled:!!ae,queryFn:()=>api(`/api/engine/context/runs/${encodeURIComponent(ae)}`).catch(()=>({run:null})),refetchInterval:ae&&la(me.data?.run?.status)?5e3:!1}),Xe=Q({queryKey:["automations","run","context",ae,"blackboard"],enabled:!!ae,queryFn:()=>api(`/api/engine/context/runs/${encodeURIComponent(ae)}/blackboard`).catch(()=>({blackboard:null})),refetchInterval:ae&&la(me.data?.run?.status)?5e3:!1}),ct=Q({queryKey:["automations","run","context",ae,"events"],enabled:!!ae,queryFn:()=>api(`/api/engine/context/runs/${encodeURIComponent(ae)}/events`).catch(()=>({events:[]})),refetchInterval:ae&&la(me.data?.run?.status)?5e3:!1}),bt=Q({queryKey:["automations","run","context",ae,"patches"],enabled:!!ae,queryFn:()=>api(`/api/engine/context/runs/${encodeURIComponent(ae)}/blackboard/patches`).catch(()=>({patches:[]})),refetchInterval:ae&&la(me.data?.run?.status)?5e3:!1}),dt=Q({queryKey:["automations","packs"],queryFn:()=>a?.packs?.list?.().catch(()=>({packs:[]}))??Promise.resolve({packs:[]}),refetchInterval:3e4}),Te=Ae({mutationFn:i=>a?.automations?.runNow?.(i),onSuccess:async()=>{t("ok","Automation triggered."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ze=Ae({mutationFn:i=>a?.automationsV2?.runNow?.(i),onSuccess:async i=>{const c=String(i?.run?.run_id||i?.run?.runId||"").trim();t("ok","Workflow automation triggered."),await p.invalidateQueries({queryKey:["automations"]}),c&&(l(c),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),rt=Ae({mutationFn:async({action:i,runId:c,family:_,reason:$})=>_==="v2"?i==="pause"?a.automationsV2.pauseRun(c,$):a.automationsV2.resumeRun(c,$):i==="pause"?a.automations.pauseRun(c,$):a.automations.resumeRun(c,$),onSuccess:async()=>{t("ok","Run action applied."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),tt=Ae({mutationFn:async i=>{const c=String(i.name||"").trim(),_=String(i.objective||"").trim(),$=String(i.cronExpression||"").trim(),ue=Number(i.intervalSeconds);if(!c)throw new Error("Automation name is required.");if(!_)throw new Error("Objective is required.");if(i.scheduleKind==="cron"&&!$)throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(ue)||ue<=0))throw new Error("Interval seconds must be greater than zero.");return a.automations.update(i.automationId,{name:c,mode:i.mode,mission:{objective:_},policy:{approval:{requires_approval:!!i.requiresApproval}},schedule:i.scheduleKind==="cron"?{cron:{expression:$}}:{interval_seconds:{seconds:Math.round(ue)}}})},onSuccess:async()=>{t("ok","Automation updated."),M(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ve=Ae({mutationFn:async i=>{const c=String(i.name||"").trim(),_=String(i.description||"").trim(),$=String(i.workspaceRoot||"").trim(),ue=Sn(i.modelProvider,i.modelId),Qe=an(i.plannerModelProvider,i.plannerModelId),gt=$a($);if(!c)throw new Error("Automation name is required.");if(gt)throw new Error(gt);if(ue)throw new Error(ue);if(Qe)throw new Error(Qe);if(i.scheduleKind==="cron"&&!String(i.cronExpression||"").trim())throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(Number(i.intervalSeconds))||Number(i.intervalSeconds)<=0))throw new Error("Interval seconds must be greater than zero.");const Mt=Hl(i),Et=Gl(Mt),xt=i.selectedMcpServers.map(Fe=>String(Fe||"").trim()).filter(Boolean),Rt=jl(xt,i.toolAccessMode,i.customToolsText),ke=P.find(Fe=>String(Fe?.automation_id||Fe?.automationId||Fe?.id||"").trim()===i.automationId),Z=Array.isArray(ke?.agents)?ke.agents.map(Fe=>({...Fe,model_policy:Et,modelPolicy:void 0,tool_policy:{...Fe?.tool_policy||{},allowlist:Rt,denylist:Array.isArray(Fe?.tool_policy?.denylist)?Fe.tool_policy.denylist:[]},mcp_policy:{...Fe?.mcp_policy||{},allowed_servers:xt,allowed_tools:null}})):[],ft=Array.isArray(ke?.flow?.nodes)?ke.flow.nodes.map((Fe,Nt)=>{const Lt=String(Fe?.node_id||Fe?.nodeId||Fe?.id||`node-${Nt}`).trim(),mt=i.nodes.find(It=>It.nodeId===Lt);return mt?{...Fe,objective:String(mt.objective||"").trim()}:Fe}):[],Re=ke?.metadata&&typeof ke.metadata=="object"?ke.metadata:{};return a.automationsV2.update(i.automationId,{name:c,description:_||null,schedule:Jl(i),workspace_root:$,execution:{...ke?.execution||{},max_parallel_agents:i.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(i.maxParallelAgents||"4"),10)||4)):1},flow:ke?.flow?{...ke.flow,nodes:ft}:ke?.flow,agents:Z,metadata:{...Re,workspace_root:$,operator_preferences:Mt,allowed_mcp_servers:xt}})},onSuccess:async()=>{t("ok","Workflow automation updated."),ie(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),st=Ae({mutationFn:async({action:i,automationId:c,family:_})=>_==="v2"?i==="delete"?a.automationsV2.delete(c):i==="pause"?a.automationsV2.pause(c):a.automationsV2.resume(c):i==="delete"?a.automations.delete(c):a.automations.update(c,{status:i==="pause"?"paused":"enabled"}),onSuccess:async(i,c)=>{c.action==="delete"&&t("ok","Automation removed."),c.action==="pause"&&t("ok","Automation paused."),c.action==="resume"&&t("ok","Automation resumed."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),yt=H(()=>{const i=[...sa(Ue.data,"automations"),...sa(Ue.data,"routines")],c=new Map;for(const _ of i){const $=String(_?.automation_id||_?.routine_id||_?.id||"").trim();$&&(c.has($)||c.set($,_))}return Array.from(c.values())},[Ue.data]),pe=sa(V.data,"runs"),Ce=H(()=>(Array.isArray(ve.data?.providers)?ve.data.providers:[]).map(c=>({id:String(c?.id||"").trim(),models:Array.isArray(c?.models)?c.models.map(_=>String(_||"").trim()).filter(Boolean):[]})).filter(c=>c.id).sort((c,_)=>c.id.localeCompare(_.id)),[ve.data]),at=H(()=>ns(Se.data),[Se.data]),ce=sa(Ne.data,"runs"),Le=H(()=>{const i=[...pe,...ce],c=new Map;for(const _ of i){const $=String(_?.run_id||_?.runId||_?.id||"").trim();$&&(c.has($)||c.set($,_))}return Array.from(c.values()).sort((_,$)=>{const ue=cn(_?.started_at_ms||_?.startedAtMs||_?.created_at_ms||_?.createdAtMs||0);return cn($?.started_at_ms||$?.startedAtMs||$?.created_at_ms||$?.createdAtMs||0)-ue})},[pe,ce]),ut=sa(dt.data,"packs"),v=Le.filter(i=>la(i?.status)),C=Le.filter(i=>{const c=String(i?.status||"").trim().toLowerCase();return c==="failed"||c==="error"}),z=me.data?.run||null,m=Xe.data?.blackboard||null,X=Array.isArray(ct.data?.events)?ct.data.events:[],we=Array.isArray(bt.data?.patches)?bt.data.patches:[],T=H(()=>{if(!oe)return{tasks:[],currentTaskId:"",taskSource:"empty"};const i=sc(z,[],fe),c=es({run:Ge.data?.run||null,tasks:Array.isArray(Ge.data?.run?.steps)?Ge.data?.run.steps:[],blackboard:m,events:X});if(c.tasks.length){const _=i?c.tasks.map($=>$.id===i&&["pending","runnable","assigned"].includes($.state)?{...$,state:"in_progress"}:$):c.tasks;return{...c,tasks:_,currentTaskId:c.currentTaskId||i}}return rc(z,i)},[oe,z,fe,m,X,Ge.data]),I=H(()=>T.tasks.find(i=>i.id===J)||null,[J,T.tasks]);ye(()=>{!I||!D.current||D.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[I]);const lt=oe?Array.isArray(m?.artifacts)?m.artifacts:[]:sa(Ee.data,"artifacts"),ht=zl(z,lt),Tt=oe?(()=>{const i=Vl(X,we);return i.length?i:(Array.isArray(et.data)?et.data:[]).map((_,$)=>({id:`persisted:${s}:${$}`,family:"run_event",type:String(Yt(_)||"run.event"),detail:String(nn(_)||"").trim(),at:wa(_),raw:_})).sort((_,$)=>Number($.at||0)-Number(_.at||0))})():Array.isArray(nt.data?.events)?nt.data.events:Array.isArray(nt.data?.history)?nt.data.history:[],Bt=H(()=>{const i=(Array.isArray(et.data)?et.data:[]).map((c,_)=>({id:`persisted:${s}:${String(c?.seq||_)}:${String(Yt(c)||"")}`,source:"automations",at:wa(c),event:c}));return oe?[...i,...X.map(c=>({id:`context:${String(c?.seq||"")}:${String(c?.event_type||"")}`,source:"context",at:Fa(c?.created_at_ms||c?.timestamp_ms||c?.timestampMs)||Date.now(),event:c}))]:i},[oe,et.data,s,X]),ea=H(()=>{const i=[...Bt,...B],c=new Set;return i.filter(_=>!_?.id||c.has(_.id)?!1:(c.add(_.id),!0)).sort((_,$)=>Number(_.at||0)-Number($.at||0))},[Bt,B]),wt=ea.filter(i=>E==="all"?!0:i.source===E),Kt=H(()=>De.flatMap((i,c)=>{const _=F[c]||"";return(Array.isArray(i.data)?i.data:[]).map(ue=>({sessionId:_,message:ue}))}),[F,De]),ia=H(()=>{const i=[];return i.push({label:"status",value:String(z?.status||"unknown")}),i.push({label:"artifacts",value:String(lt.length)}),oe&&(i.push({label:"tasks",value:String(T.tasks.length)}),i.push({label:"context events",value:String(X.length)}),i.push({label:"blackboard patches",value:String(we.length)}),Array.isArray(z?.checkpoint?.completed_nodes)&&i.push({label:"completed nodes",value:String(z.checkpoint.completed_nodes.length)}),Array.isArray(z?.checkpoint?.pending_nodes)&&i.push({label:"pending nodes",value:String(z.checkpoint.pending_nodes.length)})),String(z?.detail||"").trim()&&i.push({label:"detail",value:String(z.detail).trim()}),z?.requires_approval!==void 0&&i.push({label:"requires approval",value:String(!!z?.requires_approval)}),String(z?.approval_reason||"").trim()&&i.push({label:"approval reason",value:String(z.approval_reason).trim()}),String(z?.denial_reason||"").trim()&&i.push({label:"denial reason",value:String(z.denial_reason).trim()}),String(z?.paused_reason||"").trim()&&i.push({label:"paused reason",value:String(z.paused_reason).trim()}),i},[oe,lt.length,z,X.length,we.length,T.tasks.length]);H(()=>os(z),[z]),ye(()=>{ge(i=>i&&F.includes(i)?i:F[0]||"")},[F]),ye(()=>{W(i=>i==="all"||i&&F.includes(i)?i:"all")},[F]),ye(()=>{se([]),K("all"),S(""),f([]),Y(!0)},[s,ae]),ga(s?oe?`/api/engine/automations/v2/events?run_id=${encodeURIComponent(s)}`:`/api/engine/automations/events?run_id=${encodeURIComponent(s)}`:"",i=>{try{const c=JSON.parse(String(i?.data||"{}"));if(!c||c.status==="ready")return;const _=br(c);if(!_||_!==s)return;const $=Yt(c),ue=wa(c),Qe=`automations:${_}:${$}:${ue}:${Math.random().toString(16).slice(2,8)}`;se(gt=>[...gt.slice(-299),{id:Qe,source:"automations",at:ue,event:c}])}catch{return}},{enabled:!!s}),ga(ae?`/api/engine/context/runs/${encodeURIComponent(ae)}/events/stream?tail=50`:"",i=>{try{const c=JSON.parse(String(i?.data||"{}"));if(!c||c.status==="ready")return;const _=`context:${String(c?.seq||"")}:${String(c?.event_type||"")}`,$=Fa(c?.created_at_ms||c?.timestamp_ms||c?.timestampMs)||Date.now();se(ue=>ue.some(Qe=>Qe.id===_)?ue:[...ue.slice(-399),{id:_,source:"context",at:$,event:c}])}catch{return}},{enabled:!!ae}),ga(s&&G?`/event?sessionID=${encodeURIComponent(G)}&runID=${encodeURIComponent(s)}`:"",i=>{try{const c=JSON.parse(String(i?.data||"{}"));if(!c)return;const _=Yt(c),$=wa(c),ue=[_||"event",String(c?.properties?.sessionID||c?.sessionID||G||""),String(c?.properties?.runID||c?.runID||s||""),String(c?.properties?.messageID||c?.messageID||""),String(c?.properties?.part?.id||c?.properties?.seq||c?.timestamp_ms||$)].join(":");f(Qe=>Qe.some(gt=>gt.id===ue)?Qe:[...Qe.slice(-499),{id:ue,at:$,event:c}])}catch{return}},{enabled:!!s&&!!G}),ga(s?"/api/global/event":"",i=>{try{const c=JSON.parse(String(i?.data||"{}")),_=br(c);if(!_||_!==s)return;const $=Yt(c);if(!$||$==="server.connected"||$==="engine.lifecycle.ready")return;const ue=wa(c),Qe=`global:${_}:${$}:${ue}:${Math.random().toString(16).slice(2,8)}`;se(gt=>[...gt.slice(-299),{id:Qe,source:"global",at:ue,event:c}])}catch{return}},{enabled:!!s}),ye(()=>{const i=k.current;i&&zt(i)},[yt.length,P.length,Le.length,ce.length,ut.length,v.length,C.length,!!w,!!s,!!G,!!I,B.length,fe.length,tt.isPending,rt.isPending,Te.isPending,ze.isPending]);const g=i=>{const c=String(i||"").toLowerCase();return c==="active"||c==="completed"||c==="done"?"tcp-badge-ok":c==="running"||c==="in_progress"?"tcp-badge-warn":c==="failed"||c==="error"?"tcp-badge-err":"tcp-badge-info"},L=i=>{const c=String(i?.automation_id||i?.id||i?.routine_id||"").trim();if(!c){t("err","Cannot edit automation without an id.");return}const _=ss(i?.schedule);M({automationId:c,name:String(i?.name||c||"").trim(),objective:String(i?.mission?.objective||i?.mission_snapshot?.objective||"").trim(),mode:String(i?.mode||"").toLowerCase()==="standalone"?"standalone":"orchestrated",requiresApproval:i?.requires_approval===!0||i?.policy?.approval?.requires_approval===!0,scheduleKind:_.scheduleKind==="cron"?"cron":"interval",cronExpression:_.cronExpression,intervalSeconds:String(_.intervalSeconds)})},A=i=>{const c=String(i?.status||"").trim().toLowerCase();return c==="paused"||c==="disabled"},j=yt.length,O=P.length,re=j+O,Oe=H(()=>ic(z,fe,B),[z,fe,B]),We=H(()=>{const i=Kt.map(({sessionId:$,message:ue},Qe)=>({id:`message:${$}:${ac(ue,Qe)}`,kind:"message",sessionId:$,at:tc(ue),variant:Zl(ue),label:String(ue?.info?.role||"session").trim()||"session",body:Kn(ue),raw:ue,parts:ec(ue),sessionLabel:Ma($)})),c=fe.map($=>({id:`event:${$.id}`,kind:"event",sessionId:String($?.event?.properties?.sessionID||$?.event?.sessionID||G||"").trim(),at:$.at,variant:Yt($.event)==="session.error"?"error":Yt($.event).startsWith("session.")?"system":"tool",label:Yt($.event)||"event",body:nn($.event),raw:$.event,parts:[],sessionLabel:Ma(String($?.event?.properties?.sessionID||$?.event?.sessionID||G||"").trim())})),_=[...i,...c].sort(($,ue)=>$.at-ue.at);return N==="all"?_:_.filter($=>$.sessionId===N)},[N,G,Kt,fe]);return ye(()=>{const i=de.current;!i||!$e||(i.scrollTop=i.scrollHeight)},[We,$e]),e("div",{ref:k,className:"grid gap-4",children:[r==="list"&&ut.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Installed Packs"}),ut.map((i,c)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"📦"}),e("strong",{children:String(i?.name||i?.id||"Pack")})]}),e("span",{className:"tcp-badge-info",children:String(i?.version||"1.0.0")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:String(i?.description||i?.path||"")})]},String(i?.id||i?.name||c)))]}):null,r==="list"?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Saved Automations"}),e("span",{className:"tcp-badge-info",children:[re," saved"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-[11px] font-medium uppercase tracking-[0.24em] text-slate-500",children:"Scheduled Automations"}),e("span",{className:"tcp-subtle text-xs",children:[j," items"]})]}),yt.length>0?yt.map(i=>{const c=String(i?.automation_id||i?.id||i?.routine_id||"");return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"⏰"}),e("strong",{children:String(i?.name||c||"Automation")})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>L(i),children:e("i",{"data-lucide":"pencil"})}),e("span",{className:g(i?.status),children:String(i?.status||"active")})]})]}),e("div",{className:"tcp-subtle text-xs",children:El(i?.schedule)}),e("div",{className:"mt-2",children:e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Te.mutate(c),children:[e("i",{"data-lucide":"play"}),"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>st.mutate({action:A(i)?"resume":"pause",automationId:c,family:"legacy"}),disabled:!c||st.isPending,children:[e("i",{"data-lucide":A(i)?"play":"pause"}),A(i)?"Resume":"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{const _=Le.find(ue=>String(ue?.automation_id||ue?.routine_id||ue?.id||"").trim()===c),$=String(_?.run_id||_?.id||"").trim();$?(l($),d()):t("info","No runs yet for this automation.")},children:[e("i",{"data-lucide":"info"}),"Debug latest"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>b({automationId:c,family:"legacy",title:String(i?.name||i?.label||c||"automation")}),disabled:!c||st.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})})]},c)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No scheduled automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section shows automation definitions, not execution history."})]})]})]}):null,r==="list"?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-[11px] font-medium uppercase tracking-[0.24em] text-slate-500",children:"Workflow Automations"}),e("span",{className:"tcp-subtle text-xs",children:[O," items"]})]}),P.length>0?P.map(i=>{const c=String(i?.automation_id||i?.automationId||"").trim(),_=String(i?.status||"draft").trim(),$=_.toLowerCase()==="paused",ue=Ql(i);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"🧩"}),e("strong",{children:String(i?.name||c||"Workflow automation")}),ue?e("span",{className:"tcp-badge-ok",children:"Standup"}):null]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{if(Wl(i)){u(i);return}ie(Kl(i))},disabled:!c,title:"Edit workflow automation","aria-label":"Edit workflow automation",children:e("i",{"data-lucide":"pencil"})}),e("span",{className:g(_),children:_})]})]}),String(i?.description||"").trim()?e("div",{className:"tcp-subtle text-xs",children:String(i.description)}):null,ue?e("div",{className:"mt-1 text-xs text-emerald-200",children:["report: ",String(i?.metadata?.standup?.report_path_template||"")]}):null,e("div",{className:"tcp-subtle mt-1 text-xs",children:rs(i?.schedule)}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>ze.mutate(c),disabled:!c||ze.isPending,children:[e("i",{"data-lucide":"play"}),ze.isPending?"Starting...":"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>st.mutate({action:$?"resume":"pause",automationId:c,family:"v2"}),disabled:!c||st.isPending,children:[e("i",{"data-lucide":$?"play":"pause"}),$?"Resume":"Pause"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>b({automationId:c,family:"v2",title:String(i?.name||c||"workflow automation")}),disabled:!c||st.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},c)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No workflow automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section is separate from run history and only shows workflow automation definitions."})]})]}):null,r==="running"?v.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Active Running Tasks"}),e("span",{className:"tcp-badge-warn",children:[v.length," active"]})]}),v.slice(0,14).map((i,c)=>{const _=String(i?.run_id||i?.id||c).trim(),$=i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs;return e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"font-medium text-sm",children:Cn(i)}),e("span",{className:"tcp-subtle text-xs",children:[_||"unknown run"," · running for ",fr(i)]}),ma($)?e("span",{className:"tcp-subtle text-xs",children:["Started: ",ma($)]}):null,pa(i)?e("span",{className:"text-xs text-slate-400",children:Da(pa(i),160)}):null]}),e("span",{className:g(i?.status),children:String(i?.status||"unknown")})]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l(_),children:[e("i",{"data-lucide":"bug"}),"Inspect"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>rt.mutate({action:"pause",runId:_,family:_.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!_||rt.isPending,children:[e("i",{"data-lucide":"pause"}),"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>rt.mutate({action:"resume",runId:_,family:_.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!_||rt.isPending,children:[e("i",{"data-lucide":"play"}),"Resume"]})]})]},_||c)})]}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Active Running Tasks"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"No active runs right now. Start a run to inspect live task execution."})]}):null,r==="running"&&C.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Recently Failed Runs"}),e("span",{className:"tcp-badge-err",children:[C.length," failed"]})]}),C.slice(0,10).map((i,c)=>{const _=String(i?.run_id||i?.id||c).trim();return e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"font-medium text-sm",children:Cn(i)}),e("span",{className:"tcp-subtle text-xs",children:_||"unknown run"}),ma(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Finished:"," ",ma(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)]}):null,pa(i)?e("span",{className:"text-xs text-slate-400",children:Da(pa(i),160)}):null]}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:g(i?.status),children:String(i?.status||"failed")}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l(_),children:[e("i",{"data-lucide":"bug"}),"Inspect"]})]})]})},`failed-${_||c}`)})]}):null,Le.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:r==="running"?"Run Log Explorer":"Recent Runs"}),Le.slice(0,12).map((i,c)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"font-medium text-sm",children:Cn(i)}),e("span",{className:g(i?.status),children:String(i?.status||"unknown")})]}),e("div",{className:"mt-1 flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"tcp-subtle text-xs",children:String(i?.run_id||i?.id||"")}),ma(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Started:"," ",ma(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)]}):null,i?.finished_at_ms||i?.finishedAtMs?e("span",{className:"tcp-subtle text-xs",children:["Finished: ",ma(i?.finished_at_ms||i?.finishedAtMs)]}):null,pa(i)?e("span",{className:"text-xs text-slate-400",children:Da(pa(i),160)}):null]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{l(String(i?.run_id||i?.id||"").trim()),d()},children:[e("i",{"data-lucide":"info"}),r==="running"?"Logs":"Details"]})]})]},String(i?.run_id||i?.id||c)))]}):null,!Le.length&&r==="running"?e(qe,{text:"Run one automation, then use Logs to inspect full execution events."}):null,!re&&!ut.length&&!Le.length&&r==="list"?e(qe,{text:"No automations yet. Create your first one with the wizard!"}):null,e(ot,{children:[s?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>l(""),children:e(xe.div,{className:"tcp-confirm-dialog tcp-run-debugger-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("div",{className:"mb-3 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e("div",{className:"grid gap-1",children:[e("h3",{className:"tcp-confirm-title",children:"Run Debugger"}),e("div",{className:"tcp-subtle text-xs",children:["automation:"," ",String(z?.automation_id||z?.routine_id||"unknown")," · ","run: ",s," · ","running for ",fr(z)]}),oe?e("div",{className:"tcp-subtle text-xs",children:["completed nodes:"," ",Array.isArray(z?.checkpoint?.completed_nodes)?z.checkpoint.completed_nodes.length:0," · ","active sessions:"," ",Array.isArray(z?.active_session_ids)?z.active_session_ids.length:0]}):null]}),e("div",{className:"flex w-full flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center lg:w-auto",children:[e("span",{className:g(z?.status),children:String(z?.status||"unknown")}),s?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>rt.mutate({action:String(z?.status||"").toLowerCase()==="paused"?"resume":"pause",runId:s,family:oe?"v2":"legacy"}),disabled:!s||rt.isPending||!(String(z?.status||"").toLowerCase()==="paused"||la(z?.status)),children:[e("i",{"data-lucide":String(z?.status||"").toLowerCase()==="paused"?"play":"pause"}),String(z?.status||"").toLowerCase()==="paused"?"Resume":"Pause"]}):null,e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>{Promise.all([p.invalidateQueries({queryKey:["automations","run",s]}),p.invalidateQueries({queryKey:["automations","run","artifacts",s]}),ae?p.invalidateQueries({queryKey:["automations","run","context",ae]}):Promise.resolve(),ae?p.invalidateQueries({queryKey:["automations","run","context",ae,"blackboard"]}):Promise.resolve(),ae?p.invalidateQueries({queryKey:["automations","run","context",ae,"events"]}):Promise.resolve(),ae?p.invalidateQueries({queryKey:["automations","run","context",ae,"patches"]}):Promise.resolve(),s?p.invalidateQueries({queryKey:["automations","run","session",s]}):Promise.resolve()])},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>l(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]}),e("div",{className:"grid flex-1 gap-3 overflow-y-auto pr-1 xl:grid-cols-[1.62fr_1fr]",children:[e("div",{className:"grid min-h-0 gap-3",children:[oe?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Workflow Board"}),e("div",{className:"tcp-subtle text-xs",children:["context run: ",qn(ae||"unlinked",44)," · ","tasks: ",T.tasks.length," · ","artifacts: ",lt.length]})]}),e("span",{className:"tcp-badge-info",children:T.taskSource==="hybrid"?"blackboard + context":T.taskSource==="checkpoint"?"run checkpoint":T.taskSource})]}),e(ts,{tasks:T.tasks,currentTaskId:T.currentTaskId,selectedTaskId:J,onTaskSelect:i=>S(c=>c===i.id?"":i.id)})]}):null,I?e("div",{ref:D,className:"tcp-list-item relative max-h-[56vh] overflow-y-auto sm:max-h-[28rem]",children:[e("div",{className:"sticky -top-3 z-10 -mx-3 -mt-3 mb-2 flex items-center justify-between gap-2 rounded-t-xl border-b border-slate-800/80 bg-[color:color-mix(in_srgb,var(--color-surface-elevated)_96%,#000_4%)] px-3 py-3 backdrop-blur-sm",children:[e("div",{className:"font-medium",children:"Task Details"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7","aria-label":"Close task details",onClick:()=>S(""),children:e("i",{"data-lucide":"x-circle"})})]}),e("div",{className:"grid gap-2 pr-1 text-sm text-slate-200",children:[e("div",{className:"whitespace-pre-wrap break-words font-medium leading-snug",children:I.title}),I.description?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:I.description}):null,e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-badge-info",children:I.state}),I.assigned_role?e("span",{className:"tcp-badge-info",children:["agent: ",I.assigned_role]}):null,I.session_id?e("span",{className:"tcp-badge-info",children:Ma(I.session_id)}):null]}),I.runtime_detail?e("div",{className:"whitespace-pre-wrap break-words rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:I.runtime_detail}):null,I.error_message?e("div",{className:"whitespace-pre-wrap break-words rounded-lg border border-rose-500/30 bg-rose-950/20 p-3 text-xs text-rose-200",children:I.error_message}):null,I.dependencies.length?e("div",{className:"flex flex-wrap gap-1 text-xs",children:I.dependencies.map(i=>e("span",{className:"tcp-badge-info",children:["depends on ",i]},i))}):null]})]}):null,e("div",{className:"tcp-list-item min-h-0 xl:order-2",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Live Session Log"}),e("div",{className:"tcp-subtle text-xs",children:G?N==="all"?`Merged timeline across ${F.length||1} session${F.length===1?"":"s"}`:`Filtered to ${N}`:"This run does not expose a session transcript."})]}),e("div",{className:"flex flex-wrap gap-2",children:[F.length>1?e("select",{className:"tcp-select h-7 min-w-[12rem] max-w-full shrink-0 text-xs sm:min-w-[14rem]",value:N,onInput:i=>W(i.target.value),children:[e("option",{value:"all",children:"All sessions"}),F.map(i=>e("option",{value:i,title:i,children:Ma(i)},i))]}):G?e("span",{className:"tcp-badge-info",title:G,children:Ma(G)}):null,G?e("span",{className:"tcp-badge-info",title:G,children:["live: ",qn(G,24)]}):null,e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:!We.length,onClick:async()=>{try{await navigator.clipboard.writeText(We.map(i=>{const c=new Date(i.at).toLocaleTimeString(),_=i.sessionId?` · ${i.sessionLabel}`:"";return`[${c}] ${i.label}${_}
542
+ ${i.body||_t(i.raw)}`}).join(`
543
+
544
+ `)),t("ok","Copied session log.")}catch(i){t("err",i instanceof Error?i.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy"}),"Copy session log"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{Y(!0);const i=de.current;i&&(i.scrollTop=i.scrollHeight)},children:[e("i",{"data-lucide":"arrow-down"}),"Jump to latest"]})]})]}),e("div",{ref:de,className:"grid min-h-[12rem] gap-2 overflow-auto pr-1 sm:min-h-[14rem] sm:max-h-[18rem]",onScroll:i=>{const c=i.currentTarget,_=c.scrollHeight-(c.scrollTop+c.clientHeight)<48;Y(_)},children:We.length?We.map(i=>e("div",{className:`rounded-lg border p-3 ${i.variant==="assistant"?"border-sky-500/30 bg-sky-950/10":i.variant==="user"?"border-slate-600/60 bg-slate-900/35":i.variant==="error"?"border-rose-500/35 bg-rose-950/20":"border-slate-700/50 bg-slate-900/25"}`,children:[e("div",{className:"mb-1 flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"text-xs font-medium uppercase tracking-wide text-slate-200",children:i.label}),i.sessionId?e("span",{className:"tcp-badge-info text-[10px]",children:i.sessionLabel}):null]}),e("span",{className:"tcp-subtle text-[11px]",children:new Date(i.at).toLocaleTimeString()})]}),i.body?e("div",{className:"whitespace-pre-wrap break-words text-sm text-slate-100",children:i.body}):e("div",{className:"tcp-subtle text-xs",children:"No textual body."}),i.kind==="message"&&i.parts.some(c=>String(c?.type||"")==="tool")?e("details",{className:"mt-2",children:[e("summary",{className:"cursor-pointer text-xs text-slate-400",children:"Tool payloads"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:_t(i.parts)})]}):null,i.kind==="event"?e("details",{className:"mt-2",children:[e("summary",{className:"cursor-pointer text-xs text-slate-400",children:"Raw event"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:_t(i.raw)})]}):null]},i.id)):e("div",{className:"tcp-subtle text-xs",children:F.length?"Waiting for session transcript or live session events.":"This run does not expose a session transcript."})})]}),e("div",{className:"tcp-list-item min-h-0 xl:order-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Run Telemetry"}),e("div",{className:"flex w-full flex-wrap gap-1 sm:w-auto",children:[e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${E==="all"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>K("all"),children:["all (",ea.length,")"]}),e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${E==="automations"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>K("automations"),children:"automations"}),oe?e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${E==="context"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>K("context"),children:"context"}):null,e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${E==="global"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>K("global"),children:"global"})]})]}),wt.length?e("div",{className:"grid gap-2 overflow-auto pr-1 sm:max-h-[12rem]",children:wt.slice(-40).reverse().map(i=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/30 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:Yt(i.event)||"event"}),e("span",{className:"tcp-subtle text-[11px]",children:[yr(i.at)," · ",i.source]})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:nn(i.event)||"No summary available."})]}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:_t(i.event?.properties||i.event)})]},i.id))}):e("div",{className:"tcp-subtle text-xs",children:oe?"No workflow, context, or global telemetry has been captured for this run yet.":"No automation/global telemetry captured for this run yet."})]})]}),e("div",{className:"grid min-h-0 content-start gap-3 overflow-visible",children:[Oe.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 font-medium",children:"Blockers"}),e("div",{className:"grid gap-2",children:Oe.map(i=>e("div",{className:"rounded-lg border border-amber-500/30 bg-amber-950/20 p-3",children:[e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("strong",{children:i.title}),e("span",{className:"tcp-badge-warn",children:i.source}),i.at?e("span",{className:"tcp-subtle text-[11px]",children:new Date(i.at).toLocaleTimeString()}):null]}),e("div",{className:"whitespace-pre-wrap break-words text-sm text-amber-100/90",children:i.reason})]},i.key))})]}):null,ht.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-1 font-medium",children:"Debug hints"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:ht.map(i=>e("div",{children:i},i))})]}):null,e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Run Summary"}),e("div",{className:"mt-2 grid gap-2 text-xs text-slate-300",children:ia.map(i=>e("div",{className:"break-words",children:[i.label,": ",i.value]},i.label))})]}),e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Mission Objective"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:String(z?.mission_snapshot?.objective||"n/a")})]}),e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:["Artifacts (",lt.length,")"]}),lt.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-40",children:lt.map((i,c)=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:String(i?.name||i?.label||i?.kind||i?.type||i?.id||`artifact-${c+1}`)}),e("span",{className:"tcp-subtle text-[11px]",children:String(i?.kind||i?.type||i?.path||"").trim()||"artifact"})]})}),e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:_t(i)})]},`${String(i?.id||i?.artifact_id||c)}`))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:oe?"No blackboard artifacts have been recorded for this workflow run yet.":"No run artifacts were persisted for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"font-medium",children:oe?"Run History":"Persisted History"}),Tt.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-[14rem]",children:Tt.map((i,c)=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:String(i?.type||i?.event||i?.status||"history")}),e("span",{className:"tcp-subtle text-[11px]",children:yr(i?.ts_ms||i?.tsMs||i?.at||i?.timestamp_ms)})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(i?.detail||i?.reason||i?.family||i?.status||"No summary available.")})]}),e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:_t(i)})]},`${String(i?.id||i?.event||i?.type||"history")}-${c}`))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:oe?"No context-run history has been persisted for this workflow run yet.":"No persisted history rows returned for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Raw Run Payload"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(["=== RUN ===",_t(z),"=== ARTIFACTS ===",_t(lt),"=== TELEMETRY ===",_t(wt.map(i=>i.event)),"=== CONTEXT RUN ===",_t(Ge.data?.run||null),"=== BLACKBOARD ===",_t(m),"=== HISTORY ===",_t(Tt),"=== SESSION MESSAGES ===",_t(Kt)].join(`
545
+
546
+ `)),t("ok","Copied full debug context.")}catch(i){t("err",i instanceof Error?i.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy all debug context"]})]}),e("pre",{className:"tcp-code overflow-auto sm:max-h-[18rem]",children:_t({run:z,contextRun:Ge.data?.run||null,blackboard:m})})]})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>n("feed"),children:[e("i",{"data-lucide":"radio"}),"Open Live Feed"]}),e("button",{className:"tcp-btn",onClick:()=>l(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]})}):null,w?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>M(null),children:e(xe.div,{className:"tcp-confirm-dialog w-[min(40rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Edit automation"}),e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Name"}),e("input",{className:"tcp-input",value:w.name,onInput:i=>M(c=>c&&{...c,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[96px]",value:w.objective,onInput:i=>M(c=>c&&{...c,objective:i.target.value})})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Mode"}),e("select",{className:"tcp-input",value:w.mode,onInput:i=>M(c=>c&&{...c,mode:i.target.value}),children:[e("option",{value:"standalone",children:"standalone"}),e("option",{value:"orchestrated",children:"orchestrated"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Approval policy"}),e("button",{className:`tcp-input flex h-10 items-center justify-between px-3 text-xs ${w.requiresApproval?"border-amber-400/60 bg-amber-400/10":""}`,role:"switch","aria-checked":w.requiresApproval,onClick:()=>M(i=>i&&{...i,requiresApproval:!i.requiresApproval}),children:[e("span",{className:"flex items-center gap-2",children:[e("i",{"data-lucide":w.requiresApproval?"shield-alert":"shield-check"}),w.requiresApproval?"Manual approvals enabled":"Fully automated enabled"]}),e("span",{className:`relative h-5 w-9 rounded-full transition ${w.requiresApproval?"bg-amber-500/40":"bg-emerald-500/30"}`,children:e("span",{className:`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-slate-100 transition ${w.requiresApproval?"":"translate-x-4"}`})})]})]})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Schedule type"}),e("select",{className:"tcp-input",value:w.scheduleKind,onInput:i=>M(c=>c&&{...c,scheduleKind:i.target.value}),children:[e("option",{value:"interval",children:"interval"}),e("option",{value:"cron",children:"cron"})]})]})}),w.scheduleKind==="cron"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Cron expression"}),e("input",{className:"tcp-input font-mono",value:w.cronExpression,onInput:i=>M(c=>c&&{...c,cronExpression:i.target.value}),placeholder:"0 9 * * *"})]}):e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:w.intervalSeconds,onInput:i=>M(c=>c&&{...c,intervalSeconds:i.target.value})})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>M(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>w&&tt.mutate(w),disabled:tt.isPending,children:[e("i",{"data-lucide":"check"}),"Save"]})]})]})}):null,U?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>ie(null),children:e(xe.div,{className:"tcp-confirm-dialog tcp-workflow-editor-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("div",{className:"flex items-start justify-between gap-3 border-b border-slate-800/70 px-4 py-4",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Edit workflow automation"}),e("div",{className:"mt-1 text-sm text-slate-400",children:"Update scheduling, model routing, MCP access, and the actual step prompts."})]}),e("button",{className:"tcp-btn h-9 w-9 px-0",onClick:()=>ie(null),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"grid flex-1 gap-4 overflow-y-auto px-4 py-4 xl:grid-cols-[minmax(22rem,0.92fr)_minmax(0,1.35fr)]",children:[e("div",{className:"grid content-start gap-4",children:[e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Automation name"}),e("input",{className:"tcp-input",value:U.name,onInput:i=>ie(c=>c&&{...c,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Notes / description"}),e("textarea",{className:"tcp-input min-h-[120px]",value:U.description,onInput:i=>ie(c=>c&&{...c,description:i.target.value}),placeholder:"Add notes, delivery expectations, or operator guidance."})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("input",{className:`tcp-input ${$a(U.workspaceRoot)?"border-red-500/70 text-red-100":""}`,value:U.workspaceRoot,onInput:i=>ie(c=>c&&{...c,workspaceRoot:i.target.value})}),$a(U.workspaceRoot)?e("div",{className:"text-xs text-red-300",children:$a(U.workspaceRoot)}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Execution"}),e("div",{className:"grid gap-2 sm:grid-cols-3",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Schedule type"}),e("select",{className:"tcp-select",value:U.scheduleKind,onInput:i=>ie(c=>c&&{...c,scheduleKind:i.target.value}),children:[e("option",{value:"manual",children:"manual"}),e("option",{value:"cron",children:"cron"}),e("option",{value:"interval",children:"interval"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Execution mode"}),e("select",{className:"tcp-select",value:U.executionMode,onInput:i=>ie(c=>c&&{...c,executionMode:i.target.value}),children:Ln.map(i=>e("option",{value:i.id,children:i.label},i.id))})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Max parallel agents"}),e("input",{type:"number",min:"1",max:"16",className:"tcp-input",value:U.maxParallelAgents,onInput:i=>ie(c=>c&&{...c,maxParallelAgents:i.target.value}),disabled:U.executionMode!=="swarm"})]})]}),U.scheduleKind==="cron"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Cron expression"}),e("input",{className:"tcp-input font-mono",value:U.cronExpression,onInput:i=>ie(c=>c&&{...c,cronExpression:i.target.value})})]}):U.scheduleKind==="interval"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:U.intervalSeconds,onInput:i=>ie(c=>c&&{...c,intervalSeconds:i.target.value})})]}):null]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model provider"}),e("select",{className:"tcp-select",value:U.modelProvider,onInput:i=>ie(c=>c&&{...c,modelProvider:i.target.value,modelId:""}),children:[e("option",{value:"",children:"Workspace default"}),Ya(Ce.map(i=>i.id),U.modelProvider).map(i=>e("option",{value:i,children:i},i))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("select",{className:"tcp-select",value:U.modelId,onInput:i=>ie(c=>c&&{...c,modelId:i.target.value}),children:[e("option",{value:"",children:"Workspace default"}),Ya(Ce.find(i=>i.id===U.modelProvider)?.models||[],U.modelId).map(i=>e("option",{value:i,children:i},i))]}),Sn(U.modelProvider,U.modelId)?e("div",{className:"text-xs text-red-300",children:Sn(U.modelProvider,U.modelId)}):null]})]}),e("div",{className:"grid gap-2 rounded-lg border border-slate-800/70 bg-slate-950/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Planner fallback model"}),e("div",{className:"text-xs text-slate-400",children:"Optional. Override the workflow model only for planning and revisions."}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner provider"}),e("select",{className:"tcp-select",value:U.plannerModelProvider,onInput:i=>ie(c=>c&&{...c,plannerModelProvider:i.target.value,plannerModelId:""}),children:[e("option",{value:"",children:"Use workflow model"}),Ya(Ce.map(i=>i.id),U.plannerModelProvider).map(i=>e("option",{value:i,children:i},`planner-${i}`))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("select",{className:"tcp-select",value:U.plannerModelId,onInput:i=>ie(c=>c&&{...c,plannerModelId:i.target.value}),children:[e("option",{value:"",children:"Use workflow model"}),Ya(Ce.find(i=>i.id===U.plannerModelProvider)?.models||[],U.plannerModelId).map(i=>e("option",{value:i,children:i},`planner-model-${i}`))]}),an(U.plannerModelProvider,U.plannerModelId)?e("div",{className:"text-xs text-red-300",children:an(U.plannerModelProvider,U.plannerModelId)}):null]})]})]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${U.toolAccessMode==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>ie(i=>i&&{...i,toolAccessMode:"all"}),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access to workflow agents."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${U.toolAccessMode==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>ie(i=>i&&{...i,toolAccessMode:"custom"}),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still follow the selected servers."})]})]}),U.toolAccessMode==="custom"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Allowed built-in tools"}),e("textarea",{className:"tcp-input min-h-[96px] font-mono text-xs",value:U.customToolsText,onInput:i=>ie(c=>c&&{...c,customToolsText:i.target.value}),placeholder:`read
547
+ write
548
+ edit
549
+ bash
550
+ ls
551
+ glob
552
+ websearch`})]}):e("div",{className:"text-xs text-slate-500",children:"All built-in tools are allowed for this automation."})]}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"MCP Servers"}),at.length?e("div",{className:"flex flex-wrap gap-2",children:at.map(i=>{const c=U.selectedMcpServers.includes(i.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${c?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>ie(_=>_&&{..._,selectedMcpServers:c?_.selectedMcpServers.filter($=>$!==i.name):[..._.selectedMcpServers,i.name].sort()}),children:[i.name," ",i.connected?"• connected":"• disconnected"]},i.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet."})]})]}),e("div",{className:"grid content-start gap-4",children:e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{children:e("div",{children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Prompt Editor"}),e("div",{className:"mt-1 text-xs text-slate-400",children:"Edit the actual prompts Tandem sends for each workflow step. These objectives control what every node does at runtime."})]})}),U.nodes.length?e("div",{className:"grid gap-3",children:U.nodes.map((i,c)=>e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-sm text-slate-100",children:i.nodeId||i.title||`Step ${c+1}`}),i.agentId?e("span",{className:"tcp-badge-info",children:["agent: ",i.agentId]}):null]}),e("textarea",{className:"tcp-input min-h-[180px] text-sm leading-6",value:i.objective,onInput:_=>ie($=>$&&{...$,nodes:$.nodes.map(ue=>ue.nodeId===i.nodeId?{...ue,objective:_.target.value}:ue)}),placeholder:"Describe exactly what this step should do."})]},i.nodeId||c))}):e("div",{className:"text-xs text-slate-400",children:"This workflow does not currently expose editable node objectives."})]})})]}),e("div",{className:"tcp-confirm-actions border-t border-slate-800/70 px-4 py-3",children:[e("button",{className:"tcp-btn",onClick:()=>ie(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>U&&Ve.mutate(U),disabled:Ve.isPending,children:[e("i",{"data-lucide":"check"}),Ve.isPending?"Saving...":"Save"]})]})]})}):null,q?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>b(null),children:e(xe.div,{className:"tcp-confirm-dialog w-[min(34rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Delete automation"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:q.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>b(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger",disabled:st.isPending,onClick:()=>st.mutate({action:"delete",automationId:q.automationId,family:q.family},{onSettled:()=>b(null)}),children:[e("i",{"data-lucide":"trash-2"}),st.isPending?"Deleting...":"Delete automation"]})]})]})}):null]})]})}function mc({client:a,toast:t}){const n=jt(),r=Q({queryKey:["automations","approvals"],queryFn:()=>a?.agentTeams?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),s=Q({queryKey:["automations","instances"],queryFn:()=>a?.agentTeams?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),l=Ae({mutationFn:({requestId:p,decision:k})=>a?.agentTeams?.replyApproval?.(p,k),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["automations"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=sa(r.data,"spawnApprovals"),u=sa(s.data,"instances");return e("div",{className:"grid gap-4",children:[d.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Pending Approvals"}),d.map((p,k)=>{const q=String(p?.request_id||p?.id||`request-${k}`);return e("div",{className:"tcp-list-item border-amber-500/40",children:[e("div",{className:"mb-1 font-medium text-amber-300",children:["⚠️ ",String(p?.reason||p?.title||"Spawn request")]}),e("div",{className:"tcp-subtle text-xs",children:q}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{className:"tcp-btn-primary h-7 px-2 text-xs",onClick:()=>l.mutate({requestId:q,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>l.mutate({requestId:q,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},q)})]}):null,u.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Active Agent Teams"}),u.map((p,k)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"👥"}),e("strong",{children:String(p?.name||p?.template_id||p?.instance_id||"Instance")})]}),e("span",{className:"tcp-badge-info",children:String(p?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:["Mission: ",String(p?.mission_id||"—")]})]},String(p?.instance_id||p?.id||k)))]}):null,!d.length&&!u.length?e(qe,{text:"No pending approvals or active team instances."}):null]})}function pc({client:a,api:t,toast:n,navigate:r,providerStatus:s}){const[l,d]=y("create"),[u,p]=y("simple"),[k,q]=y(""),[b,w]=y(null);return e("div",{className:"grid gap-4",children:[e("div",{className:"flex gap-1 rounded-xl border border-slate-700/50 bg-slate-900/40 p-1",children:[{id:"create",label:"Create",icon:"sparkles"},{id:"list",label:"Automations",icon:"clipboard-list"},{id:"running",label:"Tasks",icon:"activity"},{id:"approvals",label:"Teams",icon:"users"}].map(E=>e("button",{onClick:()=>d(E.id),className:`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-all ${l===E.id?"bg-amber-500/20 text-amber-300 shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[e("i",{"data-lucide":E.icon}),e("span",{children:E.label})]},E.id))}),e(ot,{mode:"wait",children:e(xe.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-6},transition:{duration:.15},children:l==="create"?e(Xt,{title:"Create an Automation",subtitle:"Describe what you want, pick a schedule, and Tandem handles the rest",children:e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Builder Mode"}),e("div",{className:"tcp-subtle text-xs",children:"Keep the simple wizard for quick automations, or switch to the advanced swarm builder for orchestrated mission planning."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="simple"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>{p("simple"),w(null)},children:"Simple Wizard"}),e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="advanced"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>p("advanced"),children:"Advanced Swarm Builder"})]})]}),u==="advanced"?e($l,{client:a,api:t,toast:n,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel,editingAutomation:b,onShowAutomations:()=>{w(null),d("list")},onShowRuns:()=>{w(null),d("running")},onClearEditing:()=>w(null)}):e(uc,{client:a,api:t,toast:n,navigate:r,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel})]})}):l==="list"?e(Xt,{title:"My Automations",subtitle:"Installed packs, routines and run history",children:e(wr,{client:a,toast:n,navigate:r,viewMode:"list",selectedRunId:k,onSelectRunId:q,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:E=>{w(E),p("advanced"),d("create")}})}):l==="running"?e(Xt,{title:"Live Running Tasks",subtitle:"Inspect active runs and open detailed event logs for each run",children:e(wr,{client:a,toast:n,navigate:r,viewMode:"running",selectedRunId:k,onSelectRunId:q,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:E=>{w(E),p("advanced"),d("create")}})}):e(Xt,{title:"Teams & Approvals",subtitle:"Active agent teams and pending spawn approvals",children:e(mc,{client:a,toast:n})})},l)})]})}function hc({client:a,toast:t}){const n=jt(),r=Q({queryKey:["channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),s=Q({queryKey:["channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),l=Ae({mutationFn:async p=>{const q=(s.data||{})[p];if(!q)throw new Error(`No config found for ${p}`);await a.channels.put(p,q)},onSuccess:async()=>{t("ok","Channel reconfigured."),await n.invalidateQueries({queryKey:["channels"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=r.data&&typeof r.data=="object"?r.data:{},u=Object.entries(d);return e("div",{className:"grid gap-4",children:e(Xt,{title:"Channels",subtitle:"Connector health and quick reconnect",children:e("div",{className:"grid gap-2",children:u.length?u.map(([p,k])=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:p}),e("span",{className:k?.connected?"tcp-badge-ok":"tcp-badge-warn",children:k?.connected?"connected":"disconnected"})]}),e("div",{className:"tcp-subtle text-xs",children:String(k?.last_error||k?.error||"")||"No recent errors."}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l.mutate(p),children:[e("i",{"data-lucide":"refresh-cw"}),"Reconnect"]})})]},p)):e(qe,{text:"No channels configured."})})})})}function vt(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function je(a){return String(a||"").trim()}function In(a){try{return JSON.stringify(a,null,2)}catch{return"{}"}}function gc(a){return a?"ok":"ghost"}function fc(a){return je(a?.event_type||a?.type||a?.event||"workflow.event")}function bc({api:a,toast:t}){const n=jt(),[r,s]=y(""),[l,d]=y(""),[u,p]=y(""),[k,q]=y("context.task.created"),[b,w]=y(`{
553
+ "event_id": "demo-task-1"
554
+ }`),[M,E]=y([]),K=Q({queryKey:["packs","list"],queryFn:()=>a("/api/engine/packs",{method:"GET"}).catch(()=>({packs:[]})),refetchInterval:15e3}),B=Q({queryKey:["workflows","list"],queryFn:()=>a("/api/engine/workflows",{method:"GET"}).catch(()=>({workflows:[]})),refetchInterval:15e3}),se=Q({queryKey:["workflows","hooks"],queryFn:()=>a("/api/engine/workflow-hooks",{method:"GET"}).catch(()=>({hooks:[]})),refetchInterval:15e3}),G=vt(K.data,"packs"),ge=vt(B.data,"workflows"),N=vt(se.data,"hooks"),W=H(()=>l||je(G[0]?.pack_id||G[0]?.name),[G,l]),J=H(()=>u||je(ge[0]?.workflow_id),[u,ge]),S=Q({queryKey:["workflows","runs",J],queryFn:()=>a(`/api/engine/workflows/runs${J?`?workflow_id=${encodeURIComponent(J)}&limit=20`:"?limit=20"}`,{method:"GET"}).catch(()=>({runs:[]})),refetchInterval:6e3}),fe=vt(S.data,"runs"),f=Q({queryKey:["packs","detail",W],enabled:!!W,queryFn:()=>a(`/api/engine/packs/${encodeURIComponent(W)}`,{method:"GET"})}),D=Q({queryKey:["workflows","detail",J],enabled:!!J,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(J)}`,{method:"GET"})}),de=Ae({mutationFn:()=>a("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:r,source:{kind:"control-panel"}})}),onSuccess:async()=>{t("ok","Pack installed."),s(""),await Promise.all([n.invalidateQueries({queryKey:["packs"]}),n.invalidateQueries({queryKey:["workflows"]})])},onError:P=>t("err",P instanceof Error?P.message:String(P))}),$e=Ae({mutationFn:P=>a(`/api/engine/workflows/${encodeURIComponent(P)}/run`,{method:"POST"}),onSuccess:async P=>{t("ok",`Workflow ${je(P?.run?.workflow_id||J)} started.`),await Promise.all([n.invalidateQueries({queryKey:["workflows"]}),n.invalidateQueries({queryKey:["workflows","runs"]})])},onError:P=>t("err",P instanceof Error?P.message:String(P))}),Y=Ae({mutationFn:async()=>{let P={};const te=je(b);return te&&(P=JSON.parse(te)),a("/api/engine/workflows/simulate",{method:"POST",body:JSON.stringify({event_type:k,properties:P})})},onError:P=>t("err",P instanceof Error?P.message:String(P))}),U=Ae({mutationFn:({bindingId:P,enabled:te})=>a(`/api/engine/workflow-hooks/${encodeURIComponent(P)}`,{method:"PATCH",body:JSON.stringify({enabled:te})}),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["workflows","hooks"]}),n.invalidateQueries({queryKey:["workflows","detail"]})])},onError:P=>t("err",P instanceof Error?P.message:String(P))}),ie=f.data?.pack||null,oe=D.data?.workflow||null,Ue=vt(D.data,"hooks"),_e=Y.data?.simulation||null;return ga(`/api/engine/workflows/events${J?`?workflow_id=${encodeURIComponent(J)}`:""}`,P=>{try{const te=JSON.parse(P.data);if(te?.status==="ready")return;E(ve=>[...ve.slice(-59),{at:Date.now(),data:te}])}catch{}},{enabled:!0}),e(La,{className:"grid gap-4",children:[e(Ao,{eyebrow:"Operations",title:"Pack library and workflow lab",subtitle:"Inspect installed packs, see workflow extensions, toggle hooks, simulate lifecycle events, and run workflow definitions without leaving the control panel.",badges:e(qt,{children:[e(Ie,{tone:"info",children:[G.length," installed packs"]}),e(Ie,{tone:"warn",children:[ge.length," workflows"]}),e(Ie,{tone:"ghost",children:[N.length," hooks"]})]})}),e(Ea,{main:e("div",{className:"grid gap-4",children:[e(Ze,{title:"Installed packs",subtitle:"Select a pack to inspect its manifest, declared workflow contents, and hook contributions.",children:e("div",{className:"grid gap-2",children:G.length?G.map((P,te)=>{const ve=je(P?.pack_id||P?.name||te);return e("button",{type:"button",className:`tcp-list-item text-left ${ve===W?"border-amber-400/70":""}`,onClick:()=>d(ve),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:je(P?.name||ve)}),e("span",{className:"tcp-badge-info",children:je(P?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-subtle",children:je(P?.pack_type||"pack")}),e("span",{className:"tcp-subtle",children:je(P?.install_path||"")})]})]},ve)}):e(qe,{text:"No packs are installed yet."})})}),e(Ze,{title:"Workflow registry",subtitle:"This is the live workflow registry resolved from built-ins, installed packs, and workspace-local overrides.",children:e("div",{className:"grid gap-2",children:ge.length?ge.map(P=>{const te=je(P?.workflow_id),ve=te===J,Se=je(P?.source?.kind||"unknown");return e("button",{type:"button",className:`tcp-list-item text-left ${ve?"border-amber-400/70":""}`,onClick:()=>p(te),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:je(P?.name||te)}),e("span",{className:`tcp-badge-${Se==="pack"?"warn":"info"}`,children:Se})]}),e("div",{className:"tcp-subtle text-xs",children:[te," · ",vt(P?.steps,"steps").length," steps"]})]},te)}):e(qe,{text:"No workflows are currently registered."})})})]}),aside:e("div",{className:"grid gap-4",children:[e(Ze,{title:"Install pack",subtitle:"Install a local pack path and reload workflow contributions automatically.",children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:r,onInput:P=>s(P.target.value),placeholder:"/path/to/pack.zip"}),e("button",{className:"tcp-btn-primary",disabled:!r.trim()||de.isPending,onClick:()=>de.mutate(),children:[e("i",{"data-lucide":"download"}),"Install from path"]})]})}),e(Ze,{title:"Pack inspector",subtitle:"Shows which workflows and hooks a pack contributes, alongside its current capability surface.",children:ie?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:je(ie?.installed?.name||W)}),e(Ie,{tone:"info",children:je(ie?.installed?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e(Ie,{tone:"ghost",children:[Number(ie?.workflow_extensions?.workflow_count||0)," ","workflows"]}),e(Ie,{tone:"ghost",children:[Number(ie?.workflow_extensions?.workflow_hook_count||0)," ","hooks"]}),e(Ie,{tone:"ghost",children:[Number(ie?.risk?.required_capabilities_count||0)," ","required caps"]})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Entry Points"}),vt(ie?.workflow_extensions,"workflow_entrypoints").length?vt(ie?.workflow_extensions,"workflow_entrypoints").map((P,te)=>e("div",{className:"tcp-list-item text-sm",children:je(P)},`${je(P)}-${te}`)):e(qe,{text:"This pack does not declare workflow entrypoints."})]}),e("details",{className:"tcp-list-item",children:[e("summary",{className:"cursor-pointer font-medium",children:"Manifest"}),e("pre",{className:"tcp-subtle mt-3 overflow-x-auto text-xs",children:In(ie?.manifest||{})})]})]}):e(qe,{text:"Select an installed pack to inspect workflow extensions."})})]})}),e(Ea,{main:e(Ze,{title:"Workflow viewer",subtitle:"Structured view of workflow steps and source provenance for the selected workflow.",actions:e("button",{className:"tcp-btn",disabled:!J||$e.isPending,onClick:()=>J&&$e.mutate(J),children:[e("i",{"data-lucide":"play"}),"Run workflow"]}),children:oe?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:je(oe?.name||J)}),e(Ie,{tone:"info",children:je(oe?.source?.kind||"unknown")})]}),e("div",{className:"tcp-subtle text-sm",children:je(oe?.description||"No description provided.")})]}),e("div",{className:"grid gap-2",children:vt(oe,"steps").length?vt(oe,"steps").map((P,te)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 text-xs uppercase tracking-[0.24em] text-slate-400",children:["Step ",te+1]}),e("div",{className:"font-medium",children:je(P?.action||"unknown")}),P?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:In(P.with)}):null]},je(P?.step_id||te))):e(qe,{text:"This workflow does not define any linear steps."})})]}):e(qe,{text:"Select a workflow to inspect its current resolved definition."})}),aside:e("div",{className:"grid gap-4",children:[e(Ze,{title:"Hook manager",subtitle:"Enable or disable hook bindings on the live registry and inspect the attached actions.",children:e("div",{className:"grid gap-2",children:Ue.length?Ue.map(P=>{const te=je(P?.binding_id),ve=!!P?.enabled;return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:je(P?.event||te)}),e("div",{className:"tcp-subtle text-xs",children:te})]}),e("button",{className:"tcp-btn",disabled:U.isPending,onClick:()=>U.mutate({bindingId:te,enabled:!ve}),children:ve?"Disable":"Enable"})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e(Ie,{tone:gc(ve),children:ve?"Enabled":"Disabled"}),e(Ie,{tone:"ghost",children:[vt(P,"actions").length," actions"]})]}),e("div",{className:"grid gap-1",children:vt(P,"actions").map((Se,V)=>e("div",{className:"tcp-subtle text-xs",children:je(Se?.action||Se)},`${te}-${V}`))})]},te)}):e(qe,{text:"The selected workflow has no registered hooks."})})}),e(Ze,{title:"Recent workflow runs",subtitle:"Latest workflow executions for the selected workflow, including hook-triggered runs.",children:e("div",{className:"grid gap-2",children:fe.length?fe.map((P,te)=>{const ve=je(P?.status||"unknown"),Se=ve==="completed"?"ok":ve==="failed"?"err":ve==="running"?"warn":"ghost";return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:je(P?.run_id||`run-${te+1}`)}),e(Ie,{tone:Se,children:ve})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger: ",je(P?.trigger_event||"manual")]}),e("div",{className:"tcp-subtle text-xs",children:["actions: ",vt(P,"actions").length]})]},je(P?.run_id||te))}):e(qe,{text:"No workflow runs have been recorded yet."})})})]})}),e(Ea,{main:e(Ze,{title:"Workflow testing mode",subtitle:"Simulate a source event to see which hooks will match before triggering real actions.",actions:e("button",{className:"tcp-btn-primary",disabled:!k.trim()||Y.isPending,onClick:()=>Y.mutate(),children:[e("i",{"data-lucide":"flask-conical"}),"Simulate"]}),children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:k,onInput:P=>q(P.target.value),placeholder:"context.task.created"}),e("textarea",{className:"tcp-input min-h-[180px] font-mono text-xs",value:b,onInput:P=>w(P.target.value),spellCheck:!1}),_e?e("div",{className:"grid gap-3",children:[e("div",{className:"flex flex-wrap gap-2",children:vt(_e,"canonical_events").map((P,te)=>e(Ie,{tone:"info",children:je(P)},`${je(P)}-${te}`))}),e("div",{className:"grid gap-2",children:vt(_e,"matched_bindings").length?vt(_e,"matched_bindings").map(P=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:je(P?.binding_id)}),e("div",{className:"tcp-subtle text-xs",children:[je(P?.event)," · ",vt(P,"actions").length," ","actions"]})]},je(P?.binding_id))):e(qe,{text:"No workflow hooks matched this event."})})]}):e(qe,{text:"Run a simulation to inspect canonical events, matched bindings, and planned actions."})]})}),aside:e(Ze,{title:"Triggered actions",subtitle:"Preview of actions the engine plans to execute for the simulated event.",children:e("div",{className:"grid gap-2",children:vt(_e,"planned_actions").length?vt(_e,"planned_actions").map((P,te)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:je(P?.action||P)}),P?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:In(P.with)}):null]},`${je(P?.action||P)}-${te}`)):e(qe,{text:"No planned actions yet."})})})}),e(Ze,{title:"Live workflow events",subtitle:"Real-time `workflow.*` events for the selected workflow, including run start, action completion, and failures.",actions:e("button",{className:"tcp-btn",onClick:()=>E([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear stream"]}),children:e("div",{className:"grid max-h-[28rem] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:M.length?[...M].reverse().map((P,te)=>{const ve=fc(P.data),Se=ve.endsWith(".failed")?"err":ve.endsWith(".completed")?"ok":ve.endsWith(".started")?"warn":"info";return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:ve}),e(Ie,{tone:Se,children:new Date(P.at).toLocaleTimeString()})]}),e("div",{className:"tcp-subtle text-xs",children:["run: ",je(P.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle text-xs",children:["action:"," ",je(P.data?.properties?.action||P.data?.properties?.actionID||"-")]})]},`${P.at}-${te}`)}):e(qe,{text:"Run a workflow or trigger a hook to watch live workflow events here."})})})]})}function ls(a){return a>=1?"bg-rose-500":a>=.8?"bg-amber-500":"bg-emerald-500"}function qa(a,t){return!t||t<=0?0:Math.min(a/t,1)}function Xa({label:a,used:t,max:n,unit:r,advisory:s=!1}){const l=qa(t,n),d=s?l>=.8?"bg-sky-400":"bg-cyan-500":ls(l);return e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center justify-between text-xs",children:[e("span",{className:"tcp-subtle",children:a}),e("span",{className:"font-mono text-[11px] text-slate-200",children:[t.toLocaleString(),r||""," / ",n.toLocaleString(),r||""]})]}),e("div",{className:"h-1.5 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${d}`,style:{width:`${l*100}%`}})})]})}function yc({budget:a}){const[t,n]=y(!1),r=a.limits_enforced===!1,s=Math.max(qa(a.iterations_used,a.max_iterations),qa(a.tokens_used,a.max_tokens),qa(a.wall_time_secs,a.max_wall_time_secs),qa(a.subagent_runs_used,a.max_subagent_runs));return e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("button",{className:"flex w-full items-center justify-between",onClick:()=>n(l=>!l),children:[e("div",{className:"text-sm font-medium",children:"Budget + Tokens"}),e("div",{className:"flex items-center gap-2",children:[e("div",{className:"h-2 w-24 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${r?s>=.8?"bg-sky-400":"bg-cyan-500":ls(s)}`,style:{width:`${s*100}%`}})}),e("span",{className:"tcp-subtle text-xs",children:[Math.round(s*100),"%"]})]})]}),t?e("div",{className:"mt-3 grid gap-3 border-t border-slate-700/60 pt-3",children:[e(Xa,{label:"Iterations",used:a.iterations_used,max:a.max_iterations,advisory:r}),e(Xa,{label:"Tokens",used:a.tokens_used,max:a.max_tokens,advisory:r}),e(Xa,{label:"Wall time",used:a.wall_time_secs,max:a.max_wall_time_secs,unit:"s",advisory:r}),e(Xa,{label:"Agent calls",used:a.subagent_runs_used,max:a.max_subagent_runs,advisory:r}),r?e("div",{className:"rounded border border-cyan-500/30 bg-cyan-950/20 p-2 text-xs text-cyan-100",children:"Advisory usage only. This run does not expose explicit enforced budget caps, so these limits are relaxed defaults for visibility."}):null,a.exceeded&&a.exceeded_reason?e("div",{className:"rounded border border-rose-500/40 bg-rose-950/30 p-2 text-xs text-rose-200",children:a.exceeded_reason}):null]}):null]})}function On(a,t=0){return String(a?.run_id||a?.runId||`run-${t}`).trim()}function xr(a){const t=Number(a?.updated_at_ms||a?.updatedAtMs||0),n=Number(a?.created_at_ms||a?.createdAtMs||0),r=Number.isFinite(t)&&t>0?t:n;return Number.isFinite(r)&&r>0?r:0}function vc(a,t=""){const n=String(t||"").trim(),r=[...Array.isArray(a)?a:[]].sort((d,u)=>xr(u)-xr(d));if(n){const d=r.find((u,p)=>On(u,p)===n);if(d){const u=String(d?.status||"").trim().toLowerCase();if(!["completed","failed","cancelled"].includes(u))return n}}const l=r.find(d=>{const u=String(d?.status||"").trim().toLowerCase();return!["completed","failed","cancelled"].includes(u)})||r[0];return l?On(l):""}function wc(a,t){if(t.type==="sync_runs"){const n={},r=[];for(let l=0;l<t.runs.length;l+=1){const d=t.runs[l],u=On(d,l);u&&(n[u]=d,r.push(u))}let s=a.selectedRunId;return s||(s=vc(t.runs,t.preferredRunId)),{runsById:n,orderedRunIds:r,selectedRunId:s,cursorsByRunId:a.cursorsByRunId}}if(t.type==="select_run")return{...a,selectedRunId:String(t.runId||"").trim()};if(t.type==="clear_selection")return{...a,selectedRunId:""};if(t.type==="advance_cursor"){const n=String(t.runId||"").trim();if(!n)return a;const r=Number(t.seq||0);if(!Number.isFinite(r)||r<=0)return a;const s=String(t.kind||"").trim().toLowerCase(),l=a.cursorsByRunId[n]||{eventSeq:0,patchSeq:0},d={eventSeq:s==="context_run_event"?Math.max(l.eventSeq,r):l.eventSeq,patchSeq:s==="blackboard_patch"?Math.max(l.patchSeq,r):l.patchSeq};return d.eventSeq===l.eventSeq&&d.patchSeq===l.patchSeq?a:{...a,cursorsByRunId:{...a.cursorsByRunId,[n]:d}}}return a}function xc(a,t=""){const[n,r]=bs(wc,{runsById:{},orderedRunIds:[],selectedRunId:"",cursorsByRunId:{}});ye(()=>{r({type:"sync_runs",runs:Array.isArray(a)?a:[],preferredRunId:t})},[a,t]);const s=H(()=>n.orderedRunIds.map(l=>n.runsById[l]).filter(Boolean),[n.orderedRunIds,n.runsById]);return{runsById:n.runsById,orderedRunIds:n.orderedRunIds,orderedRuns:s,selectedRunId:n.selectedRunId,cursorsByRunId:n.cursorsByRunId,setSelectedRunId:l=>r({type:"select_run",runId:l}),clearSelectedRunId:()=>r({type:"clear_selection"}),advanceCursor:(l,d,u)=>r({type:"advance_cursor",runId:l,kind:d,seq:u})}}function Nc(a){const t={},n={};for(const[l,d]of Object.entries(a||{})){const u=Number(d?.eventSeq||0),p=Number(d?.patchSeq||0);u>0&&(t[l]=u),p>0&&(n[l]=p)}const s=JSON.stringify({events:t,patches:n});return!s||s==='{"events":{},"patches":{}}'?"":btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function kc({workspace:a,runIds:t,cursorToken:n,onEnvelope:r,onError:s}){const l=H(()=>[...new Set((t||[]).map(u=>String(u||"").trim()).filter(Boolean))],[t]),d=H(()=>{const u=String(a||"").trim();if(!u||!l.length)return"";const p=new URLSearchParams;return p.set("workspace",u),p.set("runIds",l.join(",")),n&&p.set("cursor",n),`/api/orchestrator/events?${p.toString()}`},[n,l,a]);ye(()=>{if(!d)return;const u=jn(d,p=>{let k=null;try{k=JSON.parse(String(p?.data||"{}"))}catch{return}!k||typeof k!="object"||r(k)},{onError:p=>{s&&s(p)}});return()=>u()},[r,s,d])}const _c={max_iterations:500,iterations_used:0,max_tokens:4e5,tokens_used:0,max_wall_time_secs:10080*60,wall_time_secs:0,max_subagent_runs:2e3,subagent_runs_used:0,exceeded:!1,exceeded_reason:"",limits_enforced:!1,source:"derived"};function Vt(a){const t=String(a||"").trim().toLowerCase();return t==="done"||t==="completed"||t==="active"?"tcp-badge-ok":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"tcp-badge-err":t==="running"||t==="in_progress"||t==="runnable"?"tcp-badge-warn":"tcp-badge-info"}function Sc(a){const t=String(a||"").trim().toLowerCase();return{created:"Created",pending:"Pending",runnable:"Ready",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"}[t]||t||"Unknown"}function Nr(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"Run":`Run ${new Date(t).toLocaleTimeString()}`}function Cc(a){return Number(a?.updated_at_ms||a?.created_at_ms||0)}function ca(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"--:--:--":new Date(t).toLocaleTimeString()}function Ic(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"0 B":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Ac(a){const t=String(a||"").trim(),n=t.lastIndexOf(".");return n<0?"":t.slice(n+1).toLowerCase()}function Ua(a){const t=String(a||"").trim().replace(/\\/g,"/");return t?t.startsWith("/")?t.replace(/\/{2,}/g,"/"):t:""}function Pc(a,t){const n=Ua(a).replace(/\/+$/,""),r=Ua(t).replace(/^\/+/,"");return n?r?`${n}/${r}`:n:r}function kr(a,t){const n=Ua(a).replace(/\/+$/,""),r=Ua(t);return!n||!r?!1:r===n?!0:r.startsWith(`${n}/`)}function _r(a){const t=[a?.workspace?.canonical_path,a?.workspace?.path,a?.workspace?.root,a?.workspace_root,a?.workspacePath,a?.cwd,a?.path];for(const n of t){const r=Ua(String(n||""));if(r.startsWith("/"))return r}return""}function Sr(a){const t={};for(const n of a){const r=String(n?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(r))continue;const s=String(n?.step_id||"").trim();if(!s)continue;const l=Number(n?.seq||0);!Number.isFinite(l)||l<=0||(t[s]=Math.max(Number(t[s]||0),l))}return t}function Tc(a){return String(a?.event_type||a?.type||a?.event||"workflow.event").trim().toLowerCase()}function Cr(a){const t=[`type: ${String(a.type||"").trim()||"unknown"}`,`task: ${String(a.taskId||"").trim()||"n/a"}`,`title: ${String(a.title||"").trim()||"n/a"}`,`mode: ${String(a.mode||"").trim()||"strict"}`,`at: ${ca(a.at)}`,"","reason:",String(a.reason||"").trim()||"No verification detail."],n=a.verification?.execution_trace;return n&&typeof n=="object"&&t.push("","execution_trace:",`session: ${String(n.session_id||"n/a")}`,`model: ${[String(n?.model?.provider||"").trim(),String(n?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"}`,`source: ${String(n?.model?.source||"n/a")}`),t.push("","verification_json:",JSON.stringify(a.verification||{},null,2)),t.join(`
555
+ `)}function va(a){const t=String(a?.task_id||a?.taskID||"").trim();if(t)return t;const n=a?.source_event_id||a?.sourceEventID,r=String(n||"").trim();if(!r)return"";const s=r.lastIndexOf(":");return s<0?"":r.slice(s+1).trim()}function Mc({api:a,toast:t,navigate:n}){const r=jt(),s=!!Er(),l=pt(null),[d,u]=y(!0),[p,k]=y(!1),[q,b]=y(""),[w,M]=y(""),[E,K]=y(!1),[B,se]=y(""),[G,ge]=y(""),[N,W]=y(!1),[J,S]=y("4"),[fe,f]=y("3"),[D,de]=y("swarm.blackboard.default"),[$e,Y]=y(""),[U,ie]=y(""),[oe,Ue]=y(""),[_e,P]=y(""),[te,ve]=y([]),[Se,V]=y(""),[Ne,me]=y(""),[Ee,F]=y(""),[De,le]=y(!1);ye(()=>{u(!0),bt()},[]);const ae=Q({queryKey:["swarm","status"],queryFn:()=>a("/api/orchestrator/status"),refetchInterval:5e3}),nt=Q({queryKey:["swarm","runs",w],queryFn:()=>a(`/api/orchestrator/runs?workspace=${encodeURIComponent(w||"")}`),refetchInterval:6e3,enabled:!!ae.data}),et=Array.isArray(nt.data?.runs)?nt.data.runs:[],Ge=xc(et,String(ae.data?.runId||"").trim()),Xe=Ge.selectedRunId,ct=Ge.setSelectedRunId,bt=Ge.clearSelectedRunId,dt=Ge.advanceCursor,Te=d?"":String(Xe||"").trim(),ze=Ge.orderedRuns,rt=H(()=>{if(!Te)return null;for(const h of ze)if(String(h?.run_id||h?.runId||"").trim()===Te)return h;return null},[ze,Te]),tt=H(()=>Nc(Ge.cursorsByRunId),[Ge.cursorsByRunId]),Ve=String(w||ae.data?.workspaceRoot||"").trim(),st=H(()=>{const h=String(Te||"").trim();return h?[h]:[]},[Te]),yt=pt(0),pe=Je(h=>{const R=String(h?.kind||"").trim().toLowerCase(),ee=String(h?.run_id||h?.runId||"").trim();if(Te&&ee&&ee!==Te)return;const Me=Number(h?.seq||0);ee&&Me>0&&(R==="context_run_event"||R==="blackboard_patch")&&dt(ee,R,Me);const Pe=Date.now();Pe-yt.current<900||(yt.current=Pe,r.invalidateQueries({queryKey:["swarm","runs"]}),Te&&r.invalidateQueries({queryKey:["swarm","run",Te]}))},[dt,r,Te]);kc({workspace:Ve,runIds:st,cursorToken:tt,onEnvelope:pe});const Ce=Q({queryKey:["swarm","run",Te],queryFn:()=>a(`/api/orchestrator/run/${encodeURIComponent(Te)}`),refetchInterval:4e3,enabled:!!Te}),at=Q({queryKey:["swarm","workspace-browser",B],enabled:E&&!!B,queryFn:()=>a(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(B)}`)}),ce=String(Ce.data?.runStatus||Ce.data?.run?.status||ae.data?.status||"idle").trim().toLowerCase(),Le=H(()=>es(Ce.data),[Ce.data]),ut=Le.tasks,v=H(()=>({..._c,...Ce.data?.budget||{}}),[Ce.data?.budget]),C=String(_r(Ce.data?.run)||_r(rt)||(Te?"":String(ae.data?.workspaceRoot||w||""))).trim();ye(()=>{C&&(ie(h=>!h||!kr(C,h)?C:h),Ue(h=>kr(C,h)?h:""))},[C]);const z=Array.isArray(at.data?.directories)?at.data.directories:[],m=String(G||"").trim().toLowerCase(),X=H(()=>m?z.filter(h=>String(h?.name||h?.path||"").trim().toLowerCase().includes(m)):z,[z,m]),we=String(at.data?.parent||"").trim(),T=String(at.data?.dir||B||"").trim(),I=Q({queryKey:["swarm","workspace-files",C,U],enabled:!!C&&!!U,queryFn:async()=>{const h=await a(`/api/orchestrator/workspaces/files?workspaceRoot=${encodeURIComponent(C)}&dir=${encodeURIComponent(U)}`).catch(()=>({directories:[],files:[],parent:null,dir:U})),R=Array.isArray(h?.directories)?h.directories:[],Me=(Array.isArray(h?.files)?h.files:[]).map(Pe=>{const Be=String(Pe?.path||"").trim();return{...Pe,name:String(Pe?.name||Be||"file"),path:Be||Pc(C,String(Pe?.name||""))}});return{ok:!0,dir:String(h?.dir||U),parent:h?.parent||null,directories:R,files:Me,fileAccessAllowed:!0}},refetchInterval:1e4}),lt=Q({queryKey:["swarm","workspace-file",C,oe],enabled:!!C&&!!oe,queryFn:async()=>a(`/api/orchestrator/workspaces/read?workspaceRoot=${encodeURIComponent(C)}&path=${encodeURIComponent(oe)}`)}),ht=Array.isArray(I.data?.directories)?I.data.directories:[],Tt=Array.isArray(I.data?.files)?I.data.files:[],Bt=String(I.data?.parent||"").trim(),ea=I.data?.fileAccessAllowed!==!1,wt=String(lt.data?.text||""),Kt=Ac(oe),ia=["md","markdown","mdx"].includes(Kt),g=["html","htm"].includes(Kt);ye(()=>{De&&!g&&le(!1)},[g,De]);const L=H(()=>ut.map(h=>`${h.id}:${h.state}:${h.error_message||""}`).join("|"),[ut]),A=H(()=>ut.find(h=>h.id===Ne)||null,[Ne,ut]),j=H(()=>{const h=Array.isArray(Ce.data?.events)?Ce.data.events:[];let R=null,ee=0;for(const Me of h){const Pe=String(Me?.type||"").trim().toLowerCase();if(!["step_completed","task_completed"].includes(Pe))continue;const Be=Me?.payload&&typeof Me.payload=="object"?Me.payload:{},He=String(Be?.session_id||"").trim();if(!He)continue;const $t=Number(Me?.ts_ms||0);(!R||$t>=ee)&&(R={sessionId:He,event:Me},ee=$t)}return R},[Ce.data?.events]),O=H(()=>{const h=Array.isArray(Ce.data?.events)?Ce.data.events:[];for(let R=h.length-1;R>=0;R-=1){const ee=h[R],Me=String(ee?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(Me))continue;const Pe=ee?.payload&&typeof ee.payload=="object"?ee.payload:{},Be=String(Pe?.session_id||"").trim();if(Be)return Be}return String(j?.sessionId||"").trim()},[j?.sessionId,Ce.data?.events]),re=H(()=>{const h=Array.isArray(Ce.data?.events)?Ce.data.events:[],R=Sr(h),ee=[];for(let Me=h.length-1;Me>=0;Me-=1){const Pe=h[Me],Be=String(Pe?.type||"").trim().toLowerCase();if(!["task_started","task_completed","task_failed","step_started","step_completed","step_failed","run_resumed","run_paused","run_completed","run_failed"].includes(Be))continue;const He=Pe?.payload&&typeof Pe.payload=="object"?Pe.payload:{},$t=String(Pe?.step_id||"").trim(),Ot=Number(Pe?.seq||0);if((Be==="task_failed"||Be==="step_failed")&&$t&&Number.isFinite(Ot)&&Ot>0&&Number(R[$t]||0)>Ot)continue;const Qt=String(He?.step_title||Pe?.step_id||Be).trim(),ta=String(He?.why_next_step||He?.error||"").trim();if(ee.push({id:`${String(Pe?.seq||Me)}-${Be}`,type:Be,title:Qt||Be,detail:ta,at:Number(Pe?.ts_ms||0)}),ee.length>=12)break}return ee},[Ce.data?.events]),Oe=H(()=>{const h=Array.isArray(Ce.data?.events)?Ce.data.events:[];for(let R=h.length-1;R>=0;R-=1){const ee=h[R],Me=String(ee?.type||"").trim().toLowerCase();if(Me==="plan_seeded_llm")return"llm";if(Me==="plan_seeded_local")return"fallback_local";if(Me==="plan_failed_llm_required")return"llm_failed"}return"unknown"},[Ce.data?.events]),We=Q({queryKey:["swarm","run-output-session",String(O||"")],queryFn:()=>a(`/api/engine/session/${encodeURIComponent(String(O||""))}`),refetchInterval:6e3,enabled:!!O}),i=H(()=>{const h=zr(We.data,"Assistant");for(let R=h.length-1;R>=0;R-=1)if(h[R]?.role==="assistant"&&String(h[R]?.text||"").trim())return String(h[R]?.text||"").trim();return""},[We.data]),c=H(()=>{const h=Array.isArray(We.data)?We.data:Array.isArray(We.data?.messages)?We.data.messages:[],R=[];for(let ee=h.length-1;ee>=0;ee-=1){const Me=h[ee],Pe=Array.isArray(Me?.parts)?Me.parts:[];for(let Be=Pe.length-1;Be>=0;Be-=1){const He=Pe[Be];if(!String(He?.type||He?.part_type||"").trim().toLowerCase().includes("tool"))continue;const Ot=String(He?.tool||He?.name||"").trim(),Ia=String(He?.state||He?.status||"").trim(),Qt=String(He?.error||"").trim(),ta=[Ot||"tool",Ia||null,Qt?`err=${Qt}`:null].filter(Boolean).join(" · ");if(R.push(ta),R.length>=10)return R}}return R},[We.data]),_=H(()=>{const h=Array.isArray(Ce.data?.events)?Ce.data.events:[],R=Sr(h),ee=[];for(let Me=h.length-1;Me>=0;Me-=1){const Pe=h[Me],Be=String(Pe?.type||"").trim().toLowerCase();if(!["task_failed","step_failed","task_completed","step_completed"].includes(Be))continue;const He=Pe?.payload&&typeof Pe.payload=="object"?Pe.payload:{},$t=String(Pe?.step_id||"").trim(),Ot=Number(Pe?.seq||0);if((Be==="task_failed"||Be==="step_failed")&&$t&&Number.isFinite(Ot)&&Ot>0&&Number(R[$t]||0)>Ot)continue;const Qt=He?.verification&&typeof He.verification=="object"?He.verification:{},ta=String(Qt?.reason||He?.error||"").trim(),be=String(Qt?.mode||"strict").trim()||"strict";if(ee.push({id:`${String(Pe?.seq||Me)}-${Be}`,taskId:$t,title:String(He?.step_title||Pe?.step_id||Be),type:Be,reason:ta,mode:be,at:Number(Pe?.ts_ms||0),verification:Qt}),ee.length>=8)break}return ee},[Ce.data?.events]),$=H(()=>_.find(h=>h.id===Ee)||null,[Ee,_]);ye(()=>{if(!$&&!A&&!De||typeof document>"u")return;const h=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=h}},[$,A,De]);const ue=String(Ce.data?.run?.workflowId||Ce.data?.run?.workflow_id||rt?.workflowId||rt?.workflow_id||D||"").trim(),Qe=Q({queryKey:["workflow","detail",ue],enabled:!!ue,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(ue)}`),refetchInterval:15e3}),gt=Q({queryKey:["workflow","runs",ue],enabled:!!ue,queryFn:()=>a(`/api/engine/workflows/runs?workflow_id=${encodeURIComponent(ue)}&limit=12`).catch(()=>({runs:[]})),refetchInterval:5e3}),Mt=Array.isArray(gt.data?.runs)?gt.data.runs:[],Et=H(()=>{const h={};for(const R of Mt){const ee=va(R);if(!ee)continue;const Me=h[ee]||{runs:0,failed:0};Me.runs+=1,String(R?.status||"").trim().toLowerCase()==="failed"&&(Me.failed+=1),h[ee]=Me}return h},[Mt]),xt=H(()=>Se?Mt.filter(h=>va(h)===Se):Mt,[Se,Mt]),Rt=H(()=>{const h=[];for(const R of xt){const ee=String(R?.run_id||"").trim(),Me=va(R);for(const Pe of Array.isArray(R?.actions)?R.actions:[])h.push({id:`${ee}:${String(Pe?.action_id||Pe?.action||h.length)}`,runId:ee,action:String(Pe?.action||"unknown action"),status:String(Pe?.status||"unknown"),detail:String(Pe?.detail||""),output:Pe?.output,updatedAt:Number(Pe?.updated_at_ms||R?.updated_at_ms||0),taskId:String(Pe?.task_id||Me||"").trim()})}return h.sort((R,ee)=>ee.updatedAt-R.updatedAt),h},[xt]);ye(()=>{const h=xt;if(!h.length){P("");return}h.some(ee=>{const Me=String(ee?.run_id||"").trim();return Me&&Me===_e})||P(String(h[0]?.run_id||"").trim())},[xt,_e]);const Z=Q({queryKey:["workflow","run",_e],enabled:!!_e,queryFn:()=>a(`/api/engine/workflows/runs/${encodeURIComponent(_e)}`),refetchInterval:5e3}).data?.run||null;ye(()=>{const h=va(Z);h&&V(h)},[Z?.run_id,Z?.source_event_id]),ye(()=>{ve([])},[ue]),ga(`/api/engine/workflows/events${ue?`?workflow_id=${encodeURIComponent(ue)}`:""}`,h=>{try{const R=JSON.parse(h.data);if(R?.status==="ready")return;ve(ee=>[...ee.slice(-79),{at:Date.now(),data:R}])}catch{}},{enabled:!!ue});const ft=Ae({mutationFn:()=>{const h=String(q||"").trim(),R=String(w||"").trim();if(!h)throw new Error("Enter a prompt first.");if(!R)throw new Error("Set workspace path first.");return a("/api/orchestrator/start",{method:"POST",body:JSON.stringify({objective:h,workspaceRoot:R,maxTasks:Number(J||4),maxAgents:Number(fe||3),workflowId:String(D||"swarm.blackboard.default").trim(),requireLlmPlan:!0,allowLocalPlannerFallback:!1,verificationMode:"strict"})})},onSuccess:async h=>{const R=String(h?.runId||"").trim();R&&ct(R),u(!1),t("ok","Planning started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:h=>t("err",h instanceof Error?h.message:String(h))}),Re=Ae({mutationFn:({path:h,body:R})=>a(h,{method:"POST",body:JSON.stringify(R)}),onSuccess:async(h,R)=>{if(R.path==="/api/orchestrator/request_revision"){const ee=String(h?.runId||"").trim();ee&&(ct(ee),Y("")),t("ok","Reworked plan created.")}R.path==="/api/orchestrator/approve"&&t("ok","Execution started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:h=>t("err",h instanceof Error?h.message:String(h))}),Fe=Ae({mutationFn:async h=>{const R=String(h||"").trim();if(!R)throw new Error("Missing run id.");return await a("/api/orchestrator/cancel",{method:"POST",body:JSON.stringify({runId:R})}).catch(()=>null),await a("/api/orchestrator/runs/hide",{method:"POST",body:JSON.stringify({runIds:[R]})}).catch(()=>null),R},onSuccess:async()=>{bt(),u(!0),Y(""),b(""),t("ok","Discarded pending plan. You can start a new prompt now."),await r.invalidateQueries({queryKey:["swarm"]})},onError:h=>t("err",h instanceof Error?h.message:String(h))}),Nt=Je(()=>{u(!0),bt(),k(!1),Y("")},[bt]);ye(()=>{const h=l.current;h&&zt(h)},[d,p,ze,Te,ce,U,ht.length,Tt.length,oe,wt,Ne,Ee,De,L]);const Lt=!Te,mt=ce==="planning"||ce==="queued",It=ce==="awaiting_approval",oa=["completed","failed","cancelled"].includes(ce),_a=ce==="running",da=ce==="paused",Sa=ce==="failed"||ce==="blocked",Ka=["queued","planning","awaiting_approval","running","paused","blocked"].includes(ce),Ca=e(qt,{children:[e(xe.aside,{className:`chat-sessions-panel ${p?"open":""}`,initial:!1,animate:s?{x:p?0:"-104%"}:{x:p?0:"-104%",transition:{duration:.18,ease:"easeOut"}},children:[e("div",{className:"chat-sessions-header",children:[e("h3",{className:"chat-sessions-title",children:[e("i",{"data-lucide":"history"}),"History"]}),e("div",{className:"flex items-center gap-1",children:e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{r.invalidateQueries({queryKey:["swarm","runs"]})},children:e("i",{"data-lucide":"refresh-cw"})})})]}),e("div",{className:"chat-session-list",children:[e(ot,{children:ze.map((h,R)=>{const ee=String(h?.run_id||h?.runId||`run-${R}`),Me=ee===Te;return e(xe.div,{className:"chat-session-row",initial:s?!1:{opacity:0,y:6},animate:s?void 0:{opacity:1,y:0},exit:s?void 0:{opacity:0,y:-6},children:e("button",{type:"button",className:`chat-session-btn ${Me?"active":""}`,onClick:()=>{u(!1),ct(ee),k(!1)},children:[e("span",{className:"mb-0.5 inline-flex items-center gap-1 text-xs font-medium",children:[e("i",{"data-lucide":"history"}),e("span",{children:Nr(Cc(h))})]}),e("span",{className:"tcp-subtle line-clamp-2 block text-[11px]",children:String(h?.objective||"").trim()||"No objective"})]})},ee)})}),ze.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No runs yet."})]})]}),e(ot,{children:p?e(xe.button,{type:"button",className:"chat-scrim open","aria-label":"Close history",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},onClick:()=>k(!1)}):null})]});if(Lt){const h=String(q||"").trim().length>0&&String(w||"").trim().length>0;return e(qt,{children:[e("div",{ref:l,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[Ca,e("div",{className:"min-h-0 min-w-0 w-full",children:e("div",{className:"flex h-full min-h-0 w-full flex-col gap-4 p-4 md:p-5",children:[e("div",{className:"mb-3",children:[e("div",{className:"inline-flex items-center gap-2 text-sm font-semibold",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"History",onClick:()=>k(R=>!R),children:e("i",{"data-lucide":"history"})}),e("span",{children:"Orchestrator"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Describe the goal. The planner will build a task board."})]}),e("div",{className:"grid min-h-0 flex-1 w-full content-start gap-3",children:[e("textarea",{className:"tcp-input min-h-[360px] md:min-h-[52vh]",placeholder:"What do you want the agents to build?",value:q,onInput:R=>b(R.target.value)}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr]",children:[e("button",{className:"tcp-btn",onClick:()=>{const R=String(w||ae.data?.workspaceRoot||"/").trim();se(R||"/"),ge(""),K(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,placeholder:"No workspace selected. Use Browse.",value:w})]}),e("div",{className:"tcp-subtle text-xs",children:["Selected folder: ",w||"none"]}),w?null:e("div",{className:"rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"Select a workspace folder before sending."}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("button",{className:"tcp-btn-primary",onClick:()=>ft.mutate(),disabled:ft.isPending||!h,children:[e("i",{"data-lucide":"send"}),"Send"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>W(R=>!R),children:[e("i",{"data-lucide":"sliders-horizontal"}),N?"Hide Advanced":"Show Advanced"]})]}),N?e("div",{className:"grid gap-2 rounded-lg border border-slate-700/60 bg-slate-900/20 p-2 md:grid-cols-3",children:[e("input",{className:"tcp-input",type:"number",min:"1",value:J,onInput:R=>S(R.target.value),title:"max tasks"}),e("input",{className:"tcp-input",type:"number",min:"1",max:"16",value:fe,onInput:R=>f(R.target.value),title:"max agents"}),e("input",{className:"tcp-input",value:D,onInput:R=>de(R.target.value),title:"workflow id"}),e("div",{className:"tcp-subtle md:col-span-3 text-xs",children:"Workflow id controls task routing template. Keep default unless you have a custom workflow."})]}):null]})]})})]}),E?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",T||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{we&&se(we)},disabled:!we,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{T&&(M(T),K(!1),ge(""),t("ok",`Workspace selected: ${T}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{K(!1),ge("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:G,onInput:R=>ge(R.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:X.length?X.map(R=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>se(String(R?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(R?.name||R?.path||"")]},String(R?.path||R?.name))):e(qe,{text:m?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}return e(qt,{children:[e("div",{ref:l,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[Ca,e("div",{className:"min-h-0 min-w-0 w-full",children:e("div",{className:"grid h-full min-h-[calc(100vh-240px)] min-w-0 w-full gap-5 p-4 md:p-5 xl:grid-cols-[1.05fr_1fr]",children:[e("div",{className:"flex h-full min-h-0 w-full flex-col gap-3",children:[e("div",{className:"mb-3",children:[e("div",{className:"inline-flex items-center gap-2 text-sm font-semibold",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"History",onClick:()=>k(h=>!h),children:e("i",{"data-lucide":"history"})}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Back to start",onClick:Nt,children:e("i",{"data-lucide":"arrow-left-to-line"})}),e("span",{children:"Orchestration Run"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Plan review and execution"})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Vt(ce),children:ce||"unknown"}),e("span",{className:"inline-flex items-center gap-1 tcp-subtle",children:[e("i",{"data-lucide":"history"}),e("span",{children:Nr(Ce.data?.run?.updated_at_ms||Ce.data?.run?.created_at_ms)})]}),e("span",{className:"tcp-subtle",children:["id: ",Te]}),e("span",{className:"tcp-subtle",children:["plan: ",Oe]})]}),mt?e("div",{className:"mb-3 rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("div",{className:"mb-1 text-sm font-medium",children:"Planner is formulating a plan..."}),e("div",{className:"tcp-subtle text-xs",children:"Waiting for tasks to be generated."})]}):null,It?e("div",{className:"mb-3 rounded-xl border border-amber-500/40 bg-amber-950/20 p-3",children:[e("div",{className:"mb-2 text-sm font-medium text-amber-200",children:"Plan Ready"}),e("div",{className:"mb-2 text-xs text-amber-100/90",children:"Review the kanban. Request a rework or execute."}),e("textarea",{className:"tcp-input mb-2 min-h-[80px]",placeholder:"Feedback to rework the plan...",value:$e,onInput:h=>Y(h.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",disabled:!$e.trim(),onClick:()=>Re.mutate({path:"/api/orchestrator/request_revision",body:{runId:Te,feedback:$e,maxTasks:Number(J||4),maxAgents:Number(fe||3),workflowId:D}}),children:[e("i",{"data-lucide":"pencil"}),"Rework Plan"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Re.mutate({path:"/api/orchestrator/approve",body:{runId:Te}}),children:[e("i",{"data-lucide":"play"}),"Execute Plan"]}),e("button",{className:"tcp-btn-danger",disabled:Fe.isPending,onClick:()=>Fe.mutate(Te),children:[e("i",{"data-lucide":"trash-2"}),"Discard Plan"]})]})]}):null,!mt&&!It?e("div",{className:"mb-3 flex flex-wrap gap-2",children:[_a?e("button",{className:"tcp-btn",onClick:()=>Re.mutate({path:"/api/orchestrator/pause",body:{runId:Te}}),children:[e("i",{"data-lucide":"square"}),"Pause"]}):null,da?e("button",{className:"tcp-btn",onClick:()=>Re.mutate({path:"/api/orchestrator/resume",body:{runId:Te}}),children:[e("i",{"data-lucide":"play"}),"Resume"]}):null,Sa?e("button",{className:"tcp-btn",onClick:()=>Re.mutate({path:"/api/orchestrator/continue",body:{runId:Te}}),children:[e("i",{"data-lucide":"rotate-cw"}),"Continue Run"]}):null,Ka?e("button",{className:"tcp-btn-danger",onClick:()=>Re.mutate({path:"/api/orchestrator/cancel",body:{runId:Te}}),children:[e("i",{"data-lucide":"x"}),"Cancel"]}):null,e("button",{className:"tcp-btn",onClick:Nt,children:[e("i",{"data-lucide":"plus"}),"New Prompt"]})]}):null,oa?e("div",{className:"mb-3 rounded-lg border border-slate-700/60 bg-slate-900/25 p-2 text-xs tcp-subtle",children:ce==="failed"?"This run is failed. Continue the run or retry a failed task.":`This run is ${ce}. Start a new prompt to continue.`}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workspace Files"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Refresh","aria-label":"Refresh",onClick:()=>{I.refetch()},disabled:!C,children:e("i",{"data-lucide":"refresh-cw"})})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Up","aria-label":"Up",disabled:!Bt,onClick:()=>{Bt&&ie(Bt)},children:e("i",{"data-lucide":"arrow-up-circle"})}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Root","aria-label":"Root",disabled:!C,onClick:()=>{C&&ie(C)},children:e("i",{"data-lucide":"home"})})]}),e("div",{className:"mb-2 tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:U||C||"No workspace"}),ea?null:e("div",{className:"mb-2 rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"File listing for this workspace is not exposed by the current server scope. Directory navigation still works."}),e("div",{className:"grid max-h-[220px] min-h-0 gap-1 overflow-auto",children:[ht.map(h=>{const R=String(h?.path||"");return e("button",{className:"tcp-list-item text-left",onClick:()=>ie(R),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(h?.name||R)})]})},`dir-${R}`)}),Tt.map(h=>{const R=String(h?.path||"");return e("button",{className:`tcp-list-item text-left ${R===oe?"border-amber-400/70":""}`,onClick:()=>Ue(R),children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"inline-flex min-w-0 items-center gap-2",children:[e("i",{"data-lucide":"file-up"}),e("span",{className:"truncate",children:String(h?.name||R)})]}),e("span",{className:"tcp-subtle shrink-0 text-[11px]",children:Ic(h?.size)})]})},`file-${R}`)}),!ht.length&&!Tt.length?e(qe,{text:"No files or folders in this workspace location."}):null]})]}),oe?e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"File Preview"}),e("div",{className:"flex items-center gap-2",children:[g?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>le(!0),children:[e("i",{"data-lucide":"fullscreen"}),"Fullscreen"]}):null,e("span",{className:"tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:oe})]})]}),lt.isLoading?e("div",{className:"tcp-subtle text-xs",children:"Loading file..."}):g?e("div",{className:"max-h-[420px] overflow-auto rounded-lg border border-slate-700/60 bg-black",children:e("iframe",{className:"h-[420px] w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:wt,title:oe,scrolling:"yes"})}):ia?e("div",{className:"tcp-markdown tcp-markdown-ai max-h-[260px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-950/40 p-3",dangerouslySetInnerHTML:{__html:Na(wt)}}):e("pre",{className:"tcp-code max-h-[260px] overflow-auto whitespace-pre-wrap break-words",children:wt||"No text content."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Executor Verification"})}),_.length?e("div",{className:"grid max-h-44 gap-2 overflow-auto",children:_.map(h=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Vt(h.type.includes("failed")?"failed":"running"),children:h.type}),e("span",{className:"tcp-subtle",children:["mode: ",h.mode]})]}),e("div",{className:"font-medium",children:h.title}),e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:h.reason||"No verification detail."}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>F(h.id),children:[e("i",{"data-lucide":"search"}),"View details"]}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(Cr(h)),t("ok","Copied verification feedback.")}catch(R){t("err",R instanceof Error?R.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),h.verification?.execution_trace?e("div",{className:"mt-2 rounded border border-slate-700/50 bg-slate-950/40 p-2 tcp-subtle",children:[e("div",{children:["session:"," ",String(h.verification?.execution_trace?.session_id||"n/a")]}),e("div",{children:["model:"," ",[String(h.verification?.execution_trace?.model?.provider||"").trim(),String(h.verification?.execution_trace?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"]}),e("div",{children:["source:"," ",String(h.verification?.execution_trace?.model?.source||"n/a")]})]}):null]},h.id))}):e("div",{className:"tcp-subtle text-xs",children:"No verification telemetry yet."})]}),e("div",{className:"mt-3 grid gap-3 xl:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Live Activity"}),e("span",{className:"tcp-subtle text-xs",children:ca(Date.now())})]}),re.length?e("div",{className:"grid max-h-40 gap-2 overflow-auto",children:re.map(h=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Vt(h.type.includes("failed")?"failed":"running"),children:h.type}),e("span",{className:"tcp-subtle",children:ca(h.at)})]}),e("div",{className:"font-medium",children:h.title}),e("div",{className:"tcp-subtle",children:h.detail||"No additional detail."})]},h.id))}):e("div",{className:"tcp-subtle text-xs",children:"No activity events yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Latest Output"})}),O?e(qt,{children:[e("div",{className:"tcp-code max-h-28 overflow-auto whitespace-pre-wrap break-words",children:i||"No assistant output text yet."}),e("div",{className:"mt-2 tcp-subtle text-xs",children:"Recent tool calls"}),e("div",{className:"tcp-code mt-1 max-h-24 overflow-auto whitespace-pre-wrap break-words",children:c.length?c.join(`
556
+ `):"No tool call records found in current session yet."})]}):e("div",{className:"tcp-subtle text-xs",children:"No completed step output session yet."})]})]})]}),e("div",{className:"flex h-full min-h-0 w-full flex-col gap-3",children:[e("div",{className:"mb-3",children:[e("div",{className:"text-sm font-semibold",children:"Kanban + Budget"}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Tasks activate after execute"})]}),e("div",{className:"mb-3",children:e(yc,{budget:v})}),e(ts,{tasks:ut,currentTaskId:Le.currentTaskId,selectedTaskId:Se,workflowSummaryByTaskId:Et,onTaskSelect:h=>{const R=Se===h.id?"":h.id;V(R),me(h.id)},onRetryTask:h=>Re.mutate({path:"/api/orchestrator/retry",body:{runId:Te,stepId:h.id}})}),Se?e("div",{className:"mt-3 rounded-xl border border-cyan-700/50 bg-cyan-950/20 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Selected Task Workflow Link"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>V(""),children:"Clear task focus"})]}),e("div",{className:"tcp-subtle text-xs",children:["Task ",e("strong",{children:Se})," is filtering workflow runs and event stream."]})]}):null,Se?e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Task Workflow Artifacts"}),e("span",{className:"tcp-subtle text-xs",children:[Rt.length," actions"]})]}),Rt.length?e("div",{className:"grid max-h-56 gap-2 overflow-auto",children:Rt.map(h=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:h.action}),e("span",{className:Vt(h.status),children:h.status})]}),e("div",{className:"tcp-subtle",children:["run: ",h.runId]}),e("div",{className:"tcp-subtle",children:["updated: ",ca(h.updatedAt)]}),h.detail?e("div",{className:"mt-1 text-rose-200",children:h.detail}):null,h.output?e("pre",{className:"tcp-code mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(h.output,null,2)}):null]},h.id))}):e("div",{className:"tcp-subtle text-xs",children:"No workflow action artifacts are linked to this task yet."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workflow Automation"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>n("packs-detail"),children:"Open Workflow Lab"})]}),e("div",{className:"mb-2 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:"tcp-badge-info",children:ue||"no workflow id"}),e("span",{className:"tcp-subtle",children:Array.isArray(Qe.data?.workflow?.steps)?`${Qe.data.workflow.steps.length} steps`:"workflow metadata pending"}),e("span",{className:"tcp-subtle",children:Array.isArray(Qe.data?.hooks)?`${Qe.data.hooks.length} hooks`:""})]}),e("div",{className:"grid gap-3 xl:grid-cols-[0.85fr_1.15fr]",children:[e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Runs"}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:xt.length?xt.map((h,R)=>{const ee=String(h?.run_id||`workflow-run-${R}`).trim(),Me=ee===_e,Pe=String(h?.status||"unknown").trim(),Be=va(h);return e("button",{type:"button",className:`tcp-list-item text-left ${Me?"border-amber-400/70":""}`,onClick:()=>P(ee),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:ee}),e("span",{className:Vt(Pe),children:Pe})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger:"," ",String(h?.trigger_event||"manual").trim()||"manual"]}),e("div",{className:"tcp-subtle text-xs",children:["task: ",Be||"n/a"]}),e("div",{className:"tcp-subtle text-xs",children:["actions:"," ",Array.isArray(h?.actions)?h.actions.length:0]})]},ee)}):e(qe,{text:Se?"No workflow runs are linked to the selected task yet.":"No workflow runs recorded for this orchestration workflow yet."})})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Run Drilldown"}),Z?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Vt(String(Z?.status||"unknown")),children:String(Z?.status||"unknown")}),e("span",{className:"tcp-subtle",children:["trigger: ",String(Z?.trigger_event||"manual")]}),e("span",{className:"tcp-subtle",children:["source: ",String(Z?.source_event_id||"n/a")]})]}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:Array.isArray(Z?.actions)&&Z.actions.length?Z.actions.map((h,R)=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:String(h?.action||"unknown action")}),e("span",{className:Vt(String(h?.status||"unknown")),children:String(h?.status||"unknown")})]}),e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-subtle",children:["task:"," ",String(h?.task_id||Z?.task_id||"n/a")]}),String(h?.task_id||Z?.task_id||"").trim()?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>V(String(h?.task_id||Z?.task_id||"").trim()),children:"Focus task"}):null]}),e("div",{className:"tcp-subtle",children:["started: ",ca(h?.started_at_ms)]}),e("div",{className:"tcp-subtle",children:["finished: ",ca(h?.finished_at_ms)]}),String(h?.error||"").trim()?e("div",{className:"mt-1 text-rose-200",children:String(h.error)}):null]},`${String(h?.action||"action")}-${R}`)):e("div",{className:"tcp-subtle text-xs",children:"No recorded workflow actions for this run."})})]}):e(qe,{text:"Select a workflow run to inspect its action timeline."})]})]})]}),e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workflow Event Stream"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Clear workflow events","aria-label":"Clear workflow events",onClick:()=>ve([]),children:e("i",{"data-lucide":"trash-2"})})]}),te.length?e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:[...te].filter(h=>{const R=va(h.data?.properties||{});if(Se&&R&&R!==Se)return!1;if(!_e)return!0;const ee=String(h.data?.properties?.runID||"").trim();return!ee||ee===_e}).reverse().map((h,R)=>{const ee=Tc(h.data);return e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Vt(ee.endsWith(".failed")?"failed":ee.endsWith(".completed")?"completed":"running"),children:ee}),e("span",{className:"tcp-subtle",children:ca(h.at)})]}),e("div",{className:"tcp-subtle",children:["run: ",String(h.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle",children:["action:"," ",String(h.data?.properties?.action||h.data?.properties?.actionID||"-")]})]},`${h.at}-${R}`)})}):e("div",{className:"tcp-subtle text-xs",children:"No workflow events streamed for this run yet."})]}),e(ot,{children:[A?e(xe.div,{className:"tcp-confirm-overlay",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close task details",onClick:()=>me("")}),e(xe.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:s?!1:{opacity:0,y:8,scale:.98},animate:s?void 0:{opacity:1,y:0,scale:1},exit:s?void 0:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Kanban Task Details"}),e("p",{className:"tcp-confirm-message",children:"Full task brief, dependencies, and runtime context for this kanban item."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>me(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Vt(A.state),children:Sc(A.state)}),e("span",{className:"tcp-badge-info",children:A.id}),A.assigned_role?e("span",{className:"tcp-subtle",children:["role: ",A.assigned_role]}):null,A.gate?e("span",{className:"tcp-subtle",children:["gate: ",A.gate]}):null,A.workflow_id?e("span",{className:"tcp-subtle",children:["workflow: ",A.workflow_id]}):null,A.session_id?e("span",{className:"tcp-subtle",children:["session: ",A.session_id]}):null]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Title"}),e("div",{className:"rounded-lg border border-slate-800/80 bg-slate-950/70 px-3 py-2 text-sm text-slate-100",children:A.title||"Untitled task"})]}),A.description?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Description"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:A.description})]}):null,e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Dependencies"}),A.dependencies.length?e("div",{className:"flex flex-wrap gap-2",children:A.dependencies.map(h=>e("span",{className:"rounded border border-slate-700/60 px-2 py-1 text-xs text-slate-200",children:["<-"," ",h]},`${A.id}-${h}`))}):e("div",{className:"tcp-subtle text-sm",children:"No blocking dependencies."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Runtime Context"}),e("div",{className:"grid gap-2 text-sm",children:[e("div",{className:"tcp-subtle",children:["runtime status: ",A.runtime_status||"n/a"]}),e("div",{className:"tcp-subtle",children:["retry count: ",Number(A.retry_count||0)]}),Et?.[A.id]?e("div",{className:"tcp-subtle",children:["workflow runs:"," ",Et[A.id].runs,Et[A.id].failed?`, failed ${Et[A.id].failed}`:""]}):null,A.runtime_detail?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:["detail: ",A.runtime_detail]}):null]})]})]}),String(A.error_message||"").trim()?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Error"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words text-rose-100",children:String(A.error_message||"").trim()})]}):null]}),e("div",{className:"tcp-confirm-actions mt-4",children:[e("button",{className:"tcp-btn",onClick:()=>{V(A.id),me("")},children:"Focus task"}),e("button",{className:"tcp-btn",onClick:()=>me(""),children:"Close"})]})]})]}):null,$?e(xe.div,{className:"tcp-confirm-overlay",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close verification details",onClick:()=>F("")}),e(xe.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:s?!1:{opacity:0,y:8,scale:.98},animate:s?void 0:{opacity:1,y:0,scale:1},exit:s?void 0:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Executor Verification Details"}),e("p",{className:"tcp-confirm-message",children:"Raw verification and execution trace for debugging task feedback."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>F(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Vt($.type.includes("failed")?"failed":"running"),children:$.type}),e("span",{className:"tcp-badge-info",children:$.title}),e("span",{className:"tcp-subtle",children:["task: ",$.taskId||"n/a"]}),e("span",{className:"tcp-subtle",children:["mode: ",$.mode]}),e("span",{className:"tcp-subtle",children:["time: ",ca($.at)]})]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Feedback"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(Cr($)),t("ok","Copied verification feedback.")}catch(h){t("err",h instanceof Error?h.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:$.reason||"No verification detail."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Verification JSON"}),e("pre",{className:"tcp-code tcp-verification-code whitespace-pre-wrap break-words",children:JSON.stringify($.verification||{},null,2)})]})]}),e("div",{className:"tcp-confirm-actions mt-4",children:e("button",{className:"tcp-btn",onClick:()=>F(""),children:"Close"})})]})]}):null]})]})]})})]}),e(ot,{children:De&&oe&&g?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>le(!1),children:e(xe.div,{className:"relative h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] overflow-hidden rounded-[1.4rem] border border-slate-700/70 bg-slate-950 shadow-[0_28px_64px_rgba(0,0,0,0.55)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:h=>h.stopPropagation(),children:[e("div",{className:"flex items-center justify-between gap-3 border-b border-slate-800/80 px-5 py-4",children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-lg font-semibold text-slate-100",children:"Fullscreen Preview"}),e("div",{className:"tcp-subtle mt-1 text-xs",style:{overflowWrap:"anywhere"},children:oe})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{lt.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8","aria-label":"Close preview",title:"Close preview",onClick:()=>le(!1),children:e("i",{"data-lucide":"x"})})]})]}),e("div",{className:"h-[calc(100%-4.5rem)] p-3",children:e("div",{className:"h-full overflow-auto rounded-xl border border-slate-700/60 bg-black",children:e("iframe",{className:"h-full w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:wt,title:`${oe} fullscreen preview`,scrolling:"yes"})})})]})}):null}),E?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",T||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{we&&se(we)},disabled:!we,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{T&&(M(T),K(!1),ge(""),t("ok",`Workspace selected: ${T}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{K(!1),ge("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:G,onInput:h=>ge(h.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:X.length?X.map(h=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>se(String(h?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(h?.name||h?.path||"")]},String(h?.path||h?.name))):e(qe,{text:m?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}function Rc(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function $c({api:a,toast:t}){const n=jt(),[r,s]=y("uploads"),l=Q({queryKey:["files",r],queryFn:()=>a(`/api/files/list?dir=${encodeURIComponent(r)}`).catch(()=>({files:[]})),refetchInterval:12e3}),d=Ae({mutationFn:p=>a("/api/files/delete",{method:"POST",body:JSON.stringify({path:p})}),onSuccess:async()=>{t("ok","File removed."),await n.invalidateQueries({queryKey:["files",r]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),u=Rc(l.data,"files");return e("div",{className:"grid gap-4",children:e(Xt,{title:"Files",subtitle:"Browse and delete uploaded files",children:[e("div",{className:"mb-3 flex gap-2",children:[e("input",{className:"tcp-input",value:r,onInput:p=>s(p.target.value),placeholder:"uploads"}),e("button",{className:"tcp-btn",onClick:()=>l.refetch(),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("div",{className:"grid gap-2",children:u.length?u.map((p,k)=>{const q=String(p?.path||p?.name||`file-${k}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{className:"truncate",children:q}),e("span",{className:"tcp-subtle text-xs",children:[String(p?.size||0)," bytes"]})]}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>d.mutate(q),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})})]},q)}):e(qe,{text:"No files found for this directory."})})]})})}function qc(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Ec({client:a,toast:t}){const n=jt(),[r,s]=y(""),[l,d]=y(null),u=Q({queryKey:["memory",r],queryFn:()=>(r.trim()?a.memory.search({query:r,limit:40}):a.memory.list({q:"",limit:40})).catch(()=>({items:[]})),refetchInterval:15e3}),p=Ae({mutationFn:b=>a.memory.delete(b),onSuccess:async()=>{t("ok","Memory record deleted."),await n.invalidateQueries({queryKey:["memory"]})},onError:b=>t("err",b instanceof Error?b.message:String(b))}),k=qc(u.data,"items"),q=H(()=>k.map((b,w)=>{const M=String(b?.id||`mem-${w}`),E=String(b?.text||b?.content||b?.value||""),K=E.length>340?`${E.slice(0,340)}...`:E;return{id:M,text:E,compact:K,html:Na(E)}}),[k]);return e(La,{className:"grid gap-4",children:e(Ze,{title:"Memory",subtitle:"Search recent records and open full entry details inline.",actions:e(qt,{children:[e(Ie,{tone:"info",children:[q.length," results"]}),r.trim()?e(Ie,{tone:"ghost",children:["Filter: ",r]}):e(Ie,{tone:"ghost",children:"Browsing latest memory"})]}),children:[e(Gt,{className:"mb-3",children:[e("input",{className:"tcp-input flex-1",value:r,onInput:b=>s(b.target.value),placeholder:"Search memory"}),e("button",{className:"tcp-btn",onClick:()=>u.refetch(),children:[e("i",{"data-lucide":"search"}),"Search"]})]}),e("div",{className:"grid gap-2",children:q.length?q.map(b=>{const w=l===b.id;return e(xe.article,{layout:!0,className:`tcp-list-item cursor-pointer ${w?"border-amber-500/60":""}`,onClick:()=>d(w?null:b.id),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{className:"truncate",children:b.id}),e("div",{className:"flex items-center gap-2",children:[e(Ie,{tone:w?"info":"ghost",children:w?"expanded":"compact"}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:M=>{M.stopPropagation(),p.mutate(b.id)},children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]}),e(ot,{initial:!1,mode:"wait",children:w?e(xe.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.18,ease:"easeOut"},className:"overflow-hidden",children:e("div",{className:"tcp-markdown tcp-markdown-ai rounded-lg border border-slate-700/60 bg-black/20 p-3 text-sm",dangerouslySetInnerHTML:{__html:b.html}})},"expanded"):e(xe.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.14,ease:"easeOut"},className:"tcp-subtle whitespace-pre-wrap text-xs",children:b.compact||"(empty)"},"compact")})]},b.id)}):e(qe,{text:"No memory records found."})})]})})}const cs=[{label:"Every hour",intervalSeconds:3600},{label:"Every morning",cron:"0 9 * * *"},{label:"Every evening",cron:"0 18 * * *"},{label:"Daily at midnight",cron:"0 0 * * *"},{label:"Weekly Monday",cron:"0 9 * * 1"},{label:"Manual only",cron:""}];function Oc(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Dc(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Fc(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function Uc(a,t){const n=String(t||"").trim();if(n)return{type:"cron",cron_expression:n,timezone:"UTC"};const r=cs.find(s=>s.label===a);return r?.intervalSeconds?{type:"interval",interval_seconds:r.intervalSeconds}:r?.cron?{type:"cron",cron_expression:r.cron,timezone:"UTC"}:{type:"manual"}}function jc(a){const t=String(a?.template_id||a?.templateID||a?.id||"").trim();if(!t)return null;const n=String(a?.display_name||a?.displayName||a?.name||"").trim(),r=String(a?.role||"worker").trim()||"worker",s=a?.default_model||a?.defaultModel||{},l=String(s?.provider_id||s?.providerId||"").trim(),d=String(s?.model_id||s?.modelId||"").trim();return{templateId:t,displayName:n||t,role:r,modelLabel:l&&d?`${l}/${d}`:""}}function Lc({client:a,toast:t}){const n=jt(),r=pt(null),[s,l]=y("Daily Engineering Standup"),[d,u]=y(""),[p,k]=y("Every morning"),[q,b]=y(""),[w,M]=y("docs/standups/{{date}}.md"),[E,K]=y([]),[B,se]=y(null),G=Q({queryKey:["teams","standup","templates"],queryFn:()=>a?.agentTeams?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:12e3}),ge=Q({queryKey:["teams","standup","health"],queryFn:()=>a?.health?.().catch(()=>({}))??Promise.resolve({}),refetchInterval:3e4});ye(()=>{const S=String(ge.data?.workspaceRoot||ge.data?.workspace_root||"").trim();S&&u(fe=>fe||S)},[ge.data]);const N=H(()=>Oc(G.data,"templates").map(jc).filter(S=>!!S),[G.data]),W=Ae({mutationFn:async()=>{const S=String(s||"").trim(),fe=String(d||"").trim();if(!S)throw new Error("Standup name is required.");const f=Dc(fe);if(f)throw new Error(f);if(!E.length)throw new Error("Select at least one participant template.");return await a?.agentTeams?.composeStandup?.({name:S,workspaceRoot:fe,schedule:Uc(p,q),participantTemplateIds:E,reportPathTemplate:String(w||"").trim()||void 0})||null},onSuccess:S=>{se(S?.automation||null)},onError:S=>t("err",S instanceof Error?S.message:String(S))}),J=Ae({mutationFn:async()=>{const S=B||(await W.mutateAsync())?.automation;if(!S)throw new Error("Standup compose failed.");return a?.automationsV2?.create?.(S)},onSuccess:async()=>{t("ok","Agent standup automation created."),se(null),await n.invalidateQueries({queryKey:["automations"]})},onError:S=>t("err",S instanceof Error?S.message:String(S))});return ye(()=>{const S=r.current;S&&zt(S)},[s,d,p,q,w,E.join(","),N.length,W.isPending,J.isPending,!!B]),e("div",{ref:r,className:"grid gap-4 rounded-2xl border border-emerald-500/20 bg-emerald-500/5 p-4",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-emerald-300",children:"Agent Standup"}),e("h3",{className:"mt-1 text-lg font-semibold text-white",children:"Build a scheduled standup from saved agents"}),e("p",{className:"mt-1 text-sm text-slate-300",children:"Choose the personalities that should participate, preview the workflow, and create the automation from the same place you manage those agents."})]}),e("span",{className:"tcp-badge-ok",children:"MVP"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"Standup name",value:s,onInput:S=>l(S.target.value)}),e("input",{className:"tcp-input",placeholder:"/absolute/workspace/root",value:d,onInput:S=>u(S.target.value)}),e("select",{className:"tcp-input",value:p,onInput:S=>k(S.target.value),children:cs.map(S=>e("option",{value:S.label,children:S.label},S.label))}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"Custom cron (optional)",value:q,onInput:S=>b(S.target.value)})]}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"docs/standups/{{date}}.md",value:w,onInput:S=>M(S.target.value)}),e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3 text-sm text-slate-300",children:"The markdown report path controls where the synthesized standup is written. Participant personalities come from the saved agents below."}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Participants"}),N.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:N.map(S=>{const fe=E.includes(S.templateId);return e("button",{type:"button",className:`tcp-list-item text-left transition-all ${fe?"border-emerald-400/60 bg-emerald-400/10":""}`,onClick:()=>K(f=>f.includes(S.templateId)?f.filter(D=>D!==S.templateId):[...f,S.templateId]),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:S.displayName}),e("span",{className:"tcp-badge-info",children:S.role})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:S.templateId}),S.modelLabel?e("div",{className:"mt-2 text-xs text-emerald-200",children:S.modelLabel}):null]},S.templateId)})}):e(qe,{text:"Create at least one saved agent below before composing a standup."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:W.isPending||!N.length,onClick:()=>W.mutate(),children:[e("i",{"data-lucide":"file-search"}),W.isPending?"Composing…":"Preview Standup Workflow"]}),e("button",{type:"button",className:"tcp-btn-primary",disabled:J.isPending||!N.length,onClick:()=>J.mutate(),children:[e("i",{"data-lucide":"rocket"}),J.isPending?"Creating…":"Create Standup Automation"]})]}),B?e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("strong",{children:String(B?.name||"Standup preview")}),e("span",{className:"tcp-badge-info",children:[Array.isArray(B?.flow?.nodes)?B.flow.nodes.length:0," nodes"]})]}),e("div",{className:"grid gap-2 text-xs text-slate-300",children:[e("div",{children:["schedule: ",Fc(B?.schedule)]}),e("div",{children:["report:"," ",String(B?.metadata?.standup?.report_path_template||w)]}),e("div",{children:["participants:"," ",String((B?.metadata?.standup?.participant_template_ids||E).join(", "))]})]})]}):null]})}const Ir=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],Bc={worker:"Executes hands-on work and reports concrete progress.",reviewer:"Critiques output, spots risks, and improves quality.",tester:"Validates behavior and looks for regressions or gaps.",watcher:"Monitors activity, incidents, and changes over time.",delegator:"Breaks work down and routes tasks across participants.",committer:"Finalizes work and drives it toward completion.",orchestrator:"Coordinates multi-agent flow and synthesizes updates."},Kc=["You are the frontend lead. Focus on shipped UI changes, active branches, visual regressions, and blockers from design or review.","You are the backend lead. Focus on APIs, database work, deploys, incidents, and blockers from reliability or dependencies.","You are the product and ops agent. Focus on launches, customer feedback, analytics, triage, and operational blockers."],Za={templateId:"",displayName:"",avatarUrl:"",role:"worker",systemPrompt:"",modelProvider:"",modelId:""};function An(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Wc(a){const t=a?.default_model||a?.defaultModel||{};return{templateId:String(a?.template_id||a?.templateID||a?.id||"").trim(),displayName:String(a?.display_name||a?.displayName||a?.name||"").trim(),avatarUrl:String(a?.avatar_url||a?.avatarUrl||"").trim(),role:String(a?.role||"worker").trim()||"worker",systemPrompt:String(a?.system_prompt||a?.systemPrompt||"").trim(),modelProvider:String(t?.provider_id||t?.providerId||"").trim(),modelId:String(t?.model_id||t?.modelId||"").trim()}}function Jc(a){const t={templateID:a.templateId.trim(),display_name:a.displayName.trim()||void 0,avatar_url:a.avatarUrl.trim()||void 0,role:a.role,system_prompt:a.systemPrompt.trim()||void 0,skills:[],default_budget:{},capabilities:{}};return a.modelProvider.trim()&&a.modelId.trim()&&(t.default_model={provider_id:a.modelProvider.trim(),model_id:a.modelId.trim()}),t}function Ar({client:a,toast:t}){const n=jt(),r=a?.agentTeams,s=pt(null),[l,d]=y(Za),[u,p]=y(null),k=pt(null),q=Q({queryKey:["teams","templates"],queryFn:()=>r?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:8e3}),b=Q({queryKey:["teams","instances"],queryFn:()=>r?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),w=Q({queryKey:["teams","approvals"],queryFn:()=>r?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),M=Ae({mutationFn:async()=>{if(!l.templateId.trim())throw new Error("Template ID is required.");return u?r?.updateTemplate?.(u,{display_name:l.displayName.trim()||void 0,avatar_url:l.avatarUrl.trim()||void 0,role:l.role,system_prompt:l.systemPrompt.trim()||void 0,default_model:l.modelProvider.trim()&&l.modelId.trim()?{provider_id:l.modelProvider.trim(),model_id:l.modelId.trim()}:void 0}):r?.createTemplate?.({template:Jc(l)})},onSuccess:async()=>{t("ok",u?"Template updated.":"Template created."),d(Za),p(null),await n.invalidateQueries({queryKey:["teams"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),E=Ae({mutationFn:f=>r?.deleteTemplate?.(f),onSuccess:async()=>{t("ok","Template deleted."),u&&(p(null),d(Za)),await n.invalidateQueries({queryKey:["teams"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),K=Ae({mutationFn:({requestId:f,decision:D})=>D==="approve"?r?.approveSpawn?.(f):r?.denySpawn?.(f),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["teams"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),B=H(()=>An(q.data,"templates").map(Wc).filter(f=>f.templateId),[q.data]),se=An(b.data,"instances"),G=An(w.data,"spawnApprovals"),ge=!!(u||l.templateId||l.displayName||l.systemPrompt),N=l.displayName.trim()||l.templateId.trim()||"New Agent",W=N.slice(0,1).toUpperCase()||"A",J=Bc[l.role],S=l.avatarUrl.trim();ye(()=>{const f=s.current;f&&zt(f)},[B.length,se.length,G.length,l.role,l.templateId,l.displayName,l.avatarUrl,l.modelProvider,l.modelId,l.systemPrompt,u,M.isPending,E.isPending,K.isPending]);const fe=f=>{if(!f)return;if(f.size>10*1024*1024){t("err","Avatar image is too large (max 10 MB).");return}const D=new FileReader;D.onload=()=>{const de=typeof D.result=="string"?D.result:"";if(!de){t("err","Failed to read avatar image.");return}d($e=>({...$e,avatarUrl:de}))},D.onerror=()=>t("err","Failed to read avatar image."),D.readAsDataURL(f)};return e("div",{ref:s,className:"grid gap-4",children:[e(Xt,{title:"Agent Standup",subtitle:"Compose scheduled standups from the same saved agents you manage here",children:e(Lc,{client:a,toast:t})}),e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(Xt,{title:"Agents",subtitle:"Create reusable agent personalities, prompts, and default models for automation workflows",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-cyan-300",children:"Reusable Personalities"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses."})]}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"template-id",value:l.templateId,disabled:!!u,onInput:f=>d(D=>({...D,templateId:f.target.value}))}),e("input",{className:"tcp-input",placeholder:"Display name",value:l.displayName,onInput:f=>d(D=>({...D,displayName:f.target.value}))}),e("select",{className:"tcp-input",value:l.role,onInput:f=>d(D=>({...D,role:f.target.value})),children:Ir.map(f=>e("option",{value:f,children:f},f))}),e("input",{className:"tcp-input",placeholder:"Avatar URL or upload (optional)",value:l.avatarUrl,onInput:f=>d(D=>({...D,avatarUrl:f.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model provider (optional)",value:l.modelProvider,onInput:f=>d(D=>({...D,modelProvider:f.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model ID (optional)",value:l.modelId,onInput:f=>d(D=>({...D,modelId:f.target.value}))})]}),e("div",{className:"grid gap-3 lg:grid-cols-[1.15fr_0.85fr]",children:[e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Prompt Guidance"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Write the lasting perspective for this agent, not a one-off task. Good prompts describe ownership and judgment: frontend lead, backend lead, product ops, incident watcher."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:Kc.map(f=>e("button",{type:"button",className:"tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs",onClick:()=>d(D=>({...D,systemPrompt:f})),children:"Use Example"},f))})]}),e("div",{className:"rounded-[28px] border border-slate-800/80 bg-[radial-gradient(circle_at_top,_rgba(34,211,238,0.18),_transparent_45%),linear-gradient(180deg,rgba(15,23,42,0.9),rgba(2,6,23,0.96))] p-5",children:[e("div",{className:"flex items-start justify-between gap-4",children:[e("div",{className:"flex items-start gap-4",children:[e("div",{className:"flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-lg font-semibold text-cyan-100",children:S?e("img",{src:S,alt:N,className:"h-full w-full object-cover"}):W}),e("div",{className:"min-w-0",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-white",children:N}),e("span",{className:"tcp-badge-info",children:l.role})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:l.templateId.trim()||"template-id"}),e("div",{className:"mt-2 text-sm text-slate-300",children:J})]})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>k.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{type:"button",className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>d(f=>({...f,avatarUrl:""})),children:e("i",{"data-lucide":"trash-2"})})]})]}),e("div",{className:"mt-3 text-xs text-slate-400",children:"Upload an image like Settings Identity preview, or paste a direct avatar URL."}),e("input",{ref:k,type:"file",accept:"image/*",className:"hidden",onChange:f=>{fe(f.target.files?.[0]||null),f.target.value=""}}),e("div",{className:"mt-4 rounded-2xl border border-slate-800/70 bg-black/20 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Personality Preview"}),e("div",{className:"mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-200",children:l.systemPrompt.trim()||"This agent will respond from the persistent personality you define here across workflows and standups."})]}),(l.modelProvider.trim()||l.modelId.trim())&&e("div",{className:"mt-3 text-xs text-cyan-200",children:["Default model: ",l.modelProvider.trim()||"provider","/",l.modelId.trim()||"model"]})]})]}),e("textarea",{className:"tcp-input min-h-[140px]",placeholder:"Persistent system prompt",value:l.systemPrompt,onInput:f=>d(D=>({...D,systemPrompt:f.target.value}))}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:M.isPending,onClick:()=>M.mutate(),children:[e("i",{"data-lucide":"save"}),u?"Update Agent":"Create Agent"]}),ge&&e("button",{type:"button",className:"tcp-btn",onClick:()=>{p(null),d(Za)},children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Saved Agents"}),e("div",{className:"tcp-subtle text-xs",children:[B.length," saved"]})]}),B.length?B.map(f=>e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[e("strong",{children:f.displayName||f.templateId}),e("span",{className:"tcp-badge-info",children:f.role}),f.modelProvider&&f.modelId?e("span",{className:"tcp-badge-ok",children:[f.modelProvider,"/",f.modelId]}):null]}),e("div",{className:"tcp-subtle text-xs",children:f.templateId}),f.systemPrompt?e("div",{className:"mt-2 line-clamp-4 text-xs text-slate-300",children:f.systemPrompt}):e("div",{className:"mt-2 text-xs text-slate-500",children:"No persistent prompt set yet."})]}),e("div",{className:"flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{p(f.templateId),d({templateId:f.templateId,displayName:f.displayName,avatarUrl:f.avatarUrl,role:Ir.includes(f.role)?f.role:"worker",systemPrompt:f.systemPrompt,modelProvider:f.modelProvider,modelId:f.modelId})},children:[e("i",{"data-lucide":"pencil"}),"Edit"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>E.mutate(f.templateId),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]})},f.templateId)):e(qe,{title:"No agents yet",text:"Create your first saved personality here, then reuse it across automation workflows and standups."})]})]})}),e(Xt,{title:"Team Instances",subtitle:"Running collaborative agent instances",children:e("div",{className:"grid gap-2",children:se.length?se.map((f,D)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(f?.template_id||f?.templateID||f?.instance_id||"Instance")}),e("span",{className:"tcp-badge-info",children:String(f?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs",children:["mission: ",String(f?.mission_id||f?.missionID||"n/a")]})]},String(f?.instance_id||f?.id||D))):e(qe,{text:"No team instances found."})})}),e(Xt,{title:"Spawn Approvals",subtitle:"Pending team approval requests",children:e("div",{className:"grid gap-2",children:G.length?G.map((f,D)=>{const de=String(f?.approval_id||f?.request_id||f?.id||`request-${D}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:String(f?.reason||f?.title||de)}),e("div",{className:"tcp-subtle text-xs",children:de}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>K.mutate({requestId:de,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>K.mutate({requestId:de,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},de)}):e(qe,{text:"No pending approvals."})})})]})]})}async function Ut(a,t={}){const n=await fetch(a,{...t,credentials:"include",headers:{"content-type":"application/json",...t.headers||{}}});if(!n.ok){const s=await n.text().catch(()=>"");let l=s||`${a} failed (${n.status})`;try{const d=s?JSON.parse(s):null;d?.error&&(l=d.error)}catch{}throw new Error(l)}const r=await n.text();return r?JSON.parse(r):{}}function en(a){return a?.type||a?.event||"event"}function Pr(a){const t=String(a||"").trim().toLowerCase();return["server.connected","engine.lifecycle.ready","engine.heartbeat","engine.lifecycle.heartbeat"].includes(t)}function Tr(a){return String(a?.type||a?.event||"").trim()==="context.run.stream"&&String(a?.run_id||a?.runId||"").trim().startsWith("workflow-")}function Qc({client:a,toast:t,navigate:n}){const[r,s]=y([]),[l,d]=y(""),[u,p]=y("all"),[k,q]=y(!0),[b,w]=y(null),M=H(()=>!b||!Tr(b.data)?"":String(b.data?.run_id||b.data?.runId||"").trim(),[b]),E=Q({queryKey:["feed","workflow-context-run",M],enabled:!!M,queryFn:()=>Ut(`/api/engine/context/runs/${encodeURIComponent(M)}`).catch(()=>({run:null}))}),K=Q({queryKey:["feed","workflow-context-blackboard",M],enabled:!!M,queryFn:()=>Ut(`/api/engine/context/runs/${encodeURIComponent(M)}/blackboard`).catch(()=>({blackboard:null}))});ga("/api/global/event",N=>{try{const W=JSON.parse(N.data);s(J=>[...J.slice(-299),{at:Date.now(),data:W}])}catch{}},{enabled:!0});const B=H(()=>{const N=new Map;for(const W of r){const J=en(W.data);k&&Pr(J)||N.set(J,(N.get(J)||0)+1)}return[...N.entries()].sort((W,J)=>J[1]-W[1])},[r,k]),se=H(()=>{const N=l.trim().toLowerCase();return r.filter(W=>{const J=en(W.data);return k&&Pr(J)||u!=="all"&&J!==u?!1:N?`${J} ${JSON.stringify(W.data||{})}`.toLowerCase().includes(N):!0}).slice(-240).reverse()},[r,l,u,k]);async function G(N){try{const W=await Ut("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:N,source:{kind:"control_panel_feed",event:"pack.detected"}})});t("ok",`Installed ${W?.installed?.name||"pack"}`)}catch(W){t("err",W instanceof Error?W.message:String(W))}}async function ge(N){try{const W=await Ut("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:String(N?.properties?.attachment_id||N?.attachment_id||""),path:String(N?.properties?.path||N?.path||""),connector:String(N?.properties?.connector||N?.connector||"")||void 0,channel_id:String(N?.properties?.channel_id||N?.channel_id||"")||void 0,sender_id:String(N?.properties?.sender_id||N?.sender_id||"")||void 0})});t("ok",`Installed ${W?.installed?.name||"pack"}`)}catch(W){t("err",W instanceof Error?W.message:String(W))}}return e(La,{className:"grid gap-4",children:[e(Ze,{title:"Live feed",subtitle:"Filter events and inspect raw payload details.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e("span",{className:"tcp-badge-info",children:[r.length," buffered"]}),e("span",{className:"tcp-badge tcp-badge-ghost",children:u==="all"?"All event types":u}),e("span",{className:k?"tcp-badge-ok":"tcp-badge-info",children:k?"noise hidden":"noise visible"}),e("button",{className:"tcp-btn",onClick:()=>s([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear feed"]}),e("button",{className:"tcp-btn",onClick:()=>n("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Pack library"]})]}),children:[e(Gt,{className:"mb-3",children:[e("input",{className:"tcp-input min-w-[220px] flex-1",value:l,onInput:N=>d(N.target.value),placeholder:"Filter by type or payload"}),e(yn,{active:u==="all",onClick:()=>p("all"),children:[e("i",{"data-lucide":"list"}),"All"]}),e(yn,{active:k,onClick:()=>q(N=>!N),children:[e("i",{"data-lucide":k?"filter":"filter-x"}),k?"Hide noise":"Show noise"]}),B.slice(0,8).map(([N,W])=>e(yn,{active:u===N,onClick:()=>p(N),children:[e("i",{"data-lucide":"activity"}),N," (",W,")"]},N))]}),e("div",{className:"grid max-h-[68vh] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:se.length?se.map((N,W)=>{const J=en(N.data),S=String(J).startsWith("pack."),fe=Tr(N.data),f=String(N.data?.properties?.path||N.data?.path||""),D=String(N.data?.properties?.attachment_id||N.data?.attachment_id||"");return e("article",{className:"tcp-list-item cursor-pointer",onClick:()=>w(N),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:J}),e("div",{className:"flex items-center gap-2",children:[fe?e("span",{className:"tcp-badge-warn",children:"workflow context"}):null,e("span",{className:"tcp-badge-info",children:new Date(N.at).toLocaleTimeString()})]})]}),e("p",{className:"tcp-subtle mt-1 text-xs",children:fe?`run: ${String(N.data?.run_id||N.data?.runId||"n/a")}`:`session: ${String(N.data?.sessionID||N.data?.sessionId||"n/a")}`}),fe?e("p",{className:"tcp-subtle mt-1 text-xs",children:["kind: ",String(N.data?.kind||"context_run_event")," · seq:"," ",String(N.data?.seq||"-")]}):null,S?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:de=>{de.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open pack library"]}),f?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:de=>{de.stopPropagation(),G(f)},children:[e("i",{"data-lucide":"download"}),"Install from path"]}):null,f&&D?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:de=>{de.stopPropagation(),ge(N.data)},children:[e("i",{"data-lucide":"paperclip"}),"Install attachment"]}):null]}):null,fe?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:de=>{de.stopPropagation(),n("orchestrator")},children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:de=>{de.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open workflow lab"]})]}):null]},`${N.at}-${W}`)}):e(qe,{text:"No events have arrived yet."})})]}),e(on,{open:!!b,onClose:()=>w(null),title:b?en(b.data):"Event",children:b?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Captured at"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:new Date(b.at).toLocaleString()})]}),M?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(E.data?.run?.objective||M)}),e("span",{className:"tcp-badge-info",children:String(E.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(K.data?.blackboard?.tasks)?K.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(K.data?.blackboard?.artifacts)?K.data.blackboard.artifacts.length:0]})]}):null,e("pre",{className:"tcp-code",children:_t(b.data)}),M?e("pre",{className:"tcp-code",children:_t({run:E.data?.run||null,blackboard:K.data?.blackboard||null})}):null]}):null})]})}function Hc({theme:a}){const t=a?.cssVars?.["--color-background"]||"#000000",n=a?.cssVars?.["--color-surface"]||"#111111",r=a?.cssVars?.["--color-primary"]||"#ffffff",s=a?.cssVars?.["--color-secondary"]||"#ffffff";return e("div",{className:"flex items-center gap-2",children:[e("span",{className:"tcp-theme-swatch",style:{background:t},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:n},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:r},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:s},"aria-hidden":"true"})]})}function Gc({themes:a,themeId:t,onChange:n}){return e("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:a.map(r=>{const s=r.id===t;return e(xe.button,{type:"button",layout:!0,onClick:()=>n(r.id),className:`tcp-theme-tile ${s?"active":""}`,whileHover:{y:-2},whileTap:{scale:.985},transition:Zt.spring.gentle,children:[e("div",{className:"tcp-theme-tile-top",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-theme-tile-title",children:r.name}),e("p",{className:"tcp-subtle mt-1 text-xs",children:r.description})]}),e(Hc,{theme:r})]}),e("div",{className:"tcp-theme-preview",children:e("div",{className:"tcp-theme-preview-bg",style:{background:r.cssVars["--color-background"]||"#000"},children:e("div",{className:"tcp-theme-preview-card",style:{background:r.cssVars["--color-surface"]||"#111",borderColor:r.cssVars["--color-border"]||"rgba(255,255,255,0.1)"},children:[e("div",{className:"tcp-theme-preview-line short",style:{background:r.cssVars["--color-text"]||"#fff"}}),e("div",{className:"tcp-theme-preview-line",style:{background:r.cssVars["--color-text-muted"]||"#aaa"}}),e("div",{className:"tcp-theme-preview-pill",style:{background:r.cssVars["--color-primary"]||"#fff"}})]})})}),e(ot,{initial:!1,children:s?e(xe.span,{className:"tcp-theme-active",initial:{opacity:0,scale:.86},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.86},transition:Zt.spring.snappy,children:[e("i",{"data-lucide":"badge-check"}),"Active"]}):null})]},r.id)})})}function Wn(a){try{return new URL(a)}catch{return null}}function Dn(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"mcp-server"}function Mr(a){const t=Wn(a);if(!t)return"";const n=String(t.hostname||"").toLowerCase();if(!n)return"";if(n.endsWith("composio.dev"))return"composio";const r=n.split(".").filter(Boolean);if(!r.length)return"";const s=["backend","api","mcp","www"].includes(r[0])&&r[1]||r[0];return Dn(s)}function ds(a){const t=Wn(a);return t?String(t.hostname||"").toLowerCase().endsWith("composio.dev"):!1}function zc({authMode:a,token:t,customHeader:n,transport:r}){const s=String(t||"").trim();if(!s||a==="none")return{};if(a==="custom"){const d=String(n||"").trim();if(!d)throw new Error("Custom header name is required.");return{[d]:s}}return a==="x-api-key"?{"x-api-key":s}:a==="bearer"?{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}:ds(r)?{"x-api-key":s}:{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}}function Vc(a,t,n,r){return!String(t||"").trim()||a==="none"?"No auth header will be sent.":a==="custom"?n?`Header preview: ${n}: <token>`:"Set a custom header name.":a==="x-api-key"?"Header preview: x-api-key: <token>":a==="bearer"?"Header preview: Authorization: Bearer <token>":ds(r)?"Auto mode: selected x-api-key for this endpoint":"Auto mode: using Authorization Bearer token"}function Pn(a,t=""){if(!a||typeof a!="object")return null;const n=a,r=String(n.name||t||"").trim();return r?{name:r,transport:String(n.transport||"").trim(),connected:!!n.connected,enabled:n.enabled!==!1,lastError:String(n.last_error||n.lastError||"").trim(),headers:n.headers&&typeof n.headers=="object"?n.headers:{},toolCache:Array.isArray(n.tool_cache||n.toolCache)?n.tool_cache||n.toolCache:[]}:null}function Yc(a){return Array.isArray(a)?a.map(t=>Pn(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):!a||typeof a!="object"?[]:Array.isArray(a.servers)?a.servers.map(t=>Pn(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):Object.entries(a).map(([t,n])=>Pn(n&&typeof n=="object"?n:{transport:String(n||"")},t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name))}function Xc(a){return(Array.isArray(a)?a:Array.isArray(a?.tools)?a.tools:[]).map(n=>typeof n=="string"?n:!n||typeof n!="object"?"":String(n.namespaced_name||n.namespacedName||n.id||n.tool_name||n.toolName||"").trim()).filter(Boolean)}function Zc(a){const t=a&&typeof a=="object"?a:{},n=Array.isArray(t.servers)?t.servers:[];return{generatedAt:String(t.generated_at||"").trim(),count:Number.isFinite(Number(t.count))?Number(t.count):n.length,servers:n.map(r=>!r||typeof r!="object"?null:{slug:String(r.slug||"").trim(),name:String(r.name||r.slug||"").trim(),description:String(r.description||"").trim(),transportUrl:String(r.transport_url||"").trim(),serverConfigName:String(r.server_config_name||r.slug||"").trim(),documentationUrl:String(r.documentation_url||"").trim(),directoryUrl:String(r.directory_url||"").trim(),toolCount:Number.isFinite(Number(r.tool_count))?Number(r.tool_count):0,requiresAuth:r.requires_auth!==!1,requiresSetup:!!r.requires_setup}).filter(r=>!!r&&!!r.slug&&!!r.transportUrl).sort((r,s)=>r.name.localeCompare(s.name))}}function Tn(a,t){const n=t&&typeof t=="object"?t:{};return{botToken:"",allowedUsers:Array.isArray(n.allowed_users)?n.allowed_users.join(", "):"",mentionOnly:n.mention_only!==!1&&a==="discord"?!0:!!n.mention_only,guildId:String(n.guild_id||"").trim(),channelId:String(n.channel_id||"").trim(),styleProfile:String(n.style_profile||"default").trim()||"default"}}function ed(a){const t=String(a||"").split(",").map(n=>n.trim()).filter(Boolean);return t.length?t:["*"]}function td(a,t){const n=String(a?.catalog_source||"").trim().toLowerCase();return n==="remote"&&t>0?{tone:"ok",text:`${t} models`}:n==="config"&&t>0?{tone:"info",text:"configured models"}:{tone:"warn",text:"manual entry"}}function ad(a,t){const n=String(a?.catalog_message||"").trim();return n||`Default model: ${t||"none"}`}function Rr({client:a,api:t,toast:n,navigate:r,currentRoute:s,identity:l,themes:d,setTheme:u,themeId:p,refreshProviderStatus:k,refreshIdentityStatus:q}){const b=jt(),w=pt(null),[M,E]=y({}),[K,B]=y(String(l?.botName||"Tandem")),[se,G]=y(String(l?.botAvatarUrl||"")),[ge,N]=y("Control Center"),[W,J]=y("providers"),[S,fe]=y(!1),[f,D]=y(!1),[de,$e]=y(!1),[Y,U]=y({}),[ie,oe]=y({}),[Ue,_e]=y(!1),[P,te]=y(""),[ve,Se]=y(""),[V,Ne]=y("none"),[me,Ee]=y(""),[F,De]=y(""),[le,ae]=y(!0),[nt,et]=y(""),[Ge,Xe]=y("manual"),[ct,bt]=y(""),[dt,Te]=y(!1),[ze,rt]=y(!1),[tt,Ve]=y(""),[st,yt]=y(""),[pe,Ce]=y(""),[at,ce]=y("auto"),[Le,ut]=y(""),[v,C]=y(""),[z,m]=y(!0),[X,we]=y(!1),[T,I]=y(!0),[lt,ht]=y(!1),[Tt,Bt]=y(""),[ea,wt]=y(""),Kt=pt(null),ia=async()=>{const o=a?.identity;return o?.get?o.get():t("/api/engine/config/identity",{method:"GET"})},g=async o=>{const x=a?.identity;return x?.patch?x.patch(o):t("/api/engine/config/identity",{method:"PATCH",body:JSON.stringify(o)})},L=Q({queryKey:["settings","identity","config"],queryFn:()=>ia().catch(()=>({identity:{}}))});ye(()=>{const o=L.data?.identity?.bot||{},x=o?.aliases||{},he=String(o?.canonicalName||o?.canonical_name||l?.botName||"Tandem").trim(),Ke=String(o?.avatarUrl||o?.avatar_url||l?.botAvatarUrl||"").trim(),it=String(x?.controlPanel||x?.control_panel||"").trim();B(he||"Tandem"),G(Ke),N(it||"Control Center")},[l?.botAvatarUrl,l?.botName,L.data]),ye(()=>{s==="mcp"&&J("mcp"),s==="channels"&&J("channels"),s==="bug-monitor"&&J("bug_monitor")},[s]);const A=Q({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[],connected:[]}))}),j=Q({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({default:"",providers:{}}))}),O=Q({queryKey:["settings","browser","status"],queryFn:()=>t("/api/engine/browser/status",{method:"GET"}).catch(()=>null),refetchInterval:3e4}),[re,Oe]=y(null),We=Ae({mutationFn:()=>t("/api/engine/browser/install",{method:"POST"}),onSuccess:async()=>{n("ok","Browser sidecar installed on the engine host."),await O.refetch()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),i=Ae({mutationFn:()=>t("/api/engine/browser/smoke-test",{method:"POST",body:JSON.stringify({url:"https://example.com"})}),onSuccess:async o=>{Oe(o),n("ok","Browser smoke test passed."),await O.refetch()},onError:o=>{Oe(null),n("err",o instanceof Error?o.message:String(o))}}),c=Q({queryKey:["settings","mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:1e4}),_=Q({queryKey:["settings","mcp","tools"],queryFn:()=>a.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),$=Q({queryKey:["settings","mcp","catalog"],queryFn:()=>t("/api/engine/mcp/catalog",{method:"GET"}).catch(()=>null),refetchInterval:6e4}),ue=Q({queryKey:["settings","bug-monitor","config"],queryFn:()=>t("/api/engine/config/bug-monitor",{method:"GET"}).catch(()=>({bug_monitor:{}}))}),Qe=Q({queryKey:["settings","bug-monitor","status"],queryFn:()=>t("/api/engine/bug-monitor/status",{method:"GET"}).catch(()=>({status:{}})),refetchInterval:1e4}),gt=Q({queryKey:["settings","bug-monitor","drafts"],queryFn:()=>t("/api/engine/bug-monitor/drafts?limit=10",{method:"GET"}).catch(()=>({drafts:[]})),refetchInterval:15e3}),Mt=Q({queryKey:["settings","bug-monitor","incidents"],queryFn:()=>t("/api/engine/bug-monitor/incidents?limit=10",{method:"GET"}).catch(()=>({incidents:[]})),refetchInterval:1e4}),Et=Q({queryKey:["settings","bug-monitor","posts"],queryFn:()=>t("/api/engine/bug-monitor/posts?limit=10",{method:"GET"}).catch(()=>({posts:[]})),refetchInterval:15e3}),xt=Q({queryKey:["settings","bug-monitor","workspace-browser",Tt],enabled:lt&&!!Tt,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(Tt)}`,{method:"GET"})}),Rt=Q({queryKey:["settings","channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),ke=Q({queryKey:["settings","channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),Z=Ae({mutationFn:async({providerId:o,modelId:x})=>a.providers.setDefaults(o,x),onSuccess:async()=>{n("ok","Updated provider defaults."),await Promise.all([b.invalidateQueries({queryKey:["settings","providers"]}),k()])},onError:o=>n("err",o instanceof Error?o.message:String(o))}),ft=Ae({mutationFn:async()=>t("/api/engine/config/bug-monitor",{method:"PATCH",body:JSON.stringify({bug_monitor:{enabled:dt,paused:ze,workspace_root:String(tt||"").trim()||null,repo:String(st||"").trim()||null,mcp_server:String(pe||"").trim()||null,provider_preference:String(at||"auto").trim(),model_policy:Le&&v?{default_model:{provider_id:Le,model_id:v}}:null,auto_create_new_issues:z,require_approval_for_new_issues:X,auto_comment_on_matched_open_issues:T,label_mode:"reporter_only"}})}),onSuccess:async()=>{n("ok","Bug Monitor settings saved."),await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})])},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),Re=Ae({mutationFn:async()=>t("/api/engine/capabilities/bindings/refresh-builtins",{method:"POST"}),onSuccess:async()=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]}),b.invalidateQueries({queryKey:["settings","mcp"]})]),n("ok","Capability bindings refreshed from built-ins.")},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),Fe=Ae({mutationFn:async({draftId:o,decision:x})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/${x}`,{method:"POST",body:JSON.stringify({reason:`${x}d from control panel settings`})}),onSuccess:async(o,x)=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor draft ${x.decision==="approve"?"approved":"denied"}.`)},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),Nt=Ae({mutationFn:async({draftId:o})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/triage-run`,{method:"POST"}),onSuccess:async o=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",o?.deduped?`Bug Monitor triage run already exists: ${o?.run?.run_id||"unknown"}`:`Bug Monitor triage run created: ${o?.run?.run_id||"unknown"}`)},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),Lt=Ae({mutationFn:async({action:o})=>t(`/api/engine/bug-monitor/${o}`,{method:"POST"}),onSuccess:async(o,x)=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor ${x.action==="pause"?"paused":"resumed"}.`)},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),mt=Ae({mutationFn:async({incidentId:o})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(o)}/replay`,{method:"POST"}),onSuccess:async o=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",o?.deduped?`Bug Monitor triage run already exists: ${o?.run?.run_id||"unknown"}`:`Bug Monitor replay queued triage: ${o?.run?.run_id||"unknown"}`)},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),It=Ae({mutationFn:async({draftId:o})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/publish`,{method:"POST"}),onSuccess:async o=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",o?.action==="comment_issue"?`Bug Monitor commented on issue #${o?.draft?.issue_number||"unknown"}.`:`Bug Monitor published issue #${o?.draft?.issue_number||"unknown"}.`)},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),oa=Ae({mutationFn:async({draftId:o})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/recheck-match`,{method:"POST"}),onSuccess:async o=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`GitHub match result: ${String(o?.action||"rechecked").replaceAll("_"," ")}.`)},onError:o=>{const x=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",x)}}),_a=Ae({mutationFn:({providerId:o,apiKey:x})=>a.providers.setApiKey(o,x),onSuccess:async()=>{n("ok","API key updated."),await k()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),da=Ae({mutationFn:async()=>{const x=(L.data?.identity?.bot||{})?.aliases||{},he=String(K||"").trim();if(!he)throw new Error("Bot name is required.");const Ke=String(se||"").trim(),it=String(ge||"").trim();return g({identity:{bot:{canonical_name:he,avatar_url:Ke||null,aliases:{...x,control_panel:it||void 0}}}})},onSuccess:async()=>{n("ok","Identity updated."),await Promise.all([b.invalidateQueries({queryKey:["settings","identity"]}),q()])},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Sa=Je(async()=>b.invalidateQueries({queryKey:["settings","channels"]}),[b]),Ka=Ae({mutationFn:async o=>{const x=Y[o];if(!x)throw new Error(`No draft found for ${o}.`);const he={allowed_users:ed(x.allowedUsers),mention_only:!!x.mentionOnly},Ke=String(x.botToken||"").trim();if(Ke&&(he.bot_token=Ke),o==="telegram"&&(he.style_profile=String(x.styleProfile||"default").trim()||"default"),o==="discord"&&(he.guild_id=String(x.guildId||"").trim()),o==="slack"){const it=String(x.channelId||"").trim();if(!it&&!Rt.data?.slack?.channel_id)throw new Error("Slack channel ID is required.");it&&(he.channel_id=it)}return a.channels.put(o,he)},onSuccess:async(o,x)=>{n("ok",`Saved ${x} channel settings.`),oe(he=>({...he,[x]:null})),U(he=>({...he,[x]:{...he[x],botToken:""}})),await Sa()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Ca=Ae({mutationFn:async o=>a.channels.delete(o),onSuccess:async(o,x)=>{n("ok",`Removed ${x} channel settings.`),oe(he=>({...he,[x]:null})),U(he=>({...he,[x]:Tn(x,null)})),await Sa()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),h=Ae({mutationFn:async o=>{const x=Y[o],he={bot_token:String(x?.botToken||"").trim()||void 0};return a.channels.verify(o,he)},onSuccess:(o,x)=>{oe(he=>({...he,[x]:o})),n("ok",`${x} verification complete.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),R=Je(async()=>b.invalidateQueries({queryKey:["settings","mcp"]}),[b]),ee=Ae({mutationFn:async({action:o,server:x})=>{if(!x)throw new Error("No MCP server selected.");if(o==="connect")return a.mcp.connect(x.name);if(o==="disconnect")return a.mcp.disconnect(x.name);if(o==="refresh")return a.mcp.refresh(x.name);if(o==="toggle-enabled")return a.mcp.setEnabled(x.name,!x.enabled);if(o==="delete")return t(`/api/engine/mcp/${encodeURIComponent(x.name)}`,{method:"DELETE"});throw new Error(`Unknown action: ${o}`)},onSuccess:async(o,x)=>{await R(),x.action==="connect"&&n("ok",`Connected ${x.server?.name}.`),x.action==="disconnect"&&n("ok",`Disconnected ${x.server?.name}.`),x.action==="refresh"&&n("ok",`Refreshed ${x.server?.name}.`),x.action==="toggle-enabled"&&n("ok",`${x.server?.enabled?"Disabled":"Enabled"} ${x.server?.name}.`),x.action==="delete"&&n("ok",`Deleted ${x.server?.name}.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Me=Ae({mutationFn:async()=>{const o=String(ve||"").trim(),x=Mr(o),he=Dn(P||x);if(!o)throw new Error("Transport URL is required.");if(!Wn(o)&&!o.startsWith("stdio:"))throw new Error("Transport must be a valid URL or stdio:* transport.");const Ke=zc({authMode:V,token:me,customHeader:F,transport:o}),it={name:he,transport:o,enabled:!0};Object.keys(Ke).length&&(it.headers=Ke);const Wt=String(nt||"").trim();if(Wt&&Wt!==he&&await t(`/api/engine/mcp/${encodeURIComponent(Wt)}`,{method:"DELETE"}).catch(()=>null),await a.mcp.add(it),le&&!(await a.mcp.connect(it.name))?.ok)throw new Error(`Added "${it.name}" but connect failed.`);return it.name},onSuccess:async o=>{await R(),_e(!1),te(""),Se(""),Ne("none"),Ee(""),De(""),ae(!0),et(""),n("ok",`Saved MCP "${o}".`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Pe=o=>{if(!o)return;if(o.size>10*1024*1024){n("err","Avatar image is too large (max 10 MB).");return}const x=new FileReader;x.onload=()=>{const he=typeof x.result=="string"?x.result:"";if(!he){n("err","Failed to read avatar image.");return}G(he)},x.onerror=()=>n("err","Failed to read avatar image."),x.readAsDataURL(o)},Be=Array.isArray(A.data?.all)?A.data.all:[],He=H(()=>Yc(c.data),[c.data]),$t=H(()=>Xc(_.data),[_.data]),Ot=H(()=>Zc($.data?.catalog||$.data||null),[$.data]),Ia=H(()=>new Set(He.map(o=>o.name.toLowerCase())),[He]),Qt=H(()=>{const o=String(ct||"").trim().toLowerCase();return Ot.servers.filter(x=>o?x.name.toLowerCase().includes(o)||x.slug.toLowerCase().includes(o)||x.transportUrl.toLowerCase().includes(o):!0).slice(0,36)},[Ot.servers,ct]),ta=He.filter(o=>o.connected).length,be=H(()=>Qe.data?.status||{},[Qe.data]),mn=H(()=>Array.isArray(gt.data?.drafts)?gt.data.drafts||[]:[],[gt.data]),pn=H(()=>Array.isArray(Mt.data?.incidents)?Mt.data.incidents||[]:[],[Mt.data]),Qn=H(()=>Array.isArray(Et.data?.posts)?Et.data.posts||[]:[],[Et.data]),aa=H(()=>He.find(o=>o.name.toLowerCase()===String(pe||"").trim().toLowerCase())||null,[pe,He]),Wa=H(()=>Be.find(o=>String(o?.id||"").toLowerCase()===String(Le||"").trim().toLowerCase())||null,[Le,Be]),hn=H(()=>{const o=Wa&&typeof Wa=="object"?Wa.models||{}:{};return Object.keys(o).sort((x,he)=>x.localeCompare(he))},[Wa]),Ja=Array.isArray(O.data?.blocking_issues)?O.data?.blocking_issues||[]:[],Hn=Array.isArray(O.data?.recommendations)?O.data?.recommendations||[]:[],Gn=Array.isArray(O.data?.install_hints)?O.data?.install_hints||[]:[],Aa=["telegram","discord","slack"],gn=Aa.filter(o=>!!ke.data?.[o]?.connected).length,fn=Array.isArray(xt.data?.directories)?xt.data.directories:[],Qa=String(ea||"").trim().toLowerCase(),zn=H(()=>Qa?fn.filter(o=>String(o?.name||o?.path||"").trim().toLowerCase().includes(Qa)):fn,[fn,Qa]),bn=String(xt.data?.parent||"").trim(),Ha=String(xt.data?.dir||Tt||"").trim();ye(()=>{const o=ue.data?.bug_monitor&&typeof ue.data?.bug_monitor=="object"?ue.data.bug_monitor:{};Te(!!o.enabled),rt(!!o.paused),Ve(String(o.workspace_root||"").trim()),yt(String(o.repo||"").trim()),Ce(String(o.mcp_server||"").trim()),ce(String(o.provider_preference||"auto").trim()||"auto"),ut(String(o.model_policy?.default_model?.provider_id||"").trim()),C(String(o.model_policy?.default_model?.model_id||"").trim()),m(o.auto_create_new_issues!==!1),we(!!o.require_approval_for_new_issues),I(o.auto_comment_on_matched_open_issues!==!1)},[ue.data]),ye(()=>{const o=Rt.data&&typeof Rt.data=="object"?Rt.data:{};U(x=>{const he={...x};for(const Ke of Aa)he[Ke]||(he[Ke]=Tn(Ke,o[Ke]));return he})},[Rt.data]);const Vn=(o,x)=>{const he=String(x||"").trim();he&&Z.mutate({providerId:o,modelId:he})},Ga=o=>{if(o){Xe("manual");const x=o.headers&&typeof o.headers=="object"?o.headers:{},he=Object.keys(x),Ke=he.find(Wt=>String(Wt).toLowerCase()==="authorization"),it=he.find(Wt=>String(Wt).toLowerCase()==="x-api-key");et(o.name),te(o.name),Se(o.transport||""),ae(o.connected||!1),it?(Ne("x-api-key"),De(""),Ee(String(x[it]||"").trim())):Ke?(Ne("bearer"),De(""),Ee(String(x[Ke]||"").replace(/^bearer\s+/i,"").trim())):he.length===1?(Ne("custom"),De(he[0]),Ee(String(x[he[0]]||"").trim())):(Ne("none"),De(""),Ee(""))}else Xe("catalog"),et(""),te(""),Se(""),Ne("none"),De(""),Ee(""),ae(!0);_e(!0)},Yn=async()=>{const o=await t("/api/engine/bug-monitor/debug",{method:"GET"});await navigator.clipboard.writeText(JSON.stringify(o,null,2)),n("ok","Bug Monitor debug payload copied.")},Xn=[{id:"providers",label:"Providers",icon:"cpu"},{id:"identity",label:"Identity",icon:"badge-check"},{id:"theme",label:"Themes",icon:"paint-bucket"},{id:"channels",label:"Channels",icon:"message-circle"},{id:"mcp",label:"MCP",icon:"plug-zap"},{id:"bug_monitor",label:"Bug Monitor",icon:"bug-play"},{id:"browser",label:"Browser",icon:"monitor-cog"}],ps=H(()=>Vc(V,me,F,ve),[V,F,me,ve]);return ye(()=>{const o=w.current;o?zt(o):zt()},[W,dt,ze,tt,pe,be.readiness?.runtime_ready,be.runtime?.monitoring_active,be.runtime?.paused,be.runtime?.pending_incidents,be.pending_drafts,mn.length,pn.length,Re.isPending,Lt.isPending,Fe.isPending,mt.isPending,Nt.isPending,ft.isPending,ee.isPending]),e(La,{className:"grid gap-4",children:e("div",{ref:w,className:"grid gap-4",children:[e("div",{className:"tcp-settings-tabs",children:Xn.map(o=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${W===o.id?"active":""}`,onClick:()=>J(o.id),children:[e("i",{"data-lucide":o.icon}),o.label]},o.id))}),e(Ea,{main:e(So,{className:"grid gap-4",children:[W==="providers"?e(Ze,{title:"Provider defaults",subtitle:"Provider catalog, model selection, and API key entry.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(Ie,{tone:String(j.data?.default||"").trim()?"ok":"warn",children:["Default: ",String(j.data?.default||"none")]}),e(Ie,{tone:"info",children:[String(A.data?.connected?.length||0)," connected"]}),e("button",{className:"tcp-btn",onClick:()=>k().then(()=>n("ok","Provider status refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh provider"]})]}),children:e("div",{className:"grid gap-3",children:[e("button",{type:"button",className:"tcp-list-item text-left",onClick:()=>$e(o=>!o),"aria-expanded":de,children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":de?"chevron-down":"chevron-right"}),e("span",{children:de?"Hide provider catalog":"Show provider catalog"})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Be.length," providers available for configuration. Expand to change models and API keys."]})]}),e(Ie,{tone:"info",children:[String(A.data?.connected?.length||0)," connected"]})]})}),e(ot,{initial:!1,children:de?e(xe.div,{className:"grid gap-3",initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:Be.length?Be.map(o=>{const x=String(o?.id||""),he=Object.keys(o?.models||{}),Ke=String(j.data?.providers?.[x]?.default_model||he[0]||""),it=String(M[x]??Ke).trim(),Wt=it.toLowerCase(),St=he.filter(Dt=>Wt?Dt.toLowerCase().includes(Wt):!0).slice(0,80),At=td(o,he.length),hs=ad(o,Ke),Zn=Jr[x]||null,er=String(Zn?.keyUrl||"").trim();return e(xe.details,{layout:!0,className:"tcp-list-item",children:[e("summary",{className:"cursor-pointer list-none",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium",children:x}),e("div",{className:"tcp-subtle text-xs",children:hs})]}),e(Ie,{tone:At.tone,children:At.text})]})}),e("div",{className:"mt-3 grid gap-3",children:[er?e("div",{className:"flex justify-end",children:e("a",{className:"tcp-btn h-8 px-3 text-xs",href:er,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Get API key"]})}):null,e("form",{className:"grid gap-2",onSubmit:Dt=>{Dt.preventDefault(),Vn(x,it)},children:[e("div",{className:"flex gap-2",children:[e("input",{className:"tcp-input",value:it,placeholder:`Type model id for ${x}`,onInput:Dt=>E(ba=>({...ba,[x]:Dt.target.value}))}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"badge-check"}),"Apply"]})]}),e("div",{className:"max-h-48 overflow-auto rounded-xl border border-slate-700/60 bg-slate-900/20 p-1",children:St.length?St.map(Dt=>e("button",{type:"button",className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${Dt===Ke?"bg-slate-700/40":""}`,onClick:()=>{E(ba=>({...ba,[x]:Dt})),Vn(x,Dt)},children:Dt},Dt)):e("div",{className:"tcp-subtle px-2 py-1 text-xs",children:he.length?"No matching models.":"No live catalog available. Type a model ID manually."})})]}),e("form",{onSubmit:Dt=>{Dt.preventDefault();const ba=Dt.currentTarget.elements.namedItem("apiKey"),tr=String(ba?.value||"").trim();tr&&(_a.mutate({providerId:x,apiKey:tr}),ba.value="")},className:"flex gap-2",children:[e("input",{name:"apiKey",className:"tcp-input",placeholder:String(Zn?.placeholder||`Set ${x} API key`)}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"save"}),"Save"]})]})]})]},x)}):e(qe,{text:"No providers were detected from the engine catalog."})}):null})]})}):null,W==="identity"?e(Ze,{title:"Identity preview",subtitle:"Live preview of how the assistant appears across the panel.",actions:e(Gt,{children:[e("button",{className:"tcp-btn",onClick:()=>q().then(()=>n("ok","Identity refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh identity"]}),e("button",{className:"tcp-btn-primary",onClick:()=>da.mutate(),disabled:da.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"inline-flex items-center gap-3",children:[e("span",{className:"tcp-brand-avatar inline-grid h-12 w-12 rounded-xl",children:se?e("img",{src:se,alt:K||"Bot",className:"block h-full w-full object-cover"}):e("i",{"data-lucide":"cpu"})}),e("div",{children:[e("div",{className:"font-semibold",children:K||"Tandem"}),e("div",{className:"tcp-subtle text-xs",children:ge||"Control Center"})]})]}),e(Gt,{children:[e("button",{className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>Kt.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>G(""),children:e("i",{"data-lucide":"trash-2"})})]})]})}),e("input",{className:"tcp-input",value:K,onInput:o=>B(o.target.value),placeholder:"Bot name"}),e("input",{className:"tcp-input",value:ge,onInput:o=>N(o.target.value),placeholder:"Control panel alias"}),e("input",{className:"tcp-input",value:se,onInput:o=>G(o.target.value),placeholder:"Avatar URL or data URL"}),e("input",{ref:Kt,type:"file",accept:"image/*",className:"hidden",onChange:o=>Pe(o.target.files?.[0]||null)})]})}):null,W==="theme"?e(Ze,{title:"Theme studio",subtitle:"Preview tiles with richer feedback and immediate switching.",children:e(Gc,{themes:d,themeId:p,onChange:u})}):null,W==="channels"?e(Ze,{title:"Channel connections",subtitle:"Telegram, Discord, and Slack delivery setup and live listener status.",actions:e(Gt,{children:[e(Ie,{tone:gn?"ok":"warn",children:[gn,"/",Aa.length," connected"]}),e("button",{className:"tcp-btn",onClick:()=>{Sa()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh channels"]})]}),children:e("div",{className:"grid gap-3",children:Aa.map(o=>{const x=Rt.data?.[o]||{},he=ke.data?.[o]||{},Ke=Y[o]||Tn(o,x),it=ie[o],Wt=!!x?.has_token||!!(Array.isArray(x?.allowed_users)&&x.allowed_users.length)||!!String(x?.guild_id||"").trim()||!!String(x?.channel_id||"").trim();return e("div",{className:"tcp-list-item grid gap-3",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-semibold capitalize",children:o}),e("div",{className:"tcp-subtle text-xs",children:o==="telegram"?"Bot token, allowed users, and style profile.":o==="discord"?"Bot token, allowed users, mention policy, and guild targeting.":"Bot token, allowed users, mention policy, and default channel."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(Ie,{tone:he.connected?"ok":"warn",children:he.connected?"Connected":he.enabled?"Configured":"Disconnected"}),e(Ie,{tone:x.has_token?"info":"warn",children:x.has_token?"Token saved":"No token"})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",type:"password",placeholder:x.has_token?String(x.token_masked||"********"):`Paste ${o} bot token`,value:Ke.botToken,onInput:St=>U(At=>({...At,[o]:{...Ke,botToken:St.target.value}}))}),x.has_token&&!Ke.botToken?e("div",{className:"tcp-subtle text-xs",children:"Token is already stored. Enter a new token only if you want to replace it."}):null,e("input",{className:"tcp-input",placeholder:"Allowed users (comma separated)",value:Ke.allowedUsers,onInput:St=>U(At=>({...At,[o]:{...Ke,allowedUsers:St.target.value}}))})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[o==="telegram"?e("input",{className:"tcp-input",placeholder:"Style profile",value:Ke.styleProfile,onInput:St=>U(At=>({...At,[o]:{...Ke,styleProfile:St.target.value}}))}):null,o==="discord"?e("input",{className:"tcp-input",placeholder:"Guild ID (optional)",value:Ke.guildId,onInput:St=>U(At=>({...At,[o]:{...Ke,guildId:St.target.value}}))}):null,o==="slack"?e("input",{className:"tcp-input",placeholder:"Default channel ID",value:Ke.channelId,onInput:St=>U(At=>({...At,[o]:{...Ke,channelId:St.target.value}}))}):null,e("label",{className:"inline-flex items-center gap-2 rounded-xl border border-slate-700/60 bg-slate-900/20 px-3 py-2 text-sm",children:[e("input",{type:"checkbox",checked:Ke.mentionOnly,onChange:St=>U(At=>({...At,[o]:{...Ke,mentionOnly:St.target.checked}}))}),"Mention only"]})]}),e("div",{className:"tcp-subtle text-xs",children:["Active sessions: ",Number(he.active_sessions||0),he.last_error?` · Last error: ${he.last_error}`:""]}),it?.hints?.length?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3 text-xs",children:[e("div",{className:"mb-1 font-medium",children:"Verification hints"}),e("div",{className:"grid gap-1",children:it.hints.map((St,At)=>e("div",{className:"tcp-subtle",children:St},`${o}-hint-${At}`))})]}):null,e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:Ka.isPending,onClick:()=>Ka.mutate(o),children:[e("i",{"data-lucide":"save"}),"Save"]}),o==="discord"?e("button",{className:"tcp-btn",disabled:h.isPending,onClick:()=>h.mutate("discord"),children:[e("i",{"data-lucide":"shield-check"}),"Verify"]}):null,e("button",{className:"tcp-btn-danger",disabled:Ca.isPending||!Wt,onClick:()=>Ca.mutate(o),children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},o)})})}):null,W==="mcp"?e(Ze,{title:"MCP connections",subtitle:"Configured MCP servers, connection state, and discovered tool coverage.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(Ie,{tone:ta?"ok":"warn",children:[ta,"/",He.length," connected"]}),e(Ie,{tone:"info",children:[$t.length," tools"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Ga(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]}),e("button",{className:"tcp-btn",onClick:()=>{R()},children:[e("i",{"data-lucide":"refresh-cw"}),"Reload"]})]}),children:e("div",{className:"grid gap-3",children:[He.length?He.map(o=>{const x=Object.keys(o.headers||{}).filter(Boolean),he=Array.isArray(o.toolCache)?o.toolCache.length:0;return e("div",{className:"tcp-list-item grid gap-2",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:o.name}),e("div",{className:"tcp-subtle text-sm",children:o.transport||"No transport set"})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(Ie,{tone:o.connected?"ok":"warn",children:o.connected?"Connected":"Disconnected"}),e(Ie,{tone:o.enabled?"info":"warn",children:o.enabled?"Enabled":"Disabled"}),e(Ie,{tone:"info",children:[he," tools"]})]})]}),o.lastError?e("div",{className:"rounded-xl border border-rose-700/60 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:o.lastError}):null,e("div",{className:"tcp-subtle text-xs",children:x.length?`Auth headers: ${x.join(", ")}`:"No stored auth headers."}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Ga(o),children:"Edit"}),e("button",{className:"tcp-btn",disabled:ee.isPending,onClick:()=>ee.mutate({action:o.connected?"disconnect":"connect",server:o}),children:o.connected?"Disconnect":"Connect"}),e("button",{className:"tcp-btn",disabled:ee.isPending,onClick:()=>ee.mutate({action:"refresh",server:o}),children:"Refresh"}),e("button",{className:"tcp-btn",disabled:ee.isPending,onClick:()=>ee.mutate({action:"toggle-enabled",server:o}),children:o.enabled?"Disable":"Enable"}),e("button",{className:"tcp-btn-danger",disabled:ee.isPending,onClick:()=>ee.mutate({action:"delete",server:o}),children:"Delete"})]})]},o.name)}):e("div",{className:"grid gap-3",children:[e(qe,{text:"No MCP servers configured."}),e("div",{className:"flex justify-start",children:e("button",{className:"tcp-btn-primary",onClick:()=>Ga(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]})})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Discovered tools"}),e("pre",{className:"tcp-code max-h-56 overflow-auto whitespace-pre-wrap break-words",children:$t.length?$t.slice(0,250).join(`
557
+ `):"No MCP tools discovered yet. Connect a server first."})]})]})}):null,W==="bug_monitor"?e(Ze,{title:"Bug monitor",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(Ie,{tone:be.runtime?.monitoring_active?be.readiness?.publish_ready?"ok":"info":be.readiness?.ingest_ready?"info":"warn",children:be.runtime?.monitoring_active?be.readiness?.publish_ready?"Monitoring":"Watching locally":be.readiness?.ingest_ready?"Ready":"Not ready"}),ze||be.runtime?.paused?e(Ie,{tone:"warn",children:"Paused"}):null,e(Ie,{tone:"info",children:[Number(be.runtime?.pending_incidents||0)," incidents"]}),e(Ie,{tone:"info",children:[Number(be.pending_drafts||0)," pending drafts"]}),e(Ie,{tone:"info",children:[Number(be.pending_posts||0)," post attempts"]}),e("button",{className:"tcp-icon-btn",title:"Reload status","aria-label":"Reload status",onClick:()=>Promise.all([Qe.refetch(),gt.refetch(),Mt.refetch(),Et.refetch()]).then(()=>n("ok","Bug Monitor status refreshed.")),children:e("i",{"data-lucide":"refresh-cw"})}),e("button",{className:"tcp-icon-btn",title:ze||be.runtime?.paused?"Resume monitoring":"Pause monitoring","aria-label":ze||be.runtime?.paused?"Resume monitoring":"Pause monitoring",disabled:Lt.isPending,onClick:()=>Lt.mutate({action:ze||be.runtime?.paused?"resume":"pause"}),children:e("i",{"data-lucide":ze||be.runtime?.paused?"play":"pause"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:Re.isPending,onClick:()=>Re.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Yn()},children:e("i",{"data-lucide":"copy"})}),e("button",{className:"tcp-icon-btn",title:"Open GitHub MCP guide","aria-label":"Open GitHub MCP guide",onClick:()=>D(!0),children:e("i",{"data-lucide":"book-open"})})]}),children:e("div",{className:"grid gap-4",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Reporter state"}),e("button",{type:"button",className:`tcp-list-item text-left ${dt?"ring-1 ring-emerald-400/40":""}`,onClick:()=>Te(o=>!o),children:[e("div",{className:"font-medium",children:dt?ze?"Paused":"Enabled":"Disabled"}),e("div",{className:"tcp-subtle text-xs",children:dt?ze?"Monitoring is paused. Resume to process new failures.":"Failure events can be analyzed once readiness is green.":"No reporter work will execute."})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Local directory"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn",type:"button",onClick:()=>{const o=String(tt||"/").trim();Bt(o||"/"),wt(""),ht(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,value:tt,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>Ve(""),disabled:!tt,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),e("div",{className:"tcp-subtle text-xs",children:tt?`Reporter analysis root: ${tt}`:"Defaults to the engine workspace root if not set."})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Target repo"}),e("input",{className:"tcp-input",value:st,onChange:o=>yt(o.target.value),placeholder:"owner/repo"})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"MCP server"}),e("select",{className:"tcp-input",value:pe,onChange:o=>Ce(o.target.value),children:[e("option",{value:"",children:"Select an MCP server"}),He.map(o=>e("option",{value:o.name,children:o.name},o.name))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider preference"}),e("select",{className:"tcp-input",value:at,onChange:o=>ce(o.target.value),children:[e("option",{value:"auto",children:"Auto"}),e("option",{value:"official_github",children:"Official GitHub"}),e("option",{value:"composio",children:"Composio"}),e("option",{value:"arcade",children:"Arcade"})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider"}),e("select",{className:"tcp-input",value:Le,onChange:o=>{const x=o.target.value;ut(x),C("")},children:[e("option",{value:"",children:"Select a provider"}),Be.map(o=>e("option",{value:String(o?.id||""),children:String(o?.id||"")},String(o?.id||"")))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Model"}),e("input",{className:"tcp-input",value:v,onChange:o=>C(o.target.value),list:"bug-monitor-models",disabled:!Le,placeholder:Le?"Type or paste a model id":"Choose a provider first",spellCheck:!1}),e("datalist",{id:"bug-monitor-models",children:hn.map(o=>e("option",{value:o},o))}),e("div",{className:"tcp-subtle text-xs",children:Le?hn.length?`${hn.length} suggested models from provider catalog`:"No provider catalog models available. Manual model ids are allowed.":"Select a provider to load model suggestions."})]}),e("div",{className:"grid gap-2 md:col-span-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"GitHub posting"}),e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("button",{type:"button",className:`tcp-list-item text-left ${z&&!X?"ring-1 ring-emerald-400/40":""}`,onClick:()=>{m(o=>!o),X&&z&&we(!1)},children:[e("div",{className:"font-medium",children:"Auto-create new issues"}),e("div",{className:"tcp-subtle text-xs",children:z?"New drafts post to GitHub automatically.":"New drafts stay internal until published manually."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${X?"ring-1 ring-amber-400/40":""}`,onClick:()=>{we(o=>{const x=!o;return x&&m(!1),x})},children:[e("div",{className:"font-medium",children:"Require approval"}),e("div",{className:"tcp-subtle text-xs",children:X?"New drafts wait for a manual publish click.":"Approval gate disabled."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${T?"ring-1 ring-sky-400/40":""}`,onClick:()=>I(o=>!o),children:[e("div",{className:"font-medium",children:"Auto-comment matches"}),e("div",{className:"tcp-subtle text-xs",children:T?"Open matching GitHub issues receive new evidence comments.":"Matching issues are detected but not updated automatically."})]})]})]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:ft.isPending,title:"Save Bug Monitor settings","aria-label":"Save Bug Monitor settings",onClick:()=>ft.mutate(),children:[e("i",{"data-lucide":"save"}),ft.isPending?"Saving...":null]}),e("button",{className:"tcp-icon-btn",title:"Add MCP server","aria-label":"Add MCP server",onClick:()=>Ga(),children:e("i",{"data-lucide":"plus"})}),e("button",{className:"tcp-icon-btn",title:"Open setup guide","aria-label":"Open setup guide",onClick:()=>D(!0),children:e("i",{"data-lucide":"external-link"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:Re.isPending,onClick:()=>Re.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Yn()},children:e("i",{"data-lucide":"copy"})}),aa?e("button",{className:"tcp-icon-btn",title:aa.connected?"Refresh selected MCP":"Connect selected MCP","aria-label":aa.connected?"Refresh selected MCP":"Connect selected MCP",disabled:ee.isPending,onClick:()=>ee.mutate({action:aa.connected?"refresh":"connect",server:aa}),children:e("i",{"data-lucide":aa.connected?"refresh-cw":"plug-zap"})}):null]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Readiness"}),e("div",{className:"mt-1 text-sm",children:be.runtime?.monitoring_active?be.readiness?.publish_ready?"Monitoring":"Watching locally":be.runtime?.paused||ze?"Paused":be.readiness?.ingest_ready?"Ready":"Blocked"}),e("div",{className:"tcp-subtle text-xs",children:be.runtime?.last_runtime_error||be.last_error||"No blocking issue reported."}),!be.readiness?.publish_ready&&Array.isArray(be.missing_required_capabilities)&&be.missing_required_capabilities.length?e("div",{className:"tcp-subtle mt-2 text-xs",children:["Missing: ",be.missing_required_capabilities.join(", ")]}):null]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Selected MCP"}),e("div",{className:"mt-1 text-sm",children:aa?.name||"None selected"}),e("div",{className:"tcp-subtle text-xs",children:aa?aa.connected?"Connected":"Disconnected":"No server selected"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Bindings: ",be.binding_source_version||"unknown version",be.bindings_last_merged_at_ms?` · merged ${new Date(be.bindings_last_merged_at_ms).toLocaleString()}`:""]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Local directory:"," ",tt||String(be.config?.workspace_root||"").trim()||"engine workspace root"]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last event:"," ",String(be.runtime?.last_incident_event_type||"").trim()||"No incidents processed yet"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Model route"}),e("div",{className:"mt-1 break-all text-sm",children:be.selected_model?.provider_id&&be.selected_model?.model_id?`${be.selected_model.provider_id} / ${be.selected_model.model_id}`:"No dedicated model selected"}),e("div",{className:"tcp-subtle text-xs",children:be.readiness?.selected_model_ready?"Available":"Fail-closed when unavailable"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last processed:"," ",be.runtime?.last_processed_at_ms?new Date(Number(be.runtime.last_processed_at_ms)).toLocaleString():"Not processed yet"]})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Capability readiness"}),e("div",{className:"tcp-subtle mt-2 grid gap-1 text-xs",children:[e("div",{children:["github.list_issues:"," ",be.required_capabilities?.github_list_issues?"ready":"missing"]}),e("div",{children:["github.get_issue:"," ",be.required_capabilities?.github_get_issue?"ready":"missing"]}),e("div",{children:["github.create_issue:"," ",be.required_capabilities?.github_create_issue?"ready":"missing"]}),e("div",{children:["github.comment_on_issue:"," ",be.required_capabilities?.github_comment_on_issue?"ready":"missing"]})]}),Array.isArray(be.resolved_capabilities)&&be.resolved_capabilities.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:be.resolved_capabilities.map((o,x)=>e("div",{children:[String(o.capability_id||"unknown"),":"," ",String(o.tool_name||"unresolved")]},`${o.capability_id||"cap"}-${x}`))}):null,Array.isArray(be.selected_server_binding_candidates)&&be.selected_server_binding_candidates.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:be.selected_server_binding_candidates.map((o,x)=>e("div",{children:[String(o.capability_id||"unknown"),":"," ",String(o.binding_tool_name||"unknown"),o.matched?" · matched":" · candidate"]},`${o.capability_id||"candidate"}-${x}`))}):null,Array.isArray(be.discovered_mcp_tools)&&be.discovered_mcp_tools.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle text-xs font-medium",children:"Discovered MCP tools"}),e("pre",{className:"tcp-code mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs",children:be.discovered_mcp_tools.join(`
558
+ `)})]}):e("div",{className:"tcp-subtle mt-3 text-xs",children:"No MCP tools were discovered for the selected server."})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Posting policy"}),e("div",{className:"tcp-subtle mt-2 grid gap-1 text-xs",children:[e("div",{children:["New issues:"," ",X?"Manual publish":z?"Auto-create":"Internal draft only"]}),e("div",{children:["Matched open issues:"," ",T?"Auto-comment":"Detect only"]}),e("div",{children:"Dedupe: Fingerprint marker + label"}),e("div",{children:"Labels: bug-monitor"}),e("div",{children:"Workspace write tools: Disabled"}),e("div",{children:"Model fallback: Fail closed"})]})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent incidents"}),pn.length?e("div",{className:"grid gap-2",children:pn.map(o=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:o.title||o.event_type}),e(Ie,{tone:o.last_error?"warn":"info",children:o.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[o.event_type," · seen"," ",Number(o.occurrence_count||0),"x"," · ",o.updated_at_ms?new Date(o.updated_at_ms).toLocaleString():"time unavailable"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:o.workspace_root||"engine workspace root"}),o.last_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.last_error}):null,o.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.detail}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-icon-btn",title:"Replay triage for this incident","aria-label":"Replay triage for this incident",disabled:mt.isPending,onClick:()=>mt.mutate({incidentId:o.incident_id}),children:e("i",{"data-lucide":"rotate-cw"})}),o.triage_run_id?e("span",{className:"tcp-subtle text-xs",children:["triage run: ",o.triage_run_id]}):null,o.draft_id?e("span",{className:"tcp-subtle text-xs",children:["draft: ",o.draft_id]}):null]})]},o.incident_id))}):e(qe,{text:"No Bug Monitor incidents yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent reporter drafts"}),mn.length?e("div",{className:"grid gap-2",children:mn.map(o=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:o.title||o.fingerprint}),e(Ie,{tone:o.status==="approval_required"?"warn":"info",children:o.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[o.repo," ·"," ",o.issue_number?`issue #${o.issue_number}`:"draft only"," ","·"," ",o.created_at_ms?new Date(o.created_at_ms).toLocaleString():"time unavailable"]}),o.github_status?e("div",{className:"tcp-subtle mt-1 text-xs",children:["GitHub: ",o.github_status,o.matched_issue_number?` · matched #${o.matched_issue_number}${o.matched_issue_state?` (${o.matched_issue_state})`:""}`:""]}):null,o.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.detail}):null,o.last_post_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.last_post_error}):null,o.triage_run_id?e("div",{className:"tcp-subtle mt-2 text-xs",children:["triage run: ",o.triage_run_id]}):null,o.status==="approval_required"?e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:Fe.isPending,title:"Approve draft","aria-label":"Approve draft",onClick:()=>Fe.mutate({draftId:o.draft_id,decision:"approve"}),children:[e("i",{"data-lucide":"check"}),Fe.isPending?"Updating...":null]}),e("button",{className:"tcp-icon-btn",title:"Deny draft","aria-label":"Deny draft",disabled:Fe.isPending,onClick:()=>Fe.mutate({draftId:o.draft_id,decision:"deny"}),children:e("i",{"data-lucide":"x"})})]}):null,o.issue_number?null:e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-icon-btn",title:"Publish this draft to GitHub now","aria-label":"Publish this draft to GitHub now",disabled:It.isPending,onClick:()=>It.mutate({draftId:o.draft_id}),children:e("i",{"data-lucide":"bug-play"})}),e("button",{className:"tcp-icon-btn",title:"Recheck GitHub for an existing matching issue","aria-label":"Recheck GitHub for an existing matching issue",disabled:oa.isPending,onClick:()=>oa.mutate({draftId:o.draft_id}),children:e("i",{"data-lucide":"refresh-cw"})})]}),(o.github_issue_url||o.github_comment_url)&&e("div",{className:"mt-3 flex flex-wrap gap-2 text-xs",children:[o.github_issue_url?e("a",{className:"tcp-btn",href:o.github_issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,o.github_comment_url?e("a",{className:"tcp-btn",href:o.github_comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]}),(o.status==="draft_ready"||o.status==="triage_queued")&&!o.triage_run_id?e("div",{className:"mt-3 flex flex-wrap gap-2",children:e("button",{className:"tcp-icon-btn",title:"Create triage run","aria-label":"Create triage run",disabled:Nt.isPending,onClick:()=>Nt.mutate({draftId:o.draft_id}),children:e("i",{"data-lucide":"sparkles"})})}):null]},o.draft_id))}):e(qe,{text:"No Bug Monitor drafts yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent GitHub posts"}),Qn.length?e("div",{className:"grid gap-2",children:Qn.map(o=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:o.operation}),e(Ie,{tone:o.status==="posted"?"ok":"warn",children:o.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[o.repo,o.issue_number?` · issue #${o.issue_number}`:"",o.updated_at_ms?` · ${new Date(o.updated_at_ms).toLocaleString()}`:""]}),o.error?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.error}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[o.issue_url?e("a",{className:"tcp-btn",href:o.issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,o.comment_url?e("a",{className:"tcp-btn",href:o.comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]})]},o.post_id))}):e(qe,{text:"No GitHub post attempts yet."})]})]})}):null,W==="browser"?e(Ze,{title:"Browser readiness",subtitle:"Operational browser status, diagnostics, and recovery actions.",actions:e(Gt,{children:[e("button",{className:"tcp-btn",onClick:()=>{O.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>We.mutate(),disabled:We.isPending,children:[e("i",{"data-lucide":"download"}),We.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>i.mutate(),disabled:i.isPending,children:[e("i",{"data-lucide":"globe"}),i.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>fe(!0),children:[e("i",{"data-lucide":"activity"}),"Diagnostics"]})]}),children:[e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Status"}),e("div",{className:"mt-1 text-sm",children:O.data?O.data.runnable?"Ready":O.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",O.data?.headless_default?"yes":"no"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Sidecar"}),e("div",{className:"mt-1 break-all text-sm",children:O.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:O.data?.sidecar?.version||"No version detected"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Browser"}),e("div",{className:"mt-1 break-all text-sm",children:O.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:O.data?.browser?.version||O.data?.browser?.channel||"No version detected"})]})]}),Ja.length?e("div",{className:"mt-3 grid gap-2",children:Ja.map((o,x)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:o.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:o.message||"Unknown browser issue."})]},`${o.code||"issue"}-${x}`))}):null,re?e("div",{className:"mt-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:[e("div",{className:"font-medium",children:["Smoke test passed",re.title?`: ${re.title}`:""]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:re.final_url||re.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",re.load_state||"unknown"," · elements:"," ",String(re.element_count??0)," · closed:"," ",re.closed?"yes":"no"]}),re.excerpt?e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words",children:re.excerpt}):null]}):null]}):null]}),aside:e("div",{className:"grid gap-4",children:[e(Ze,{title:"Readiness snapshot",subtitle:"High-signal operational summary for this configuration state.",children:e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Connected providers"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[String(A.data?.connected?.length||0)," connected, default"," ",String(j.data?.default||"none")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Browser automation"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:O.data?O.data.runnable?"Ready":O.data.enabled?"Enabled but blocked":"Disabled":"Unknown"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Theme"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:d.find(o=>o.id===p)?.name||p})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"MCP"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[ta," connected, ",$t.length," discovered tools"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Bug monitor"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[be.readiness?.runtime_ready?"Ready":dt?"Enabled but blocked":"Disabled"," · ",Number(be.pending_drafts||0)," pending drafts"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Channels"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[gn," connected, ",Aa.length," available"]})]})]})}),e(Ze,{title:"Quick access",subtitle:"Jump straight to the section you need.",children:e("div",{className:"grid gap-2",children:Xn.map(o=>e("button",{className:"tcp-list-item flex items-center justify-between text-left",onClick:()=>J(o.id),children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":o.icon}),o.label]}),W===o.id?e(Ie,{tone:"ok",children:"open"}):null]},o.id))})})]})}),e(on,{open:f,onClose:()=>D(!1),title:"Official GitHub MCP guide",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Recommended for Bug Monitor: use the official GitHub MCP endpoint instead of a third-party wrapper when you want stable issue read/write operations."}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Transport URL"}),e("div",{className:"mt-1 break-all text-sm",children:"https://api.githubcopilot.com/mcp/"}),e("div",{className:"tcp-subtle text-xs",children:"Use this as the MCP server transport in Tandem Settings."})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Auth mode"}),e("div",{className:"mt-1 text-sm",children:"Authorization Bearer"}),e("div",{className:"tcp-subtle text-xs",children:"Paste a GitHub token in the MCP server dialog and use bearer auth."})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommended setup"}),e("div",{className:"tcp-list-item text-sm",children:["1. Open `Add MCP server`.",e("br",{}),"2. Name it `github` or another stable name.",e("br",{}),"3. Set transport to `https://api.githubcopilot.com/mcp/`.",e("br",{}),"4. Set auth mode to `Authorization Bearer`.",e("br",{}),"5. Paste a GitHub Personal Access Token.",e("br",{}),"6. Save, connect, then select that MCP server in Bug Monitor settings."]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Token guidance"}),e("div",{className:"tcp-list-item text-sm",children:"For failure reporting, the token needs issue read/write access on the target repository so the runtime can create issues and add comments."})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Direct links"}),e("div",{className:"flex flex-wrap gap-2",children:[e("a",{className:"tcp-btn",href:"https://github.com/github/github-mcp-server?tab=readme-ov-file",target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"GitHub MCP README"]}),e("a",{className:"tcp-btn",href:"https://docs.github.com/en/copilot/how-tos/provide-context/use-mcp/use-the-github-mcp-server",target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"GitHub Docs"]})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Issue tools to expect"}),e("div",{className:"tcp-list-item text-sm",children:"The reporter should be able to resolve issue-list, issue-read, issue-create, and issue-comment operations from the selected GitHub MCP server. If readiness still fails, compare the discovered MCP tools shown in Settings against those issue operations."})]})]})}),e(ot,{children:lt?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close Bug Monitor workspace dialog",onClick:()=>{ht(!1),wt("")}}),e(xe.div,{className:"tcp-confirm-dialog max-w-2xl",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Select Bug Monitor Directory"}),e("p",{className:"tcp-confirm-message",children:["Current: ",Ha||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{bn&&Bt(bn)},disabled:!bn,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{Ha&&(Ve(Ha),ht(!1),wt(""),n("ok",`Bug Monitor directory selected: ${Ha}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{ht(!1),wt("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ea,onInput:o=>wt(o.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:zn.length?zn.map(o=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Bt(String(o?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(o?.name||o?.path||"")]},String(o?.path||o?.name))):e(qe,{text:Qa?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e(on,{open:S,onClose:()=>fe(!1),title:"Browser diagnostics",children:e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Status"}),e("div",{className:"mt-1 text-sm",children:O.data?O.data.runnable?"Ready":O.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",O.data?.headless_default?"yes":"no"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Sidecar"}),e("div",{className:"mt-1 break-all text-sm",children:O.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:O.data?.sidecar?.version||"No version detected"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Browser"}),e("div",{className:"mt-1 break-all text-sm",children:O.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:O.data?.browser?.version||O.data?.browser?.channel||"No version detected"})]})]}),e(Gt,{children:[e("button",{className:"tcp-btn",onClick:()=>{O.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>We.mutate(),disabled:We.isPending,children:[e("i",{"data-lucide":"download"}),We.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>i.mutate(),disabled:i.isPending,children:[e("i",{"data-lucide":"globe"}),i.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>t("/api/engine/browser/status",{method:"GET"}).then(()=>n("ok","Browser diagnostics refreshed.")).catch(o=>n("err",o instanceof Error?o.message:String(o))),children:[e("i",{"data-lucide":"activity"}),"Re-run diagnostics"]})]}),O.isLoading?e(qe,{text:"Loading browser diagnostics..."}):O.data?e(qt,{children:[Ja.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Blocking issues"}),Ja.map((o,x)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:o.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:o.message||"Unknown browser issue."})]},`${o.code||"issue"}-${x}`))]}):e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Browser automation is ready on this machine."}),re?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Latest smoke test"}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:re.title||"Smoke test"}),e("div",{className:"tcp-subtle text-xs",children:re.final_url||re.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",re.load_state||"unknown"," · elements:"," ",String(re.element_count??0)," · closed:"," ",re.closed?"yes":"no"]}),re.excerpt?e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:re.excerpt}):null]})]}):null,Hn.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommendations"}),Hn.map((o,x)=>e("div",{className:"tcp-list-item text-sm",children:o},`browser-recommendation-${x}`))]}):null,Gn.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Install hints"}),Gn.map((o,x)=>e("div",{className:"tcp-list-item text-sm",children:o},`browser-install-hint-${x}`))]}):null,O.data?.last_error?e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-3 text-xs",children:["Last error: ",O.data.last_error]}):null]}):e(qe,{text:"Browser diagnostics are unavailable."})]})}),e(ot,{children:Ue?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close MCP server dialog",onClick:()=>_e(!1)}),e(xe.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:nt?"Edit MCP Server":"Add MCP Server"}),e("p",{className:"tcp-confirm-message",children:"Configure transport and auth without leaving Settings."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>_e(!1),children:e("i",{"data-lucide":"x"})})]}),e("form",{className:"grid gap-3",onSubmit:o=>{o.preventDefault(),Me.mutate()},children:[e("div",{className:"tcp-settings-tabs",children:[e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${Ge==="catalog"?"active":""}`,onClick:()=>Xe("catalog"),children:[e("i",{"data-lucide":"blocks"}),"Built-in packs"]}),e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${Ge==="manual"?"active":""}`,onClick:()=>Xe("manual"),children:[e("i",{"data-lucide":"square-pen"}),"Manual"]})]}),Ge==="catalog"?e("div",{className:"grid gap-3",children:[e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"tcp-subtle text-sm",children:Ot.generatedAt?`Built-in MCP packs · generated ${Ot.generatedAt}`:"Built-in MCP packs"}),e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{$.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("input",{className:"tcp-input",value:ct,onInput:o=>bt(o.target.value),placeholder:"Search built-in MCP packs"}),e("div",{className:"grid max-h-[26rem] gap-2 overflow-auto pr-1 md:grid-cols-2",children:Qt.length?Qt.map(o=>{const x=Ia.has(String(o.serverConfigName||o.slug||"").toLowerCase());return e("div",{className:"tcp-list-item grid gap-2",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:o.name}),e("div",{className:"tcp-subtle text-xs",children:[o.slug,o.requiresSetup?" · setup required":""]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(Ie,{tone:"info",children:[o.toolCount," tools"]}),e(Ie,{tone:o.requiresAuth?"warn":"ok",children:o.requiresAuth?"Auth":"Authless"})]})]}),e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:o.description||o.transportUrl}),e("div",{className:"tcp-subtle break-all text-xs",children:o.transportUrl}),e("div",{className:"mt-auto flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{te(Dn(o.serverConfigName||o.slug||o.name)),Se(o.transportUrl),Xe("manual"),n("ok",`Loaded ${o.name}. Review and save when ready.`)},children:"Use pack"}),o.documentationUrl?e("a",{className:"tcp-btn h-8 px-3 text-xs",href:o.documentationUrl,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Docs"]}):null,x?e(Ie,{tone:"ok",children:"added"}):null]})]},o.slug)}):e(qe,{text:"No built-in MCP packs match this search."})})]}):e(qt,{children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Name"}),e("input",{className:"tcp-input",value:P,onInput:o=>te(o.target.value),placeholder:"mcp-server"})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Auth mode"}),e("select",{className:"tcp-select",value:V,onChange:o=>Ne(o.target.value),children:[e("option",{value:"none",children:"No Auth Header"}),e("option",{value:"auto",children:"Auto"}),e("option",{value:"x-api-key",children:"x-api-key"}),e("option",{value:"bearer",children:"Authorization Bearer"}),e("option",{value:"custom",children:"Custom Header"})]})]})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Transport URL"}),e("input",{className:"tcp-input",value:ve,onInput:o=>{const x=o.target.value;if(Se(x),!String(P||"").trim()||P==="mcp-server"){const he=Mr(x);he&&te(he)}},placeholder:"https://example.com/mcp"})]}),V==="custom"?e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Custom header name"}),e("input",{className:"tcp-input",value:F,onInput:o=>De(o.target.value),placeholder:"X-My-Token"})]}):null,e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Token"}),e("input",{className:"tcp-input",type:"password",value:me,onInput:o=>Ee(o.target.value),placeholder:"token"}),e("div",{className:"tcp-subtle text-xs",children:ps})]}),e("label",{className:"inline-flex items-center gap-2 text-sm text-slate-200",children:[e("input",{type:"checkbox",className:"accent-slate-400",checked:le,onChange:o=>ae(o.target.checked)}),"Connect after save"]})]}),e("div",{className:"tcp-confirm-actions mt-2",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>_e(!1),children:"Cancel"}),e("button",{type:"submit",className:"tcp-btn-primary",disabled:Me.isPending,children:[e("i",{"data-lucide":"save"}),"Save MCP server"]})]})]})]})]}):null})]})})}function nd({routeId:a,pageProps:t}){switch(Un(a)){case"chat":return e(gl,{...t});case"automations":case"packs":case"teams":return e(pc,{...t});case"agents":return e(Ar,{...t});case"channels":return e(hc,{...t});case"mcp":return e(Rr,{...t});case"packs-detail":return e(bc,{...t});case"orchestrator":return e(Mc,{...t});case"files":return e($c,{...t});case"memory":return e(Ec,{...t});case"teams-detail":return e(Ar,{...t});case"feed":return e(Qc,{...t});case"settings":return e(Rr,{...t});default:return e(Lo,{...t})}}const rd={dashboard:{title:"Overview",subtitle:"Command status, activity, and fast paths into the system."},chat:{title:"Chat",subtitle:"Session-driven conversation, tools, uploads, and live responses."},automations:{title:"Automations",subtitle:"Templates, routines, approvals, and execution history."},agents:{title:"Agents",subtitle:"Persistent personalities, default models, and prompts reused across automation workflows."},orchestrator:{title:"Orchestrator",subtitle:"Plan-driven task execution with workspace visibility and approvals."},memory:{title:"Memory",subtitle:"Searchable memory records and operational context snapshots."},feed:{title:"Live Feed",subtitle:"Global event stream with pack-aware actions and debugging detail."},settings:{title:"Settings",subtitle:"Provider defaults, identity, themes, and runtime diagnostics."},mcp:{title:"MCP",subtitle:"Catalog, readiness, and generated integration details."},files:{title:"Files",subtitle:"Uploaded assets and workspace-adjacent file management."},"packs-detail":{title:"Packs",subtitle:"Starter packs, installation paths, and detected attachments."},"teams-detail":{title:"Teams",subtitle:"Team instances, approvals, and shared execution state."}};function sd({identity:a,currentRoute:t,providerLocked:n,navRoutes:r,onNavigate:s,onPaletteOpen:l,onThemeCycle:d,onLogout:u,statusBar:p,routeKey:k,children:q,providerGate:b}){const[w,M]=y(!1),[E,K]=y(!1),B=String(a.botAvatarUrl||"").trim(),se=Lr();ye(()=>{M(!1)},[t]),ye(()=>{try{zt()}catch{}},[t,w,p.bugMonitor?.enabled,p.bugMonitor?.monitoringActive,p.bugMonitor?.paused,p.bugMonitor?.pendingIncidents,p.bugMonitor?.blocked]),ye(()=>{K(!1)},[B]);const G=rd[t]||{title:String(r.find(([f])=>f===t)?.[1]||"Control Panel"),subtitle:"Desktop-inspired operations UI for Tandem."},ge=H(()=>r.find(([f])=>f===t)||r[0],[t,r]),N=H(()=>{const f=p.bugMonitor;return f?.enabled?f.blocked?{toneClass:"blocked",label:"Bug Monitor blocked",shortLabel:"Blocked"}:f.paused?{toneClass:"paused",label:"Bug Monitor paused",shortLabel:"Paused"}:f.pendingIncidents>0?{toneClass:"incidents",label:`Bug Monitor incidents: ${f.pendingIncidents}`,shortLabel:`${f.pendingIncidents} incident${f.pendingIncidents===1?"":"s"}`}:f.monitoringActive?{toneClass:"watching",label:"Bug Monitor watching",shortLabel:"Watching"}:{toneClass:"ready",label:"Bug Monitor ready",shortLabel:"Ready"}:null},[p.bugMonitor]),W=()=>B&&!E?e("img",{src:B,alt:a.botName,className:"block h-full w-full object-cover",onError:()=>K(!0)}):e("span",{className:"text-sm font-semibold uppercase",children:String(a.botName||"T").trim().slice(0,1)||"T"}),J=()=>r.map(([f,D,de])=>{const $e=t===f,Y=n&&f!=="settings";return e("button",{type:"button",title:D,disabled:Y,className:`tcp-rail-icon ${$e?"active":""} ${Y?"locked":""}`,onClick:()=>s(f),children:[$e?e(xe.span,{layoutId:"tcp-icon-indicator",className:"tcp-rail-icon-indicator"}):null,e("i",{"data-lucide":de})]},f)}),S=(f=!1)=>r.map(([D,de,$e])=>{const Y=t===D,U=n&&D!=="settings";return e("button",{type:"button",disabled:U,className:`tcp-context-link ${Y?"active":""} ${U?"locked":""}`,onClick:()=>{s(D),f&&M(!1)},children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":$e}),e("span",{children:de})]}),Y?e("span",{className:"tcp-context-link-dot"}):null]},D)}),fe=(f=!1)=>e(qt,{children:[f?e("div",{className:"tcp-context-hero",children:[e(sn,{className:"tcp-context-hero-glow"}),e("div",{className:"relative z-10 flex items-center gap-3",children:[e("div",{className:"tcp-brand-avatar h-11 w-11",children:W()}),e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:a.controlPanelName||`${a.botName} Control Panel`}),e("div",{className:"tcp-subtle text-xs",children:"Workspace navigation and system status"})]})]})]}):null,e("div",{className:`tcp-context-section ${f?"":"xl:hidden"}`.trim(),children:[e("div",{className:"tcp-context-section-label",children:"Navigation"}),e("nav",{className:"grid gap-1",children:S(f)})]}),f?e("div",{className:"tcp-context-section",children:[e("div",{className:"tcp-context-section-label",children:"System"}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Engine"}),p.engineHealthy?e(Ht,{tone:"ok",text:"healthy"}):e(Ht,{tone:"warn",text:"checking"})]}),e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Provider"}),e("span",{className:p.providerBadge,children:p.providerText})]}),e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Active runs"}),p.activeRuns>0?e(Ht,{tone:"live",text:String(p.activeRuns)}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"idle"})]}),N?e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Bug Monitor"}),e("button",{type:"button",className:`tcp-bug-monitor-pill ${N.toneClass}`,title:p.bugMonitor?.lastError?`${N.label}: ${p.bugMonitor.lastError}`:N.label,onClick:()=>{s("bug-monitor"),f&&M(!1)},children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:N.shortLabel})]})]}):null]})]}):null,e("div",{className:"tcp-context-section mt-auto",children:[e("div",{className:"tcp-context-section-label",children:"Actions"}),e("div",{className:"grid gap-2",children:[e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{l(),f&&M(!1)},children:[e("i",{"data-lucide":"search"}),"Command palette"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{d(),f&&M(!1)},children:[e("i",{"data-lucide":"paint-bucket"}),"Cycle theme"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{u(),f&&M(!1)},children:[e("i",{"data-lucide":"log-out"}),"Logout"]})]})]})]});return e("div",{className:"tcp-shell",children:[e(sn,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("aside",{className:"tcp-icon-rail hidden xl:flex",children:[e("button",{type:"button",className:"tcp-rail-brand",onClick:()=>s("dashboard"),children:e("div",{className:"tcp-brand-avatar h-10 w-10",children:W()})}),e("nav",{className:"tcp-rail-nav",children:J()}),e("div",{className:"tcp-rail-footer",children:[e(Ra,{title:"Command palette",onClick:l,children:e("i",{"data-lucide":"search"})}),e(Ra,{title:"Cycle theme",onClick:d,children:e("i",{"data-lucide":"paint-bucket"})}),e(Ra,{title:"Logout",onClick:u,children:e("i",{"data-lucide":"log-out"})}),e("div",{className:"mt-2 flex justify-center",children:p.engineHealthy?e(Ht,{tone:"ok"}):e(Ht,{tone:"warn"})})]})]}),e("aside",{className:"tcp-context-rail hidden lg:flex xl:hidden",children:fe(!1)}),e("main",{className:"tcp-main-shell",children:[e("section",{className:"tcp-mobile-topbar lg:hidden",children:[e("button",{type:"button",className:"tcp-btn h-10 px-3",onClick:()=>M(!0),children:[e("i",{"data-lucide":"menu"}),"Menu"]}),e("div",{className:"min-w-0 flex-1",children:[e("div",{className:"truncate text-sm font-semibold",children:G.title}),e("div",{className:"tcp-subtle truncate text-xs",children:ge?.[1]||G.subtitle})]}),N?e("button",{type:"button",className:`tcp-bug-monitor-pill ${N.toneClass}`,title:p.bugMonitor?.lastError?`${N.label}: ${p.bugMonitor.lastError}`:N.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"})]}):null,p.activeRuns>0?e(Ht,{tone:"live",text:String(p.activeRuns)}):null]}),e("section",{className:"tcp-topbar",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Tandem Control"}),e("h1",{className:"tcp-main-title",children:G.title}),e("p",{className:"tcp-subtle mt-1 max-w-2xl",children:G.subtitle})]}),e("div",{className:"tcp-topbar-status",children:[N?e("button",{type:"button",className:`tcp-bug-monitor-pill ${N.toneClass}`,title:p.bugMonitor?.lastError?`${N.label}: ${p.bugMonitor.lastError}`:N.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:N.shortLabel})]}):null,e("span",{className:p.providerBadge,children:p.providerText}),p.engineHealthy?e(Ht,{tone:"ok",text:"Engine healthy"}):e(Ht,{tone:"warn",text:"Checking engine"}),p.activeRuns>0?e(Ht,{tone:"live",text:`${p.activeRuns} run`}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"No active runs"})]})]}),e(ot,{mode:"wait",children:e(xe.section,{className:"tcp-main-content",initial:se?!1:{opacity:0,y:18},animate:se?void 0:{opacity:1,y:0},exit:se?void 0:{opacity:0,y:-14},transition:se?void 0:{duration:Zt.duration.normal,ease:Zt.easing.standard},children:q},k)})]}),e(ot,{children:w?e(xe.div,{className:"tcp-mobile-drawer lg:hidden",initial:se?!1:{opacity:0},animate:se?void 0:{opacity:1},exit:se?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-mobile-drawer-backdrop","aria-label":"Close navigation",onClick:()=>M(!1)}),e(xe.aside,{className:"tcp-mobile-drawer-panel",initial:se?!1:{x:"-100%"},animate:se?void 0:{x:0},exit:se?void 0:{x:"-100%"},transition:se?void 0:Zt.spring.drawer,children:[e("div",{className:"mb-3 flex items-center justify-between",children:[e("div",{children:[e("div",{className:"text-sm font-semibold",children:a.botName}),e("div",{className:"tcp-subtle text-xs",children:G.title})]}),e(Ra,{title:"Close",onClick:()=>M(!1),children:e("i",{"data-lucide":"x"})})]}),fe(!0)]})]}):null}),e(ot,{children:b||null})]})}function us(a){const t=String(a||"").trim().toLowerCase();return!!t&&t!=="ollama"&&t!=="local"}function id(a,t){const n=String(t||"").trim().toLowerCase();if(!n||!a||typeof a!="object")return!1;const r=s=>!s||typeof s!="object"?!1:s.has_key===!0||s.hasKey===!0||s.configured===!0&&!us(n);return r(a[n])||r(a.providers?.[n])}function od(a,t,n){const r=String(a?.default||a?.selected_model?.provider_id||"").trim(),s=a?.providers?.[r]||{},l=String(s.default_model||s.defaultModel||a?.selected_model?.model_id||"").trim(),d=Array.isArray(t?.connected)?t.connected:[],u=new Set(d.map(q=>String(q||"").trim().toLowerCase())),p=id(n,r),k=!!r&&!!l&&u.has(r.toLowerCase())&&(!us(r)||p);return{ready:k,defaultProvider:r,defaultModel:l,connected:[...u],error:"",needsOnboarding:!k}}function ld(a=!0){return Q({queryKey:["system","health"],queryFn:()=>Ut("/api/system/health"),enabled:a,refetchInterval:a?15e3:!1})}function cd(a=!0){return Q({queryKey:["swarm","status"],queryFn:()=>Ut("/api/swarm/status"),enabled:a,refetchInterval:a?5e3:!1})}const Jn="tandem_control_panel_token";function $r(){try{return localStorage.getItem(Jn)||""}catch{return""}}function dd(a){try{localStorage.setItem(Jn,a)}catch{}}function ud(){try{localStorage.removeItem(Jn)}catch{}}function md(a,t){return Q({queryKey:["provider","status"],enabled:t&&!!a,refetchInterval:t?15e3:!1,queryFn:async()=>{if(!a)return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:"",needsOnboarding:!1};try{const[n,r,s]=await Promise.all([a.providers.config(),a.providers.catalog(),a.providers.authStatus().catch(()=>({}))]);return od(n,r,s)}catch(n){return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:n instanceof Error?n.message:String(n),needsOnboarding:!0}}}})}function pd(a,t){return Q({queryKey:["identity"],enabled:t&&!!a,refetchInterval:t?3e4:!1,queryFn:async()=>{if(!a)return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"};try{const r=(await Ut("/api/engine/config/identity",{method:"GET"}))?.identity||{},s=String(r?.bot?.canonical_name||r?.bot?.canonicalName||"").trim(),l=r?.bot?.aliases||{},d=String(r?.bot?.avatar_url||r?.bot?.avatarUrl||"").trim(),u=String(l?.control_panel||l?.controlPanel||"").trim(),p=s||"Tandem";return{botName:p,botAvatarUrl:d,controlPanelName:u||`${p} Control Panel`}}catch{return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"}}}})}function hd(a){return Q({queryKey:["bug-monitor","status"],enabled:a,refetchInterval:a?1e4:!1,queryFn:async()=>{try{return await Ut("/api/engine/bug-monitor/status",{method:"GET"})}catch{return null}}})}function gd(){const a=jt(),{toast:t}=Uo(),{route:n,navigate:r}=Do(),[s,l]=y(xo()),[d,u]=y(!1),[p,k]=y(!1),q=pt(!1);ye(()=>{No(s)},[s]);const w=Q({queryKey:["auth","me"],retry:!1,refetchInterval:3e4,queryFn:()=>Ut("/api/auth/me",{method:"GET"})}).isSuccess;ye(()=>{try{zt()}catch{}},[w,n]);const M=H(()=>w?new Vi({baseUrl:"/api/engine",token:"session"}):null,[w]),E=md(M,w),K=pd(M,w),B=ld(w),se=cd(w),G=hd(w),ge=Ae({mutationFn:async({token:me})=>{await Ut("/api/auth/login",{method:"POST",body:JSON.stringify({token:me})})},onSuccess:(me,Ee)=>{Ee.remember?dd(Ee.token):ud(),a.invalidateQueries({queryKey:["auth","me"]}),t("ok","Signed in."),r("dashboard")},onError:me=>{t("err",me instanceof Error?me.message:String(me))}});ye(()=>{if(w||ge.isPending||q.current)return;const me=$r().trim();if(!me){q.current=!0;return}q.current=!0,ge.mutate({token:me,remember:!0})},[w,ge]);const N=Je(async()=>{await Ut("/api/auth/logout",{method:"POST"}).catch(()=>{}),a.removeQueries({queryKey:["auth"]}),a.removeQueries({queryKey:["provider"]}),a.removeQueries({queryKey:["identity"]}),a.invalidateQueries({queryKey:["auth","me"]}),t("info","Logged out.")},[a,t]),W=H(()=>new Set(["chat","agents","orchestrator","teams"]),[]),J=!!E.data?.needsOnboarding,S=w&&J;ye(()=>{if(!S){k(!1);return}W.has(n)&&(r("settings"),p||(k(!0),t("info","Set provider + default model first to unlock the control panel.")))},[W,r,p,S,n,t]);const fe=S&&W.has(n)?"settings":n,f=Je(async()=>{await a.invalidateQueries({queryKey:["provider","status"]})},[a]),D=Je(async()=>{await a.invalidateQueries({queryKey:["identity"]})},[a]),de=Je(me=>{const Ee=ko(me);return l(Ee.id),Ee},[l]),$e=K.data||{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"},Y={client:M,api:Ut,toast:t,navigate:r,currentRoute:fe,providerStatus:{ready:!!E.data?.ready,defaultProvider:E.data?.defaultProvider||"",defaultModel:E.data?.defaultModel||"",connected:E.data?.connected||[],error:E.data?.error||"",needsOnboarding:!!E.data?.needsOnboarding},identity:$e,refreshProviderStatus:f,refreshIdentityStatus:D,providerHints:Jr,themes:xa,setTheme:de,themeId:s},U=H(()=>{const me=Qr.map(([F,De])=>({id:`route:${F}`,label:`Go to ${De}`,group:"Routes",onSelect:()=>r(F)})),Ee=[{id:"action:new-chat",label:"New chat session",group:"Actions",onSelect:()=>{window.dispatchEvent(new CustomEvent("tcp:new-chat")),r("chat")}},{id:"action:start-engine-check",label:"Check engine health",group:"Actions",onSelect:async()=>{try{const F=await Ut("/api/system/health"),De=F?.engine?.ready||F?.engine?.healthy?"healthy":"unhealthy";t("info",`Engine ${De}: ${F?.engineUrl||"n/a"}`)}catch(F){t("err",F instanceof Error?F.message:String(F))}}},{id:"action:open-settings",label:"Open provider settings",group:"Actions",onSelect:()=>r("settings")},{id:"action:open-orchestrator",label:"Open orchestrator",group:"Actions",onSelect:()=>r("orchestrator")}];return[...me,...Ee]},[r,t]);if(To(()=>u(me=>!me)),!w)return e(Po,{loginMutation:ge,savedToken:$r(),controlPanelName:$e.controlPanelName,onCheckEngine:async()=>{const me=await Ut("/api/system/health");return`Engine check: ${me?.engine?.ready||me?.engine?.healthy?"healthy":"unhealthy"} at ${me?.engineUrl||"n/a"}`}});const ie=E.data?.ready?"tcp-badge-ok":"tcp-badge-warn",oe=E.data?.ready?`${E.data?.defaultProvider||"none"}/${E.data?.defaultModel||"none"}`:"provider setup required",Ue=G.data||null,_e=!!Ue?.config?.enabled,P=Number(Ue?.runtime?.pending_incidents||0),te=!!Ue?.runtime?.monitoring_active,ve=!!Ue?.runtime?.paused,Se=!!Ue?.readiness?.ingest_ready,V=!!Ue?.readiness?.publish_ready,Ne=String(Ue?.runtime?.last_runtime_error||Ue?.last_error||"").trim();return e(qt,{children:[e(sd,{identity:$e,currentRoute:fe,providerLocked:S,navRoutes:$o,onNavigate:r,onPaletteOpen:()=>u(!0),onThemeCycle:()=>de(wo(s)),onLogout:N,statusBar:{engineHealthy:!!(B.data?.engine?.ready||B.data?.engine?.healthy),providerBadge:ie,providerText:oe,activeRuns:["planning","awaiting_approval","running"].includes(String(se.data?.status||"").toLowerCase())?1:0,bugMonitor:_e?{enabled:!0,monitoringActive:te,paused:ve,pendingIncidents:P,blocked:!Se,lastError:te&&!V&&Ne?`Watching locally only. ${Ne}`:Ne}:null},routeKey:fe,providerGate:S&&fe!=="settings"?e(xe.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e(xe.div,{className:"tcp-confirm-dialog",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Provider Setup Required"}),e("p",{className:"tcp-confirm-message",children:"Configure provider and default model in Settings to unlock all sections."}),e("div",{className:"tcp-confirm-actions",children:e("button",{className:"tcp-btn-primary",onClick:()=>r("settings"),children:"Open Settings"})})]})}):null,children:e(nd,{routeId:fe,pageProps:Y})}),e(Mo,{open:d,onClose:()=>u(!1),actions:U})]})}function fd(){return e(Fo,{children:e(gd,{})})}const bd=new Oi({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),ms=document.getElementById("app");if(!ms)throw new Error("Missing #app host");ys(ms).render(e(qt,{children:e(ws,{client:bd,children:e(fd,{})})}));