@frumu/tandem-panel 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{index-4aX9RGDL.css → index-DF-KLBYn.css} +1 -1
- package/dist/assets/index-DvotFhS5.js +35 -0
- package/dist/assets/react-query-DqS47hY2.js +1 -0
- package/dist/assets/vendor-B5SLbWPm.js +42 -0
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/dist/assets/index-CpH1IYO9.js +0 -22
- package/dist/assets/react-query-PgFuErlI.js +0 -1
- package/dist/assets/vendor-CdeM8LjL.js +0 -42
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import{u as e,d as y,A as wt,y as ie,T as V,q as Ee,R as Ls,x as Bs,k as Qt,h as js,e as Ks,f as Js}from"./preact-vendor-jo0muZ28.js";import{u as j,a as Lt,b as me,Q as Ws}from"./react-query-PgFuErlI.js";import{b as K,o as xt,c as Vn,r as cs,d as zn,e as Ut,f as fn,g as Qs,W as Hs,U as Gs,C as Vs,X as zs,T as Ys,h as Xs,S as Zs,j as er,k as tr,l as nr,m as ar,p as sr,q as rr,t as ir,u as or,v as lr,w as cr,x as dr,y as ur,R as mr,z as pr,A as hr,P as gr,B as fr,D as br,E as yr,F as vr,G as wr,H as xr,I as Nr,J as kr,K as Sr,L as _r,N as Cr,O as Ir,V as Ar,Y as Pr,Z as Rr,_ as $r,$ as Mr,a0 as qr,a1 as Tr,a2 as Er,a3 as Or,a4 as Fr,a5 as Dr,a6 as Ur,a7 as Lr,a8 as Br,a9 as jr,aa as Kr,ab as Jr,ac as Wr,ad as Qr,ae as Hr,af as Gr,ag as Vr,ah as zr,ai as Yr,aj as Xr,ak as Zr,al as ei,am as ti,an as ni,ao as ai,ap as si,aq as ri,ar as ii,as as oi}from"./vendor-CdeM8LjL.js";import{m as te,A as Ze,u as ds}from"./motion-BCvrfAt1.js";import{g as us,p as li}from"./markdown-DMcD1LHz.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&s(c)}).observe(document,{childList:!0,subtree:!0});function a(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function s(i){if(i.ep)return;i.ep=!0;const l=a(i);fetch(i.href,l)}})();class ci extends Error{constructor(t,a,s,i){super(`Tandem API Validation Error [${a}] at ${t}: ${s.length} issues found.`),this.endpoint=t,this.status=a,this.issues=s,this.rawSnippet=i,this.name="TandemValidationError"}}const Ea=K().or(xt({id:K().optional(),runID:K().optional(),runId:K().optional(),run_id:K().optional(),sessionID:K().optional(),sessionId:K().optional(),session_id:K().optional(),missionID:K().optional(),missionId:K().optional(),mission_id:K().optional(),instanceID:K().optional(),instanceId:K().optional(),instance_id:K().optional()})).transform(n=>typeof n=="string"?n:n.id||n.runID||n.runId||n.run_id||n.sessionID||n.sessionId||n.session_id||n.missionID||n.missionId||n.mission_id||n.instanceID||n.instanceId||n.instance_id);Vn().transform(n=>n);cs(K(),Vn()).transform(n=>n);const di=xt({ready:zn().optional(),phase:K().optional(),workspace_root:K().optional(),workspaceRoot:K().optional()}).passthrough().transform(n=>({...n,workspaceRoot:n.workspace_root??n.workspaceRoot})),jn=xt({id:K(),title:K(),created_at_ms:Ut().optional(),createdAtMs:Ut().optional(),directory:K().optional(),workspace_root:K().optional(),workspaceRoot:K().optional(),archived:zn().optional()}).passthrough().transform(n=>({...n,createdAtMs:n.created_at_ms??n.createdAtMs??0,workspaceRoot:n.workspace_root??n.workspaceRoot})),Oa=xt({sessions:fn(jn).optional().default([]),count:Ut().optional().default(0)}).passthrough(),ui=xt({active:xt({runID:K().optional(),runId:K().optional(),run_id:K().optional(),attachEventStream:K().optional()}).passthrough().nullable().optional()}).passthrough().transform(n=>n.active?{active:{...n.active,runId:n.active.runId||n.active.runID||n.active.run_id}}:{active:null}),ms=xt({ok:zn().optional(),runID:K().optional(),runId:K().optional(),run_id:K().optional(),status:K().optional()}).passthrough().transform(n=>({...n,runId:n.runId||n.runID||n.run_id})),ps=xt({id:K().optional(),runID:K().optional(),runId:K().optional(),run_id:K().optional(),routine_id:K().optional(),automation_id:K().optional(),status:K().optional(),started_at_ms:Ut().optional(),finished_at_ms:Ut().optional()}).passthrough().transform(n=>({...n,runId:n.runId||n.runID||n.run_id,routineId:n.routine_id,automationId:n.automation_id,startedAtMs:n.started_at_ms,finishedAtMs:n.finished_at_ms})),Fa=xt({ok:zn().default(!0),rev:Ut().optional()}).passthrough(),hs=xt({key:K(),value:Vn(),rev:Ut().optional(),updated_at_ms:Ut().optional(),updated_by:K().optional()}).passthrough().transform(n=>({...n,updatedAtMs:n.updated_at_ms,updatedBy:n.updated_by})),mi=xt({items:fn(hs).optional().default([]),count:Ut().optional().default(0)}).passthrough(),pi=xt({id:K().optional(),text:K().optional(),content:K().optional(),user_id:K().optional(),userID:K().optional(),source_type:K().optional(),sourceType:K().optional(),tags:fn(K()).optional(),source:K().optional(),session_id:K().optional(),sessionID:K().optional(),run_id:K().optional(),runID:K().optional()}).passthrough().transform(n=>({...n,text:n.text||n.content,content:n.content||n.text,userId:n.userID||n.user_id,sourceType:n.sourceType||n.source_type,sessionId:n.session_id||n.sessionID,runId:n.run_id||n.runID})),hi=xt({items:fn(pi).optional().default([]),count:Ut().optional().default(0)}).passthrough(),gi=xt({id:K(),text:K().optional(),content:K().optional(),score:Ut().optional(),source_type:K().optional(),sourceType:K().optional(),run_id:K().optional(),runID:K().optional(),tags:fn(K()).optional()}).passthrough().transform(n=>({...n,text:n.text||n.content,content:n.content||n.text,sourceType:n.sourceType||n.source_type,runId:n.runID||n.run_id})),fi=xt({results:fn(gi).optional().default([]),count:Ut().optional().default(0)}).passthrough(),bi=xt({type:K(),properties:cs(K(),Vn()).optional().default({}),sessionID:K().optional(),session_id:K().optional(),sessionId:K().optional(),runID:K().optional(),run_id:K().optional(),runId:K().optional(),timestamp:K().optional()}).passthrough().transform(n=>({...n,properties:n.properties,sessionId:n.sessionId||n.sessionID||n.session_id,runId:n.runId||n.runID||n.run_id}));function pt(n,t,a,s){const i=n.safeParse(t);if(!i.success){const l=JSON.stringify(t).substring(0,200);throw new ci(a,s,i.error.issues,l)}return i.data}function yi(n){const t=n.trim();if(!t||t===": keep-alive"||t.startsWith(":"))return null;try{const a=JSON.parse(t),s=bi.safeParse(a);return s.success?s.data:null}catch{return null}}async function*cn(n,t,a){const s=a?.connectTimeoutMs??3e4,i=new AbortController,l=setTimeout(()=>i.abort(),s),c=a?.signal?vi([i.signal,a.signal]):i.signal;let u;try{u=await fetch(n,{headers:{Accept:"text/event-stream",Authorization:`Bearer ${t}`,"Cache-Control":"no-cache"},signal:c})}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,w=u.body.getReader();let M="";try{for(;;){const{done:b,value:S}=await w.read();if(b)break;M+=p.decode(S,{stream:!0});const q=M.split(`
|
|
2
|
-
`);M=q.pop()??"";let T="";for(const X of q)if(X.startsWith("data:"))T+=X.slice(5).trimStart();else if(X===""&&T){const z=yi(T);z&&(yield z),T=""}}}finally{w.releaseLock()}}function vi(n){const t=new AbortController;for(const a of n){if(a.aborted){t.abort(a.reason);break}a.addEventListener("abort",()=>t.abort(a.reason),{once:!0})}return t.signal}const Pt=n=>typeof n=="string"&&n.trim().length>0?n:null,wi=n=>{try{const t=Ea.parse(n);if(t)return t}catch{const t=n.run||null;if(t)try{const a=Ea.parse(t);if(a)return a}catch{}}throw new Error("Run ID missing in engine response")};class xi{constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.timeoutMs=t.timeoutMs??2e4;const a=this._request.bind(this);this.sessions=new _i(this.baseUrl,this.token,this.timeoutMs,a),this.permissions=new Ci(a),this.questions=new Ii(a),this.providers=new Ai(a),this.identity=new Pi(a),this.channels=new Ri(a),this.mcp=new $i(a,this._requestText.bind(this));const s=()=>this.token;this.routines=new Di(this.baseUrl,s,a),this.automations=new Li(this.baseUrl,s,a),this.automationsV2=new Bi(this.baseUrl,s,a),this.workflowPlans=new Ui(a),this.memory=new Mi(a),this.skills=new qi(a),this.packs=new Ti(a),this.capabilities=new Ei(a),this.resources=new Oi(this.baseUrl,s,a),this.browser=new Ni(a),this.workflows=new ki(this.baseUrl,s,a),this.bugMonitor=new Si(a),this.coder=new Fi(a),this.agentTeams=new ji(a),this.missions=new Ki(a)}setToken(t){this.token=t,this.sessions.setToken(t)}async health(){const t=await this._request("/global/health");return pt(di,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,a){return this._request("/tool/execute",{method:"POST",body:JSON.stringify({tool:t,args:a??{}})})}stream(t,a,s){const i=new URLSearchParams({sessionID:t});a&&i.set("runID",a);const l=`${this.baseUrl}/event?${i.toString()}`;return cn(l,this.token,s)}globalStream(t){const a=`${this.baseUrl}/global/event`;return cn(a,this.token,t)}async runEvents(t,a){const s=new URLSearchParams;a?.sinceSeq!==void 0&&s.set("since_seq",String(a.sinceSeq)),a?.tail!==void 0&&s.set("tail",String(a.tail));const i=s.toString()?`?${s.toString()}`:"",l=await this._request(`/run/${encodeURIComponent(t)}/events${i}`);return Array.isArray(l)?l:[]}async _request(t,a={}){const s=new AbortController,i=setTimeout(()=>s.abort(),this.timeoutMs);let l;try{l=await fetch(`${this.baseUrl}${t}`,{...a,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,...a.headers??{}},signal:s.signal})}catch(c){throw c instanceof Error&&c.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):c}finally{clearTimeout(i)}if(l.status!==204){if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`Request failed (${l.status} ${l.statusText}): ${c}`)}return l.json()}}async _requestText(t,a={}){const s=new AbortController,i=setTimeout(()=>s.abort(),this.timeoutMs);let l;try{l=await fetch(`${this.baseUrl}${t}`,{...a,headers:{Authorization:`Bearer ${this.token}`,...a.headers??{}},signal:s.signal})}catch(c){throw c instanceof Error&&c.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):c}finally{clearTimeout(i)}if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`Request failed (${l.status} ${l.statusText}): ${c}`)}return l.text()}}class Ni{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 ki{constructor(t,a,s){this.baseUrl=t,this.getToken=a,this.req=s}async list(){const a=await this.req("/workflows")??{},s=Array.isArray(a.workflows)?a.workflows:[];return{workflows:s,count:typeof a.count=="number"?a.count:s.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 a=new URLSearchParams,s=t?.workflow_id??t?.workflowId,i=t?.run_id??t?.runId;s&&a.set("workflow_id",s),i&&a.set("run_id",i);const l=a.toString()?`?${a.toString()}`:"";return cn(`${this.baseUrl}/workflows/events${l}`,this.getToken(),{signal:t?.signal})}async listRuns(t){const a=new URLSearchParams,s=t?.workflow_id??t?.workflowId;s&&a.set("workflow_id",s),t?.limit!==void 0&&a.set("limit",String(t.limit));const i=a.toString()?`?${a.toString()}`:"",c=await this.req(`/workflows/runs${i}`)??{},u=Array.isArray(c.runs)?c.runs:[];return{runs:u,count:typeof c.count=="number"?c.count:u.length}}async getRun(t){return(await this.req(`/workflows/runs/${encodeURIComponent(t)}`)).run??{}}async run(t,a){return this.req(`/workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(a??{})})}async listHooks(t){const a=new URLSearchParams,s=t?.workflow_id??t?.workflowId;s&&a.set("workflow_id",s);const i=a.toString()?`?${a.toString()}`:"",c=await this.req(`/workflow-hooks${i}`)??{},u=Array.isArray(c.hooks)?c.hooks:[];return{hooks:u,count:typeof c.count=="number"?c.count:u.length}}async patchHook(t,a){return this.req(`/workflow-hooks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}}class Si{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 a=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/incidents${a}`)}async getIncident(t){return(await this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}`)).incident??{}}async replayIncident(t,a){return this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}/replay`,{method:"POST",body:JSON.stringify(a??{})})}async listDrafts(t){const a=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/drafts${a}`)}async listPosts(t){const a=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/posts${a}`)}async getDraft(t){return(await this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}`)).draft??{}}async approveDraft(t,a){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:a})})}async denyDraft(t,a){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:a})})}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,a){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(a)})}async createIssueDraft(t,a){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/issue-draft`,{method:"POST",body:JSON.stringify(a??{})})}async publishDraft(t,a){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/publish`,{method:"POST",body:JSON.stringify(a??{})})}async recheckMatch(t,a){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/recheck-match`,{method:"POST",body:JSON.stringify(a??{})})}}class _i{constructor(t,a,s,i){this.baseUrl=t,this.token=a,this.timeoutMs=s,this.req=i}setToken(t){this.token=t}async create(t={}){const a={title:t.title??"Tandem SDK Session",directory:t.directory??"."};return t.permissions&&(a.permission=t.permissions),t.model&&t.provider&&(a.model={providerID:t.provider,modelID:t.model},a.provider=t.provider),(await this.req("/session",{method:"POST",body:JSON.stringify(a)})).id}async list(t={}){const a=new URLSearchParams;t.q&&a.set("q",t.q),t.page!==void 0&&a.set("page",String(t.page)),t.pageSize!==void 0&&a.set("page_size",String(t.pageSize)),t.archived!==void 0&&a.set("archived",String(t.archived)),t.scope&&a.set("scope",t.scope),t.workspace&&a.set("workspace",t.workspace);const s=a.toString()?`?${a.toString()}`:"",i=await this.req(`/session${s}`);return pt(Oa,i,"/session",200)}async get(t){const a=await this.req(`/session/${encodeURIComponent(t)}`);return pt(jn,a,`/session/${t}`,200)}async update(t,a){const s=await this.req(`/session/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)});return pt(jn,s,`/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 a=await this.req(`/session/${encodeURIComponent(t)}/todo`);return Array.isArray(a)?a:a.todos??[]}async activeRun(t){const a=await this.req(`/session/${encodeURIComponent(t)}/run`);return pt(ui,a,`/session/${t}/run`,200)}async promptAsync(t,a,s,i){return this.promptAsyncParts(t,[{type:"text",text:a}],s,i)}async promptAsyncParts(t,a,s,i){const l={parts:a};s?.provider&&s?.model&&(l.model={providerID:s.provider,modelID:s.model}),i?.toolMode&&(l.toolMode=i.toolMode),i?.toolAllowlist?.length&&(l.toolAllowlist=i.toolAllowlist),i?.contextMode&&(l.contextMode=i.contextMode);const c=`/session/${encodeURIComponent(t)}/prompt_async?return=run`,u=new AbortController,p=setTimeout(()=>u.abort(),this.timeoutMs);let w;try{w=await fetch(`${this.baseUrl}${c}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(l),signal:u.signal})}finally{clearTimeout(p)}if(w.status===409){const S=(await w.json().catch(()=>({}))).activeRun,q=Pt(S?.runID)||Pt(S?.runId)||Pt(S?.run_id);if(q)return{runId:q}}if(!w.ok){const b=await w.text().catch(()=>"");throw new Error(`promptAsyncParts failed (${w.status}): ${b}`)}const M=await w.json();return{runId:wi(M)}}async promptSync(t,a){const s={parts:[{type:"text",text:a}]},i=await this.req(`/session/${encodeURIComponent(t)}/prompt_sync`,{method:"POST",body:JSON.stringify(s)});return Pt(i.reply)||Pt(i.text)||Pt(i.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,a){return this.req(`/session/${encodeURIComponent(t)}/run/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})})}async fork(t){const a=await this.req(`/session/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify({})});return pt(jn,a,`/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 a=await this.req(`/session/${encodeURIComponent(t)}/children`);return pt(Oa,a,`/session/${t}/children`,200).sessions}async summarize(t){return this.req(`/session/${encodeURIComponent(t)}/summarize`,{method:"POST",body:JSON.stringify({})})}async attach(t,a){return this.req(`/session/${encodeURIComponent(t)}/attach`,{method:"POST",body:JSON.stringify({target_workspace:a})})}}class Ci{constructor(t){this.req=t}async list(){return this.req("/permission")}async reply(t,a){const s=await this.req(`/permission/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({reply:a})});if(!s.ok)throw new Error(`Permission reply rejected: ${s.error??t}`);return{ok:!0}}}class Ii{constructor(t){this.req=t}async list(){const t=await this.req("/question");return Array.isArray(t)?{questions:t}:t}async reply(t,a){return this.req(`/question/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({answer:a})})}async reject(t){return this.req(`/question/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({})})}}class Ai{constructor(t){this.req=t}async catalog(){return this.req("/provider")}async config(){return this.req("/config/providers")}async setDefaults(t,a){await this.req("/config",{method:"PATCH",body:JSON.stringify({default_provider:t,providers:{[t]:{default_model:a}}})})}async setApiKey(t,a){await this.req(`/auth/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({apiKey:a})})}async authStatus(){return this.req("/provider/auth")}}class Pi{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 Ri{constructor(t){this.req=t}async config(){return this.req("/channels/config")}async status(){return this.req("/channels/status")}async put(t,a){return this.req(`/channels/${t}`,{method:"PUT",body:JSON.stringify(a)})}async delete(t){return this.req(`/channels/${t}`,{method:"DELETE"})}async verify(t,a={}){return this.req(`/channels/${t}/verify`,{method:"POST",body:JSON.stringify(a)})}}class $i{constructor(t,a){this.req=t,this.reqText=a}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,a){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:a})})}async delete(t){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})}async auth(t,a){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"POST",body:JSON.stringify(a??{})})}async deleteAuth(t){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"DELETE"})}async authCallback(t,a){return this.req(`/mcp/${encodeURIComponent(t)}/auth/callback`,{method:"POST",body:JSON.stringify(a)})}async authenticate(t,a){return this.req(`/mcp/${encodeURIComponent(t)}/auth/authenticate`,{method:"POST",body:JSON.stringify(a??{})})}async catalogToml(t){if(!this.reqText)throw new Error("Text request helper unavailable");return this.reqText(`/mcp/catalog/${encodeURIComponent(t)}/toml`)}}class Mi{constructor(t){this.req=t}async put(t){return this.req("/memory/put",{method:"POST",body:JSON.stringify(t)})}async search(t){const a=await this.req("/memory/search",{method:"POST",body:JSON.stringify(t)});return pt(fi,a,"/memory/search",200)}async list(t){const a=new URLSearchParams;t?.q&&a.set("q",t.q),t?.limit!==void 0&&a.set("limit",String(t.limit)),t?.offset!==void 0&&a.set("offset",String(t.offset)),t?.userId&&a.set("user_id",t.userId);const s=a.toString()?`?${a.toString()}`:"",i=await this.req(`/memory${s}`);return pt(hi,i,"/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 a={id:t.id,run_id:t.runId};return this.req("/memory/demote",{method:"POST",body:JSON.stringify(a)})}async audit(t){const a=new URLSearchParams;t?.run_id&&a.set("run_id",t.run_id),t?.limit!==void 0&&a.set("limit",String(t.limit));const s=a.toString()?`?${a.toString()}`:"",i=await this.req(`/memory/audit${s}`);return Array.isArray(i)?{entries:i,count:i.length}:i}}class qi{constructor(t){this.req=t}async list(t){const a=t?`?location=${encodeURIComponent(t)}`:"",s=await this.req(`/skills${a}`);return Array.isArray(s)?{skills:s,count:s.length}:s}async get(t){return this.req(`/skills/${encodeURIComponent(t)}`)}async import(t){const a={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(a)})}async preview(t){const a={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(a)})}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"),a=Array.isArray(t)?t:[];return{skills:a,count:a.length}}async validate(t){const a={content:t.content,file_or_path:t.file_or_path??t.fileOrPath};return this.req("/skills/validate",{method:"POST",body:JSON.stringify(a)})}async match(t){const a={goal:t.goal,max_matches:t.max_matches??t.maxMatches,threshold:t.threshold};return this.req("/skills/router/match",{method:"POST",body:JSON.stringify(a)})}async evalBenchmark(t){const a={threshold:t.threshold,cases:t.cases.map(s=>({prompt:s.prompt,expected_skill:s.expected_skill??s.expectedSkill}))};return this.req("/skills/evals/benchmark",{method:"POST",body:JSON.stringify(a)})}async evalTriggers(t){const a={skill_name:t.skill_name??t.skillName,prompts:t.prompts,threshold:t.threshold};return this.req("/skills/evals/triggers",{method:"POST",body:JSON.stringify(a)})}async compile(t){const a={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(a)})}async generate(t){return this.req("/skills/generate",{method:"POST",body:JSON.stringify(t)})}async generateInstall(t){const a={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(a)})}}class Ti{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 s=await this.req(`/packs/${encodeURIComponent(t)}/updates`)||{},i=Array.isArray(s.updates)?s.updates:[];return{pack_id:Pt(s.pack_id)??void 0,name:Pt(s.name)??void 0,current_version:Pt(s.current_version)??void 0,updates:i}}async update(t,a){const s=await this.req(`/packs/${encodeURIComponent(t)}/update`,{method:"POST",body:JSON.stringify(a??{})});return{updated:!!s.updated,pack_id:Pt(s.pack_id)??void 0,name:Pt(s.name)??void 0,current_version:Pt(s.current_version)??void 0,target_version:Pt(s.target_version)??void 0,reason:Pt(s.reason)??void 0}}}class Ei{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 Oi{constructor(t,a,s){this.baseUrl=t,this.getToken=a,this.req=s}async list(t){const a=new URLSearchParams;t?.prefix&&a.set("prefix",t.prefix),t?.limit!==void 0&&a.set("limit",String(t.limit));const s=a.toString()?`?${a.toString()}`:"",i=await this.req(`/resource${s}`);return pt(mi,i,"/resource",200)}async write(t){return this.req("/resource",{method:"PUT",body:JSON.stringify(t)})}async get(t){const a=await this.req(`/resource/${encodeURIComponent(t)}`);return pt(hs,a,`/resource/${t}`,200)}async putKey(t,a,s){const i=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({value:a,...s??{}})});return pt(Fa,i,`/resource/${t}`,200)}async patchKey(t,a){const s=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)});return pt(Fa,s,`/resource/${t}`,200)}async delete(t,a){return this.req("/resource",{method:"DELETE",body:JSON.stringify({key:t,...a})})}async deleteKey(t){return this.req(`/resource/${encodeURIComponent(t)}`,{method:"DELETE"})}events(t){const a=new URLSearchParams;t?.sinceSeq!==void 0&&a.set("since_seq",String(t.sinceSeq)),t?.tail!==void 0&&a.set("tail",String(t.tail));const s=a.toString()?`?${a.toString()}`:"";return cn(`${this.baseUrl}/resource/events${s}`,this.getToken())}}class Fi{constructor(t){this.req=t}async createRun(t){return this.req("/coder/runs",{method:"POST",body:JSON.stringify(t)})}async listRuns(t){const a=new URLSearchParams;t?.limit!==void 0&&a.set("limit",String(t.limit));const s=t?.workflow_mode??t?.workflowMode,i=t?.repo_slug??t?.repoSlug;s&&a.set("workflow_mode",s),i&&a.set("repo_slug",i);const l=a.toString()?`?${a.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 s=await this.req(`/coder/runs/${encodeURIComponent(t)}`)??{};return{...s,coderRun:s.coder_run??void 0,coder_run:s.coder_run??void 0,run:s.run??void 0}}async executeNext(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-next`,{method:"POST",body:JSON.stringify(a??{})})}async executeAll(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-all`,{method:"POST",body:JSON.stringify(a??{})})}async createFollowOnRun(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/follow-on-run`,{method:"POST",body:JSON.stringify(a)})}async approveRun(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:a})})}async cancelRun(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:a})})}async listArtifacts(t){const s=await this.req(`/coder/runs/${encodeURIComponent(t)}/artifacts`)??{},i=Array.isArray(s.artifacts)?s.artifacts:[];return{...s,artifacts:i,count:typeof s.count=="number"?s.count:i.length}}async getMemoryHits(t,a){const s=new URLSearchParams;a?.query&&s.set("q",a.query),a?.limit!==void 0&&s.set("limit",String(a.limit));const i=s.toString()?`?${s.toString()}`:"",c=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-hits${i}`)??{},u=Array.isArray(c.hits)?c.hits:[];return{...c,hits:u,count:typeof c.count=="number"?c.count:u.length}}async createTriageInspectionReport(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-inspection-report`,{method:"POST",body:JSON.stringify(a)})}async createTriageReproductionReport(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-reproduction-report`,{method:"POST",body:JSON.stringify(a)})}async createTriageSummary(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(a)})}async createPrReviewEvidence(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-evidence`,{method:"POST",body:JSON.stringify(a)})}async createPrReviewSummary(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-summary`,{method:"POST",body:JSON.stringify(a)})}async createIssueFixValidationReport(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-validation-report`,{method:"POST",body:JSON.stringify(a)})}async createIssueFixSummary(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-summary`,{method:"POST",body:JSON.stringify(a)})}async createPrDraft(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-draft`,{method:"POST",body:JSON.stringify(a??{})})}async submitPr(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-submit`,{method:"POST",body:JSON.stringify(a??{})})}async createMergeReadinessReport(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-readiness-report`,{method:"POST",body:JSON.stringify(a)})}async createMergeRecommendationSummary(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-recommendation-summary`,{method:"POST",body:JSON.stringify(a)})}async listMemoryCandidates(t){const s=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`)??{},i=Array.isArray(s.candidates)?s.candidates:[];return{...s,candidates:i,count:typeof s.count=="number"?s.count:i.length}}async createMemoryCandidate(t,a){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`,{method:"POST",body:JSON.stringify(a)})}async promoteMemoryCandidate(t,a,s){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates/${encodeURIComponent(a)}/promote`,{method:"POST",body:JSON.stringify(s??{})})}}class Di{constructor(t,a,s){this.baseUrl=t,this.getToken=a,this.req=s}async list(){return this.req("/routines")}async create(t){const a={...t};return"prompt"in a&&!("entrypoint"in a)&&(a.entrypoint=a.prompt),this.req("/routines",{method:"POST",body:JSON.stringify(a)})}async update(t,a){return this.req(`/routines/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}async delete(t){await this.req(`/routines/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const a=await this.req(`/routines/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return pt(ms,a,`/routines/${t}/run_now`,200)}async listRuns(t){const a=new URLSearchParams;t?.routine_id&&a.set("routine_id",t.routine_id),t?.limit!==void 0&&a.set("limit",String(t.limit));const s=a.toString()?`?${a.toString()}`:"";return this.req(`/routines/runs${s}`)}async getRunsForRoutine(t,a=25){return this.req(`/routines/${encodeURIComponent(t)}/runs?limit=${a}`)}async getRun(t){const a=await this.req(`/routines/runs/${encodeURIComponent(t)}`);return pt(ps,a,`/routines/runs/${t}`,200)}async listArtifacts(t){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,a){return this.req(`/routines/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:a??""})})}async denyRun(t,a){return this.req(`/routines/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:a??""})})}async pauseRun(t,a){return this.req(`/routines/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:a??""})})}async resumeRun(t,a){return this.req(`/routines/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:a??""})})}async history(t,a){const s=a!==void 0?`?limit=${a}`:"",i=await this.req(`/routines/${encodeURIComponent(t)}/history${s}`);return Array.isArray(i)?{history:i,count:i.length}:i}events(t){const a=new URLSearchParams,s=t?.routine_id??t?.routineId;s&&a.set("routine_id",s);const i=a.toString()?`?${a.toString()}`:"";return cn(`${this.baseUrl}/routines/events${i}`,this.getToken(),{signal:t?.signal})}addArtifact(t,a){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(a)})}}class Ui{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 Li{constructor(t,a,s){this.baseUrl=t,this.getToken=a,this.req=s}async list(){return this.req("/automations")}async create(t){return this.req("/automations",{method:"POST",body:JSON.stringify(t)})}async update(t,a){return this.req(`/automations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}async delete(t){await this.req(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const a=await this.req(`/automations/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return pt(ms,a,`/automations/${t}/run_now`,200)}async listRuns(t){const a=new URLSearchParams;t?.automation_id&&a.set("automation_id",t.automation_id),t?.limit!==void 0&&a.set("limit",String(t.limit));const s=a.toString()?`?${a.toString()}`:"";return this.req(`/automations/runs${s}`)}async getRunsForAutomation(t,a=25){return this.req(`/automations/${encodeURIComponent(t)}/runs?limit=${a}`)}async getRun(t){const a=await this.req(`/automations/runs/${encodeURIComponent(t)}`);return pt(ps,a,`/automations/runs/${t}`,200)}async listArtifacts(t){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,a){return this.req(`/automations/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:a??""})})}async denyRun(t,a){return this.req(`/automations/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:a??""})})}async pauseRun(t,a){return this.req(`/automations/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:a??""})})}async resumeRun(t,a){return this.req(`/automations/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:a??""})})}async history(t,a){const s=a!==void 0?`?limit=${a}`:"",i=await this.req(`/automations/${encodeURIComponent(t)}/history${s}`);return Array.isArray(i)?{history:i,count:i.length}:i}events(t){const a=new URLSearchParams,s=t?.automation_id??t?.automationId,i=t?.run_id??t?.runId;s&&a.set("automation_id",s),i&&a.set("run_id",i);const l=a.toString()?`?${a.toString()}`:"";return cn(`${this.baseUrl}/automations/events${l}`,this.getToken(),{signal:t?.signal})}addArtifact(t,a){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(a)})}}class Bi{constructor(t,a,s){this.baseUrl=t,this.getToken=a,this.req=s}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,a){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}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,a){return this.req(`/automations/v2/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:a??""})})}async resume(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({})})}async listRuns(t,a=50){return this.req(`/automations/v2/${encodeURIComponent(t)}/runs?limit=${a}`)}async getRun(t){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}`)}async pauseRun(t,a){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:a??""})})}async resumeRun(t,a){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:a??""})})}async cancelRun(t,a){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:a??""})})}events(t){const a=new URLSearchParams,s=t?.automation_id??t?.automationId,i=t?.run_id??t?.runId;s&&a.set("automation_id",s),i&&a.set("run_id",i);const l=a.toString()?`?${a.toString()}`:"";return cn(`${this.baseUrl}/automations/v2/events${l}`,this.getToken(),{signal:t?.signal})}}class ji{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,a){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(a)})}async deleteTemplate(t){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"DELETE"})}async listInstances(t){const a=new URLSearchParams;t?.missionID&&a.set("missionID",t.missionID),t?.parentInstanceID&&a.set("parentInstanceID",t.parentInstanceID),t?.status&&a.set("status",t.status);const s=a.toString()?`?${a.toString()}`:"";return this.req(`/agent-team/instances${s}`)}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,a){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:a??""})})}async denySpawn(t,a){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:a??""})})}}class Ki{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,a){return this.req(`/mission/${encodeURIComponent(t)}/event`,{method:"POST",body:JSON.stringify({event:a})})}}const Wn="charcoal_fire",hn=[{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 ya(n){let t=String(n||"").trim()||Wn;return t==="web_control"&&(t=Wn),hn.find(a=>a.id===t)||hn[0]}function Ji(n){const t=ya(n).id,a=hn.findIndex(s=>s.id===t);return a<0?Wn:hn[(a+1)%hn.length].id}function gs(n,t=typeof document<"u"?document.documentElement:null){const a=ya(n);if(!t)return a;for(const[s,i]of Object.entries(a.cssVars))i!=null&&t.style.setProperty(s,i);return t.dataset.theme=a.id,t.style.colorScheme=a.id==="porcelain"?"light":"dark",a}function fs(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const bs="tandem.themeId";function Wi(){try{const n=localStorage.getItem(bs);return ya(n).id}catch{return Wn}}function Qi(n){return gs(n)}function Hi(n){const t=gs(n);try{localStorage.setItem(bs,t.id)}catch{}return t}function $n(){const[n,t]=y(()=>fs());return ie(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia("(prefers-reduced-motion: reduce)"),s=()=>t(a.matches);return s(),typeof a.addEventListener=="function"?(a.addEventListener("change",s),()=>a.removeEventListener("change",s)):(a.addListener(s),()=>a.removeListener(s))},[]),n}function Gi(n,t,a){return Math.min(a,Math.max(t,n))}function Qn({className:n="",children:t}){return e("div",{className:`tcp-glow-layer ${n}`.trim(),children:t})}function Mn({className:n="",children:t}){const a=$n();return e(te.div,{className:n,initial:a?!1:{opacity:0,y:14},animate:a?void 0:{opacity:1,y:0},exit:a?void 0:{opacity:0,y:-10},transition:a?void 0:{duration:zt.duration.normal,ease:zt.easing.standard},children:t})}function Vi({className:n="",children:t}){const a=$n();return e(te.div,{className:n,initial:a?!1:"hidden",animate:a?void 0:"show",variants:a?void 0:{hidden:{},show:{transition:{staggerChildren:.06,delayChildren:.02}}},children:t})}function ys({className:n="",children:t,as:a="div"}){const s=$n(),i=a==="section"?te.section:a==="article"?te.article:te.div;return e(i,{className:n,variants:s?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:s?!1:"hidden",animate:s?void 0:"show",children:t})}function zi({value:n,format:t=s=>String(s),className:a=""}){const s=$n(),[i,l]=y(()=>Number(n||0)),c=wt(Number(n||0));return ie(()=>{const u=Number(n||0);if(!Number.isFinite(u)){l(0),c.current=0;return}if(s){l(u),c.current=u;return}const p=c.current,w=u-p;if(!w){l(u),c.current=u;return}const M=performance.now();let b=0;const S=q=>{const T=Gi((q-M)/420,0,1),X=1-Math.pow(1-T,3),z=p+w*X;l(z),T<1?b=window.requestAnimationFrame(S):c.current=u};return b=window.requestAnimationFrame(S),()=>window.cancelAnimationFrame(b)},[s,n]),e("span",{className:a,children:t(Number.isFinite(i)?i:0)})}function Jt({tone:n="ok",text:t,className:a=""}){return e("span",{className:`tcp-status-pulse ${n} ${a}`.trim(),children:[e("span",{className:"tcp-status-pulse-dot","aria-hidden":"true"}),t?e("span",{children:t}):null]})}function Wt({className:n="",children:t}){return e("div",{className:`tcp-toolbar ${n}`.trim(),children:t})}function kn({className:n="",title:t,children:a,...s}){return e("button",{type:"button",title:t,className:`tcp-icon-btn ${n}`.trim(),...s,children:a})}function ae({tone:n="info",className:t="",children:a}){return e("span",{className:`${n==="ok"?"tcp-badge-ok":n==="warn"?"tcp-badge-warn":n==="err"?"tcp-badge-err":n==="ghost"?"tcp-badge tcp-badge-ghost":"tcp-badge-info"} ${t}`.trim(),children:a})}function aa({active:n=!1,className:t="",children:a,...s}){return e("button",{type:"button",className:`tcp-filter-chip ${n?"active":""} ${t}`.trim(),...s,children:a})}function Le({title:n,subtitle:t,actions:a,className:s="",children:i}){return e(ys,{as:"section",className:`tcp-panel-card ${s}`.trim(),children:[n||t||a?e("div",{className:"tcp-panel-card-head",children:[e("div",{className:"min-w-0",children:[n?e("h3",{className:"tcp-title",children:n}):null,t?e("p",{className:"tcp-subtle mt-1",children:t}):null]}),a?e("div",{className:"shrink-0",children:a}):null]}):null,i]})}function Yi({text:n,title:t="Nothing here yet",action:a,className:s=""}){return e("div",{className:`tcp-empty-state ${s}`.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:n}),a?e("div",{className:"mt-3",children:a}):null]})]})}function Xi({eyebrow:n,title:t,subtitle:a,badges:s,actions:i,className:l=""}){return e(ys,{className:`tcp-page-header ${l}`.trim(),children:[e(Qn,{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:[n?e("div",{className:"tcp-page-eyebrow",children:n}):null,e("h1",{className:"tcp-page-title",children:t}),a?e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:a}):null,s?e("div",{className:"mt-3 flex flex-wrap gap-2",children:s}):null]}),i?e(Wt,{className:"justify-start lg:justify-end",children:i}):null]})]})}function In({className:n="",mainClassName:t="",asideClassName:a="",main:s,aside:i}){return e("div",{className:`tcp-split-view ${n}`.trim(),children:[e("div",{className:`min-w-0 ${t}`.trim(),children:s}),i?e("div",{className:`min-w-0 ${a}`.trim(),children:i}):null]})}function Hn({open:n,title:t,onClose:a,children:s}){const i=$n();return e(Ze,{children:n?e(te.div,{className:"tcp-drawer-root",initial:i?!1:{opacity:0},animate:i?void 0:{opacity:1},exit:i?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-drawer-backdrop","aria-label":"Close",onClick:a}),e(te.aside,{className:"tcp-drawer-panel",initial:i?!1:{x:"100%"},animate:i?void 0:{x:0},exit:i?void 0:{x:"100%"},transition:i?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(kn,{title:"Close drawer",onClick:a,children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:s})]})]}):null})}function Zi({loginMutation:n,savedToken:t,onCheckEngine:a,controlPanelName:s}){const[i,l]=y(t),[c,u]=y(!0),[p,w]=y(""),[M,b]=y(!1);return e("main",{className:"relative min-h-screen overflow-hidden px-5 py-8",children:[e(Qn,{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(Le,{title:s,subtitle:"Authenticate against your Tandem engine to continue.",children:e("form",{className:"grid gap-3",onSubmit:S=>{if(S.preventDefault(),!i.trim()){b(!1),w("Token is required.");return}n.mutate({token:i.trim(),remember:c})},children:[e("label",{className:"text-sm tcp-subtle",children:"Engine token"}),e("input",{className:"tcp-input",type:"password",value:i,onInput:S=>l(S.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:c,onChange:S=>u(S.target.checked)}),"Remember token on this browser"]}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{disabled:n.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 S=await a();b(!0),w(S)}catch(S){b(!1),w(S instanceof Error?S.message:String(S))}},children:[e("i",{"data-lucide":"activity"}),"Check engine"]})]}),e("div",{className:`min-h-[1.2rem] text-sm ${M?"text-lime-300":"text-rose-300"}`,children:n.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(Jt,{tone:M?"ok":"warn",text:M?"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 eo(n){ie(()=>{const t=a=>{(a.metaKey||a.ctrlKey)&&a.key.toLowerCase()==="k"&&(a.preventDefault(),n())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[n])}function to({open:n,onClose:t,actions:a}){const[s,i]=y("");ie(()=>{n||i("")},[n]),ie(()=>{if(!n)return;const c=u=>{u.key==="Escape"&&t()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[n,t]);const l=V(()=>{const c=s.trim().toLowerCase();return c?a.filter(u=>`${u.label} ${u.group}`.toLowerCase().includes(c)):a},[a,s]);return e(Ze,{children:n?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:e(te.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:c=>c.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:s,onInput:c=>i(c.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(c=>e("button",{type:"button",className:"tcp-btn w-full justify-between",onClick:()=>{c.onSelect(),t()},children:[e("span",{className:"inline-flex items-center gap-1.5",children:[e("i",{"data-lucide":"list"}),e("span",{children:c.label})]}),e("span",{className:"tcp-subtle text-xs",children:c.group})]},c.id)),l.length?null:e("p",{className:"tcp-subtle px-1 py-2",children:"No matching action."})]})]})]})}):null})}const vs=[["dashboard","Dashboard","home"],["chat","Chat","message-square"],["automations","Automations","bot"],["orchestrator","Orchestrator","sparkles"],["memory","Memory","database"],["feed","Live Feed","radio"],["settings","Settings","settings"],["agents","Routines","clock"],["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"]],no=vs.filter(([n])=>["dashboard","chat","automations","orchestrator","memory","feed","settings"].includes(n)),ws={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"}},xs=vs,ao=no,so=new Map([["agents","automations"],["packs","automations"],["teams","automations"],["swarm","orchestrator"],["failure-reporter","bug-monitor"]]),ro=new Set(xs.map(([n])=>n));function va(n,t="dashboard"){const a=so.get(String(n||"").trim());return a||(ro.has(n)?n:t)}function Da(n="dashboard"){const t=(window.location.hash||`#/${n}`).replace(/^#\//,"");return va(t.split("?")[0].split("/")[0].trim(),n)}function io(n){window.location.hash=`#/${n}`}function oo(){const[n,t]=y(()=>Da());ie(()=>{const s=()=>t(Da());return window.addEventListener("hashchange",s),()=>window.removeEventListener("hashchange",s)},[]);const a=Ee(s=>{const i=va(s);if(window.location.hash!==`#/${i}`){io(i);return}t(i)},[]);return{route:n,navigate:a}}const Ns=Ls({toast:()=>{}});function lo({children:n}){const[t,a]=y([]),s=Ee((l,c)=>{const u=Math.random().toString(36).slice(2);a(p=>[...p,{id:u,kind:l,text:c}].slice(-4)),window.setTimeout(()=>{a(p=>p.filter(w=>w.id!==u))},3500)},[]),i=V(()=>({toast:s}),[s]);return e(Ns.Provider,{value:i,children:[n,e("div",{className:"toasts","aria-live":"polite","aria-atomic":"true",children:e(Ze,{children:t.map(l=>e(te.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 co(){return Bs(Ns)}function an({title:n,subtitle:t,children:a,actions:s,className:i}){return e(Le,{title:n,subtitle:t,actions:s,className:i||"",children:a})}function Se({text:n,title:t,action:a}){return e(Yi,{text:n,title:t,action:a})}function kt(n){return JSON.stringify(n,null,2)}function sa(n,t){return Array.isArray(n)?n:Array.isArray(n?.[t])?n[t]:[]}function uo(n){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(Number(n||0))}function mo(n){const{api:t,client:a,navigate:s,providerStatus:i}=n,[l,c]=y(""),u=new Set(["workflow","bug_monitor_triage"]),p=j({queryKey:["dashboard","health"],queryFn:()=>t("/api/system/health"),refetchInterval:15e3}),w=j({queryKey:["dashboard","sessions"],queryFn:()=>a.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),M=j({queryKey:["dashboard","routines"],queryFn:()=>a.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),b=j({queryKey:["dashboard","swarm"],queryFn:()=>t("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),S=j({queryKey:["dashboard","workflow-context-runs"],queryFn:()=>t("/api/engine/context/runs?limit=12").catch(()=>({runs:[]})),refetchInterval:6e3}),q=j({queryKey:["dashboard","workflow-context-run",l],enabled:!!l,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(l)}`).catch(()=>({run:null}))}),T=j({queryKey:["dashboard","workflow-context-blackboard",l],enabled:!!l,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(l)}/blackboard`).catch(()=>({blackboard:null}))}),X=sa(w.data,"sessions"),z=sa(M.data,"routines"),J=sa(S.data,"runs").filter(E=>u.has(String(E?.run_type||"").trim().toLowerCase())),ne=!!(p.data?.engine?.ready||p.data?.engine?.healthy),G=String(b.data?.status||"unknown"),x=["planning","awaiting_approval","running","executing"].includes(G.toLowerCase()),O=J.filter(E=>["queued","planning","running","awaiting_approval"].includes(String(E?.status||"").trim().toLowerCase())),B=V(()=>[{label:"Recent sessions",value:X.length,tone:"info",helper:"Latest active conversation surfaces"},{label:"Automations",value:z.length,tone:"ok",helper:"Configured routines and schedules"},{label:"Swarm status",value:x?1:0,tone:x?"warn":"ghost",helper:G},{label:"Provider ready",value:i.ready?1:0,tone:i.ready?"ok":"warn",helper:i.ready?i.defaultModel:"Needs setup"},{label:"Workflow contexts",label:"Context runs",value:J.length,tone:O.length?"warn":"info",helper:O.length?`${O.length} active`:"Workflow + triage visibility"}],[O.length,i.defaultModel,i.ready,z.length,X.length,x,G,J.length]);return e(Mn,{className:"grid gap-4",children:[e(Le,{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(ae,{tone:ne?"ok":"warn",children:ne?"Engine healthy":"Engine checking"}),e(ae,{tone:i.ready?"ok":"warn",children:i.ready?i.defaultProvider:"Provider setup required"}),x?e(Jt,{tone:"live",text:`Swarm ${G}`}):e(ae,{tone:"ghost",children:["Swarm ",G]})]})]}),e("div",{className:"grid gap-3",children:e(Wt,{className:"justify-start",children:[e("button",{className:"tcp-btn-primary w-full sm:w-auto",onClick:()=>s("chat"),children:[e("i",{"data-lucide":"message-square"}),"Chat session"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>s("orchestrator"),children:[e("i",{"data-lucide":"sparkles"}),"Plan work"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>s("automations"),children:[e("i",{"data-lucide":"bot"}),"Automations"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>s("settings"),children:[e("i",{"data-lucide":"settings"}),"Configure runtime"]})]})})]}),e("div",{className:"mt-5",children:[e("div",{className:"dashboard-kpis",children:B.map(E=>e("div",{children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("span",{className:"dashboard-kpi-label",children:E.label}),e(ae,{tone:E.tone,children:E.helper})]}),e("strong",{children:e(zi,{value:E.value,format:uo})})]},E.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:ne?"100%":"45%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:"dashboard-bar-fill completed",style:{width:ne?"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:i.ready?"100%":"30%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${i.ready?"running":"queued"}`,style:{width:i.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:[z.length," routines"]})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${z.length?"scheduled":"manual"}`,style:{width:`${Math.min(100,Math.max(12,z.length*12))}%`}})})]})]})]})]}),e(In,{main:e(Le,{title:"Recent sessions",subtitle:"Latest conversations, ready to reopen.",children:e("div",{className:"grid gap-2",children:X.length?X.map(E=>e("button",{className:"tcp-list-item text-left",onClick:()=>s("chat"),children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"messages-square"}),String(E.title||E.id||"Session")]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(E.id||E.session_id||"")})]},String(E.id||E.session_id||Math.random()))):e(Se,{text:"Start a conversation to populate recent sessions here."})})}),aside:e("div",{className:"grid gap-4",children:[e(Le,{title:"Context visibility",subtitle:"Recent workflow and failure-triage context runs with their current projection state.",children:[e(Wt,{className:"mb-3",children:[e(ae,{tone:O.length?"warn":"info",children:[J.length," recent"]}),e("button",{className:"tcp-btn",onClick:()=>s("orchestrator"),children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]})]}),e("div",{className:"grid gap-2",children:J.length?J.slice(0,5).map(E=>e("button",{className:"tcp-list-item text-left",onClick:()=>c(String(E?.run_id||"").trim()),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:String(E?.objective||E?.run_id||"Context run")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e(ae,{tone:"ghost",children:String(E?.run_type||"context")}),e(ae,{tone:["failed","cancelled"].includes(String(E?.status||"").toLowerCase())?"err":["running","queued","planning"].includes(String(E?.status||"").toLowerCase())?"warn":"ok",children:String(E?.status||"unknown")})]})]}),e("div",{className:"tcp-subtle text-xs",children:String(E?.run_id||"")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Array.isArray(E?.tasks)?E.tasks.length:0," tasks ·"," ",Array.isArray(E?.steps)?E.steps.length:0," steps"]})]},String(E?.run_id||Math.random()))):e(Se,{text:"Workflow and failure-triage context runs will appear here once they execute."})})]}),e(Le,{title:"Automation snapshot",subtitle:"Schedules and run-ready routines.",children:[e(Wt,{className:"mb-3",children:[e(ae,{tone:"info",children:[z.length," loaded"]}),e("button",{className:"tcp-btn",onClick:()=>s("automations"),children:[e("i",{"data-lucide":"bot"}),"Manage"]})]}),e("div",{className:"grid gap-2",children:z.length?z.slice(0,4).map(E=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:String(E.name||E.id||"Routine")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(E.schedule||E.status||"manual")})]},String(E.id||E.routine_id||Math.random()))):e(Se,{text:"No routines are configured yet."})})]}),e(Le,{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: ",G]})]}),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:()=>s("memory"),children:"Open memory"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>s("feed"),children:"Open live feed"})]})]})]})})]})}),e(Hn,{open:!!l,onClose:()=>c(""),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(q.data?.run?.objective||l)}),e(ae,{tone:"info",children:String(q.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["type: ",String(q.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(T.data?.blackboard?.tasks)?T.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(T.data?.blackboard?.artifacts)?T.data.blackboard.artifacts.length:0]})]}),e("pre",{className:"tcp-code",children:kt({run:q.data?.run||null,blackboard:T.data?.blackboard||null})})]}):null})]})}const po={Activity:ii,Archive:ri,ArrowLeftToLine:si,ArrowUpCircle:ai,BadgeCheck:ni,Binary:ti,Bug:ei,BugPlay:Zr,Bot:Xr,BookOpen:Yr,Check:zr,ClipboardList:Vr,Clock:Gr,Clock3:Hr,Copy:Qr,CopyPlus:Wr,ExternalLink:Jr,Cpu:Kr,Database:jr,Download:Br,FileUp:Lr,Filter:Ur,FilterX:Dr,FlaskConical:Fr,FolderOpen:Or,History:Er,Home:Tr,Info:qr,KeyRound:Mr,Link:$r,LoaderCircle:Rr,List:Pr,LogOut:Ar,MessageCircle:Ir,MessageSquare:Cr,MessagesSquare:_r,Menu:Sr,MonitorCog:kr,Paperclip:Nr,Package:xr,PaintBucket:wr,Pencil:vr,Play:yr,PlugZap:br,Plus:fr,Pause:gr,Radio:hr,RefreshCw:pr,RotateCw:mr,Save:ur,Search:dr,Send:cr,Settings:lr,Settings2:or,ShieldAlert:ir,ShieldCheck:rr,SlidersHorizontal:sr,Sparkles:ar,Siren:nr,Share2:tr,Shield:er,Square:Zs,Trash2:Xs,TriangleAlert:Ys,X:zs,XCircle:Vs,Users:Gs,Workflow:Hs},ma=new Set;let pa=0;function ho(){pa=0;const n=[...ma];ma.clear();for(const t of n)Qs({icons:po,attrs:{width:"16",height:"16","stroke-width":"1.8"},...t?{root:t}:{}})}function dn(n){ma.add(n||null),!pa&&(pa=window.requestAnimationFrame(ho))}us.setOptions({gfm:!0,breaks:!0});function wa(n){const t=String(n||""),a=us.parse(t,{async:!1});return li.sanitize(a)}const ha="tcp.chat.session";function ks(n){return String(n?.id||n?.session_id||n?.sessionID||"").trim()}function go(n){const t=String(n?.title||n?.name||"").trim();if(t)return t;const a=ks(n);return a?`Session ${a.slice(0,8)}`:"Session"}function fo(n){return Array.isArray(n)?n:Array.isArray(n?.sessions)?n.sessions:[]}function bo(n){return String(n?.title||"").trim().toLowerCase().startsWith("__provider_test__")}function Ua(n){return fo(n).filter(t=>!bo(t)).map(t=>({id:ks(t),title:go(t),raw:t})).filter(t=>!!t.id)}async function yo(n,t){try{const a=await n.sessions.list({pageSize:50}),s=Ua(a);if(s.length>0)return s}catch{}try{const a=await t("/api/engine/session?page_size=50",{method:"GET"});return Ua(a)}catch{return[]}}function La(){try{return localStorage.getItem(ha)||""}catch{return""}}function vo(n){try{n?localStorage.setItem(ha,n):localStorage.removeItem(ha)}catch{}}function wo(n){return Array.isArray(n)?n.map(a=>a?typeof a=="string"?a:typeof a.text=="string"?a.text:typeof a.delta=="string"?a.delta:typeof a.content=="string"?a.content:"":"").filter(Boolean).join(`
|
|
3
|
-
`).trim():""}function xo(n){return String(n?.info?.role||n?.role||n?.message_role||n?.type||n?.author||"assistant").trim().toLowerCase()}function No(n){const t=wo(n?.parts);if(t)return t;const a=[n?.content,n?.text,n?.message,n?.delta,n?.body].map(i=>typeof i=="string"?i:"").find(i=>i.trim().length>0);if(a)return a.trim();const s=n?.content;if(Array.isArray(s)){const i=s.map(l=>l?typeof l=="string"?l:typeof l?.text=="string"?l.text:typeof l?.content=="string"?l.content:"":"").filter(Boolean);if(i.length)return i.join(`
|
|
4
|
-
`).trim()}return""}function ko(n,t){return n==="assistant"?t||"Assistant":n==="user"?"User":n==="system"?"System":n||"Assistant"}function So(n,t,a){const s=xo(n),i=No(n),l=s==="assistant"||s==="system";return{id:String(n?.id||n?.messageID||n?.message_id||n?.event_id||`${s}-${t}`).trim()||`${s}-${t}`,role:s,displayRole:ko(s,a),text:i,markdown:l}}function Ss(n,t){return(Array.isArray(n)?n:Array.isArray(n?.messages)?n.messages:[]).map((s,i)=>So(s,i,t))}const Ba=new Set(["tool.called","tool_call.started","session.tool_call"]),ja=new Set(["tool.result","tool_call.completed","tool_call.failed","session.tool_result"]),_o=new Set(["run.complete","run.completed","session.run.finished","session.run.completed"]),Co=new Set(["run.failed","session.run.failed","run.cancelled","run.canceled","session.run.cancelled","session.run.canceled"]);function _s(n){return String(n||"").trim().replace(/\s+/g," ").replace(/[<>]/g,"")}function mn(n){const t=n||{},a=t.call||t.toolCall||t.part||{};return _s(t.tool||t.name||t.toolName||t.tool_id||t.toolID||a.tool||a.name||a.toolName||"")}function Nn(n){const t=n||{},a=t.call||t.toolCall||t.part||{};return String(t.callID||t.toolCallID||t.tool_call_id||t.id||a.callID||a.toolCallID||a.tool_call_id||a.id||"").trim()}function ra(n,t=""){const a=n?.properties||{};return String(n?.runId||n?.runID||n?.run_id||a.runID||a.runId||a.run_id||a.run?.id||t).trim()}function Un(n){if(!n)return null;const t=n.request||n.approval||n.permission||{},a=String(n.id||n.requestID||n.requestId||n.approvalID||t.id||t.requestID||"").trim();return a?{id:a,tool:_s(n.tool||t.tool||t.name||"tool")||"tool",permission:String(n.permission||t.permission||"").trim(),pattern:String(n.pattern||t.pattern||"").trim(),sessionId:String(n.sessionId||n.sessionID||n.session_id||t.sessionId||t.sessionID||"").trim(),status:String(n.status||t.status||"").trim().toLowerCase()}:null}function Ka(n){const t=String(n||"").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 Io(n,t){const a=t&&typeof t=="object"?t:{},s=String(n||"").trim()||"pack.event",i=String(a.path||"").trim(),l=String(a.attachment_id||a.attachmentId||"").trim(),c=String(a.connector||"").trim(),u=String(a.channel_id||a.channelId||"").trim(),p=String(a.sender_id||a.senderId||"").trim(),w=String(a.name||"").trim(),M=String(a.version||"").trim(),b=String(a.error||"").trim(),S=[];w&&S.push(w),M&&S.push(M),i&&S.push(i),c&&S.push(c),u&&S.push(`channel=${u}`),p&&S.push(`sender=${p}`);const q=S.join(" · ");return{id:`${s}:${l||i||w||"event"}`,type:s,path:i,attachmentId:l,connector:c,channelId:u,senderId:p,error:b,summary:q||s,at:Date.now()}}const An=new Map;function Cs(n,t){return`${t?"cred":"anon"}:${n}`}function Ao(n,t=!0){const a=Cs(n,t),s=An.get(a);if(s&&!s.closed)return s;const i=new EventSource(n,{withCredentials:t}),l={source:i,listeners:new Set,errorListeners:new Set,refs:0,closed:!1};return i.onmessage=c=>{for(const u of[...l.listeners])try{u(c)}catch{}},i.onerror=c=>{for(const u of[...l.errorListeners])try{u(c)}catch{}i.readyState===EventSource.CLOSED&&(l.closed=!0,An.delete(a))},An.set(a,l),l}function xa(n,t,a={}){const s=a.withCredentials!==!1,i=Cs(n,s),l=Ao(n,s);return l.refs+=1,l.listeners.add(t),typeof a.onError=="function"&&l.errorListeners.add(a.onError),()=>{const c=An.get(i);c&&(c.listeners.delete(t),typeof a.onError=="function"&&c.errorListeners.delete(a.onError),c.refs=Math.max(0,c.refs-1),c.refs===0&&(c.closed=!0,c.source.close(),An.delete(i)))}}const Po="control-panel",Is="tandem_control_panel_chat_auto_approve_tools",Ro="tandem.automations.plannerSeed",$o={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 Ja(n=""){const t=String(n).toLowerCase().split(".").pop()||"";return $o[t]||"application/octet-stream"}function Mo(n="",t=""){if(!n||!t)return t||"";const a=String(n).replace(/[\\/]+$/,""),s=String(t).replace(/^[\\/]+/,"");return`${a}/${s}`}function qo(n){const t=Number(n||0);return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function ia(n,t){return!n||!t?!0:String(n).trim()===String(t).trim()}function To(n){const t=String(n||"").trim();return t!=="server.connected"&&t!=="engine.lifecycle.ready"}function Eo(n){return n==="completed"?"chat-tool-chip-ok":n==="failed"?"chat-tool-chip-failed":"chat-tool-chip-running"}function Oo(){try{return localStorage.getItem(Is)==="1"}catch{return!1}}function Fo(n){try{localStorage.setItem(Is,n?"1":"0")}catch{}}function Do(n){try{const t=String(n?.prompt||n?.goal||"").trim();if(!t)return;sessionStorage.setItem(Ro,JSON.stringify({prompt:t,plan_source:String(n?.plan_source||"chat_setup").trim()||"chat_setup"}))}catch{}}function rn(n){return n instanceof Error?n.message:String(n)}function Uo(n){return n.decision==="pass_through"?null:n.intent_kind==="provider_setup"?{title:"Provider setup",body:`Configure ${n.slots.provider_ids[0]||"a provider"} in Settings.`,cta:"Open Settings",actionType:"open_provider_setup",payload:n.proposed_action.payload||{}}:n.intent_kind==="integration_setup"?{title:"Tool connection",body:`Connect ${n.slots.integration_targets[0]||"the matching tool"} through MCP.`,cta:"Open MCP",actionType:"open_mcp_setup",payload:n.proposed_action.payload||{}}:n.intent_kind==="automation_create"?{title:"Automation setup",body:n.slots.goal||"Create an automation from this request.",cta:"Open Automations",actionType:"open_automations",payload:n.proposed_action.payload||{}}:{title:"Setup help",body:n.clarifier?.question||"Choose a setup path.",cta:"Open Settings",actionType:"open_provider_setup",payload:n.proposed_action.payload||{},clarifier:n.clarifier||void 0}}function Lo({client:n,api:t,toast:a,providerStatus:s,identity:i,navigate:l}){const c=Lt(),u=!!ds(),p=wt(null),w=wt(null),M=wt(null),b=wt(null),S=wt(null),q=wt(!0),T=wt(null),X=wt(null),[z,J]=y([]),[ne,G]=y(!1),[x,O]=y(La()),[B,E]=y([]),[D,F]=y(!1),[W,oe]=y(""),[xe,Ie]=y([]),[pe,Ne]=y([]),[fe,Oe]=y(!1),[se,I]=y(""),[P,ee]=y(!1),[ce,N]=y([]),[ue,be]=y(new Set),[Re,Me]=y([]),[Te,st]=y(new Set),[Ae,ht]=y([]),[gt,We]=y(new Set),[Qe,ft]=y(Oo()),[bt,He]=y(!1),[le,Be]=y([]),[dt,ye]=y(null),[Ke,St]=y(null),$t=V(()=>z.find(R=>R.id===x)?.title||"Chat",[x,z]);ie(()=>(q.current=!0,()=>{q.current=!1,S.current?.abort(),T.current&&window.clearTimeout(T.current),X.current&&window.clearTimeout(X.current)}),[]),ie(()=>{const h=p.current;h&&dn(h)},[z,xe,pe,Ae,ce,Re,B,ne,P,se]),ie(()=>{vo(x)},[x]),ie(()=>{const h=w.current;h&&(h.style.height="0px",h.style.height=`${Math.min(h.scrollHeight,180)}px`)},[W]),ie(()=>{const h=b.current;h&&(h.scrollTop=h.scrollHeight)},[B,se,P]);const Ye=Ee(async()=>{const h=await yo(n,t);q.current&&(J(h),O(R=>{if(R&&h.some($=>$.id===R))return R;const v=La();return v&&h.some($=>$.id===v)?v:h[0]?.id||""}))},[t,n]),ge=Ee(async()=>{const h=String(s.defaultProvider||"").trim(),R=String(s.defaultModel||"").trim();if(h&&R)return{providerID:h,modelID:R};try{const v=await n.providers.config(),$=String(v?.default||"").trim(),A=String(v?.providers?.[$]?.defaultModel||"").trim();if($&&A)return{providerID:$,modelID:A}}catch{}return null},[n.providers,s.defaultModel,s.defaultProvider]),je=Ee(async()=>{const h=await ge(),R={title:`Chat ${new Date().toLocaleTimeString()}`};h&&(R.provider=h.providerID,R.model=h.modelID);const v=await n.sessions.create(R),$=String(v||"").trim();if(!$)throw new Error("Failed to create session.");return O($),await Ye(),$},[n.sessions,Ye,ge]),Ge=Ee(h=>{const R=Ss(h,i.botName||"Assistant");E(R)},[i.botName]),De=Ee(async()=>{if(!x){E([]);return}F(!0);try{const h=await n.sessions.messages(x).catch(()=>({messages:[]}));if(!q.current)return;Ge(h)}finally{q.current&&F(!1)}},[n.sessions,Ge,x]),ut=Ee(()=>{N([]),be(new Set)},[]),g=Ee(()=>{Me([]),st(new Set)},[]),k=Ee((h,R,v="")=>{const $=String(h||"").trim();if(!$)return;let A=!0;v&&(be(H=>{if(H.has(v))return A=!1,H;const Ce=new Set(H);return Ce.add(v),Ce.size>1e3?new Set([v]):Ce}),!A)||N(H=>[{id:`${$}:${R}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:$,status:R,at:Date.now()},...H].slice(0,80))},[]),ve=Ee((h,R)=>{const v=Io(h,R);if(!String(v.type).toLowerCase().startsWith("pack."))return;let A=!0;st(H=>{if(H.has(v.id))return A=!1,H;const Ce=new Set(H);return Ce.add(v.id),Ce.size>400?new Set([v.id]):Ce}),A&&Me(H=>[v,...H].slice(0,80))},[]),ke=Ee(h=>{Ka(h?.status||"")&&ht(R=>{const v=R.findIndex($=>$.id===h.id);if(v>=0){const $=[...R];return $[v]={...$[v],...h},$}return[h,...R]})},[]),o=Ee(h=>{ht(R=>R.filter(v=>v.id!==h))},[]),d=Ee(async()=>{const h=await n.permissions.list().catch(()=>({requests:[]})),v=(Array.isArray(h?.requests)?h.requests:[]).map($=>Un($)).filter($=>!!$).filter($=>ia($.sessionId,x)).filter($=>Ka($.status));q.current&&ht(v.slice(0,80))},[n.permissions,x]),C=Ee(async(h,R,v=!1)=>{if(!(!h||gt.has(h))){We(A=>{const H=new Set(A);return H.add(h),H});try{await n.permissions.reply(h,R),o(h),v||a("ok",`Permission ${R==="deny"?"denied":"approved"} (${h}).`)}catch(A){v||a("err",rn(A))}finally{We(A=>{const H=new Set(A);return H.delete(h),H}),d()}}},[n.permissions,gt,d,o,a]),Q=Ee(async()=>{if(!(!Qe||bt||Ae.length===0)){He(!0);try{for(const h of[...Ae])await C(h.id,"always",!0)}finally{q.current&&He(!1)}}},[Qe,bt,Ae,C]),qe=Ee(h=>(Array.isArray(h)?h:Array.isArray(h?.tools)?h.tools:[]).map(v=>{if(typeof v=="string")return v;const $=v||{};return String($.name||$.id||$.tool||"").trim()}).filter(Boolean),[]),Ve=Ee(async()=>{try{const h=await n.listTools?.().catch(()=>null);let R=qe(h||[]);if(!R.length){const v=await t("/api/engine/tool",{method:"GET"}).catch(()=>[]);R=qe(v||[])}if(q.current){const v=[...new Set(R)].sort(($,A)=>$.localeCompare(A));Be(v)}}catch{q.current&&Be([])}},[t,n,qe]),nt=Ee(h=>new Promise((R,v)=>{const $=`${Date.now()}-${Math.random().toString(16).slice(2)}`;Ne(H=>[...H,{id:$,name:h.name,progress:0,error:""}]);const A=new XMLHttpRequest;A.open("POST",`/api/files/upload?dir=${encodeURIComponent(Po)}`),A.withCredentials=!0,A.responseType="json",A.setRequestHeader("x-file-name",encodeURIComponent(h.name)),A.upload.onprogress=H=>{if(!H.lengthComputable)return;const Ce=H.loaded/H.total*100;Ne(Ue=>Ue.map(Je=>Je.id===$?{...Je,progress:Ce}:Je))},A.onerror=()=>{Ne(H=>H.map(Ce=>Ce.id===$?{...Ce,error:"Network error"}:Ce)),window.setTimeout(()=>{Ne(H=>H.filter(Ce=>Ce.id!==$))},1200),v(new Error(`Upload failed: ${h.name}`))},A.onload=()=>{const H=A.response||{};if(A.status<200||A.status>=300||H?.ok===!1){const Ce=String(H?.error||`Upload failed (${A.status})`);Ne(Ue=>Ue.map(Je=>Je.id===$?{...Je,error:Ce}:Je)),window.setTimeout(()=>{Ne(Ue=>Ue.filter(Je=>Je.id!==$))},1600),v(new Error(Ce));return}Ne(Ce=>Ce.filter(Ue=>Ue.id!==$)),R(H)},A.send(h)}),[]),Et=Ee(async h=>{const R=[...h||[]];if(!R.length)return;let v=0;for(const $ of R)try{const A=await nt($);Ie(H=>[{name:String(A?.name||$.name),path:String(A?.path||$.name),size:Number(A?.size||$.size||0),mime:$.type||Ja(String(A?.name||$.name)),url:String(A?.absPath||Mo(A?.root,A?.path)||A?.path||$.name)},...H]),v+=1}catch(A){a("err",rn(A))}v>0&&a("ok",`Uploaded ${v} file${v===1?"":"s"}.`)},[a,nt]),Zt=Ee(async h=>{if(await n.sessions.delete(h),J(R=>R.filter(v=>v.id!==h)),ye(null),a("ok","Session deleted."),x===h){const R=z.find(v=>v.id!==h)?.id||"";if(R)O(R);else{const v=await je();O(v)}}},[n.sessions,je,x,z,a]),ot=Ee((h,R)=>{const v=String(h||"").trim();if(!v)return;const $=R>0?`
|
|
5
|
-
|
|
6
|
-
${R} attachment${R===1?"":"s"}`:"";E(A=>[...A,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",displayRole:"User",text:`${v}${$}`,markdown:!1}])},[]),Ht=Ee(async()=>{if(fe)return;const h=W.trim(),R=[...xe],v=h||(R.length?"Please analyze the attached file(s).":"");if(v){try{const $=await t("/api/engine/setup/understand",{method:"POST",body:JSON.stringify({surface:"control_panel_chat",session_id:x||void 0,text:v,channel:null,trigger:{source:"direct_message",is_direct_message:!0,was_explicitly_mentioned:!1,is_reply_to_bot:!1},scope:{kind:"direct",id:x||"control-panel-chat"}})});if($.decision!=="pass_through"){const A=Uo($);if(A){St(A),oe("");return}}}catch{}oe(""),Oe(!0),ot(v,R.length);try{let $=x;if($||($=await je()),!$)throw new Error("No active session.");const A=await ge();if(!A)throw new Error("No default provider/model configured. Set it in Settings before sending chat.");const H=R.map(we=>({type:"file",mime:we.mime||Ja(we.name||we.path),filename:we.name||we.path||"attachment",url:we.url||we.path}));H.push({type:"text",text:v});const Ce=async()=>{const we=await fetch(`/api/engine/session/${encodeURIComponent($)}/run`,{method:"GET",credentials:"include"});if(!we.ok)return"";const L=await we.json().catch(()=>({}));return L?.active?.runID||L?.active?.runId||L?.active?.run_id||""},Ue=async()=>{const we=await Ce().catch(()=>"");we&&await fetch(`/api/engine/session/${encodeURIComponent($)}/run/${encodeURIComponent(we)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent($)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{});for(let L=0;L<50;L+=1){if(!await Ce().catch(()=>""))return!0;await new Promise(he=>window.setTimeout(he,200))}return!1},Je=async()=>fetch(`/api/engine/session/${encodeURIComponent($)}/prompt_async?return=run`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({parts:H,model:{providerID:A.providerID,modelID:A.modelID}})});let rt=await Je(),ze="";if(rt.status===409){if(!await Ue())throw new Error("Session has a stuck active run. Cancel it and retry.");if(rt=await Je(),rt.ok){const L=await rt.json().catch(()=>({}));ze=L?.runID||L?.runId||L?.run_id||""}else{if(rt.status===409)throw new Error("Session is still busy with another run. Retry in a moment.");{const L=await rt.text().catch(()=>"");throw new Error(`prompt_async retry failed (${rt.status}): ${L}`)}}}else if(rt.ok){const we=await rt.json().catch(()=>({}));ze=we?.runID||we?.runId||we?.run_id||""}else{const we=await rt.text().catch(()=>"");throw new Error(`prompt_async failed (${rt.status}): ${we}`)}if(!ze)throw new Error("No run ID returned from engine.");R.length&&Ie([]),I(""),ee(!0);const et=new AbortController;S.current?.abort(),S.current=et;let at=!1,qt=!1,Bt="";const Ot=3e4,Ft=18e4,_t=async(we,L)=>{const lt=Date.now();for(;Date.now()-lt<L;){const he=await Ce().catch(()=>we);if(await De(),!he||he!==we)return!0;await new Promise(tt=>window.setTimeout(tt,350))}return!1},Tt=()=>{T.current&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{qt=!0,Bt="no-events-timeout",et.abort("no-events-timeout")},Ot)};Tt(),X.current&&window.clearTimeout(X.current),X.current=window.setTimeout(()=>{qt=!0,Bt="max-stream-window",et.abort("max-stream-window")},Ft);try{for await(const we of n.stream($,ze,{signal:et.signal})){const L=we;if(To(L.type)&&Tt(),L.type==="approval.requested"||L.type==="permission.request"||L.type==="permission.asked"){const he=Un(L.properties||{});he&&ia(he.sessionId,$)?(ke(he),Q()):d()}if(L.type==="approval.resolved"||L.type==="permission.resolved"||L.type==="permission.replied"){const he=Un(L.properties||{});he?.id&&o(he.id),d()}String(L.type||"").toLowerCase().startsWith("pack.")&&ve(L.type,L.properties||{});const lt=ra(L);if(!(lt&<!==ze)){if(L.type==="session.response"){const he=String(L.properties?.delta||"");if(!he)continue;at=!0,ee(!1),I(tt=>`${tt}${he}`)}if(Ba.has(L.type)){const he=mn(L.properties)||"tool",tt=Nn(L.properties);k(he,"started",`${tt||lt||ze}:${he}:started`)}if(ja.has(L.type)){const he=mn(L.properties)||"tool",tt=Nn(L.properties),yt=String(L.properties?.status||L.properties?.state||"").toLowerCase(),jt=L.type==="tool_call.failed"||yt.includes("fail")||yt.includes("error")||!!L.properties?.error;k(he,jt?"failed":"completed",`${tt||lt||ze}:${he}:${jt?"failed":"completed"}`)}if(L.type==="message.part.updated"){const he=L.properties?.part||{},tt=String(he.type||"").trim().toLowerCase().replace(/_/g,"-"),yt=mn(he)||mn(L.properties),jt=Nn(he),ct=he?.state,Ct=String((ct&&typeof ct=="object"?ct.status:ct)||he.status||"").trim().toLowerCase(),en=!!he.error||!!(ct&&typeof ct=="object"&&ct.error)||Ct.includes("fail")||Ct.includes("error")||Ct.includes("deny")||Ct.includes("reject")||Ct.includes("cancel"),bn=!!he.result||!!he.output||!!(ct&&typeof ct=="object"&&(ct.output||ct.result))||Ct.includes("done")||Ct.includes("complete")||Ct.includes("success");if(yt&&(tt==="tool"||tt==="tool-invocation")){const sn=en?"failed":bn?"completed":"started";k(yt,sn,`${jt||lt||ze}:${yt}:${sn}`)}yt&&tt==="tool-result"&&k(yt,en?"failed":"completed",`${jt||lt||ze}:${yt}:${en?"failed":"completed"}`)}if(Co.has(L.type))throw new Error(String(L.properties?.error||"Run failed."));if((L.type==="session.updated"||L.type==="session.status")&&String(L.properties?.status||"").toLowerCase()==="idle"||_o.has(L.type))break}}}catch(we){const L=String(we?.message||we||"").toLowerCase();if(!(qt||L.includes("abort")||L.includes("terminated")||L.includes("networkerror")))throw we}finally{T.current&&window.clearTimeout(T.current),X.current&&window.clearTimeout(X.current)}if(qt){const we=await _t(ze,45e3);if(await De(),!we)throw new Error("Run stream timed out and the run is still active. Check logs and retry.")}if(at||ee(!0),await De(),await new Promise(we=>window.setTimeout(we,180)),await De(),await new Promise(we=>window.setTimeout(we,220)),await De(),!at&&await Ce().catch(()=>"")===ze)if(await _t(ze,3e4))await De();else throw new Error(`Run ${ze} is still active without a final response (${Bt||"stream-ended"}).`);I(""),ee(!1),await Ye(),await c.invalidateQueries({queryKey:["chat"]}).catch(()=>{})}catch($){const A=rn($),H=A.includes("no-events-timeout")||A.includes("max-stream-window")||A.includes("AbortError")||A.toLowerCase().includes("terminated")?"Run stream timed out before events were received. Check engine/provider logs and retry.":A;a("err",H),await De()}finally{q.current&&(Oe(!1),ee(!1))}}},[t,ot,Q,n,je,W,c,ve,k,De,d,Ye,o,ge,x,fe,a,xe,ke]);ie(()=>{Ye(),Ve();const h=async()=>{const v=await je().catch(()=>"");v&&O(v),G(!1)};window.addEventListener("tcp:new-chat",h);const R=window.setInterval(()=>{Ye()},8e3);return()=>{window.removeEventListener("tcp:new-chat",h),window.clearInterval(R)}},[je,Ve,Ye]),ie(()=>{x&&(S.current?.abort(),G(!1),ut(),g(),d(),De())},[De,d,g,ut,x]),ie(()=>{x||E([])},[x]),ie(()=>{!x&&z.length===0&&je().catch(()=>{})},[je,x,z.length]),ie(()=>{Fo(Qe),Qe&&Q()},[Qe,Q]),ie(()=>{const h=window.setInterval(()=>{x&&d()},2500);return()=>window.clearInterval(h)},[d,x]),ie(()=>{const h=xa("/api/global/event",R=>{let v=null;try{v=JSON.parse(String(R.data||"{}"))}catch{return}const $=String(v?.type||"").trim();if(!$)return;const A=v?.properties||{},H=Un(A);if(H&&ia(H.sessionId,x)&&(($==="approval.requested"||$==="permission.request"||$==="permission.asked")&&ke(H),($==="approval.resolved"||$==="permission.resolved"||$==="permission.replied")&&o(H.id)),$.toLowerCase().startsWith("pack.")&&ve($,A),Ba.has($)){const Ce=mn(A)||"tool",Ue=Nn(A),Je=ra(v,"global");k(Ce,"started",`${Ue||Je}:${Ce}:started`)}if(ja.has($)){const Ce=mn(A)||"tool",Ue=Nn(A),Je=ra(v,"global"),rt=String(A?.status||A?.state||"").toLowerCase(),ze=$==="tool_call.failed"||rt.includes("fail")||!!A?.error;k(Ce,ze?"failed":"completed",`${Ue||Je}:${Ce}:${ze?"failed":"completed"}`)}},{withCredentials:!0});return()=>h()},[ve,k,o,x,ke]);const Mt=xe.length;return e("div",{ref:p,className:"chat-layout chat-layout-fill min-w-0 min-h-0 h-full flex-1",children:[e(te.aside,{className:`chat-sessions-panel ${ne?"open":""}`,initial:!1,animate:u?{x:ne?0:"-104%"}:{x:ne?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:()=>{je().catch(h=>a("err",rn(h))),G(!1)},children:[e("i",{"data-lucide":"plus"}),"New"]}),e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{Ye()},children:e("i",{"data-lucide":"refresh-cw"})})]})]}),e("div",{className:"chat-session-list",children:[e(Ze,{children:z.map(h=>e(te.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 ${h.id===x?"active":""}`,title:h.id,onClick:()=>{O(h.id),G(!1)},children:e("span",{className:"block truncate",children:h.title})}),e("button",{type:"button",className:"chat-session-del",title:"Delete session",onClick:()=>ye({id:h.id,title:h.title}),children:e("i",{"data-lucide":"trash-2"})})]},h.id))}),z.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No sessions yet."})]})]}),e(Ze,{children:ne?e(te.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:()=>G(!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:()=>G(h=>!h),children:e("i",{"data-lucide":"history"})}),e("div",{className:"chat-main-dot"}),e("h3",{className:"tcp-title chat-main-title",children:$t}),le.length?e("span",{className:"chat-main-tools",children:[le.length," tools"]}):null]}),Ke?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:Ke.title}),e("div",{className:"tcp-subtle text-sm",children:Ke.body})]}),e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>St(null),children:"Dismiss"})]}),Ke.clarifier?e("div",{className:"mb-2 flex flex-wrap gap-2",children:Ke.clarifier.options.map(h=>e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>St({title:h.id==="provider_setup"?"Provider setup":h.id==="integration_setup"?"Tool connection":"Automation setup",body:h.id==="provider_setup"?"Open Settings to configure a provider.":h.id==="integration_setup"?"Open MCP to connect the tool you need.":"Open Automations to build the workflow.",cta:h.id==="provider_setup"?"Open Settings":h.id==="integration_setup"?"Open MCP":"Open Automations",actionType:h.id==="provider_setup"?"open_provider_setup":h.id==="integration_setup"?"open_mcp_setup":"open_automations",payload:Ke.payload}),children:h.label},h.id))}):null,e("button",{type:"button",className:"tcp-btn",onClick:()=>{Ke.actionType==="open_provider_setup"?l("settings"):Ke.actionType==="open_mcp_setup"?l("mcp"):Ke.actionType==="open_automations"&&(Do(Ke.payload),l("automations"))},children:Ke.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:[D&&!B.length?e("p",{className:"chat-rail-empty",children:"Loading messages..."}):null,!D&&!B.length&&!P&&!se?e("p",{className:"chat-rail-empty",children:"No messages yet. Send a prompt to start."}):null,e(Ze,{initial:!1,children:B.map(h=>{const R=h.role==="assistant"||h.role==="system",v=R?"assistant":"user";return e(te.article,{className:`chat-msg ${v}`,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:R?e("span",{className:"inline-flex items-center gap-2",children:[i.botAvatarUrl?e("img",{src:i.botAvatarUrl,alt:i.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:h.displayRole})]}):h.displayRole}),h.markdown?e("div",{className:"tcp-markdown tcp-markdown-ai",dangerouslySetInnerHTML:{__html:wa(h.text||"")}}):e("pre",{className:"chat-msg-pre",children:h.text})]},h.id)})}),P||se?e("article",{className:"chat-msg assistant",children:[e("div",{className:"chat-msg-role",children:e("span",{className:"inline-flex items-center gap-2",children:[i.botAvatarUrl?e("img",{src:i.botAvatarUrl,alt:i.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:i.botName||"Assistant"})]})}),P&&!se?e("div",{className:"tcp-thinking","aria-live":"polite",children:[e("span",{children:"Thinking"}),e("i",{}),e("i",{}),e("i",{})]}):null,se?e("pre",{className:"chat-msg-pre",children:se}):null]}):null]}),e("div",{className:"chat-composer shrink-0",children:[e("div",{className:`chat-attach-row mb-2 ${Mt?"":"hidden"}`,children:[e("span",{className:"tcp-subtle",children:[Mt," attached"]}),e("div",{className:"chat-files-line",children:xe.map((h,R)=>e("span",{className:"chat-file-pill min-w-0",children:[e("span",{className:"chat-file-pill-name",title:h.path,children:h.path}),e("span",{className:"chat-file-pill-size",children:qo(h.size)}),e("button",{type:"button",className:"chat-file-pill-btn chat-file-pill-btn-danger",title:"Remove from list",onClick:()=>Ie(v=>v.filter(($,A)=>A!==R)),children:e("i",{"data-lucide":"x"})})]},`${h.path}-${R}`))})]}),pe.length?e("div",{className:"mb-2 grid gap-1.5",children:pe.map(h=>{const R=Math.max(0,Math.min(100,Number(h.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:h.name}),e("span",{className:h.error?"chat-upload-meta-error":"chat-upload-meta",children:h.error||`${R.toFixed(0)}%`})]}),e("div",{className:"chat-upload-bar",children:e("div",{className:"chat-upload-bar-fill",style:{width:`${R}%`}})})]},h.id)})}):null,e("div",{className:"chat-input-wrap",children:[e("input",{ref:M,type:"file",className:"hidden",multiple:!0,onChange:h=>{Et(h.target.files),h.target.value=""}}),e("button",{type:"button",className:"chat-icon-btn chat-icon-btn-inner",title:"Attach files",onClick:()=>M.current?.click(),children:e("i",{"data-lucide":"paperclip"})}),e("textarea",{ref:w,rows:1,value:W,className:"tcp-input chat-input-with-clip chat-input-modern resize-none",placeholder:"Ask anything... (Enter to send, Shift+Enter newline)",onInput:h=>oe(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),Ht())}}),e("button",{type:"button",className:"chat-send-btn",title:"Send",disabled:fe,onClick:()=>{Ht()},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:le.length})]}),e("div",{className:"chat-tools-list",children:le.length?le.slice(0,32).map(h=>e("button",{type:"button",className:"chat-tool-pill",title:`Insert ${h}`,onClick:()=>{oe(R=>R.trim()?`${R} ${h}`:h),w.current?.focus()},children:h},h)):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 h=Ae.map(v=>v.id).filter(Boolean);if(!h.length)return;for(const v of h)await C(v,"once",!0);await d();const R=h.filter(v=>Ae.some($=>String($.id||"").trim()===v)).length;R>0?a("warn",`${R} request${R===1?"":"s"} still pending (likely stale/expired).`):a("ok",`Approved ${h.length} pending request${h.length===1?"":"s"}.`)},children:"Approve all"}),e("label",{className:"chat-auto-approve-label",children:[e("input",{type:"checkbox",className:"chat-auto-approve-checkbox",checked:Qe,onChange:h=>ft(h.target.checked)}),"Auto"]})]}),e("div",{className:"chat-tools-activity",children:Ae.length?Ae.slice(0,20).map(h=>{const R=gt.has(h.id),v=[h.permission,h.pattern].filter(Boolean).join(" ");return e("article",{className:"chat-pack-event-card",children:[e("div",{className:"chat-pack-event-title truncate",title:h.id,children:h.tool}),e("div",{className:"chat-pack-event-summary mt-0.5",children:v||h.id}),e("div",{className:"mt-1 flex gap-1",children:[e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:R,onClick:()=>{C(h.id,"once")},children:"Allow"}),e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:R,onClick:()=>{C(h.id,"always")},children:"Always"}),e("button",{className:"tcp-btn-danger h-6 px-1.5 text-[10px]",disabled:R,onClick:()=>{C(h.id,"deny")},children:"Deny"})]})]},h.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:Re.length}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:()=>{g()},children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]})]}),e("div",{className:"chat-tools-activity",children:Re.length?Re.slice(0,20).map(h=>e(te.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:h.type,children:h.type}),e("span",{className:"chat-pack-event-time",children:new Date(h.at).toLocaleTimeString()})]}),e("div",{className:"chat-pack-event-summary mt-0.5",children:h.summary}),h.error?e("div",{className:"chat-pack-event-error mt-1",children:h.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"]}),h.path?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const R=await t("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:h.path,source:{kind:"control_panel_chat",event:"pack.detected"}})});a("ok",`Installed ${R?.installed?.name||"pack"} ${R?.installed?.version||""}`.trim())}catch(R){a("err",`Install failed: ${rn(R)}`)}},children:[e("i",{"data-lucide":"download"}),"Install path"]}):null,h.path&&h.attachmentId?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const R=await t("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:h.attachmentId,path:h.path,connector:h.connector||void 0,channel_id:h.channelId||void 0,sender_id:h.senderId||void 0})});a("ok",`Installed ${R?.installed?.name||"pack"} ${R?.installed?.version||""}`.trim())}catch(R){a("err",`Install failed: ${rn(R)}`)}},children:[e("i",{"data-lucide":"paperclip"}),"Install attach"]}):null]})]},`${h.id}-${h.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:ce.length?ce.slice(0,24).map(h=>e("div",{className:`chat-tool-chip ${Eo(h.status)}`,children:[h.tool,": ",h.status]},h.id)):e("p",{className:"chat-rail-empty",children:"No tool events yet."})})]})]})]}),e(Ze,{children:dt?e(te.div,{className:"tcp-confirm-overlay",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>ye(null),children:e(te.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:h=>h.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:dt.title})," and all its messages."]}),e("div",{className:"tcp-confirm-actions",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>ye(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{type:"button",className:"tcp-btn-danger",onClick:()=>{Zt(dt.id).catch(h=>a("err",rn(h)))},children:[e("i",{"data-lucide":"trash-2"}),"Delete session"]})]})]})}):null})]})}function gn(n,t,a={}){ie(()=>{if(!(!a.enabled||!n))return xa(n,t,{withCredentials:a.withCredentials})},[t,a.enabled,a.withCredentials,n])}const Gn=[{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:""}],Na=[{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"}],Wa=["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"],Qa="tandem.automations.plannerSeed";function Vt(n,t){return Array.isArray(n)?n:Array.isArray(n?.[t])?n[t]:[]}function As(n){return Array.isArray(n?.servers)?n.servers.map(t=>{const a=String(t?.name||"").trim();return a?{name:a,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(t=>!!t).sort((t,a)=>t.name.localeCompare(a.name)):n&&typeof n=="object"?Object.entries(n).map(([t,a])=>{const s=String(t||"").trim();if(!s)return null;const i=a&&typeof a=="object"?a:{};return{name:s,connected:!!i.connected,enabled:i.enabled!==!1}}).filter(t=>!!t).sort((t,a)=>t.name.localeCompare(a.name)):[]}function Bo(n){const t=String(n.cron||"").trim();if(t)return{cron:{expression:t}};const a=Gn.find(s=>s.label===n.schedulePreset);return a?.intervalSeconds?{interval_seconds:{seconds:a.intervalSeconds}}:a?.cron?{cron:{expression:a.cron}}:{type:"manual"}}function jo(n){const t=String(n?.cron?.expression||n?.cron_expression||"").trim();if(t)return t;const a=Number(n?.interval_seconds?.seconds);return Number.isFinite(a)&&a>0?a%3600===0?`Every ${a/3600}h`:a%60===0?`Every ${a/60}m`:`Every ${a}s`:"manual"}function Ps(n){const t=String(n?.type||"").trim().toLowerCase();if(t==="cron")return String(n?.cron_expression||n?.cronExpression||"cron");if(t==="interval"){const a=Number(n?.interval_seconds||n?.intervalSeconds||0);return!Number.isFinite(a)||a<=0?"interval":a%3600===0?`Every ${a/3600}h`:a%60===0?`Every ${a/60}m`:`Every ${a}s`}return"manual"}function Sn(n){const t=String(n||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Kn(n,t){const a=String(n||"").trim(),s=String(t||"").trim();return!a&&!s?"":a?s?"":"Planner model is required when a planner provider is set.":"Planner model provider is required when a planner model is set."}function oa(n,t){const a=String(n||"").trim(),s=String(t||"").trim();return!a&&!s?"":a?s?"":"Model is required when a provider is set.":"Model provider is required when a model is set."}function Ko(n){let t;const a=String(n.roleModelsJson||"").trim();if(a)try{const u=JSON.parse(a);u&&typeof u=="object"&&!Array.isArray(u)&&(t=u)}catch{t=void 0}const s=String(n.plannerModelProvider||"").trim(),i=String(n.plannerModelId||"").trim();s&&i&&(t={...t||{}},t.planner={provider_id:s,model_id:i});const l=n.mode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(n.maxAgents||"4"),10)||4)):1,c={execution_mode:n.mode,max_parallel_agents:l};return String(n.modelProvider||"").trim()&&(c.model_provider=String(n.modelProvider).trim()),String(n.modelId||"").trim()&&(c.model_id=String(n.modelId).trim()),t&&Object.keys(t).length&&(c.role_models=t),c}function Jo(n){const t=String(n||"").trim();if(!t)return"";try{const a=JSON.parse(t);return!a||typeof a!="object"||Array.isArray(a)?"Role model overrides must be a JSON object.":""}catch{return"Role model overrides must be valid JSON."}}function Rs(n){const t=String(n?.type||"").trim().toLowerCase(),a=String(n?.cron?.expression||n?.cron_expression||n?.cron||"").trim(),s=Number(n?.interval_seconds?.seconds||n?.interval_seconds||n?.intervalSeconds||3600),i=Number.isFinite(s)&&s>0?Math.round(s):3600;return{scheduleKind:t==="manual"?"manual":a?"cron":"interval",cronExpression:a,intervalSeconds:i}}function Wo(n){let t="",a=!1;for(const s of String(n||"").trim())/^[a-z0-9]$/i.test(s)?(t+=s.toLowerCase(),a=!1):a||(t+="_",a=!0);return t.replace(/^_+|_+$/g,"")||"mcp"}function Qo(n){const t=new Set,a=[];for(const s of n){const i=String(s||"").trim();!i||t.has(i)||(t.add(i),a.push(i))}return a}function Ho(n){return Qo(["read","websearch","webfetch","webfetch_html",...n.map(t=>`mcp.${Wo(t)}.*`)])}function Go(n){const t=n?.metadata?.operator_preferences||n?.metadata?.operatorPreferences;if(t&&typeof t=="object")return t;const a=Array.isArray(n?.agents)?n.agents[0]:null,s=a?.model_policy?.default_model||a?.modelPolicy?.defaultModel||null,i=a?.model_policy?.role_models||a?.modelPolicy?.roleModels||null,l={};return(s?.provider_id||s?.providerId)&&(l.model_provider=s.provider_id||s.providerId),(s?.model_id||s?.modelId)&&(l.model_id=s.model_id||s.modelId),i&&typeof i=="object"&&(l.role_models=i),(n?.execution?.max_parallel_agents||n?.execution?.maxParallelAgents)&&(l.max_parallel_agents=n.execution.max_parallel_agents||n.execution.maxParallelAgents),l}function Vo(n){const t=String(n?.automation_id||n?.automationId||n?.id||"").trim();if(!t)return null;const a=Rs(n?.schedule),s=Go(n),i=s?.role_models?.planner||s?.roleModels?.planner||{},l=Number(s?.max_parallel_agents??s?.maxParallelAgents??n?.execution?.max_parallel_agents??n?.execution?.maxParallelAgents??1),c=String(s?.execution_mode||s?.executionMode||"").trim(),u=Array.isArray(n?.metadata?.allowed_mcp_servers)?n.metadata.allowed_mcp_servers:Array.isArray(n?.agents?.[0]?.mcp_policy?.allowed_servers)?n.agents[0].mcp_policy.allowed_servers:[];return{automationId:t,name:String(n?.name||t).trim(),description:String(n?.description||"").trim(),scheduleKind:a.scheduleKind,cronExpression:a.cronExpression,intervalSeconds:String(a.intervalSeconds),workspaceRoot:String(n?.workspace_root||n?.workspaceRoot||n?.metadata?.workspace_root||"").trim(),executionMode:c==="single"||c==="swarm"||c==="team"?c:l>1?"swarm":"team",maxParallelAgents:String(Number.isFinite(l)&&l>0?Math.round(l):1),modelProvider:String(s?.model_provider||s?.modelProvider||"").trim(),modelId:String(s?.model_id||s?.modelId||"").trim(),plannerModelProvider:String(i?.provider_id||i?.providerId||"").trim(),plannerModelId:String(i?.model_id||i?.modelId||"").trim(),selectedMcpServers:u.map(p=>String(p||"").trim()).filter(Boolean)}}function zo(n){return n.scheduleKind==="manual"?{type:"manual",timezone:"UTC",misfire_policy:"run_once"}:n.scheduleKind==="cron"?{type:"cron",cron_expression:String(n.cronExpression||"").trim(),timezone:"UTC",misfire_policy:"run_once"}:{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(n.intervalSeconds||"3600"),10)||3600),timezone:"UTC",misfire_policy:"run_once"}}function Yo(n){const t={execution_mode:n.executionMode,max_parallel_agents:n.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(n.maxParallelAgents||"4"),10)||4)):1},a=String(n.modelProvider||"").trim(),s=String(n.modelId||"").trim();a&&(t.model_provider=a),s&&(t.model_id=s);const i=String(n.plannerModelProvider||"").trim(),l=String(n.plannerModelId||"").trim();return i&&l&&(t.role_models={planner:{provider_id:i,model_id:l}}),t}function Xo(n){const t={};return n.model_provider&&n.model_id&&(t.default_model={provider_id:n.model_provider,model_id:n.model_id}),n.role_models&&typeof n.role_models=="object"&&(t.role_models=n.role_models),Object.keys(t).length?t:null}function Ha(n){const t=String(n||"").trim().toLowerCase();return["queued","running","in_progress","executing","pending_approval","awaiting_approval"].includes(t)}function Ga(n){const t=Number(n?.started_at_ms||n?.fired_at_ms||n?.created_at_ms||0);if(!Number.isFinite(t)||t<=0)return"time unavailable";const a=Date.now()-t,s=Math.max(0,Math.floor(a/1e3));return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:`${Math.floor(s/3600)}h`}function Zo(n,t){const a=[],s=String(n?.status||"").trim().toLowerCase();return(s==="pending_approval"||s==="awaiting_approval")&&a.push("Run is waiting for approval before external actions."),s==="blocked_policy"&&a.push("Run was blocked by policy. Check tool allowlist and integration permissions."),(s==="failed"||s==="error")&&a.push("Run failed. Inspect detail/error fields for root cause."),(s==="completed"||s==="done")&&!t.length&&a.push("Run completed but produced no artifacts. Verify output target and tool actions."),n?.requires_approval===!0&&a.push("Automation policy requires human approval. Disable it for fully automated runs."),a}function Va(n){const t=n?.properties||{};return String(n?.run_id||n?.runId||n?.runID||t?.run_id||t?.runId||t?.runID||t?.run?.id||"").trim()}function tn(n){return String(n?.type||n?.event_type||n?.event||"").trim()}function Jn(n){const t=n?.properties||{},a=n?.timestamp_ms||n?.timestampMs||t?.timestamp_ms||t?.timestampMs||t?.firedAtMs||Date.now(),s=Number(a);return Number.isFinite(s)?s:Date.now()}function _n(n){const t=Number(n||0);return!Number.isFinite(t)||t<=0?Date.now():t<1e12?t*1e3:t}function Pn(n,t=88){const a=String(n||"").replace(/\s+/g," ").trim();return a?a.length>t?`${a.slice(0,t-1).trimEnd()}…`:a:""}function ln(n){return String(n?.mission_snapshot?.objective||n?.mission?.objective||n?.objective||n?.name||"").replace(/\s+/g," ").trim()}function la(n){const t=String(n?.name||"").trim();if(t)return t;const a=ln(n);if(a)return Pn(a,96);const s=String(n?.automation_id||n?.routine_id||"").trim();return s||"Run"}function on(n){const t=Number(n||0);return!Number.isFinite(t)||t<=0?"":new Date(_n(t)).toLocaleString()}function $s(n){const t=Array.isArray(n?.active_session_ids)?n.active_session_ids:Array.isArray(n?.activeSessionIds)?n.activeSessionIds:[],a=[String(n?.latest_session_id||"").trim(),String(n?.latestSessionId||"").trim()].filter(Boolean),s=Object.values(n?.checkpoint?.node_outputs||n?.checkpoint?.nodeOutputs||{}).map(i=>{const l=i?.content||{};return String(l?.session_id||l?.sessionId||"").trim()}).filter(Boolean);return Array.from(new Set([...a,...t.map(i=>String(i||"").trim()).filter(Boolean),...s].filter(Boolean)))}function el(n){const t=n?.checkpoint?.node_outputs||n?.checkpoint?.nodeOutputs||{};return Object.entries(t).map(([a,s])=>({nodeId:a,value:s}))}function tl(n){const t=String(n?.summary||"").trim(),a=n?.content||{},s=String(a?.text||a?.raw_text||"").trim();return[t,s].filter(Boolean).join(`
|
|
7
|
-
`).trim()}function Ms(n){return(Array.isArray(n?.parts)?n.parts:[]).map(s=>{const i=String(s?.type||"").trim();if(i==="text"||i==="reasoning")return String(s?.text||"").trim();if(i==="tool"){const l=String(s?.tool||"tool").trim(),c=String(s?.error||"").trim(),u=s?.result?kt(s.result):"";return[`tool: ${l}`,c?`error: ${c}`:"",u].filter(Boolean).join(`
|
|
8
|
-
`)}return String(s?.text||"").trim()}).filter(Boolean).join(`
|
|
9
|
-
|
|
10
|
-
`).trim()}function nl(n){const t=String(n?.info?.role||"").trim().toLowerCase();if(t==="user")return"user";if(t==="assistant")return"assistant";const a=Ms(n).toLowerCase();return a.includes("engine_error")||a.includes("error")?"error":"system"}function al(n){return Array.isArray(n?.parts)?n.parts:[]}function ga(n){const t=n?.properties||n||{};return String(t?.reason||t?.detail||t?.error?.message||t?.error||t?.message||t?.status||"").trim()}function sl(n,t,a){const s=[],i=(l,c,u,p,w)=>{u.trim()&&(s.some(M=>M.key===l)||s.push({key:l,title:c,reason:u,source:p,at:w}))};if((n?.requires_approval===!0||String(n?.status||"").trim()==="pending_approval")&&i("approval-required","Approval required",String(n?.approval_reason||"Manual approval required before external side effects.").trim(),"policy"),String(n?.denial_reason||"").trim()&&i("denied","Run denied",String(n.denial_reason).trim(),"run"),String(n?.paused_reason||"").trim()&&i("paused","Run paused",String(n.paused_reason).trim(),"run"),String(n?.detail||"").trim()){const l=String(n.detail).trim();(l.toLowerCase().includes("tool")||l.toLowerCase().includes("permission")||l.toLowerCase().includes("approval")||l.toLowerCase().includes("mcp")||l.toLowerCase().includes("auth"))&&i("detail","Run detail",l,"run")}$s(n).length||i("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 el(n)){const c=tl(l.value);if(!c)continue;const u=c.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"))&&i(`node-output-${l.nodeId}`,`Node issue: ${l.nodeId}`,Pn(c,360),l.nodeId,Number(l.value?.created_at_ms||l.value?.createdAtMs||0))}return[...t,...a].forEach(l=>{const c=String(tn(l?.event||l)||"").trim(),u=ga(l?.event||l),p=Number(l?.at||Jn(l?.event||l)||0);(c==="permission.asked"||c==="approval.required"||c==="routine.approval_required")&&i(`event-${c}`,"Permission or approval required",u||c,"permission",p),c==="mcp.auth.required"&&i(`event-${c}`,"MCP auth required",u||"An MCP connector requires authorization.","mcp",p),(c==="session.error"||c==="run.failed"||c==="routine.run.failed")&&i(`event-${c}`,"Execution failure",u||c,"session",p),u.toLowerCase().includes("no further tool calls")&&i("tool-mode","Tool policy blocked progress",u,"policy",p),u.toLowerCase().includes("timed out")&&i(`timeout-${c||p}`,"Timeout",u,"session",p)}),s.sort((l,c)=>(c.at||0)-(l.at||0))}function rl({value:n,onChange:t,routedSkill:a,routingConfidence:s,validationBadge:i,generatedSkill:l,advancedMode:c,customSkillName:u,customSkillDescription:p,customWorkflowKind:w,onToggleAdvancedMode:M,onChangeCustomSkillName:b,onChangeCustomSkillDescription:S,onChangeCustomWorkflowKind:q,showArtifactPreview:T,onToggleArtifactPreview:X,artifactPreviewKey:z,onSelectArtifactPreviewKey:J,onGenerateSkill:ne,onInstallGeneratedSkill:G,isGeneratingSkill:x,isInstallingSkill:O,installStatus:B,topMatches:E,isMatching:D}){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. "${Wa[0]}"`,value:n,onInput:W=>t(W.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:Wa.slice(1).map(W=>e("button",{className:"tcp-btn truncate text-left text-xs",style:{maxWidth:"280px"},onClick:()=>t(W),children:W},W))})]}),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:D?"Analyzing…":"Ready"})]}),a?e("p",{className:"mt-1",children:["Reusable flow match: ",e("strong",{children:a})," ",s?`(${s})`:"",i?e("span",{className:`ml-2 ${i==="validated"?"tcp-badge-ok":"tcp-badge-warn"}`,children:i==="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."}),E.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:E.slice(0,3).map((W,oe)=>e("span",{className:"tcp-badge-info",children:[String(W?.skill_name||"unknown")," ",typeof W?.confidence=="number"?`${Math.round(W.confidence*100)}%`:""]},`${String(W?.skill_name||"match")}-${oe}`))}):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:M,children:c?"Hide Export Options":"Show Export Options"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:ne,disabled:!n.trim()||x,children:x?"Generating…":"Generate Reusable Skill Draft"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:G,disabled:!l?.artifacts||O,children:O?"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."}),c?e("div",{className:"mt-2 grid gap-2",children:[e("input",{className:"tcp-input text-xs",placeholder:"skill-name",value:u,onInput:W=>b(W.target.value)}),e("input",{className:"tcp-input text-xs",placeholder:"Short skill description",value:p,onInput:W=>S(W.target.value)}),e("select",{className:"tcp-input text-xs",value:w,onInput:W=>q(W.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:X,children:T?"Hide Raw":"Show Raw"}),T?e("select",{className:"tcp-input h-7 text-xs",value:z,onInput:W=>J(W.target.value),children:Object.keys(l?.artifacts||{}).map(W=>e("option",{value:W,children:W},W))}):null]}),T?e("textarea",{className:"tcp-input min-h-[140px] font-mono text-[11px]",readOnly:!0,value:String(l?.artifacts?.[z]||"")}):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."}),B?e("p",{className:"mt-2 text-slate-300",children:B}):null]})]})}function il({selected:n,onSelect:t,customCron:a,onCustomCron:s}){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:Gn.map(i=>e("button",{onClick:()=>t(i),className:`tcp-list-item flex flex-col items-start gap-1 text-left transition-all ${n===i.label?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("div",{className:"flex items-center gap-2 font-medium",children:[e("span",{children:i.icon}),e("span",{children:i.label})]}),e("span",{className:"tcp-subtle text-xs",children:i.desc}),i.cron?e("code",{className:"rounded bg-slate-800/60 px-1.5 py-0.5 text-xs text-slate-400",children:i.cron}):null]},i.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:a,onInput:i=>s(i.target.value)})]})]})}function ol({selected:n,onSelect:t,maxAgents:a,onMaxAgents:s,workspaceRoot:i,onWorkspaceRootChange:l,providerOptions:c,providerId:u,modelId:p,plannerProviderId:w,plannerModelId:M,onProviderChange:b,onModelChange:S,onPlannerProviderChange:q,onPlannerModelChange:T,roleModelsJson:X,onRoleModelsChange:z,roleModelsError:J,mcpServers:ne,selectedMcpServers:G,onToggleMcpServer:x,onOpenMcpSettings:O,workspaceRootError:B,plannerModelError:E,workspaceBrowserOpen:D,workspaceBrowserDir:F,workspaceBrowserSearch:W,onWorkspaceBrowserSearchChange:oe,onOpenWorkspaceBrowser:xe,onCloseWorkspaceBrowser:Ie,onBrowseWorkspaceParent:pe,onBrowseWorkspaceDirectory:Ne,onSelectWorkspaceDirectory:fe,workspaceBrowserParentDir:Oe,workspaceCurrentBrowseDir:se,filteredWorkspaceDirectories:I}){const P=c.find(N=>N.id===u)?.models||[],ee=c.find(N=>N.id===w)?.models||[],ce=String(W||"").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:Na.map(N=>e("button",{onClick:()=>t(N.id),className:`tcp-list-item flex items-start gap-4 text-left transition-all ${n===N.id?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("span",{className:"mt-0.5 text-2xl",children:N.icon}),e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-semibold",children:N.label}),N.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:N.desc}),e("span",{className:"tcp-subtle text-xs",children:["Best for: ",N.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":n===N.id?!0:void 0})]},N.id))}),n==="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:a,onInput:N=>s(N.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:xe,children:"Browse"}),e("input",{className:`tcp-input text-sm ${B?"border-red-500/70 text-red-100":""}`,value:i,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>l(""),disabled:!i,children:"Clear"})]}),e("div",{className:"text-xs text-slate-500",children:"Tandem will run this automation from this workspace directory."}),B?e("div",{className:"text-xs text-red-300",children:B}):null]})]}),e(Ze,{children:D?e(te.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:Ie}),e(te.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:pe,disabled:!Oe,children:"Up"}),e("button",{className:"tcp-btn-primary",type:"button",onClick:fe,disabled:!se,children:"Select This Folder"}),e("button",{className:"tcp-btn",type:"button",onClick:Ie,children:"Close"})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:W,onInput:N=>oe(N.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:I.length?I.map(N=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>Ne(String(N?.path||"")),children:String(N?.name||N?.path||"")},String(N?.path||N?.name))):e(Se,{text:ce?"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:N=>b(N.target.value),children:[e("option",{value:"",children:"Use workspace default"}),c.map(N=>e("option",{value:N.id,children:N.id},N.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:N=>S(N.target.value),placeholder:"Use workspace default model"}),u?e("datalist",{id:`models-${u}`,children:P.map(N=>e("option",{value:N},N))}):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:w,onInput:N=>q(N.target.value),children:[e("option",{value:"",children:"Disabled"}),c.map(N=>e("option",{value:N.id,children:N.id},`planner-${N.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:M,list:w?`planner-models-${w}`:void 0,onInput:N=>T(N.target.value),placeholder:"Disabled unless provider and model are set"}),w?e("datalist",{id:`planner-models-${w}`,children:ee.map(N=>e("option",{value:N},N))}):null]})]}),E?e("div",{className:"text-xs text-red-300",children:E}):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 ${J?"border-red-500/70 text-red-100":""}`,value:X,onInput:N=>z(N.target.value),placeholder:'{"planner":{"provider_id":"openai","model_id":"gpt-5"},"worker":{"provider_id":"anthropic","model_id":"claude-sonnet-4"}}'}),J?e("div",{className:"text-xs text-red-300",children:J}):null]})]}),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:O,children:"Add MCP Server"})]}),ne.length?e("div",{className:"flex flex-wrap gap-2",children:ne.map(N=>{const ue=G.includes(N.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${ue?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>x(N.name),children:[N.name," ",N.connected?"• connected":"• disconnected"]},N.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 ll({wizard:n,onToggleExportPackDraft:t,onSubmit:a,isPending:s,planPreview:i,isPreviewing:l,planningConversation:c,planningChangeSummary:u,onSendPlanningMessage:p,isSendingPlanningMessage:w,onResetPlanningChat:M,isResettingPlanningChat:b,plannerError:S,plannerDiagnostics:q,generatedSkill:T,installStatus:X}){const[z,J]=y(""),ne=n.cron?n.cron:Gn.find(P=>P.label===n.schedulePreset)?.intervalSeconds?`Every ${Gn.find(P=>P.label===n.schedulePreset).intervalSeconds/3600}h`:n.schedulePreset||"Manual",G=i&&typeof i=="object"?i.operator_preferences||i.operatorPreferences||{}:{},x=String(G?.execution_mode||n.mode||"team").trim(),O=Na.find(P=>P.id===x),B=Number(G?.max_parallel_agents??G?.maxParallelAgents??(x==="swarm"?n.maxAgents:1)),E=!!i,D=String(E?G?.model_provider||G?.modelProvider||"":n.modelProvider||"").trim(),F=String(E?G?.model_id||G?.modelId||"":n.modelId||"").trim(),W=G&&typeof G=="object"&&(G?.role_models?.planner||G?.roleModels?.planner),oe=String(E?W?.provider_id||W?.providerId||"":n.plannerModelProvider||"").trim(),xe=String(E?W?.model_id||W?.modelId||"":n.plannerModelId||"").trim(),Ie=!!(oe&&xe||D&&F),pe=String(i?.workspace_root||i?.workspaceRoot||n.workspaceRoot||"").trim(),Ne=Array.isArray(i?.allowed_mcp_servers||i?.allowedMcpServers)?i?.allowed_mcp_servers||i?.allowedMcpServers||[]:n.selectedMcpServers,fe=i?.schedule?Ps(i.schedule):ne,Oe=String(i?.title||"").trim(),se=String(q?.fallback_reason||q?.fallbackReason||"").trim(),I=String(q?.detail||"").trim();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:[Oe?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:Oe})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Goal"}),e("span",{className:"text-sm text-slate-100 italic",children:['"',n.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:fe})]}),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:[O?.icon," ",O?.label||x,Number.isFinite(B)&&B>1?` · ${B} agents`:""]})]})]}),E||D||F?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:D||F?`${D||"default provider"} / ${F||"default model"}`:"Workspace default"})]}):null,E||oe||xe?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:oe||xe?`${oe||"default provider"} / ${xe||"default model"}`:D||F?`Using model override: ${D||"default provider"} / ${F||"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:Ie?"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:pe||"engine workspace root"})]}),E||Ne.length?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"MCP Servers"}),Ne.length?e("div",{className:"flex flex-wrap gap-1",children:Ne.map(P=>e("span",{className:"tcp-badge-info",children:P},P))}):e("span",{className:"text-sm font-medium text-slate-400",children:"None"})]}):null,n.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:[n.routedSkill,n.routingConfidence?` (${n.routingConfidence})`:""]})]}):null,n.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:n.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…"}):i?e("div",{className:"grid gap-1 text-sm text-slate-300",children:[e("span",{children:["Confidence: ",e("strong",{children:String(i?.confidence||"unknown")})]}),e("span",{children:["Execution target:"," ",e("strong",{children:String(i?.execution_target||"automation_v2")})]}),Oe?e("span",{children:["Title: ",e("strong",{children:Oe})]}):null,e("span",{children:["Steps:"," ",e("strong",{children:Array.isArray(i?.steps)?i.steps.length:0})]}),Array.isArray(i?.steps)&&i.steps.length?e("div",{className:"mt-1 grid gap-1",children:i.steps.map((P,ee)=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40 px-2 py-1",children:[e("div",{className:"text-xs font-medium text-slate-200",children:[String(P?.step_id||P?.stepId||`step-${ee+1}`),P?.kind?e("span",{className:"ml-2 text-[11px] uppercase tracking-wide text-slate-500",children:String(P.kind)}):null]}),typeof P?.objective=="string"&&P.objective.trim()?e("div",{className:"text-xs text-slate-400",children:P.objective}):null]},`${String(P?.step_id||P?.stepId||ee)}-${ee}`))}):null,typeof i?.description=="string"&&i.description.trim()?e("span",{children:i.description}):null]}):e("span",{className:"text-sm text-slate-400",children:"Workflow preview has not been generated yet."})]})]}),S?e("div",{className:"rounded-xl border border-red-500/40 bg-red-950/30 p-3 text-sm text-red-200",children:S}):null,se?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:se})]}),I?e("div",{className:"mt-2 text-xs text-amber-200/90 whitespace-pre-wrap",children:I}):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((P,ee)=>e("span",{className:"tcp-badge-ok",children:P},`${P}-${ee}`))})]}):null,i?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||!i?.plan_id,onClick:M,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:Ie?"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(c?.messages)&&c.messages.length?e("div",{className:"grid gap-3",children:c.messages.map((P,ee)=>e("div",{className:"grid gap-1",children:[e("span",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:String(P?.role||"assistant")}),e("div",{className:"text-sm text-slate-200",children:String(P?.text||"").trim()})]},`${P?.created_at_ms||ee}-${ee}`))}):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:z,onInput:P=>J(P.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:w||!z.trim()||!i?.plan_id,onClick:()=>{const P=z.trim();P&&(p(P),J(""))},children:w?"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:n.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."})]})]})}),T||X?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:[T?e(Qt,{children:[e("span",{children:["Draft status:"," ",e("strong",{className:"text-slate-300",children:String(T?.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,X?e("span",{children:X}):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:O?.label||x})," that runs"," ",e("strong",{className:"text-slate-300",children:fe}),". You can pause, edit or delete it anytime."]}),e("button",{className:"tcp-btn-primary",disabled:s||l||!n.goal.trim()||!i,onClick:a,children:s?"Creating automation…":"🚀 Create Automation"})]})}function cl({client:n,api:t,toast:a,navigate:s,defaultProvider:i,defaultModel:l}){const c=Lt(),[u,p]=y(1),[w,M]=y("automations_page"),[b,S]=y([]),[q,T]=y(null),[X,z]=y(null),[J,ne]=y([]),[G,x]=y(""),[O,B]=y(null),[E,D]=y(!1),[F,W]=y(""),[oe,xe]=y(""),[Ie,pe]=y(""),[Ne,fe]=y(null),[Oe,se]=y(!1),[I,P]=y("SKILL.md"),[ee,ce]=y(""),[N,ue]=y({goal:"",workspaceRoot:"",schedulePreset:"Every morning",cron:"",mode:"team",maxAgents:"4",routedSkill:"",routingConfidence:"",modelProvider:String(i||""),modelId:String(l||""),plannerModelProvider:"",plannerModelId:"",roleModelsJson:"",selectedMcpServers:[],exportPackDraft:!1,advancedMode:!1,customSkillName:"",customSkillDescription:"",customWorkflowKind:"pack_builder_recipe"}),be=j({queryKey:["settings","providers","catalog"],queryFn:()=>n.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),Re=j({queryKey:["settings","providers","config"],queryFn:()=>n.providers.config().catch(()=>({})),refetchInterval:3e4}),Me=j({queryKey:["mcp","servers"],queryFn:()=>n.mcp.list().catch(()=>({})),refetchInterval:12e3}),Te=j({queryKey:["global","health"],queryFn:()=>n.health().catch(()=>({})),refetchInterval:3e4}),st=j({queryKey:["automations","workspace-browser",F],enabled:E&&!!F,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(F)}`,{method:"GET"})}),Ae=V(()=>(Array.isArray(be.data?.all)?be.data.all:[]).map(k=>({id:String(k?.id||"").trim(),models:Object.keys(k?.models||{})})).filter(k=>!!k.id).sort((k,ve)=>k.id.localeCompare(ve.id)),[be.data]),ht=V(()=>As(Me.data),[Me.data]),gt=Array.isArray(st.data?.directories)?st.data.directories:[],We=String(st.data?.parent||"").trim(),Qe=String(st.data?.dir||F||"").trim(),ft=String(oe||"").trim().toLowerCase(),bt=V(()=>ft?gt.filter(g=>String(g?.name||g?.path||"").trim().toLowerCase().includes(ft)):gt,[gt,ft]);ie(()=>{const g=String(Re.data?.default||i||"").trim();if(!g)return;const k=Ae.find(ke=>ke.id===g)?.models||[],ve=String(Re.data?.providers?.[g]?.default_model||l||k[0]||"").trim();ue(ke=>ke.modelProvider&&ke.modelId?ke:{...ke,modelProvider:ke.modelProvider||g,modelId:ke.modelId||ve})},[l,i,Ae,Re.data]),ie(()=>{const g=String(Te.data?.workspaceRoot||Te.data?.workspace_root||"").trim();g&&ue(k=>String(k.workspaceRoot||"").trim()?k:{...k,workspaceRoot:g})},[Te.data]);const He=me({mutationFn:async g=>!g.trim()||!n?.skills?.match?null:n.skills.match({goal:g,maxMatches:3,threshold:.35}),onError:()=>{}}),le=me({mutationFn:async()=>{if(!n?.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 n.workflowPlans.chatStart({prompt:N.goal,schedule:Bo(N),plan_source:w,allowed_mcp_servers:N.selectedMcpServers,workspace_root:N.workspaceRoot,operator_preferences:Ko(N)})||null},onSuccess:g=>{T(g?.plan||null),z(g?.conversation||null),ne([]),x(""),B(g?.planner_diagnostics||g?.plannerDiagnostics||null)},onError:g=>{T(null),z(null),ne([]),x(g instanceof Error?g.message:String(g)),B(null)}}),Be=me({mutationFn:async g=>!n?.workflowPlans?.chatMessage||!q?.plan_id?null:n.workflowPlans.chatMessage({plan_id:q.plan_id,message:g}),onSuccess:g=>{T(g?.plan||null),z(g?.conversation||null),ne(Array.isArray(g?.change_summary)?g.change_summary.map(k=>String(k||"").trim()).filter(Boolean):[]),x(typeof g?.clarifier?.question=="string"?String(g.clarifier.question):""),B(g?.planner_diagnostics||g?.plannerDiagnostics||null)},onError:g=>{const k=g instanceof Error?g.message:String(g);x(k),a("err",k)}}),dt=me({mutationFn:async()=>!n?.workflowPlans?.chatReset||!q?.plan_id?null:n.workflowPlans.chatReset({plan_id:q.plan_id}),onSuccess:g=>{T(g?.plan||null),z(g?.conversation||null),ne([]),x(""),B(g?.planner_diagnostics||g?.plannerDiagnostics||null)},onError:g=>{const k=g instanceof Error?g.message:String(g);x(k),a("err",k)}}),ye=me({mutationFn:async g=>{if(!n?.skills?.get||!n?.skills?.validate)return null;const ve=(await n.skills.get(g))?.content;return ve?n.skills.validate({content:ve}):null},onSuccess:g=>{if(!g){pe("");return}pe(g.invalid>0?"not_validated":"validated")},onError:()=>pe("not_validated")}),Ke=me({mutationFn:async()=>{if(!n?.skills?.generate||!N.goal.trim())return null;const g=N.advancedMode?[N.goal.trim(),N.customSkillName?`Skill name: ${N.customSkillName}`:"",N.customSkillDescription?`Description: ${N.customSkillDescription}`:"",`Workflow kind: ${N.customWorkflowKind}`].filter(Boolean).join(`
|
|
11
|
-
`):N.goal;return n.skills.generate({prompt:g})},onSuccess:g=>{fe(g);const k=Object.keys(g?.artifacts||{})[0];P(k||"SKILL.md"),se(!1),ce("")},onError:()=>{fe(null),se(!1),ce("Optional skill generation failed.")}}),St=me({mutationFn:async()=>{if(!n?.skills?.generateInstall)return null;const g=Ne?.artifacts;if(!g||!g["SKILL.md"])throw new Error("No generated artifacts available to install.");return n.skills.generateInstall({location:"project",conflictPolicy:"rename",artifacts:{"SKILL.md":g["SKILL.md"],"workflow.yaml":g["workflow.yaml"],"automation.example.yaml":g["automation.example.yaml"]}})},onSuccess:g=>{const k=g?.skill?.name;ce(k?`Installed optional skill as '${String(k)}' in project skills.`:"Installed optional skill in project skills."),c.invalidateQueries({queryKey:["automations"]})},onError:g=>ce(`Install failed: ${g instanceof Error?g.message:String(g)}`)}),$t=me({mutationFn:async()=>{if(!N.goal.trim())throw new Error("Please describe your goal first.");const g=q||await le.mutateAsync().catch(ve=>{throw ve instanceof Error?ve:new Error(String(ve))}),k=g?.plan||g;if(!k)throw new Error("Workflow plan preview failed.");return n.workflowPlans.apply({plan:k,creator_id:"control-panel",...N.exportPackDraft?{pack_builder_export:{enabled:!0,auto_apply:!1}}:{}})},onSuccess:async g=>{g?.pack_builder_export?.status==="preview_pending"?a("ok","🎉 Automation created and reusable pack draft exported. Check Pack Builder to continue."):a("ok","🎉 Automation created! Check 'My Automations' to see it running."),await Promise.all([c.invalidateQueries({queryKey:["automations"]}),c.invalidateQueries({queryKey:["mcp"]})]),ue({goal:"",workspaceRoot:String(Te.data?.workspaceRoot||Te.data?.workspace_root||"").trim(),schedulePreset:"Every morning",cron:"",mode:"team",maxAgents:"4",routedSkill:"",routingConfidence:"",modelProvider:String(i||""),modelId:String(l||""),plannerModelProvider:"",plannerModelId:"",roleModelsJson:"",selectedMcpServers:[],exportPackDraft:!1,advancedMode:!1,customSkillName:"",customSkillDescription:"",customWorkflowKind:"pack_builder_recipe"}),S([]),M("automations_page"),T(null),z(null),ne([]),x(""),pe(""),fe(null),se(!1),P("SKILL.md"),ce(""),p(1)},onError:g=>{const k=g instanceof Error?g.message:String(g);x(k),a("err",k)}}),Ye=Sn(N.workspaceRoot),ge=Kn(N.plannerModelProvider,N.plannerModelId),je=Jo(N.roleModelsJson),Ge=u===1?N.goal.trim().length>8:u===2?!!N.schedulePreset||!!N.cron.trim():u===3?!!N.mode&&!Ye&&!ge&&!je:!0,De=["What?","When?","How?","Review"],ut=async()=>{if(u===1){const k=await He.mutateAsync(N.goal);k&&k.decision==="match"&&k.skill_name?(ye.mutateAsync(String(k.skill_name)),ue(ke=>({...ke,routedSkill:String(k.skill_name),routingConfidence:typeof k.confidence=="number"?`${Math.round(k.confidence*100)}%`:""}))):(pe(""),ue(ke=>({...ke,routedSkill:"",routingConfidence:""})));const ve=Array.isArray(k?.top_matches)?k.top_matches:[];S(ve)}const g=u+1;if(g===4){x(""),T(null),z(null),ne([]);try{await le.mutateAsync()}catch{return}}p(g)};return ie(()=>{if(u===1)try{const g=sessionStorage.getItem(Qa);if(!g)return;sessionStorage.removeItem(Qa);const k=JSON.parse(g),ve=String(k?.prompt||"").trim();if(!ve)return;const ke=String(k?.plan_source||"chat_setup").trim()||"chat_setup";M(ke),ue(o=>({...o,goal:ve}))}catch{}},[u]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex items-center gap-2",children:De.map((g,k)=>{const ve=k+1,ke=ve===u,o=ve<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 ${ke?"bg-amber-500/20 text-amber-300":o?"text-slate-400":"text-slate-600"}`,onClick:()=>o&&p(ve),children:[e("span",{className:`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${ke?"bg-amber-500 text-black":o?"bg-slate-600 text-white":"bg-slate-800 text-slate-500"}`,children:o?"✓":ve}),g]}),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:o?"100%":ke?"50%":"0%"}})})]},g)})}),e(Ze,{mode:"wait",children:e(te.div,{initial:{opacity:0,x:16},animate:{opacity:1,x:0},exit:{opacity:0,x:-16},transition:{duration:.18},children:u===1?e(rl,{value:N.goal,onChange:g=>ue(k=>({...k,goal:g})),routedSkill:N.routedSkill,routingConfidence:N.routingConfidence,validationBadge:Ie,generatedSkill:Ne,advancedMode:N.advancedMode,customSkillName:N.customSkillName,customSkillDescription:N.customSkillDescription,customWorkflowKind:N.customWorkflowKind,onToggleAdvancedMode:()=>ue(g=>({...g,advancedMode:!g.advancedMode})),onChangeCustomSkillName:g=>ue(k=>({...k,customSkillName:g})),onChangeCustomSkillDescription:g=>ue(k=>({...k,customSkillDescription:g})),onChangeCustomWorkflowKind:g=>ue(k=>({...k,customWorkflowKind:g})),showArtifactPreview:Oe,onToggleArtifactPreview:()=>se(g=>!g),artifactPreviewKey:I,onSelectArtifactPreviewKey:g=>P(g),onGenerateSkill:()=>{Ke.mutateAsync()},onInstallGeneratedSkill:()=>{St.mutateAsync()},isGeneratingSkill:Ke.isPending,isInstallingSkill:St.isPending,installStatus:ee,topMatches:b,isMatching:He.isPending}):u===2?e(il,{selected:N.schedulePreset,onSelect:g=>ue(k=>({...k,schedulePreset:g.label,cron:g.cron})),customCron:N.cron,onCustomCron:g=>ue(k=>({...k,cron:g,schedulePreset:""}))}):u===3?e(ol,{selected:N.mode,onSelect:g=>ue(k=>({...k,mode:g})),maxAgents:N.maxAgents,onMaxAgents:g=>ue(k=>({...k,maxAgents:g})),workspaceRoot:N.workspaceRoot,onWorkspaceRootChange:g=>ue(k=>({...k,workspaceRoot:g})),providerOptions:Ae,providerId:N.modelProvider,modelId:N.modelId,plannerProviderId:N.plannerModelProvider,plannerModelId:N.plannerModelId,onProviderChange:g=>ue(k=>({...k,modelProvider:g,modelId:g===k.modelProvider?k.modelId:""})),onModelChange:g=>ue(k=>({...k,modelId:g})),onPlannerProviderChange:g=>ue(k=>({...k,plannerModelProvider:g,plannerModelId:g===k.plannerModelProvider?k.plannerModelId:""})),onPlannerModelChange:g=>ue(k=>({...k,plannerModelId:g})),roleModelsJson:N.roleModelsJson,onRoleModelsChange:g=>ue(k=>({...k,roleModelsJson:g})),roleModelsError:je,mcpServers:ht,selectedMcpServers:N.selectedMcpServers,onToggleMcpServer:g=>ue(k=>({...k,selectedMcpServers:k.selectedMcpServers.includes(g)?k.selectedMcpServers.filter(ve=>ve!==g):[...k.selectedMcpServers,g]})),onOpenMcpSettings:()=>s("mcp"),workspaceRootError:Ye,plannerModelError:ge,workspaceBrowserOpen:E,workspaceBrowserDir:F,workspaceBrowserSearch:oe,onWorkspaceBrowserSearchChange:xe,onOpenWorkspaceBrowser:()=>{const g=String(N.workspaceRoot||Te.data?.workspaceRoot||Te.data?.workspace_root||"/").trim();W(g||"/"),xe(""),D(!0)},onCloseWorkspaceBrowser:()=>{D(!1),xe("")},onBrowseWorkspaceParent:()=>{We&&W(We)},onBrowseWorkspaceDirectory:g=>W(g),onSelectWorkspaceDirectory:()=>{Qe&&(ue(g=>({...g,workspaceRoot:Qe})),D(!1),xe(""),a("ok",`Workspace selected: ${Qe}`))},workspaceBrowserParentDir:We,workspaceCurrentBrowseDir:Qe,filteredWorkspaceDirectories:bt}):e(ll,{wizard:N,onToggleExportPackDraft:()=>ue(g=>({...g,exportPackDraft:!g.exportPackDraft})),onSubmit:()=>$t.mutate(),isPending:$t.isPending,planPreview:q,isPreviewing:le.isPending,planningConversation:X,planningChangeSummary:J,onSendPlanningMessage:g=>{Be.mutateAsync(g)},isSendingPlanningMessage:Be.isPending,onResetPlanningChat:()=>{dt.mutateAsync()},isResettingPlanningChat:dt.isPending,plannerError:G,plannerDiagnostics:O,generatedSkill:Ne,installStatus:ee})},u)}),u<4?e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn",disabled:u===1||le.isPending,onClick:()=>p(g=>g-1),children:"← Back"}),e("button",{className:"tcp-btn-primary",disabled:!Ge||le.isPending,onClick:()=>{ut()},children:le.isPending?"Generating Plan...":"Next →"})]}):null]})}function za({client:n,toast:t,navigate:a,viewMode:s,selectedRunId:i,onSelectRunId:l,onOpenRunningView:c}){const u=Lt(),p=wt(null),[w,M]=y(null),[b,S]=y(null),[q,T]=y("all"),[X,z]=y([]),[J,ne]=y(""),[G,x]=y([]),O=wt(null),[B,E]=y(!0),[D,F]=y(null),W=i.startsWith("automation-v2-run-"),oe=V(()=>Vt(Ie.data,"automations").map(o=>String(o?.automation_id||o?.automationId||o?.id||"").trim()).filter(Boolean),[Ie.data]),xe=j({queryKey:["automations","list"],queryFn:()=>n?.automations?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Ie=j({queryKey:["automations","v2","list"],queryFn:()=>n?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),pe=j({queryKey:["providers","catalog","workflow-edit"],queryFn:()=>n?.providers?.catalog?.().catch(()=>({providers:[]}))??Promise.resolve({providers:[]}),refetchInterval:3e4}),Ne=j({queryKey:["mcp","servers","workflow-edit"],queryFn:()=>n?.mcp?.list?.().catch(()=>({servers:[]}))??Promise.resolve({servers:[]}),refetchInterval:15e3}),fe=j({queryKey:["automations","runs"],queryFn:()=>n?.automations?.listRuns?.({limit:20}).catch(()=>({runs:[]}))??Promise.resolve({runs:[]}),refetchInterval:9e3}),Oe=j({queryKey:["automations","v2","runs",oe],enabled:!!n?.automationsV2?.listRuns,queryFn:async()=>oe.length?{runs:(await Promise.all(oe.map(async d=>{const C=await n?.automationsV2?.listRuns?.(d,12).catch(()=>({runs:[]}));return Array.isArray(C?.runs)?C.runs:[]}))).flat()}:{runs:[]},refetchInterval:9e3}),se=j({queryKey:["automations","run",i],enabled:!!i,queryFn:()=>(W?n?.automationsV2?.getRun?.(i):n?.automations?.getRun?.(i))?.catch(()=>({run:null}))??Promise.resolve({run:null}),refetchInterval:i?5e3:!1}),I=j({queryKey:["automations","run","artifacts",i],enabled:!!i&&!W,queryFn:()=>n?.automations?.listArtifacts?.(i).catch(()=>({artifacts:[]})),refetchInterval:i?8e3:!1}),P=V(()=>$s(se.data?.run),[se.data]),ee=j({queryKey:["automations","run","session",i,J,"messages"],enabled:!!i&&!!J,queryFn:()=>n?.sessions?.messages?.(J).catch(()=>[])??Promise.resolve([]),refetchInterval:i&&J&&Ha(se.data?.run?.status)?4e3:!1}),ce=String(se.data?.run?.automation_id||se.data?.run?.routine_id||"").trim(),N=j({queryKey:["automations","history",ce],enabled:!!ce,queryFn:()=>n?.automations?.history?.(ce,80).catch(()=>({events:[]})),refetchInterval:i?1e4:!1}),ue=j({queryKey:["automations","packs"],queryFn:()=>n?.packs?.list?.().catch(()=>({packs:[]}))??Promise.resolve({packs:[]}),refetchInterval:3e4}),be=me({mutationFn:o=>n?.automations?.runNow?.(o),onSuccess:async()=>{t("ok","Automation triggered."),await u.invalidateQueries({queryKey:["automations"]})},onError:o=>t("err",o instanceof Error?o.message:String(o))}),Re=me({mutationFn:o=>n?.automationsV2?.runNow?.(o),onSuccess:async o=>{const d=String(o?.run?.run_id||o?.run?.runId||"").trim();t("ok","Workflow automation triggered."),await u.invalidateQueries({queryKey:["automations"]}),d&&(l(d),c())},onError:o=>t("err",o instanceof Error?o.message:String(o))}),Me=me({mutationFn:async({action:o,runId:d,family:C,reason:Q})=>C==="v2"?o==="pause"?n.automationsV2.pauseRun(d,Q):n.automationsV2.resumeRun(d,Q):o==="pause"?n.automations.pauseRun(d,Q):n.automations.resumeRun(d,Q),onSuccess:async()=>{t("ok","Run action applied."),await u.invalidateQueries({queryKey:["automations"]})},onError:o=>t("err",o instanceof Error?o.message:String(o))}),Te=me({mutationFn:async o=>{const d=String(o.name||"").trim(),C=String(o.objective||"").trim(),Q=String(o.cronExpression||"").trim(),qe=Number(o.intervalSeconds);if(!d)throw new Error("Automation name is required.");if(!C)throw new Error("Objective is required.");if(o.scheduleKind==="cron"&&!Q)throw new Error("Cron expression is required.");if(o.scheduleKind==="interval"&&(!Number.isFinite(qe)||qe<=0))throw new Error("Interval seconds must be greater than zero.");return n.automations.update(o.automationId,{name:d,mode:o.mode,mission:{objective:C},policy:{approval:{requires_approval:!!o.requiresApproval}},schedule:o.scheduleKind==="cron"?{cron:{expression:Q}}:{interval_seconds:{seconds:Math.round(qe)}}})},onSuccess:async()=>{t("ok","Automation updated."),S(null),await u.invalidateQueries({queryKey:["automations"]})},onError:o=>t("err",o instanceof Error?o.message:String(o))}),st=me({mutationFn:async o=>{const d=String(o.name||"").trim(),C=String(o.description||"").trim(),Q=String(o.workspaceRoot||"").trim(),qe=oa(o.modelProvider,o.modelId),Ve=Kn(o.plannerModelProvider,o.plannerModelId),nt=Sn(Q);if(!d)throw new Error("Automation name is required.");if(nt)throw new Error(nt);if(qe)throw new Error(qe);if(Ve)throw new Error(Ve);if(o.scheduleKind==="cron"&&!String(o.cronExpression||"").trim())throw new Error("Cron expression is required.");if(o.scheduleKind==="interval"&&(!Number.isFinite(Number(o.intervalSeconds))||Number(o.intervalSeconds)<=0))throw new Error("Interval seconds must be greater than zero.");const Et=Yo(o),Zt=Xo(Et),ot=o.selectedMcpServers.map(v=>String(v||"").trim()).filter(Boolean),Ht=Ho(ot),Mt=We.find(v=>String(v?.automation_id||v?.automationId||v?.id||"").trim()===o.automationId),h=Array.isArray(Mt?.agents)?Mt.agents.map(v=>({...v,model_policy:Zt,modelPolicy:void 0,tool_policy:{...v?.tool_policy||{},allowlist:Ht,denylist:Array.isArray(v?.tool_policy?.denylist)?v.tool_policy.denylist:[]},mcp_policy:{...v?.mcp_policy||{},allowed_servers:ot,allowed_tools:null}})):[],R=Mt?.metadata&&typeof Mt.metadata=="object"?Mt.metadata:{};return n.automationsV2.update(o.automationId,{name:d,description:C||null,schedule:zo(o),workspace_root:Q,execution:{...Mt?.execution||{},max_parallel_agents:o.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(o.maxParallelAgents||"4"),10)||4)):1},agents:h,metadata:{...R,workspace_root:Q,operator_preferences:Et,allowed_mcp_servers:ot}})},onSuccess:async()=>{t("ok","Workflow automation updated."),F(null),await u.invalidateQueries({queryKey:["automations"]})},onError:o=>t("err",o instanceof Error?o.message:String(o))}),Ae=me({mutationFn:async({action:o,automationId:d,family:C})=>C==="v2"?o==="delete"?n.automationsV2.delete(d):o==="pause"?n.automationsV2.pause(d):n.automationsV2.resume(d):o==="delete"?n.automations.delete(d):n.automations.update(d,{status:o==="pause"?"paused":"enabled"}),onSuccess:async(o,d)=>{d.action==="delete"&&t("ok","Automation removed."),d.action==="pause"&&t("ok","Automation paused."),d.action==="resume"&&t("ok","Automation resumed."),await u.invalidateQueries({queryKey:["automations"]})},onError:o=>t("err",o instanceof Error?o.message:String(o))}),ht=V(()=>{const o=[...Vt(xe.data,"automations"),...Vt(xe.data,"routines")],d=new Map;for(const C of o){const Q=String(C?.automation_id||C?.routine_id||C?.id||"").trim();Q&&(d.has(Q)||d.set(Q,C))}return Array.from(d.values())},[xe.data]),gt=Vt(fe.data,"runs"),We=Vt(Ie.data,"automations"),Qe=V(()=>(Array.isArray(pe.data?.providers)?pe.data.providers:[]).map(d=>({id:String(d?.id||"").trim(),models:Array.isArray(d?.models)?d.models.map(C=>String(C||"").trim()).filter(Boolean):[]})).filter(d=>d.id).sort((d,C)=>d.id.localeCompare(C.id)),[pe.data]),ft=V(()=>As(Ne.data),[Ne.data]),bt=Vt(Oe.data,"runs"),He=V(()=>{const o=[...gt,...bt],d=new Map;for(const C of o){const Q=String(C?.run_id||C?.runId||C?.id||"").trim();Q&&(d.has(Q)||d.set(Q,C))}return Array.from(d.values()).sort((C,Q)=>{const qe=_n(C?.started_at_ms||C?.startedAtMs||C?.created_at_ms||C?.createdAtMs||0);return _n(Q?.started_at_ms||Q?.startedAtMs||Q?.created_at_ms||Q?.createdAtMs||0)-qe})},[gt,bt]),le=Vt(ue.data,"packs"),Be=He.filter(o=>Ha(o?.status)),dt=He.filter(o=>{const d=String(o?.status||"").trim().toLowerCase();return d==="failed"||d==="error"}),ye=se.data?.run||null,Ke=Vt(I.data,"artifacts"),St=Zo(ye,Ke),$t=Array.isArray(N.data?.events)?N.data.events:Array.isArray(N.data?.history)?N.data.history:[],Ye=X.filter(o=>q==="all"?!0:o.source===q),ge=Array.isArray(ee.data)?ee.data:[];ie(()=>{ne(o=>o&&P.includes(o)?o:P[0]||"")},[P]),ie(()=>{z([]),T("all"),x([]),E(!0)},[i]),gn(i?`/api/engine/automations/events?run_id=${encodeURIComponent(i)}`:"",o=>{try{const d=JSON.parse(String(o?.data||"{}"));if(!d||d.status==="ready")return;const C=Va(d);if(!C||C!==i)return;const Q=tn(d),qe=Jn(d),Ve=`automations:${C}:${Q}:${qe}:${Math.random().toString(16).slice(2,8)}`;z(nt=>[...nt.slice(-299),{id:Ve,source:"automations",at:qe,event:d}])}catch{return}},{enabled:!!i}),gn(i&&J?`/event?sessionID=${encodeURIComponent(J)}&runID=${encodeURIComponent(i)}`:"",o=>{try{const d=JSON.parse(String(o?.data||"{}"));if(!d)return;const C=tn(d),Q=Jn(d),qe=[C||"event",String(d?.properties?.sessionID||d?.sessionID||J||""),String(d?.properties?.runID||d?.runID||i||""),String(d?.properties?.messageID||d?.messageID||""),String(d?.properties?.part?.id||d?.properties?.seq||d?.timestamp_ms||Q)].join(":");x(Ve=>Ve.some(nt=>nt.id===qe)?Ve:[...Ve.slice(-499),{id:qe,at:Q,event:d}])}catch{return}},{enabled:!!i&&!!J}),gn(i?"/api/global/event":"",o=>{try{const d=JSON.parse(String(o?.data||"{}")),C=Va(d);if(!C||C!==i)return;const Q=tn(d);if(!Q||Q==="server.connected"||Q==="engine.lifecycle.ready")return;const qe=Jn(d),Ve=`global:${C}:${Q}:${qe}:${Math.random().toString(16).slice(2,8)}`;z(nt=>[...nt.slice(-299),{id:Ve,source:"global",at:qe,event:d}])}catch{return}},{enabled:!!i}),ie(()=>{const o=p.current;o&&dn(o)},[ht.length,We.length,He.length,bt.length,le.length,Be.length,dt.length,!!b,!!i,!!J,X.length,G.length,Te.isPending,Me.isPending,be.isPending,Re.isPending]);const je=o=>{const d=String(o||"").toLowerCase();return d==="active"||d==="completed"||d==="done"?"tcp-badge-ok":d==="running"||d==="in_progress"?"tcp-badge-warn":d==="failed"||d==="error"?"tcp-badge-err":"tcp-badge-info"},Ge=o=>{const d=String(o?.automation_id||o?.id||o?.routine_id||"").trim();if(!d){t("err","Cannot edit automation without an id.");return}const C=Rs(o?.schedule);S({automationId:d,name:String(o?.name||d||"").trim(),objective:String(o?.mission?.objective||o?.mission_snapshot?.objective||"").trim(),mode:String(o?.mode||"").toLowerCase()==="standalone"?"standalone":"orchestrated",requiresApproval:o?.requires_approval===!0||o?.policy?.approval?.requires_approval===!0,scheduleKind:C.scheduleKind,cronExpression:C.cronExpression,intervalSeconds:String(C.intervalSeconds)})},De=o=>{const d=String(o?.status||"").trim().toLowerCase();return d==="paused"||d==="disabled"},ut=ht.length,g=We.length,k=ut+g,ve=V(()=>sl(ye,G,X),[ye,G,X]),ke=V(()=>{const o=ge.map((C,Q)=>({id:`message:${String(C?.info?.id||Q)}`,kind:"message",at:_n(C?.info?.time?.created),variant:nl(C),label:String(C?.info?.role||"session").trim()||"session",body:Ms(C),raw:C,parts:al(C)})),d=G.map(C=>({id:`event:${C.id}`,kind:"event",at:C.at,variant:tn(C.event)==="session.error"?"error":tn(C.event).startsWith("session.")?"system":"tool",label:tn(C.event)||"event",body:ga(C.event),raw:C.event,parts:[]}));return[...o,...d].sort((C,Q)=>C.at-Q.at)},[ge,G]);return ie(()=>{const o=O.current;!o||!B||(o.scrollTop=o.scrollHeight)},[ke,B]),e("div",{ref:p,className:"grid gap-4",children:[s==="list"&&le.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"}),le.map((o,d)=>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(o?.name||o?.id||"Pack")})]}),e("span",{className:"tcp-badge-info",children:String(o?.version||"1.0.0")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:String(o?.description||o?.path||"")})]},String(o?.id||o?.name||d)))]}):null,s==="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:[k," 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:[ut," items"]})]}),ht.length>0?ht.map(o=>{const d=String(o?.automation_id||o?.id||o?.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(o?.name||d||"Automation")})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ge(o),children:e("i",{"data-lucide":"pencil"})}),e("span",{className:je(o?.status),children:String(o?.status||"active")})]})]}),e("div",{className:"tcp-subtle text-xs",children:jo(o?.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:()=>be.mutate(d),children:[e("i",{"data-lucide":"play"}),"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ae.mutate({action:De(o)?"resume":"pause",automationId:d,family:"legacy"}),disabled:!d||Ae.isPending,children:[e("i",{"data-lucide":De(o)?"play":"pause"}),De(o)?"Resume":"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{const C=He.find(qe=>String(qe?.automation_id||qe?.routine_id||qe?.id||"").trim()===d),Q=String(C?.run_id||C?.id||"").trim();Q?(l(Q),c()):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:()=>M({automationId:d,family:"legacy",title:String(o?.name||o?.label||d||"automation")}),disabled:!d||Ae.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})})]},d)}):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,s==="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:[g," items"]})]}),We.length>0?We.map(o=>{const d=String(o?.automation_id||o?.automationId||"").trim(),C=String(o?.status||"draft").trim(),Q=C.toLowerCase()==="paused";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(o?.name||d||"Workflow automation")})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>F(Vo(o)),disabled:!d,title:"Edit workflow automation","aria-label":"Edit workflow automation",children:e("i",{"data-lucide":"pencil"})}),e("span",{className:je(C),children:C})]})]}),String(o?.description||"").trim()?e("div",{className:"tcp-subtle text-xs",children:String(o.description)}):null,e("div",{className:"tcp-subtle mt-1 text-xs",children:Ps(o?.schedule)}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Re.mutate(d),disabled:!d||Re.isPending,children:[e("i",{"data-lucide":"play"}),Re.isPending?"Starting...":"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ae.mutate({action:Q?"resume":"pause",automationId:d,family:"v2"}),disabled:!d||Ae.isPending,children:[e("i",{"data-lucide":Q?"play":"pause"}),Q?"Resume":"Pause"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>M({automationId:d,family:"v2",title:String(o?.name||d||"workflow automation")}),disabled:!d||Ae.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},d)}):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,s==="running"?Be.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:[Be.length," active"]})]}),Be.slice(0,14).map((o,d)=>{const C=String(o?.run_id||o?.id||d).trim(),Q=o?.started_at_ms||o?.startedAtMs||o?.created_at_ms||o?.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:la(o)}),e("span",{className:"tcp-subtle text-xs",children:[C||"unknown run"," · running for ",Ga(o)]}),on(Q)?e("span",{className:"tcp-subtle text-xs",children:["Started: ",on(Q)]}):null,ln(o)?e("span",{className:"text-xs text-slate-400",children:Pn(ln(o),160)}):null]}),e("span",{className:je(o?.status),children:String(o?.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(C),children:[e("i",{"data-lucide":"bug"}),"Inspect"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Me.mutate({action:"pause",runId:C,family:C.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!C||Me.isPending,children:[e("i",{"data-lucide":"pause"}),"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Me.mutate({action:"resume",runId:C,family:C.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!C||Me.isPending,children:[e("i",{"data-lucide":"play"}),"Resume"]})]})]},C||d)})]}):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,s==="running"&&dt.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:[dt.length," failed"]})]}),dt.slice(0,10).map((o,d)=>{const C=String(o?.run_id||o?.id||d).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:la(o)}),e("span",{className:"tcp-subtle text-xs",children:C||"unknown run"}),on(o?.finished_at_ms||o?.finishedAtMs||o?.updated_at_ms||o?.updatedAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Finished:"," ",on(o?.finished_at_ms||o?.finishedAtMs||o?.updated_at_ms||o?.updatedAtMs)]}):null,ln(o)?e("span",{className:"text-xs text-slate-400",children:Pn(ln(o),160)}):null]}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:je(o?.status),children:String(o?.status||"failed")}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l(C),children:[e("i",{"data-lucide":"bug"}),"Inspect"]})]})]})},`failed-${C||d}`)})]}):null,He.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:s==="running"?"Run Log Explorer":"Recent Runs"}),He.slice(0,12).map((o,d)=>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:la(o)}),e("span",{className:je(o?.status),children:String(o?.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(o?.run_id||o?.id||"")}),on(o?.started_at_ms||o?.startedAtMs||o?.created_at_ms||o?.createdAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Started:"," ",on(o?.started_at_ms||o?.startedAtMs||o?.created_at_ms||o?.createdAtMs)]}):null,o?.finished_at_ms||o?.finishedAtMs?e("span",{className:"tcp-subtle text-xs",children:["Finished: ",on(o?.finished_at_ms||o?.finishedAtMs)]}):null,ln(o)?e("span",{className:"text-xs text-slate-400",children:Pn(ln(o),160)}):null]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{l(String(o?.run_id||o?.id||"").trim()),c()},children:[e("i",{"data-lucide":"info"}),s==="running"?"View logs":"Details"]})]})]},String(o?.run_id||o?.id||d)))]}):null,!He.length&&s==="running"?e(Se,{text:"Run one automation, then use View logs to inspect full execution events."}):null,!k&&!le.length&&!He.length&&s==="list"?e(Se,{text:"No automations yet. Create your first one with the wizard!"}):null,e(Ze,{children:[i?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>l(""),children:e(te.div,{className:"tcp-confirm-dialog tcp-run-debugger-modal overflow-hidden",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:o=>o.stopPropagation(),children:[e("div",{className:"mb-3 flex flex-wrap items-start justify-between gap-3",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(ye?.automation_id||ye?.routine_id||"unknown")," · ","run: ",i," · ","running for ",Ga(ye)]}),W?e("div",{className:"tcp-subtle text-xs",children:["completed nodes:"," ",Array.isArray(ye?.checkpoint?.completed_nodes)?ye.checkpoint.completed_nodes.length:0," · ","active sessions:"," ",Array.isArray(ye?.active_session_ids)?ye.active_session_ids.length:0]}):null]}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:je(ye?.status),children:String(ye?.status||"unknown")}),P.length>1?e("select",{className:"tcp-input h-8 min-w-[16rem] text-xs",value:J,onInput:o=>ne(o.target.value),children:P.map(o=>e("option",{value:o,children:o},o))}):J?e("span",{className:"tcp-badge-info",children:J}):e("span",{className:"tcp-badge-warn",children:"no session"}),e("button",{className:"tcp-btn h-8 px-2 text-xs",onClick:()=>{Promise.all([u.invalidateQueries({queryKey:["automations","run",i]}),u.invalidateQueries({queryKey:["automations","run","artifacts",i]}),J?u.invalidateQueries({queryKey:["automations","run","session",i,J,"messages"]}):Promise.resolve()])},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{className:"tcp-btn h-8 px-2 text-xs",onClick:()=>l(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]}),e("div",{className:"grid max-h-[calc(88vh-8rem)] gap-3 overflow-hidden xl:grid-cols-[1.62fr_1fr]",children:[e("div",{className:"grid min-h-0 gap-3 overflow-hidden",children:[ve.length?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-2 font-medium",children:"Blockers"}),e("div",{className:"grid gap-2",children:ve.map(o=>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:o.title}),e("span",{className:"tcp-badge-warn",children:o.source}),o.at?e("span",{className:"tcp-subtle text-[11px]",children:new Date(o.at).toLocaleTimeString()}):null]}),e("div",{className:"text-sm text-amber-100/90",children:o.reason})]},o.key))})]}):null,e("div",{className:"tcp-list-item min-h-0 overflow-hidden",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:J?`Streaming session ${J}`:"This run does not expose a session transcript."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:!ke.length,onClick:async()=>{try{await navigator.clipboard.writeText(ke.map(o=>`[${new Date(o.at).toLocaleTimeString()}] ${o.label}
|
|
12
|
-
${o.body||kt(o.raw)}`).join(`
|
|
13
|
-
|
|
14
|
-
`)),t("ok","Copied session log.")}catch(o){t("err",o instanceof Error?o.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy"}),"Copy session log"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{E(!0);const o=O.current;o&&(o.scrollTop=o.scrollHeight)},children:[e("i",{"data-lucide":"arrow-down"}),"Jump to latest"]})]})]}),e("div",{ref:O,className:"grid max-h-[30rem] min-h-[18rem] gap-2 overflow-auto pr-1",onScroll:o=>{const d=o.currentTarget,C=d.scrollHeight-(d.scrollTop+d.clientHeight)<48;E(C)},children:ke.length?ke.map(o=>e("div",{className:`rounded-lg border p-3 ${o.variant==="assistant"?"border-sky-500/30 bg-sky-950/10":o.variant==="user"?"border-slate-600/60 bg-slate-900/35":o.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("span",{className:"text-xs font-medium uppercase tracking-wide text-slate-200",children:o.label}),e("span",{className:"tcp-subtle text-[11px]",children:new Date(o.at).toLocaleTimeString()})]}),o.body?e("div",{className:"whitespace-pre-wrap break-words text-sm text-slate-100",children:o.body}):e("div",{className:"tcp-subtle text-xs",children:"No textual body."}),o.kind==="message"&&o.parts.some(d=>String(d?.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:kt(o.parts)})]}):null,o.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:kt(o.raw)})]}):null]},o.id)):e("div",{className:"tcp-subtle text-xs",children:J?"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 overflow-hidden",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 flex-wrap gap-1",children:[e("button",{className:`tcp-btn h-7 px-2 text-[11px] ${q==="all"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>T("all"),children:["all (",X.length,")"]}),e("button",{className:`tcp-btn h-7 px-2 text-[11px] ${q==="automations"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>T("automations"),children:"automations"}),e("button",{className:`tcp-btn h-7 px-2 text-[11px] ${q==="global"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>T("global"),children:"global"})]})]}),Ye.length?e("div",{className:"grid max-h-[18rem] gap-2 overflow-auto pr-1",children:Ye.slice(-40).reverse().map(o=>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:tn(o.event)||"event"}),e("span",{className:"tcp-subtle text-[11px]",children:[new Date(o.at).toLocaleTimeString()," · ",o.source]})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:ga(o.event)||"No summary available."})]}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:kt(o.event?.properties||o.event)})]},o.id))}):e("div",{className:"tcp-subtle text-xs",children:"No automation/global telemetry captured for this run yet."})]})]}),e("div",{className:"grid min-h-0 gap-3 overflow-hidden",children:[St.length?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:"Debug hints"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:St.map(o=>e("div",{children:o},o))})]}):null,e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Run Summary"}),e("div",{className:"mt-2 grid gap-2 text-xs text-slate-300",children:[e("div",{children:["status: ",String(ye?.status||"unknown")]}),e("div",{children:["artifacts: ",String(Ke.length)]}),e("div",{children:["detail: ",String(ye?.detail||"n/a")]}),e("div",{children:["requires_approval: ",String(ye?.requires_approval??"unknown")]}),e("div",{children:["approval_reason: ",String(ye?.approval_reason||"none")]}),e("div",{children:["denial_reason: ",String(ye?.denial_reason||"none")]}),e("div",{children:["paused_reason: ",String(ye?.paused_reason||"none")]})]})]}),e("div",{className:"tcp-list-item",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(ye?.mission_snapshot?.objective||ye?.detail||"n/a")})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:["Artifacts (",Ke.length,")"]}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto",children:kt(Ke)})]}),e("div",{className:"tcp-list-item min-h-0 overflow-hidden",children:[e("div",{className:"font-medium",children:"Persisted History"}),$t.length?e("div",{className:"mt-2 grid max-h-[14rem] gap-2 overflow-auto pr-1",children:$t.map((o,d)=>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(o?.event||o?.type||o?.status||"history")}),e("span",{className:"tcp-subtle text-[11px]",children:new Date(_n(o?.ts_ms||o?.tsMs||o?.at||o?.timestamp_ms)).toLocaleTimeString()})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(o?.detail||o?.reason||o?.status||"No summary available.")})]}),e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:kt(o)})]},`${String(o?.event||o?.type||"history")}-${d}`))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:"No persisted history rows returned for this automation."})]}),e("div",{className:"tcp-list-item min-h-0 overflow-hidden",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 ===",kt(ye),"=== ARTIFACTS ===",kt(Ke),"=== TELEMETRY ===",kt(Ye.map(o=>o.event)),"=== SESSION MESSAGES ===",kt(ge)].join(`
|
|
15
|
-
|
|
16
|
-
`)),t("ok","Copied full debug context.")}catch(o){t("err",o instanceof Error?o.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy all debug context"]})]}),e("pre",{className:"tcp-code max-h-[18rem] overflow-auto",children:kt(ye)})]})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>a("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,b?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>S(null),children:e(te.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:o=>o.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:b.name,onInput:o=>S(d=>d&&{...d,name:o.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:b.objective,onInput:o=>S(d=>d&&{...d,objective:o.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:b.mode,onInput:o=>S(d=>d&&{...d,mode:o.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 ${b.requiresApproval?"border-amber-400/60 bg-amber-400/10":""}`,role:"switch","aria-checked":b.requiresApproval,onClick:()=>S(o=>o&&{...o,requiresApproval:!o.requiresApproval}),children:[e("span",{className:"flex items-center gap-2",children:[e("i",{"data-lucide":b.requiresApproval?"shield-alert":"shield-check"}),b.requiresApproval?"Manual approvals enabled":"Fully automated enabled"]}),e("span",{className:`relative h-5 w-9 rounded-full transition ${b.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 ${b.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:b.scheduleKind,onInput:o=>S(d=>d&&{...d,scheduleKind:o.target.value}),children:[e("option",{value:"interval",children:"interval"}),e("option",{value:"cron",children:"cron"})]})]})}),b.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:b.cronExpression,onInput:o=>S(d=>d&&{...d,cronExpression:o.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:b.intervalSeconds,onInput:o=>S(d=>d&&{...d,intervalSeconds:o.target.value})})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>S(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>b&&Te.mutate(b),disabled:Te.isPending,children:[e("i",{"data-lucide":"check"}),"Save"]})]})]})}):null,D?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>F(null),children:e(te.div,{className:"tcp-confirm-dialog w-[min(56rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:o=>o.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Edit workflow 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:D.name,onInput:o=>F(d=>d&&{...d,name:o.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-[96px]",value:D.description,onInput:o=>F(d=>d&&{...d,description:o.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 ${Sn(D.workspaceRoot)?"border-red-500/70 text-red-100":""}`,value:D.workspaceRoot,onInput:o=>F(d=>d&&{...d,workspaceRoot:o.target.value})}),Sn(D.workspaceRoot)?e("div",{className:"text-xs text-red-300",children:Sn(D.workspaceRoot)}):null]}),e("div",{className:"grid gap-1 sm:grid-cols-3 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:D.scheduleKind,onInput:o=>F(d=>d&&{...d,scheduleKind:o.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-input",value:D.executionMode,onInput:o=>F(d=>d&&{...d,executionMode:o.target.value}),children:Na.map(o=>e("option",{value:o.id,children:o.label},o.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:D.maxParallelAgents,onInput:o=>F(d=>d&&{...d,maxParallelAgents:o.target.value}),disabled:D.executionMode!=="swarm"})]})]}),D.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:D.cronExpression,onInput:o=>F(d=>d&&{...d,cronExpression:o.target.value})})]}):D.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:D.intervalSeconds,onInput:o=>F(d=>d&&{...d,intervalSeconds:o.target.value})})]}):null,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:"Model provider"}),e("select",{className:"tcp-input",value:D.modelProvider,onInput:o=>F(d=>d&&{...d,modelProvider:o.target.value,modelId:""}),children:[e("option",{value:"",children:"Workspace default"}),Qe.map(o=>e("option",{value:o.id,children:o.id},o.id))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("select",{className:"tcp-input",value:D.modelId,onInput:o=>F(d=>d&&{...d,modelId:o.target.value}),children:[e("option",{value:"",children:"Workspace default"}),(Qe.find(o=>o.id===D.modelProvider)?.models||[]).map(o=>e("option",{value:o,children:o},o))]}),oa(D.modelProvider,D.modelId)?e("div",{className:"text-xs text-red-300",children:oa(D.modelProvider,D.modelId)}):null]})]}),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:"Planner provider"}),e("select",{className:"tcp-input",value:D.plannerModelProvider,onInput:o=>F(d=>d&&{...d,plannerModelProvider:o.target.value,plannerModelId:""}),children:[e("option",{value:"",children:"Use workflow model"}),Qe.map(o=>e("option",{value:o.id,children:o.id},o.id))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("select",{className:"tcp-input",value:D.plannerModelId,onInput:o=>F(d=>d&&{...d,plannerModelId:o.target.value}),children:[e("option",{value:"",children:"Use workflow model"}),(Qe.find(o=>o.id===D.plannerModelProvider)?.models||[]).map(o=>e("option",{value:o,children:o},o))]}),Kn(D.plannerModelProvider,D.plannerModelId)?e("div",{className:"text-xs text-red-300",children:Kn(D.plannerModelProvider,D.plannerModelId)}):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:"MCP Servers"}),ft.length?e("div",{className:"flex flex-wrap gap-2",children:ft.map(o=>{const d=D.selectedMcpServers.includes(o.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${d?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>F(C=>C&&{...C,selectedMcpServers:d?C.selectedMcpServers.filter(Q=>Q!==o.name):[...C.selectedMcpServers,o.name].sort()}),children:[o.name," ",o.connected?"• connected":"• disconnected"]},o.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet."})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>F(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>D&&st.mutate(D),disabled:st.isPending,children:[e("i",{"data-lucide":"check"}),st.isPending?"Saving...":"Save"]})]})]})}):null,w?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>M(null),children:e(te.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:o=>o.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:w.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>M(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger",disabled:Ae.isPending,onClick:()=>Ae.mutate({action:"delete",automationId:w.automationId,family:w.family},{onSettled:()=>M(null)}),children:[e("i",{"data-lucide":"trash-2"}),Ae.isPending?"Deleting...":"Delete automation"]})]})]})}):null]})]})}function dl({client:n,toast:t}){const a=Lt(),s=j({queryKey:["automations","approvals"],queryFn:()=>n?.agentTeams?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),i=j({queryKey:["automations","instances"],queryFn:()=>n?.agentTeams?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),l=me({mutationFn:({requestId:p,decision:w})=>n?.agentTeams?.replyApproval?.(p,w),onSuccess:async()=>{t("ok","Approval updated."),await a.invalidateQueries({queryKey:["automations"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),c=Vt(s.data,"spawnApprovals"),u=Vt(i.data,"instances");return e("div",{className:"grid gap-4",children:[c.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"}),c.map((p,w)=>{const M=String(p?.request_id||p?.id||`request-${w}`);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:M}),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:M,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:M,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},M)})]}):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,w)=>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||w)))]}):null,!c.length&&!u.length?e(Se,{text:"No pending approvals or active team instances."}):null]})}function ul({client:n,api:t,toast:a,navigate:s,providerStatus:i}){const[l,c]=y("create"),[u,p]=y("");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 New",icon:"sparkles"},{id:"list",label:"My Automations",icon:"clipboard-list"},{id:"running",label:"Live Tasks",icon:"activity"},{id:"approvals",label:"Teams & Approvals",icon:"users"}].map(M=>e("button",{onClick:()=>c(M.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===M.id?"bg-amber-500/20 text-amber-300 shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[e("i",{"data-lucide":M.icon}),e("span",{children:M.label})]},M.id))}),e(Ze,{mode:"wait",children:e(te.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-6},transition:{duration:.15},children:l==="create"?e(an,{title:"Create an Automation",subtitle:"Describe what you want, pick a schedule, and Tandem handles the rest",children:e(cl,{client:n,api:t,toast:a,navigate:s,defaultProvider:i.defaultProvider,defaultModel:i.defaultModel})}):l==="list"?e(an,{title:"My Automations",subtitle:"Installed packs, routines and run history",children:e(za,{client:n,toast:a,navigate:s,viewMode:"list",selectedRunId:u,onSelectRunId:p,onOpenRunningView:()=>c("running")})}):l==="running"?e(an,{title:"Live Running Tasks",subtitle:"Inspect active runs and open detailed event logs for each run",children:e(za,{client:n,toast:a,navigate:s,viewMode:"running",selectedRunId:u,onSelectRunId:p,onOpenRunningView:()=>c("running")})}):e(an,{title:"Teams & Approvals",subtitle:"Active agent teams and pending spawn approvals",children:e(dl,{client:n,toast:a})})},l)})]})}function ml({client:n,toast:t}){const a=Lt(),s=j({queryKey:["channels","status"],queryFn:()=>n.channels.status().catch(()=>({})),refetchInterval:6e3}),i=j({queryKey:["channels","config"],queryFn:()=>n.channels.config().catch(()=>({})),refetchInterval:15e3}),l=me({mutationFn:async p=>{const M=(i.data||{})[p];if(!M)throw new Error(`No config found for ${p}`);await n.channels.put(p,M)},onSuccess:async()=>{t("ok","Channel reconfigured."),await a.invalidateQueries({queryKey:["channels"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),c=s.data&&typeof s.data=="object"?s.data:{},u=Object.entries(c);return e("div",{className:"grid gap-4",children:e(an,{title:"Channels",subtitle:"Connector health and quick reconnect",children:e("div",{className:"grid gap-2",children:u.length?u.map(([p,w])=>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:w?.connected?"tcp-badge-ok":"tcp-badge-warn",children:w?.connected?"connected":"disconnected"})]}),e("div",{className:"tcp-subtle text-xs",children:String(w?.last_error||w?.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(Se,{text:"No channels configured."})})})})}function it(n,t){return Array.isArray(n)?n:Array.isArray(n?.[t])?n[t]:[]}function _e(n){return String(n||"").trim()}function ca(n){try{return JSON.stringify(n,null,2)}catch{return"{}"}}function pl(n){return n?"ok":"ghost"}function hl(n){return _e(n?.event_type||n?.type||n?.event||"workflow.event")}function gl({api:n,toast:t}){const a=Lt(),[s,i]=y(""),[l,c]=y(""),[u,p]=y(""),[w,M]=y("context.task.created"),[b,S]=y(`{
|
|
17
|
-
"event_id": "demo-task-1"
|
|
18
|
-
}`),[q,T]=y([]),X=j({queryKey:["packs","list"],queryFn:()=>n("/api/engine/packs",{method:"GET"}).catch(()=>({packs:[]})),refetchInterval:15e3}),z=j({queryKey:["workflows","list"],queryFn:()=>n("/api/engine/workflows",{method:"GET"}).catch(()=>({workflows:[]})),refetchInterval:15e3}),J=j({queryKey:["workflows","hooks"],queryFn:()=>n("/api/engine/workflow-hooks",{method:"GET"}).catch(()=>({hooks:[]})),refetchInterval:15e3}),ne=it(X.data,"packs"),G=it(z.data,"workflows"),x=it(J.data,"hooks"),O=V(()=>l||_e(ne[0]?.pack_id||ne[0]?.name),[ne,l]),B=V(()=>u||_e(G[0]?.workflow_id),[u,G]),E=j({queryKey:["workflows","runs",B],queryFn:()=>n(`/api/engine/workflows/runs${B?`?workflow_id=${encodeURIComponent(B)}&limit=20`:"?limit=20"}`,{method:"GET"}).catch(()=>({runs:[]})),refetchInterval:6e3}),D=it(E.data,"runs"),F=j({queryKey:["packs","detail",O],enabled:!!O,queryFn:()=>n(`/api/engine/packs/${encodeURIComponent(O)}`,{method:"GET"})}),W=j({queryKey:["workflows","detail",B],enabled:!!B,queryFn:()=>n(`/api/engine/workflows/${encodeURIComponent(B)}`,{method:"GET"})}),oe=me({mutationFn:()=>n("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:s,source:{kind:"control-panel"}})}),onSuccess:async()=>{t("ok","Pack installed."),i(""),await Promise.all([a.invalidateQueries({queryKey:["packs"]}),a.invalidateQueries({queryKey:["workflows"]})])},onError:I=>t("err",I instanceof Error?I.message:String(I))}),xe=me({mutationFn:I=>n(`/api/engine/workflows/${encodeURIComponent(I)}/run`,{method:"POST"}),onSuccess:async I=>{t("ok",`Workflow ${_e(I?.run?.workflow_id||B)} started.`),await Promise.all([a.invalidateQueries({queryKey:["workflows"]}),a.invalidateQueries({queryKey:["workflows","runs"]})])},onError:I=>t("err",I instanceof Error?I.message:String(I))}),Ie=me({mutationFn:async()=>{let I={};const P=_e(b);return P&&(I=JSON.parse(P)),n("/api/engine/workflows/simulate",{method:"POST",body:JSON.stringify({event_type:w,properties:I})})},onError:I=>t("err",I instanceof Error?I.message:String(I))}),pe=me({mutationFn:({bindingId:I,enabled:P})=>n(`/api/engine/workflow-hooks/${encodeURIComponent(I)}`,{method:"PATCH",body:JSON.stringify({enabled:P})}),onSuccess:async()=>{await Promise.all([a.invalidateQueries({queryKey:["workflows","hooks"]}),a.invalidateQueries({queryKey:["workflows","detail"]})])},onError:I=>t("err",I instanceof Error?I.message:String(I))}),Ne=F.data?.pack||null,fe=W.data?.workflow||null,Oe=it(W.data,"hooks"),se=Ie.data?.simulation||null;return gn(`/api/engine/workflows/events${B?`?workflow_id=${encodeURIComponent(B)}`:""}`,I=>{try{const P=JSON.parse(I.data);if(P?.status==="ready")return;T(ee=>[...ee.slice(-59),{at:Date.now(),data:P}])}catch{}},{enabled:!0}),e(Mn,{className:"grid gap-4",children:[e(Xi,{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(ae,{tone:"info",children:[ne.length," installed packs"]}),e(ae,{tone:"warn",children:[G.length," workflows"]}),e(ae,{tone:"ghost",children:[x.length," hooks"]})]})}),e(In,{main:e("div",{className:"grid gap-4",children:[e(Le,{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:ne.length?ne.map((I,P)=>{const ee=_e(I?.pack_id||I?.name||P);return e("button",{type:"button",className:`tcp-list-item text-left ${ee===O?"border-amber-400/70":""}`,onClick:()=>c(ee),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:_e(I?.name||ee)}),e("span",{className:"tcp-badge-info",children:_e(I?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-subtle",children:_e(I?.pack_type||"pack")}),e("span",{className:"tcp-subtle",children:_e(I?.install_path||"")})]})]},ee)}):e(Se,{text:"No packs are installed yet."})})}),e(Le,{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:G.length?G.map(I=>{const P=_e(I?.workflow_id),ee=P===B,ce=_e(I?.source?.kind||"unknown");return e("button",{type:"button",className:`tcp-list-item text-left ${ee?"border-amber-400/70":""}`,onClick:()=>p(P),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:_e(I?.name||P)}),e("span",{className:`tcp-badge-${ce==="pack"?"warn":"info"}`,children:ce})]}),e("div",{className:"tcp-subtle text-xs",children:[P," · ",it(I?.steps,"steps").length," steps"]})]},P)}):e(Se,{text:"No workflows are currently registered."})})})]}),aside:e("div",{className:"grid gap-4",children:[e(Le,{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:s,onInput:I=>i(I.target.value),placeholder:"/path/to/pack.zip"}),e("button",{className:"tcp-btn-primary",disabled:!s.trim()||oe.isPending,onClick:()=>oe.mutate(),children:[e("i",{"data-lucide":"download"}),"Install from path"]})]})}),e(Le,{title:"Pack inspector",subtitle:"Shows which workflows and hooks a pack contributes, alongside its current capability surface.",children:Ne?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:_e(Ne?.installed?.name||O)}),e(ae,{tone:"info",children:_e(Ne?.installed?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e(ae,{tone:"ghost",children:[Number(Ne?.workflow_extensions?.workflow_count||0)," ","workflows"]}),e(ae,{tone:"ghost",children:[Number(Ne?.workflow_extensions?.workflow_hook_count||0)," ","hooks"]}),e(ae,{tone:"ghost",children:[Number(Ne?.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"}),it(Ne?.workflow_extensions,"workflow_entrypoints").length?it(Ne?.workflow_extensions,"workflow_entrypoints").map((I,P)=>e("div",{className:"tcp-list-item text-sm",children:_e(I)},`${_e(I)}-${P}`)):e(Se,{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:ca(Ne?.manifest||{})})]})]}):e(Se,{text:"Select an installed pack to inspect workflow extensions."})})]})}),e(In,{main:e(Le,{title:"Workflow viewer",subtitle:"Structured view of workflow steps and source provenance for the selected workflow.",actions:e("button",{className:"tcp-btn",disabled:!B||xe.isPending,onClick:()=>B&&xe.mutate(B),children:[e("i",{"data-lucide":"play"}),"Run workflow"]}),children:fe?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:_e(fe?.name||B)}),e(ae,{tone:"info",children:_e(fe?.source?.kind||"unknown")})]}),e("div",{className:"tcp-subtle text-sm",children:_e(fe?.description||"No description provided.")})]}),e("div",{className:"grid gap-2",children:it(fe,"steps").length?it(fe,"steps").map((I,P)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 text-xs uppercase tracking-[0.24em] text-slate-400",children:["Step ",P+1]}),e("div",{className:"font-medium",children:_e(I?.action||"unknown")}),I?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:ca(I.with)}):null]},_e(I?.step_id||P))):e(Se,{text:"This workflow does not define any linear steps."})})]}):e(Se,{text:"Select a workflow to inspect its current resolved definition."})}),aside:e("div",{className:"grid gap-4",children:[e(Le,{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:Oe.length?Oe.map(I=>{const P=_e(I?.binding_id),ee=!!I?.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:_e(I?.event||P)}),e("div",{className:"tcp-subtle text-xs",children:P})]}),e("button",{className:"tcp-btn",disabled:pe.isPending,onClick:()=>pe.mutate({bindingId:P,enabled:!ee}),children:ee?"Disable":"Enable"})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e(ae,{tone:pl(ee),children:ee?"Enabled":"Disabled"}),e(ae,{tone:"ghost",children:[it(I,"actions").length," actions"]})]}),e("div",{className:"grid gap-1",children:it(I,"actions").map((ce,N)=>e("div",{className:"tcp-subtle text-xs",children:_e(ce?.action||ce)},`${P}-${N}`))})]},P)}):e(Se,{text:"The selected workflow has no registered hooks."})})}),e(Le,{title:"Recent workflow runs",subtitle:"Latest workflow executions for the selected workflow, including hook-triggered runs.",children:e("div",{className:"grid gap-2",children:D.length?D.map((I,P)=>{const ee=_e(I?.status||"unknown"),ce=ee==="completed"?"ok":ee==="failed"?"err":ee==="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:_e(I?.run_id||`run-${P+1}`)}),e(ae,{tone:ce,children:ee})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger: ",_e(I?.trigger_event||"manual")]}),e("div",{className:"tcp-subtle text-xs",children:["actions: ",it(I,"actions").length]})]},_e(I?.run_id||P))}):e(Se,{text:"No workflow runs have been recorded yet."})})})]})}),e(In,{main:e(Le,{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:!w.trim()||Ie.isPending,onClick:()=>Ie.mutate(),children:[e("i",{"data-lucide":"flask-conical"}),"Simulate"]}),children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:w,onInput:I=>M(I.target.value),placeholder:"context.task.created"}),e("textarea",{className:"tcp-input min-h-[180px] font-mono text-xs",value:b,onInput:I=>S(I.target.value),spellCheck:!1}),se?e("div",{className:"grid gap-3",children:[e("div",{className:"flex flex-wrap gap-2",children:it(se,"canonical_events").map((I,P)=>e(ae,{tone:"info",children:_e(I)},`${_e(I)}-${P}`))}),e("div",{className:"grid gap-2",children:it(se,"matched_bindings").length?it(se,"matched_bindings").map(I=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:_e(I?.binding_id)}),e("div",{className:"tcp-subtle text-xs",children:[_e(I?.event)," · ",it(I,"actions").length," ","actions"]})]},_e(I?.binding_id))):e(Se,{text:"No workflow hooks matched this event."})})]}):e(Se,{text:"Run a simulation to inspect canonical events, matched bindings, and planned actions."})]})}),aside:e(Le,{title:"Triggered actions",subtitle:"Preview of actions the engine plans to execute for the simulated event.",children:e("div",{className:"grid gap-2",children:it(se,"planned_actions").length?it(se,"planned_actions").map((I,P)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:_e(I?.action||I)}),I?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:ca(I.with)}):null]},`${_e(I?.action||I)}-${P}`)):e(Se,{text:"No planned actions yet."})})})}),e(Le,{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:()=>T([]),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:q.length?[...q].reverse().map((I,P)=>{const ee=hl(I.data),ce=ee.endsWith(".failed")?"err":ee.endsWith(".completed")?"ok":ee.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:ee}),e(ae,{tone:ce,children:new Date(I.at).toLocaleTimeString()})]}),e("div",{className:"tcp-subtle text-xs",children:["run: ",_e(I.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle text-xs",children:["action:"," ",_e(I.data?.properties?.action||I.data?.properties?.actionID||"-")]})]},`${I.at}-${P}`)}):e(Se,{text:"Run a workflow or trigger a hook to watch live workflow events here."})})})]})}function qs(n){return n>=1?"bg-rose-500":n>=.8?"bg-amber-500":"bg-emerald-500"}function Cn(n,t){return!t||t<=0?0:Math.min(n/t,1)}function Ln({label:n,used:t,max:a,unit:s,advisory:i=!1}){const l=Cn(t,a),c=i?l>=.8?"bg-sky-400":"bg-cyan-500":qs(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:n}),e("span",{className:"font-mono text-[11px] text-slate-200",children:[t.toLocaleString(),s||""," / ",a.toLocaleString(),s||""]})]}),e("div",{className:"h-1.5 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${c}`,style:{width:`${l*100}%`}})})]})}function fl({budget:n}){const[t,a]=y(!1),s=n.limits_enforced===!1,i=Math.max(Cn(n.iterations_used,n.max_iterations),Cn(n.tokens_used,n.max_tokens),Cn(n.wall_time_secs,n.max_wall_time_secs),Cn(n.subagent_runs_used,n.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:()=>a(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 ${s?i>=.8?"bg-sky-400":"bg-cyan-500":qs(i)}`,style:{width:`${i*100}%`}})}),e("span",{className:"tcp-subtle text-xs",children:[Math.round(i*100),"%"]})]})]}),t?e("div",{className:"mt-3 grid gap-3 border-t border-slate-700/60 pt-3",children:[e(Ln,{label:"Iterations",used:n.iterations_used,max:n.max_iterations,advisory:s}),e(Ln,{label:"Tokens",used:n.tokens_used,max:n.max_tokens,advisory:s}),e(Ln,{label:"Wall time",used:n.wall_time_secs,max:n.max_wall_time_secs,unit:"s",advisory:s}),e(Ln,{label:"Agent calls",used:n.subagent_runs_used,max:n.max_subagent_runs,advisory:s}),s?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,n.exceeded&&n.exceeded_reason?e("div",{className:"rounded border border-rose-500/40 bg-rose-950/30 p-2 text-xs text-rose-200",children:n.exceeded_reason}):null]}):null]})}const bl={created:"Created",pending:"Pending",runnable:"Runnable",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"};function yl(n){return n==="done"||n==="validated"?"tcp-badge-ok":n==="failed"?"tcp-badge-err":n==="in_progress"||n==="runnable"||n==="assigned"?"tcp-badge-warn":"tcp-badge-info"}function vl(n){return n==="in_progress"||n==="assigned"?e("i",{"data-lucide":"loader-circle",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null}function wl({task:n,isCurrent:t,isSelected:a,workflowSummary:s,onTaskSelect:i,onRetryTask:l}){const[c,u]=y(!1),p=n.state==="failed"||n.state==="blocked"?String(n.error_message||"").trim():"";return e("div",{className:`rounded-lg border p-2 ${a?"border-cyan-400/70 bg-cyan-950/20":t?"border-amber-400/70":"border-slate-700/60 bg-slate-900/20"}`,onClick:()=>i?.(n),children:[e("div",{className:"mb-1 flex items-start justify-between gap-2",children:[e("div",{className:"text-xs font-medium leading-snug",title:n.title,children:n.title}),e("span",{className:`${yl(n.state)} inline-flex shrink-0 items-center gap-1`,children:[vl(n.state),e("span",{children:bl[n.state]})]})]}),n.description?e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:n.description}):null,n.assigned_role||n.gate?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[n.assigned_role?e("span",{className:"rounded border border-cyan-600/50 bg-cyan-950/30 px-1.5 py-0.5",children:["role: ",n.assigned_role]}):null,n.gate?e("span",{className:"rounded border border-amber-600/50 bg-amber-950/30 px-1.5 py-0.5",children:["gate: ",n.gate]}):null]}):null,s&&s.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: ",s.runs]}),s.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: ",s.failed]}):null]}):null,p?e("div",{className:"mt-1 text-xs text-rose-300",children:[e("div",{className:c?"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(w=>!w),children:c?"Less":"More"}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-1",children:n.dependencies.map(w=>e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["<-"," ",w]},w))}),n.state==="failed"&&l?e("button",{className:"tcp-btn mt-2 h-7 px-2 text-xs",onClick:w=>{w.stopPropagation(),l(n)},children:"Retry Task"}):null]})}function xl({tasks:n,currentTaskId:t,selectedTaskId:a,workflowSummaryByTaskId:s,onTaskSelect:i,onRetryTask:l}){const c=V(()=>{const p={created:[],pending:[],runnable:[],assigned:[],in_progress:[],blocked:[],done:[],failed:[],validated:[]};for(const S of n)p[S.state].push(S);const w=new Set([...p.done,...p.validated].map(S=>S.id)),M=[...p.runnable],b=[];for(const S of[...p.created,...p.pending])S.dependencies.length===0||S.dependencies.every(T=>w.has(T))?M.push(S):b.push(S);return{runnable:M,waiting:b,assigned:p.assigned,in_progress:p.in_progress,blocked:p.blocked,done:[...p.done,...p.validated],failed:p.failed}},[n]),u=[{key:"runnable",label:"Ready",tasks:c.runnable},{key:"waiting",label:"Waiting on deps",tasks:c.waiting},{key:"assigned",label:"Assigned",tasks:c.assigned},{key:"in_progress",label:"In Progress",tasks:c.in_progress},{key:"blocked",label:"Blocked",tasks:c.blocked},{key:"done",label:"Done",tasks:c.done},{key:"failed",label:"Failed",tasks:c.failed}];return n.length?e("div",{className:"grid gap-3 xl:grid-cols-3",children:u.map(p=>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:p.label}),e("div",{className:"tcp-subtle text-xs",children:p.tasks.length})]}),e("div",{className:"grid max-h-[280px] gap-2 overflow-auto",children:[p.tasks.map(w=>e(wl,{task:w,isCurrent:w.id===t,isSelected:w.id===a,workflowSummary:s?.[w.id],onTaskSelect:i,onRetryTask:l},w.id)),p.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},p.key))}):e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-4",children:"No tasks yet."})}function Ts(n){const t=String(n||"").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 Nl(n){const t={};for(const a of Array.isArray(n)?n:[]){const s=String(a?.step_id||a?.payload?.task_id||"").trim();if(!s)continue;const i=a?.payload&&typeof a.payload=="object"?a.payload:{},l=t[s]||{assignedRole:"",errorMessage:"",runtimeDetail:"",runtimeStatus:"",sessionId:""};t[s]={assignedRole:String(i?.assigned_agent||i?.agent_id||l.assignedRole||""),errorMessage:String(i?.error||l.errorMessage||""),runtimeDetail:String(i?.why_next_step||l.runtimeDetail||""),runtimeStatus:String(i?.step_status||l.runtimeStatus||""),sessionId:String(i?.session_id||l.sessionId||"")}}return t}function kl(n,t){const a=Ts(n?.status);return{id:String(n?.id||""),title:String(n?.payload?.title||n?.task_type||n?.id||"Untitled task"),description:String(n?.payload?.description||""),dependencies:Array.isArray(n?.depends_on_task_ids)?n.depends_on_task_ids.map(s=>String(s||"")).filter(Boolean):[],state:a,retry_count:Number(n?.attempt||n?.retry_count||0),error_message:a==="failed"||a==="blocked"?String(n?.last_error||t?.errorMessage||""):"",runtime_status:String(t?.runtimeStatus||""),runtime_detail:String(t?.runtimeDetail||""),assigned_role:String(n?.assigned_agent||n?.lease_owner||t?.assignedRole||""),workflow_id:String(n?.workflow_id||""),session_id:String(t?.sessionId||"")}}function Sl(n,t){const a=Ts(n?.stepStatus||n?.status);return{id:String(n?.taskId||n?.step_id||""),title:String(n?.title||n?.step_id||"Untitled step"),description:String(n?.description||""),dependencies:Array.isArray(n?.dependsOn)?n.dependsOn.map(s=>String(s||"")).filter(Boolean):[],state:a,retry_count:Number(n?.retry_count||0),error_message:a==="failed"||a==="blocked"?String(n?.error_message||t?.errorMessage||""):"",runtime_status:String(n?.runtime_status||t?.runtimeStatus||""),runtime_detail:String(n?.runtime_detail||t?.runtimeDetail||""),assigned_role:String(n?.assignedAgent||t?.assignedRole||""),workflow_id:String(n?.workflowId||""),session_id:String(n?.sessionId||n?.session_id||t?.sessionId||"")}}function _l(n){const t=Nl(n?.events),a=Array.isArray(n?.run?.tasks)?n.run.tasks:[],s=a.length?a:Array.isArray(n?.blackboard?.tasks)?n.blackboard.tasks:[],i=Array.isArray(n?.tasks)?n.tasks:[],l=s.map(b=>kl(b,t[String(b?.id||"").trim()])).filter(b=>b.id),c=i.map(b=>Sl(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 c){if(!u.has(b.id)){u.set(b.id,b);continue}const S=u.get(b.id);S&&u.set(b.id,{...S,session_id:S.session_id||b.session_id,runtime_status:S.runtime_status||b.runtime_status,runtime_detail:S.runtime_detail||b.runtime_detail,assigned_role:S.assigned_role||b.assigned_role,error_message:S.error_message||b.error_message})}const p=[...u.values()],w=String(n?.run?.current_step_id||"").trim()||p.find(b=>b.state==="in_progress"||b.state==="assigned")?.id||"",M=l.length?c.length?"hybrid":(a.length,"blackboard"):c.length?"context_steps":"empty";return{currentTaskId:w,taskSource:M,tasks:p}}function fa(n,t=0){return String(n?.run_id||n?.runId||`run-${t}`).trim()}function Ya(n){const t=Number(n?.updated_at_ms||n?.updatedAtMs||0),a=Number(n?.created_at_ms||n?.createdAtMs||0),s=Number.isFinite(t)&&t>0?t:a;return Number.isFinite(s)&&s>0?s:0}function Cl(n,t=""){const a=String(t||"").trim(),s=[...Array.isArray(n)?n:[]].sort((c,u)=>Ya(u)-Ya(c));if(a){const c=s.find((u,p)=>fa(u,p)===a);if(c){const u=String(c?.status||"").trim().toLowerCase();if(!["completed","failed","cancelled"].includes(u))return a}}const l=s.find(c=>{const u=String(c?.status||"").trim().toLowerCase();return!["completed","failed","cancelled"].includes(u)})||s[0];return l?fa(l):""}function Il(n,t){if(t.type==="sync_runs"){const a={},s=[];for(let l=0;l<t.runs.length;l+=1){const c=t.runs[l],u=fa(c,l);u&&(a[u]=c,s.push(u))}let i=n.selectedRunId;return i||(i=Cl(t.runs,t.preferredRunId)),{runsById:a,orderedRunIds:s,selectedRunId:i,cursorsByRunId:n.cursorsByRunId}}if(t.type==="select_run")return{...n,selectedRunId:String(t.runId||"").trim()};if(t.type==="clear_selection")return{...n,selectedRunId:""};if(t.type==="advance_cursor"){const a=String(t.runId||"").trim();if(!a)return n;const s=Number(t.seq||0);if(!Number.isFinite(s)||s<=0)return n;const i=String(t.kind||"").trim().toLowerCase(),l=n.cursorsByRunId[a]||{eventSeq:0,patchSeq:0},c={eventSeq:i==="context_run_event"?Math.max(l.eventSeq,s):l.eventSeq,patchSeq:i==="blackboard_patch"?Math.max(l.patchSeq,s):l.patchSeq};return c.eventSeq===l.eventSeq&&c.patchSeq===l.patchSeq?n:{...n,cursorsByRunId:{...n.cursorsByRunId,[a]:c}}}return n}function Al(n,t=""){const[a,s]=js(Il,{runsById:{},orderedRunIds:[],selectedRunId:"",cursorsByRunId:{}});ie(()=>{s({type:"sync_runs",runs:Array.isArray(n)?n:[],preferredRunId:t})},[n,t]);const i=V(()=>a.orderedRunIds.map(l=>a.runsById[l]).filter(Boolean),[a.orderedRunIds,a.runsById]);return{runsById:a.runsById,orderedRunIds:a.orderedRunIds,orderedRuns:i,selectedRunId:a.selectedRunId,cursorsByRunId:a.cursorsByRunId,setSelectedRunId:l=>s({type:"select_run",runId:l}),clearSelectedRunId:()=>s({type:"clear_selection"}),advanceCursor:(l,c,u)=>s({type:"advance_cursor",runId:l,kind:c,seq:u})}}function Pl(n){const t={},a={};for(const[l,c]of Object.entries(n||{})){const u=Number(c?.eventSeq||0),p=Number(c?.patchSeq||0);u>0&&(t[l]=u),p>0&&(a[l]=p)}const i=JSON.stringify({events:t,patches:a});return!i||i==='{"events":{},"patches":{}}'?"":btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Rl({workspace:n,runIds:t,cursorToken:a,onEnvelope:s,onError:i}){const l=V(()=>[...new Set((t||[]).map(u=>String(u||"").trim()).filter(Boolean))],[t]),c=V(()=>{const u=String(n||"").trim();if(!u||!l.length)return"";const p=new URLSearchParams;return p.set("workspace",u),p.set("runIds",l.join(",")),a&&p.set("cursor",a),`/api/orchestrator/events?${p.toString()}`},[a,l,n]);ie(()=>{if(!c)return;const u=xa(c,p=>{let w=null;try{w=JSON.parse(String(p?.data||"{}"))}catch{return}!w||typeof w!="object"||s(w)},{onError:p=>{i&&i(p)}});return()=>u()},[s,i,c])}const $l={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 Gt(n){const t=String(n||"").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 Ml(n){const t=String(n||"").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 Xa(n){const t=Number(n||0);return!Number.isFinite(t)||t<=0?"Run":`Run ${new Date(t).toLocaleTimeString()}`}function ql(n){return Number(n?.updated_at_ms||n?.created_at_ms||0)}function nn(n){const t=Number(n||0);return!Number.isFinite(t)||t<=0?"--:--:--":new Date(t).toLocaleTimeString()}function Tl(n){const t=Number(n||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 El(n){const t=String(n||"").trim(),a=t.lastIndexOf(".");return a<0?"":t.slice(a+1).toLowerCase()}function Rn(n){const t=String(n||"").trim().replace(/\\/g,"/");return t?t.startsWith("/")?t.replace(/\/{2,}/g,"/"):t:""}function Ol(n,t){const a=Rn(n).replace(/\/+$/,""),s=Rn(t).replace(/^\/+/,"");return a?s?`${a}/${s}`:a:s}function Za(n,t){const a=Rn(n).replace(/\/+$/,""),s=Rn(t);return!a||!s?!1:s===a?!0:s.startsWith(`${a}/`)}function es(n){const t=[n?.workspace?.canonical_path,n?.workspace?.path,n?.workspace?.root,n?.workspace_root,n?.workspacePath,n?.cwd,n?.path];for(const a of t){const s=Rn(String(a||""));if(s.startsWith("/"))return s}return""}function ts(n){const t={};for(const a of n){const s=String(a?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(s))continue;const i=String(a?.step_id||"").trim();if(!i)continue;const l=Number(a?.seq||0);!Number.isFinite(l)||l<=0||(t[i]=Math.max(Number(t[i]||0),l))}return t}function Fl(n){return String(n?.event_type||n?.type||n?.event||"workflow.event").trim().toLowerCase()}function ns(n){const t=[`type: ${String(n.type||"").trim()||"unknown"}`,`task: ${String(n.taskId||"").trim()||"n/a"}`,`title: ${String(n.title||"").trim()||"n/a"}`,`mode: ${String(n.mode||"").trim()||"strict"}`,`at: ${nn(n.at)}`,"","reason:",String(n.reason||"").trim()||"No verification detail."],a=n.verification?.execution_trace;return a&&typeof a=="object"&&t.push("","execution_trace:",`session: ${String(a.session_id||"n/a")}`,`model: ${[String(a?.model?.provider||"").trim(),String(a?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"}`,`source: ${String(a?.model?.source||"n/a")}`),t.push("","verification_json:",JSON.stringify(n.verification||{},null,2)),t.join(`
|
|
19
|
-
`)}function pn(n){const t=String(n?.task_id||n?.taskID||"").trim();if(t)return t;const a=n?.source_event_id||n?.sourceEventID,s=String(a||"").trim();if(!s)return"";const i=s.lastIndexOf(":");return i<0?"":s.slice(i+1).trim()}function Dl({api:n,toast:t,navigate:a}){const s=Lt(),i=!!ds(),l=wt(null),[c,u]=y(!0),[p,w]=y(!1),[M,b]=y(""),[S,q]=y(""),[T,X]=y(!1),[z,J]=y(""),[ne,G]=y(""),[x,O]=y(!1),[B,E]=y("4"),[D,F]=y("3"),[W,oe]=y("swarm.blackboard.default"),[xe,Ie]=y(""),[pe,Ne]=y(""),[fe,Oe]=y(""),[se,I]=y(""),[P,ee]=y([]),[ce,N]=y(""),[ue,be]=y(""),[Re,Me]=y(""),[Te,st]=y(!1);ie(()=>{u(!0),bt()},[]);const Ae=j({queryKey:["swarm","status"],queryFn:()=>n("/api/orchestrator/status"),refetchInterval:5e3}),ht=j({queryKey:["swarm","runs",S],queryFn:()=>n(`/api/orchestrator/runs?workspace=${encodeURIComponent(S||"")}`),refetchInterval:6e3,enabled:!!Ae.data}),gt=Array.isArray(ht.data?.runs)?ht.data.runs:[],We=Al(gt,String(Ae.data?.runId||"").trim()),Qe=We.selectedRunId,ft=We.setSelectedRunId,bt=We.clearSelectedRunId,He=We.advanceCursor,le=c?"":String(Qe||"").trim(),Be=We.orderedRuns,dt=V(()=>{if(!le)return null;for(const m of Be)if(String(m?.run_id||m?.runId||"").trim()===le)return m;return null},[Be,le]),ye=V(()=>Pl(We.cursorsByRunId),[We.cursorsByRunId]),Ke=String(S||Ae.data?.workspaceRoot||"").trim(),St=V(()=>{const m=String(le||"").trim();return m?[m]:[]},[le]),$t=wt(0),Ye=Ee(m=>{const _=String(m?.kind||"").trim().toLowerCase(),U=String(m?.run_id||m?.runId||"").trim();if(le&&U&&U!==le)return;const de=Number(m?.seq||0);U&&de>0&&(_==="context_run_event"||_==="blackboard_patch")&&He(U,_,de);const re=Date.now();re-$t.current<900||($t.current=re,s.invalidateQueries({queryKey:["swarm","runs"]}),le&&s.invalidateQueries({queryKey:["swarm","run",le]}))},[He,s,le]);Rl({workspace:Ke,runIds:St,cursorToken:ye,onEnvelope:Ye});const ge=j({queryKey:["swarm","run",le],queryFn:()=>n(`/api/orchestrator/run/${encodeURIComponent(le)}`),refetchInterval:4e3,enabled:!!le}),je=j({queryKey:["swarm","workspace-browser",z],enabled:T&&!!z,queryFn:()=>n(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(z)}`)}),Ge=String(ge.data?.runStatus||ge.data?.run?.status||Ae.data?.status||"idle").trim().toLowerCase(),De=V(()=>_l(ge.data),[ge.data]),ut=De.tasks,g=V(()=>({...$l,...ge.data?.budget||{}}),[ge.data?.budget]),k=String(es(ge.data?.run)||es(dt)||(le?"":String(Ae.data?.workspaceRoot||S||""))).trim();ie(()=>{k&&(Ne(m=>!m||!Za(k,m)?k:m),Oe(m=>Za(k,m)?m:""))},[k]);const ve=Array.isArray(je.data?.directories)?je.data.directories:[],ke=String(ne||"").trim().toLowerCase(),o=V(()=>ke?ve.filter(m=>String(m?.name||m?.path||"").trim().toLowerCase().includes(ke)):ve,[ve,ke]),d=String(je.data?.parent||"").trim(),C=String(je.data?.dir||z||"").trim(),Q=j({queryKey:["swarm","workspace-files",k,pe],enabled:!!k&&!!pe,queryFn:async()=>{const m=await n(`/api/orchestrator/workspaces/files?workspaceRoot=${encodeURIComponent(k)}&dir=${encodeURIComponent(pe)}`).catch(()=>({directories:[],files:[],parent:null,dir:pe})),_=Array.isArray(m?.directories)?m.directories:[],de=(Array.isArray(m?.files)?m.files:[]).map(re=>{const Pe=String(re?.path||"").trim();return{...re,name:String(re?.name||Pe||"file"),path:Pe||Ol(k,String(re?.name||""))}});return{ok:!0,dir:String(m?.dir||pe),parent:m?.parent||null,directories:_,files:de,fileAccessAllowed:!0}},refetchInterval:1e4}),qe=j({queryKey:["swarm","workspace-file",k,fe],enabled:!!k&&!!fe,queryFn:async()=>n(`/api/orchestrator/workspaces/read?workspaceRoot=${encodeURIComponent(k)}&path=${encodeURIComponent(fe)}`)}),Ve=Array.isArray(Q.data?.directories)?Q.data.directories:[],nt=Array.isArray(Q.data?.files)?Q.data.files:[],Et=String(Q.data?.parent||"").trim(),Zt=Q.data?.fileAccessAllowed!==!1,ot=String(qe.data?.text||""),Ht=El(fe),Mt=["md","markdown","mdx"].includes(Ht),h=["html","htm"].includes(Ht);ie(()=>{Te&&!h&&st(!1)},[h,Te]);const R=V(()=>ut.map(m=>`${m.id}:${m.state}:${m.error_message||""}`).join("|"),[ut]),v=V(()=>ut.find(m=>m.id===ue)||null,[ue,ut]),$=V(()=>{const m=Array.isArray(ge.data?.events)?ge.data.events:[];let _=null,U=0;for(const de of m){const re=String(de?.type||"").trim().toLowerCase();if(!["step_completed","task_completed"].includes(re))continue;const Pe=de?.payload&&typeof de.payload=="object"?de.payload:{},Fe=String(Pe?.session_id||"").trim();if(!Fe)continue;const Nt=Number(de?.ts_ms||0);(!_||Nt>=U)&&(_={sessionId:Fe,event:de},U=Nt)}return _},[ge.data?.events]),A=V(()=>{const m=Array.isArray(ge.data?.events)?ge.data.events:[];for(let _=m.length-1;_>=0;_-=1){const U=m[_],de=String(U?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(de))continue;const re=U?.payload&&typeof U.payload=="object"?U.payload:{},Pe=String(re?.session_id||"").trim();if(Pe)return Pe}return String($?.sessionId||"").trim()},[$?.sessionId,ge.data?.events]),H=V(()=>{const m=Array.isArray(ge.data?.events)?ge.data.events:[],_=ts(m),U=[];for(let de=m.length-1;de>=0;de-=1){const re=m[de],Pe=String(re?.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(Pe))continue;const Fe=re?.payload&&typeof re.payload=="object"?re.payload:{},Nt=String(re?.step_id||"").trim(),It=Number(re?.seq||0);if((Pe==="task_failed"||Pe==="step_failed")&&Nt&&Number.isFinite(It)&&It>0&&Number(_[Nt]||0)>It)continue;const Kt=String(Fe?.step_title||re?.step_id||Pe).trim(),Yt=String(Fe?.why_next_step||Fe?.error||"").trim();if(U.push({id:`${String(re?.seq||de)}-${Pe}`,type:Pe,title:Kt||Pe,detail:Yt,at:Number(re?.ts_ms||0)}),U.length>=12)break}return U},[ge.data?.events]),Ce=V(()=>{const m=Array.isArray(ge.data?.events)?ge.data.events:[];for(let _=m.length-1;_>=0;_-=1){const U=m[_],de=String(U?.type||"").trim().toLowerCase();if(de==="plan_seeded_llm")return"llm";if(de==="plan_seeded_local")return"fallback_local";if(de==="plan_failed_llm_required")return"llm_failed"}return"unknown"},[ge.data?.events]),Ue=j({queryKey:["swarm","run-output-session",String(A||"")],queryFn:()=>n(`/api/engine/session/${encodeURIComponent(String(A||""))}`),refetchInterval:6e3,enabled:!!A}),Je=V(()=>{const m=Ss(Ue.data,"Assistant");for(let _=m.length-1;_>=0;_-=1)if(m[_]?.role==="assistant"&&String(m[_]?.text||"").trim())return String(m[_]?.text||"").trim();return""},[Ue.data]),rt=V(()=>{const m=Array.isArray(Ue.data)?Ue.data:Array.isArray(Ue.data?.messages)?Ue.data.messages:[],_=[];for(let U=m.length-1;U>=0;U-=1){const de=m[U],re=Array.isArray(de?.parts)?de.parts:[];for(let Pe=re.length-1;Pe>=0;Pe-=1){const Fe=re[Pe];if(!String(Fe?.type||Fe?.part_type||"").trim().toLowerCase().includes("tool"))continue;const It=String(Fe?.tool||Fe?.name||"").trim(),wn=String(Fe?.state||Fe?.status||"").trim(),Kt=String(Fe?.error||"").trim(),Yt=[It||"tool",wn||null,Kt?`err=${Kt}`:null].filter(Boolean).join(" · ");if(_.push(Yt),_.length>=10)return _}}return _},[Ue.data]),ze=V(()=>{const m=Array.isArray(ge.data?.events)?ge.data.events:[],_=ts(m),U=[];for(let de=m.length-1;de>=0;de-=1){const re=m[de],Pe=String(re?.type||"").trim().toLowerCase();if(!["task_failed","step_failed","task_completed","step_completed"].includes(Pe))continue;const Fe=re?.payload&&typeof re.payload=="object"?re.payload:{},Nt=String(re?.step_id||"").trim(),It=Number(re?.seq||0);if((Pe==="task_failed"||Pe==="step_failed")&&Nt&&Number.isFinite(It)&&It>0&&Number(_[Nt]||0)>It)continue;const Kt=Fe?.verification&&typeof Fe.verification=="object"?Fe.verification:{},Yt=String(Kt?.reason||Fe?.error||"").trim(),Z=String(Kt?.mode||"strict").trim()||"strict";if(U.push({id:`${String(re?.seq||de)}-${Pe}`,taskId:Nt,title:String(Fe?.step_title||re?.step_id||Pe),type:Pe,reason:Yt,mode:Z,at:Number(re?.ts_ms||0),verification:Kt}),U.length>=8)break}return U},[ge.data?.events]),et=V(()=>ze.find(m=>m.id===Re)||null,[Re,ze]);ie(()=>{if(!et&&!v&&!Te||typeof document>"u")return;const m=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=m}},[et,v,Te]);const at=String(ge.data?.run?.workflowId||ge.data?.run?.workflow_id||dt?.workflowId||dt?.workflow_id||W||"").trim(),qt=j({queryKey:["workflow","detail",at],enabled:!!at,queryFn:()=>n(`/api/engine/workflows/${encodeURIComponent(at)}`),refetchInterval:15e3}),Bt=j({queryKey:["workflow","runs",at],enabled:!!at,queryFn:()=>n(`/api/engine/workflows/runs?workflow_id=${encodeURIComponent(at)}&limit=12`).catch(()=>({runs:[]})),refetchInterval:5e3}),Ot=Array.isArray(Bt.data?.runs)?Bt.data.runs:[],Ft=V(()=>{const m={};for(const _ of Ot){const U=pn(_);if(!U)continue;const de=m[U]||{runs:0,failed:0};de.runs+=1,String(_?.status||"").trim().toLowerCase()==="failed"&&(de.failed+=1),m[U]=de}return m},[Ot]),_t=V(()=>ce?Ot.filter(m=>pn(m)===ce):Ot,[ce,Ot]),Tt=V(()=>{const m=[];for(const _ of _t){const U=String(_?.run_id||"").trim(),de=pn(_);for(const re of Array.isArray(_?.actions)?_.actions:[])m.push({id:`${U}:${String(re?.action_id||re?.action||m.length)}`,runId:U,action:String(re?.action||"unknown action"),status:String(re?.status||"unknown"),detail:String(re?.detail||""),output:re?.output,updatedAt:Number(re?.updated_at_ms||_?.updated_at_ms||0),taskId:String(re?.task_id||de||"").trim()})}return m.sort((_,U)=>U.updatedAt-_.updatedAt),m},[_t]);ie(()=>{const m=_t;if(!m.length){I("");return}m.some(U=>{const de=String(U?.run_id||"").trim();return de&&de===se})||I(String(m[0]?.run_id||"").trim())},[_t,se]);const L=j({queryKey:["workflow","run",se],enabled:!!se,queryFn:()=>n(`/api/engine/workflows/runs/${encodeURIComponent(se)}`),refetchInterval:5e3}).data?.run||null;ie(()=>{const m=pn(L);m&&N(m)},[L?.run_id,L?.source_event_id]),ie(()=>{ee([])},[at]),gn(`/api/engine/workflows/events${at?`?workflow_id=${encodeURIComponent(at)}`:""}`,m=>{try{const _=JSON.parse(m.data);if(_?.status==="ready")return;ee(U=>[...U.slice(-79),{at:Date.now(),data:_}])}catch{}},{enabled:!!at});const lt=me({mutationFn:()=>{const m=String(M||"").trim(),_=String(S||"").trim();if(!m)throw new Error("Enter a prompt first.");if(!_)throw new Error("Set workspace path first.");return n("/api/orchestrator/start",{method:"POST",body:JSON.stringify({objective:m,workspaceRoot:_,maxTasks:Number(B||4),maxAgents:Number(D||3),workflowId:String(W||"swarm.blackboard.default").trim(),requireLlmPlan:!0,allowLocalPlannerFallback:!1,verificationMode:"strict"})})},onSuccess:async m=>{const _=String(m?.runId||"").trim();_&&ft(_),u(!1),t("ok","Planning started."),await s.invalidateQueries({queryKey:["swarm"]})},onError:m=>t("err",m instanceof Error?m.message:String(m))}),he=me({mutationFn:({path:m,body:_})=>n(m,{method:"POST",body:JSON.stringify(_)}),onSuccess:async(m,_)=>{if(_.path==="/api/orchestrator/request_revision"){const U=String(m?.runId||"").trim();U&&(ft(U),Ie("")),t("ok","Reworked plan created.")}_.path==="/api/orchestrator/approve"&&t("ok","Execution started."),await s.invalidateQueries({queryKey:["swarm"]})},onError:m=>t("err",m instanceof Error?m.message:String(m))}),tt=me({mutationFn:async m=>{const _=String(m||"").trim();if(!_)throw new Error("Missing run id.");return await n("/api/orchestrator/cancel",{method:"POST",body:JSON.stringify({runId:_})}).catch(()=>null),await n("/api/orchestrator/runs/hide",{method:"POST",body:JSON.stringify({runIds:[_]})}).catch(()=>null),_},onSuccess:async()=>{bt(),u(!0),Ie(""),b(""),t("ok","Discarded pending plan. You can start a new prompt now."),await s.invalidateQueries({queryKey:["swarm"]})},onError:m=>t("err",m instanceof Error?m.message:String(m))}),yt=Ee(()=>{u(!0),bt(),w(!1),Ie("")},[bt]);ie(()=>{const m=l.current;m&&dn(m)},[c,p,Be,le,Ge,pe,Ve.length,nt.length,fe,ot,ue,Re,Te,R]);const jt=!le,ct=Ge==="planning"||Ge==="queued",Ct=Ge==="awaiting_approval",en=["completed","failed","cancelled"].includes(Ge),bn=Ge==="running",sn=Ge==="paused",yn=Ge==="failed"||Ge==="blocked",qn=["queued","planning","awaiting_approval","running","paused","blocked"].includes(Ge),vn=e(Qt,{children:[e(te.aside,{className:`chat-sessions-panel ${p?"open":""}`,initial:!1,animate:i?{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:()=>{s.invalidateQueries({queryKey:["swarm","runs"]})},children:e("i",{"data-lucide":"refresh-cw"})})})]}),e("div",{className:"chat-session-list",children:[e(Ze,{children:Be.map((m,_)=>{const U=String(m?.run_id||m?.runId||`run-${_}`),de=U===le;return e(te.div,{className:"chat-session-row",initial:i?!1:{opacity:0,y:6},animate:i?void 0:{opacity:1,y:0},exit:i?void 0:{opacity:0,y:-6},children:e("button",{type:"button",className:`chat-session-btn ${de?"active":""}`,onClick:()=>{u(!1),ft(U),w(!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:Xa(ql(m))})]}),e("span",{className:"tcp-subtle line-clamp-2 block text-[11px]",children:String(m?.objective||"").trim()||"No objective"})]})},U)})}),Be.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No runs yet."})]})]}),e(Ze,{children:p?e(te.button,{type:"button",className:"chat-scrim open","aria-label":"Close history",initial:i?!1:{opacity:0},animate:i?void 0:{opacity:1},exit:i?void 0:{opacity:0},onClick:()=>w(!1)}):null})]});if(jt){const m=String(M||"").trim().length>0&&String(S||"").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:[vn,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:()=>w(_=>!_),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:M,onInput:_=>b(_.target.value)}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr]",children:[e("button",{className:"tcp-btn",onClick:()=>{const _=String(S||Ae.data?.workspaceRoot||"/").trim();J(_||"/"),G(""),X(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,placeholder:"No workspace selected. Use Browse.",value:S})]}),e("div",{className:"tcp-subtle text-xs",children:["Selected folder: ",S||"none"]}),S?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:()=>lt.mutate(),disabled:lt.isPending||!m,children:[e("i",{"data-lucide":"send"}),"Send"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>O(_=>!_),children:[e("i",{"data-lucide":"sliders-horizontal"}),x?"Hide Advanced":"Show Advanced"]})]}),x?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:B,onInput:_=>E(_.target.value),title:"max tasks"}),e("input",{className:"tcp-input",type:"number",min:"1",max:"16",value:D,onInput:_=>F(_.target.value),title:"max agents"}),e("input",{className:"tcp-input",value:W,onInput:_=>oe(_.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]})]})})]}),T?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: ",C||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{d&&J(d)},disabled:!d,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{C&&(q(C),X(!1),G(""),t("ok",`Workspace selected: ${C}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{X(!1),G("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ne,onInput:_=>G(_.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:o.length?o.map(_=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>J(String(_?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(_?.name||_?.path||"")]},String(_?.path||_?.name))):e(Se,{text:ke?"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:[vn,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:()=>w(m=>!m),children:e("i",{"data-lucide":"history"})}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Back to start",onClick:yt,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:Gt(Ge),children:Ge||"unknown"}),e("span",{className:"inline-flex items-center gap-1 tcp-subtle",children:[e("i",{"data-lucide":"history"}),e("span",{children:Xa(ge.data?.run?.updated_at_ms||ge.data?.run?.created_at_ms)})]}),e("span",{className:"tcp-subtle",children:["id: ",le]}),e("span",{className:"tcp-subtle",children:["plan: ",Ce]})]}),ct?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,Ct?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:xe,onInput:m=>Ie(m.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",disabled:!xe.trim(),onClick:()=>he.mutate({path:"/api/orchestrator/request_revision",body:{runId:le,feedback:xe,maxTasks:Number(B||4),maxAgents:Number(D||3),workflowId:W}}),children:[e("i",{"data-lucide":"pencil"}),"Rework Plan"]}),e("button",{className:"tcp-btn-primary",onClick:()=>he.mutate({path:"/api/orchestrator/approve",body:{runId:le}}),children:[e("i",{"data-lucide":"play"}),"Execute Plan"]}),e("button",{className:"tcp-btn-danger",disabled:tt.isPending,onClick:()=>tt.mutate(le),children:[e("i",{"data-lucide":"trash-2"}),"Discard Plan"]})]})]}):null,!ct&&!Ct?e("div",{className:"mb-3 flex flex-wrap gap-2",children:[bn?e("button",{className:"tcp-btn",onClick:()=>he.mutate({path:"/api/orchestrator/pause",body:{runId:le}}),children:[e("i",{"data-lucide":"square"}),"Pause"]}):null,sn?e("button",{className:"tcp-btn",onClick:()=>he.mutate({path:"/api/orchestrator/resume",body:{runId:le}}),children:[e("i",{"data-lucide":"play"}),"Resume"]}):null,yn?e("button",{className:"tcp-btn",onClick:()=>he.mutate({path:"/api/orchestrator/continue",body:{runId:le}}),children:[e("i",{"data-lucide":"rotate-cw"}),"Continue Run"]}):null,qn?e("button",{className:"tcp-btn-danger",onClick:()=>he.mutate({path:"/api/orchestrator/cancel",body:{runId:le}}),children:[e("i",{"data-lucide":"x"}),"Cancel"]}):null,e("button",{className:"tcp-btn",onClick:yt,children:[e("i",{"data-lucide":"plus"}),"New Prompt"]})]}):null,en?e("div",{className:"mb-3 rounded-lg border border-slate-700/60 bg-slate-900/25 p-2 text-xs tcp-subtle",children:Ge==="failed"?"This run is failed. Continue the run or retry a failed task.":`This run is ${Ge}. 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:()=>{Q.refetch()},disabled:!k,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:!Et,onClick:()=>{Et&&Ne(Et)},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:!k,onClick:()=>{k&&Ne(k)},children:e("i",{"data-lucide":"home"})})]}),e("div",{className:"mb-2 tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:pe||k||"No workspace"}),Zt?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:[Ve.map(m=>{const _=String(m?.path||"");return e("button",{className:"tcp-list-item text-left",onClick:()=>Ne(_),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(m?.name||_)})]})},`dir-${_}`)}),nt.map(m=>{const _=String(m?.path||"");return e("button",{className:`tcp-list-item text-left ${_===fe?"border-amber-400/70":""}`,onClick:()=>Oe(_),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(m?.name||_)})]}),e("span",{className:"tcp-subtle shrink-0 text-[11px]",children:Tl(m?.size)})]})},`file-${_}`)}),!Ve.length&&!nt.length?e(Se,{text:"No files or folders in this workspace location."}):null]})]}),fe?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:[h?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>st(!0),children:[e("i",{"data-lucide":"fullscreen"}),"Fullscreen"]}):null,e("span",{className:"tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:fe})]})]}),qe.isLoading?e("div",{className:"tcp-subtle text-xs",children:"Loading file..."}):h?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:ot,title:fe,scrolling:"yes"})}):Mt?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:wa(ot)}}):e("pre",{className:"tcp-code max-h-[260px] overflow-auto whitespace-pre-wrap break-words",children:ot||"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"})}),ze.length?e("div",{className:"grid max-h-44 gap-2 overflow-auto",children:ze.map(m=>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:Gt(m.type.includes("failed")?"failed":"running"),children:m.type}),e("span",{className:"tcp-subtle",children:["mode: ",m.mode]})]}),e("div",{className:"font-medium",children:m.title}),e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:m.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:()=>Me(m.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(ns(m)),t("ok","Copied verification feedback.")}catch(_){t("err",_ instanceof Error?_.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),m.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(m.verification?.execution_trace?.session_id||"n/a")]}),e("div",{children:["model:"," ",[String(m.verification?.execution_trace?.model?.provider||"").trim(),String(m.verification?.execution_trace?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"]}),e("div",{children:["source:"," ",String(m.verification?.execution_trace?.model?.source||"n/a")]})]}):null]},m.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:nn(Date.now())})]}),H.length?e("div",{className:"grid max-h-40 gap-2 overflow-auto",children:H.map(m=>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:Gt(m.type.includes("failed")?"failed":"running"),children:m.type}),e("span",{className:"tcp-subtle",children:nn(m.at)})]}),e("div",{className:"font-medium",children:m.title}),e("div",{className:"tcp-subtle",children:m.detail||"No additional detail."})]},m.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"})}),A?e(Qt,{children:[e("div",{className:"tcp-code max-h-28 overflow-auto whitespace-pre-wrap break-words",children:Je||"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:rt.length?rt.join(`
|
|
20
|
-
`):"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(fl,{budget:g})}),e(xl,{tasks:ut,currentTaskId:De.currentTaskId,selectedTaskId:ce,workflowSummaryByTaskId:Ft,onTaskSelect:m=>{const _=ce===m.id?"":m.id;N(_),be(m.id)},onRetryTask:m=>he.mutate({path:"/api/orchestrator/retry",body:{runId:le,stepId:m.id}})}),ce?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:()=>N(""),children:"Clear task focus"})]}),e("div",{className:"tcp-subtle text-xs",children:["Task ",e("strong",{children:ce})," is filtering workflow runs and event stream."]})]}):null,ce?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:[Tt.length," actions"]})]}),Tt.length?e("div",{className:"grid max-h-56 gap-2 overflow-auto",children:Tt.map(m=>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:m.action}),e("span",{className:Gt(m.status),children:m.status})]}),e("div",{className:"tcp-subtle",children:["run: ",m.runId]}),e("div",{className:"tcp-subtle",children:["updated: ",nn(m.updatedAt)]}),m.detail?e("div",{className:"mt-1 text-rose-200",children:m.detail}):null,m.output?e("pre",{className:"tcp-code mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(m.output,null,2)}):null]},m.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:()=>a("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:at||"no workflow id"}),e("span",{className:"tcp-subtle",children:Array.isArray(qt.data?.workflow?.steps)?`${qt.data.workflow.steps.length} steps`:"workflow metadata pending"}),e("span",{className:"tcp-subtle",children:Array.isArray(qt.data?.hooks)?`${qt.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:_t.length?_t.map((m,_)=>{const U=String(m?.run_id||`workflow-run-${_}`).trim(),de=U===se,re=String(m?.status||"unknown").trim(),Pe=pn(m);return e("button",{type:"button",className:`tcp-list-item text-left ${de?"border-amber-400/70":""}`,onClick:()=>I(U),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:U}),e("span",{className:Gt(re),children:re})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger:"," ",String(m?.trigger_event||"manual").trim()||"manual"]}),e("div",{className:"tcp-subtle text-xs",children:["task: ",Pe||"n/a"]}),e("div",{className:"tcp-subtle text-xs",children:["actions:"," ",Array.isArray(m?.actions)?m.actions.length:0]})]},U)}):e(Se,{text:ce?"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"}),L?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:Gt(String(L?.status||"unknown")),children:String(L?.status||"unknown")}),e("span",{className:"tcp-subtle",children:["trigger: ",String(L?.trigger_event||"manual")]}),e("span",{className:"tcp-subtle",children:["source: ",String(L?.source_event_id||"n/a")]})]}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:Array.isArray(L?.actions)&&L.actions.length?L.actions.map((m,_)=>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(m?.action||"unknown action")}),e("span",{className:Gt(String(m?.status||"unknown")),children:String(m?.status||"unknown")})]}),e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-subtle",children:["task:"," ",String(m?.task_id||L?.task_id||"n/a")]}),String(m?.task_id||L?.task_id||"").trim()?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>N(String(m?.task_id||L?.task_id||"").trim()),children:"Focus task"}):null]}),e("div",{className:"tcp-subtle",children:["started: ",nn(m?.started_at_ms)]}),e("div",{className:"tcp-subtle",children:["finished: ",nn(m?.finished_at_ms)]}),String(m?.error||"").trim()?e("div",{className:"mt-1 text-rose-200",children:String(m.error)}):null]},`${String(m?.action||"action")}-${_}`)):e("div",{className:"tcp-subtle text-xs",children:"No recorded workflow actions for this run."})})]}):e(Se,{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:()=>ee([]),children:e("i",{"data-lucide":"trash-2"})})]}),P.length?e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:[...P].filter(m=>{const _=pn(m.data?.properties||{});if(ce&&_&&_!==ce)return!1;if(!se)return!0;const U=String(m.data?.properties?.runID||"").trim();return!U||U===se}).reverse().map((m,_)=>{const U=Fl(m.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:Gt(U.endsWith(".failed")?"failed":U.endsWith(".completed")?"completed":"running"),children:U}),e("span",{className:"tcp-subtle",children:nn(m.at)})]}),e("div",{className:"tcp-subtle",children:["run: ",String(m.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle",children:["action:"," ",String(m.data?.properties?.action||m.data?.properties?.actionID||"-")]})]},`${m.at}-${_}`)})}):e("div",{className:"tcp-subtle text-xs",children:"No workflow events streamed for this run yet."})]}),e(Ze,{children:[v?e(te.div,{className:"tcp-confirm-overlay",initial:i?!1:{opacity:0},animate:i?void 0:{opacity:1},exit:i?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close task details",onClick:()=>be("")}),e(te.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:i?!1:{opacity:0,y:8,scale:.98},animate:i?void 0:{opacity:1,y:0,scale:1},exit:i?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:()=>be(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Gt(v.state),children:Ml(v.state)}),e("span",{className:"tcp-badge-info",children:v.id}),v.assigned_role?e("span",{className:"tcp-subtle",children:["role: ",v.assigned_role]}):null,v.gate?e("span",{className:"tcp-subtle",children:["gate: ",v.gate]}):null,v.workflow_id?e("span",{className:"tcp-subtle",children:["workflow: ",v.workflow_id]}):null,v.session_id?e("span",{className:"tcp-subtle",children:["session: ",v.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:v.title||"Untitled task"})]}),v.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:v.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"}),v.dependencies.length?e("div",{className:"flex flex-wrap gap-2",children:v.dependencies.map(m=>e("span",{className:"rounded border border-slate-700/60 px-2 py-1 text-xs text-slate-200",children:["<-"," ",m]},`${v.id}-${m}`))}):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: ",v.runtime_status||"n/a"]}),e("div",{className:"tcp-subtle",children:["retry count: ",Number(v.retry_count||0)]}),Ft?.[v.id]?e("div",{className:"tcp-subtle",children:["workflow runs:"," ",Ft[v.id].runs,Ft[v.id].failed?`, failed ${Ft[v.id].failed}`:""]}):null,v.runtime_detail?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:["detail: ",v.runtime_detail]}):null]})]})]}),String(v.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(v.error_message||"").trim()})]}):null]}),e("div",{className:"tcp-confirm-actions mt-4",children:[e("button",{className:"tcp-btn",onClick:()=>{N(v.id),be("")},children:"Focus task"}),e("button",{className:"tcp-btn",onClick:()=>be(""),children:"Close"})]})]})]}):null,et?e(te.div,{className:"tcp-confirm-overlay",initial:i?!1:{opacity:0},animate:i?void 0:{opacity:1},exit:i?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close verification details",onClick:()=>Me("")}),e(te.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:i?!1:{opacity:0,y:8,scale:.98},animate:i?void 0:{opacity:1,y:0,scale:1},exit:i?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:()=>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:Gt(et.type.includes("failed")?"failed":"running"),children:et.type}),e("span",{className:"tcp-badge-info",children:et.title}),e("span",{className:"tcp-subtle",children:["task: ",et.taskId||"n/a"]}),e("span",{className:"tcp-subtle",children:["mode: ",et.mode]}),e("span",{className:"tcp-subtle",children:["time: ",nn(et.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(ns(et)),t("ok","Copied verification feedback.")}catch(m){t("err",m instanceof Error?m.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:et.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(et.verification||{},null,2)})]})]}),e("div",{className:"tcp-confirm-actions mt-4",children:e("button",{className:"tcp-btn",onClick:()=>Me(""),children:"Close"})})]})]}):null]})]})]})})]}),e(Ze,{children:Te&&fe&&h?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>st(!1),children:e(te.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:m=>m.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:fe})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{qe.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:()=>st(!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:ot,title:`${fe} fullscreen preview`,scrolling:"yes"})})})]})}):null}),T?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: ",C||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{d&&J(d)},disabled:!d,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{C&&(q(C),X(!1),G(""),t("ok",`Workspace selected: ${C}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{X(!1),G("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ne,onInput:m=>G(m.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:o.length?o.map(m=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>J(String(m?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(m?.name||m?.path||"")]},String(m?.path||m?.name))):e(Se,{text:ke?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}function Ul(n,t){return Array.isArray(n)?n:Array.isArray(n?.[t])?n[t]:[]}function Ll({api:n,toast:t}){const a=Lt(),[s,i]=y("uploads"),l=j({queryKey:["files",s],queryFn:()=>n(`/api/files/list?dir=${encodeURIComponent(s)}`).catch(()=>({files:[]})),refetchInterval:12e3}),c=me({mutationFn:p=>n("/api/files/delete",{method:"POST",body:JSON.stringify({path:p})}),onSuccess:async()=>{t("ok","File removed."),await a.invalidateQueries({queryKey:["files",s]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),u=Ul(l.data,"files");return e("div",{className:"grid gap-4",children:e(an,{title:"Files",subtitle:"Browse and delete uploaded files",children:[e("div",{className:"mb-3 flex gap-2",children:[e("input",{className:"tcp-input",value:s,onInput:p=>i(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,w)=>{const M=String(p?.path||p?.name||`file-${w}`);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:M}),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:()=>c.mutate(M),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})})]},M)}):e(Se,{text:"No files found for this directory."})})]})})}function Bl(n,t){return Array.isArray(n)?n:Array.isArray(n?.[t])?n[t]:[]}function jl({client:n,toast:t}){const a=Lt(),[s,i]=y(""),[l,c]=y(null),u=j({queryKey:["memory",s],queryFn:()=>(s.trim()?n.memory.search({query:s,limit:40}):n.memory.list({q:"",limit:40})).catch(()=>({items:[]})),refetchInterval:15e3}),p=me({mutationFn:b=>n.memory.delete(b),onSuccess:async()=>{t("ok","Memory record deleted."),await a.invalidateQueries({queryKey:["memory"]})},onError:b=>t("err",b instanceof Error?b.message:String(b))}),w=Bl(u.data,"items"),M=V(()=>w.map((b,S)=>{const q=String(b?.id||`mem-${S}`),T=String(b?.text||b?.content||b?.value||""),X=T.length>340?`${T.slice(0,340)}...`:T;return{id:q,text:T,compact:X,html:wa(T)}}),[w]);return e(Mn,{className:"grid gap-4",children:e(Le,{title:"Memory",subtitle:"Search recent records and open full entry details inline.",actions:e(Qt,{children:[e(ae,{tone:"info",children:[M.length," results"]}),s.trim()?e(ae,{tone:"ghost",children:["Filter: ",s]}):e(ae,{tone:"ghost",children:"Browsing latest memory"})]}),children:[e(Wt,{className:"mb-3",children:[e("input",{className:"tcp-input flex-1",value:s,onInput:b=>i(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:M.length?M.map(b=>{const S=l===b.id;return e(te.article,{layout:!0,className:`tcp-list-item cursor-pointer ${S?"border-amber-500/60":""}`,onClick:()=>c(S?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(ae,{tone:S?"info":"ghost",children:S?"expanded":"compact"}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:q=>{q.stopPropagation(),p.mutate(b.id)},children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]}),e(Ze,{initial:!1,mode:"wait",children:S?e(te.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(te.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(Se,{text:"No memory records found."})})]})})}function as(n,t){return Array.isArray(n)?n:Array.isArray(n?.[t])?n[t]:[]}function Kl({client:n,toast:t}){const a=Lt(),s=j({queryKey:["teams","instances"],queryFn:()=>n?.agentTeams?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),i=j({queryKey:["teams","approvals"],queryFn:()=>n?.agentTeams?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),l=me({mutationFn:({requestId:p,decision:w})=>w==="approve"?n?.agentTeams?.approveSpawn?.(p):n?.agentTeams?.denySpawn?.(p),onSuccess:async()=>{t("ok","Approval updated."),await a.invalidateQueries({queryKey:["teams"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),c=as(s.data,"instances"),u=as(i.data,"spawnApprovals");return e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(an,{title:"Team Instances",subtitle:"Running collaborative agent instances",children:e("div",{className:"grid gap-2",children:c.length?c.map((p,w)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(p?.name||p?.instance_id||"Instance")}),e("span",{className:"tcp-badge-info",children:String(p?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs",children:String(p?.workspace||p?.workspaceRoot||"")})]},String(p?.instance_id||p?.id||w))):e(Se,{text:"No team instances found."})})}),e(an,{title:"Spawn Approvals",subtitle:"Pending team approval requests",children:e("div",{className:"grid gap-2",children:u.length?u.map((p,w)=>{const M=String(p?.request_id||p?.id||`request-${w}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:String(p?.reason||p?.title||M)}),e("div",{className:"tcp-subtle text-xs",children:M}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>l.mutate({requestId:M,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:M,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},M)}):e(Se,{text:"No pending approvals."})})})]})}async function Rt(n,t={}){const a=await fetch(n,{...t,credentials:"include",headers:{"content-type":"application/json",...t.headers||{}}});if(!a.ok){const i=await a.text().catch(()=>"");let l=i||`${n} failed (${a.status})`;try{const c=i?JSON.parse(i):null;c?.error&&(l=c.error)}catch{}throw new Error(l)}const s=await a.text();return s?JSON.parse(s):{}}function Bn(n){return n?.type||n?.event||"event"}function ss(n){const t=String(n||"").trim().toLowerCase();return["server.connected","engine.lifecycle.ready","engine.heartbeat","engine.lifecycle.heartbeat"].includes(t)}function rs(n){return String(n?.type||n?.event||"").trim()==="context.run.stream"&&String(n?.run_id||n?.runId||"").trim().startsWith("workflow-")}function Jl({client:n,toast:t,navigate:a}){const[s,i]=y([]),[l,c]=y(""),[u,p]=y("all"),[w,M]=y(!0),[b,S]=y(null),q=V(()=>!b||!rs(b.data)?"":String(b.data?.run_id||b.data?.runId||"").trim(),[b]),T=j({queryKey:["feed","workflow-context-run",q],enabled:!!q,queryFn:()=>Rt(`/api/engine/context/runs/${encodeURIComponent(q)}`).catch(()=>({run:null}))}),X=j({queryKey:["feed","workflow-context-blackboard",q],enabled:!!q,queryFn:()=>Rt(`/api/engine/context/runs/${encodeURIComponent(q)}/blackboard`).catch(()=>({blackboard:null}))});gn("/api/global/event",x=>{try{const O=JSON.parse(x.data);i(B=>[...B.slice(-299),{at:Date.now(),data:O}])}catch{}},{enabled:!0});const z=V(()=>{const x=new Map;for(const O of s){const B=Bn(O.data);w&&ss(B)||x.set(B,(x.get(B)||0)+1)}return[...x.entries()].sort((O,B)=>B[1]-O[1])},[s,w]),J=V(()=>{const x=l.trim().toLowerCase();return s.filter(O=>{const B=Bn(O.data);return w&&ss(B)||u!=="all"&&B!==u?!1:x?`${B} ${JSON.stringify(O.data||{})}`.toLowerCase().includes(x):!0}).slice(-240).reverse()},[s,l,u,w]);async function ne(x){try{const O=await Rt("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:x,source:{kind:"control_panel_feed",event:"pack.detected"}})});t("ok",`Installed ${O?.installed?.name||"pack"}`)}catch(O){t("err",O instanceof Error?O.message:String(O))}}async function G(x){try{const O=await Rt("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:String(x?.properties?.attachment_id||x?.attachment_id||""),path:String(x?.properties?.path||x?.path||""),connector:String(x?.properties?.connector||x?.connector||"")||void 0,channel_id:String(x?.properties?.channel_id||x?.channel_id||"")||void 0,sender_id:String(x?.properties?.sender_id||x?.sender_id||"")||void 0})});t("ok",`Installed ${O?.installed?.name||"pack"}`)}catch(O){t("err",O instanceof Error?O.message:String(O))}}return e(Mn,{className:"grid gap-4",children:[e(Le,{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:[s.length," buffered"]}),e("span",{className:"tcp-badge tcp-badge-ghost",children:u==="all"?"All event types":u}),e("span",{className:w?"tcp-badge-ok":"tcp-badge-info",children:w?"noise hidden":"noise visible"}),e("button",{className:"tcp-btn",onClick:()=>i([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear feed"]}),e("button",{className:"tcp-btn",onClick:()=>a("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Pack library"]})]}),children:[e(Wt,{className:"mb-3",children:[e("input",{className:"tcp-input min-w-[220px] flex-1",value:l,onInput:x=>c(x.target.value),placeholder:"Filter by type or payload"}),e(aa,{active:u==="all",onClick:()=>p("all"),children:[e("i",{"data-lucide":"list"}),"All"]}),e(aa,{active:w,onClick:()=>M(x=>!x),children:[e("i",{"data-lucide":w?"filter":"filter-x"}),w?"Hide noise":"Show noise"]}),z.slice(0,8).map(([x,O])=>e(aa,{active:u===x,onClick:()=>p(x),children:[e("i",{"data-lucide":"activity"}),x," (",O,")"]},x))]}),e("div",{className:"grid max-h-[68vh] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:J.length?J.map((x,O)=>{const B=Bn(x.data),E=String(B).startsWith("pack."),D=rs(x.data),F=String(x.data?.properties?.path||x.data?.path||""),W=String(x.data?.properties?.attachment_id||x.data?.attachment_id||"");return e("article",{className:"tcp-list-item cursor-pointer",onClick:()=>S(x),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:B}),e("div",{className:"flex items-center gap-2",children:[D?e("span",{className:"tcp-badge-warn",children:"workflow context"}):null,e("span",{className:"tcp-badge-info",children:new Date(x.at).toLocaleTimeString()})]})]}),e("p",{className:"tcp-subtle mt-1 text-xs",children:D?`run: ${String(x.data?.run_id||x.data?.runId||"n/a")}`:`session: ${String(x.data?.sessionID||x.data?.sessionId||"n/a")}`}),D?e("p",{className:"tcp-subtle mt-1 text-xs",children:["kind: ",String(x.data?.kind||"context_run_event")," · seq:"," ",String(x.data?.seq||"-")]}):null,E?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:oe=>{oe.stopPropagation(),a("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open pack library"]}),F?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:oe=>{oe.stopPropagation(),ne(F)},children:[e("i",{"data-lucide":"download"}),"Install from path"]}):null,F&&W?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:oe=>{oe.stopPropagation(),G(x.data)},children:[e("i",{"data-lucide":"paperclip"}),"Install attachment"]}):null]}):null,D?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:oe=>{oe.stopPropagation(),a("orchestrator")},children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:oe=>{oe.stopPropagation(),a("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open workflow lab"]})]}):null]},`${x.at}-${O}`)}):e(Se,{text:"No events have arrived yet."})})]}),e(Hn,{open:!!b,onClose:()=>S(null),title:b?Bn(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()})]}),q?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(T.data?.run?.objective||q)}),e("span",{className:"tcp-badge-info",children:String(T.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(X.data?.blackboard?.tasks)?X.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(X.data?.blackboard?.artifacts)?X.data.blackboard.artifacts.length:0]})]}):null,e("pre",{className:"tcp-code",children:kt(b.data)}),q?e("pre",{className:"tcp-code",children:kt({run:T.data?.run||null,blackboard:X.data?.blackboard||null})}):null]}):null})]})}function Wl({theme:n}){const t=n?.cssVars?.["--color-background"]||"#000000",a=n?.cssVars?.["--color-surface"]||"#111111",s=n?.cssVars?.["--color-primary"]||"#ffffff",i=n?.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:a},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:s},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:i},"aria-hidden":"true"})]})}function Ql({themes:n,themeId:t,onChange:a}){return e("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:n.map(s=>{const i=s.id===t;return e(te.button,{type:"button",layout:!0,onClick:()=>a(s.id),className:`tcp-theme-tile ${i?"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:s.name}),e("p",{className:"tcp-subtle mt-1 text-xs",children:s.description})]}),e(Wl,{theme:s})]}),e("div",{className:"tcp-theme-preview",children:e("div",{className:"tcp-theme-preview-bg",style:{background:s.cssVars["--color-background"]||"#000"},children:e("div",{className:"tcp-theme-preview-card",style:{background:s.cssVars["--color-surface"]||"#111",borderColor:s.cssVars["--color-border"]||"rgba(255,255,255,0.1)"},children:[e("div",{className:"tcp-theme-preview-line short",style:{background:s.cssVars["--color-text"]||"#fff"}}),e("div",{className:"tcp-theme-preview-line",style:{background:s.cssVars["--color-text-muted"]||"#aaa"}}),e("div",{className:"tcp-theme-preview-pill",style:{background:s.cssVars["--color-primary"]||"#fff"}})]})})}),e(Ze,{initial:!1,children:i?e(te.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})]},s.id)})})}function ka(n){try{return new URL(n)}catch{return null}}function ba(n){return String(n||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"mcp-server"}function is(n){const t=ka(n);if(!t)return"";const a=String(t.hostname||"").toLowerCase();if(!a)return"";if(a.endsWith("composio.dev"))return"composio";const s=a.split(".").filter(Boolean);if(!s.length)return"";const i=["backend","api","mcp","www"].includes(s[0])&&s[1]||s[0];return ba(i)}function Es(n){const t=ka(n);return t?String(t.hostname||"").toLowerCase().endsWith("composio.dev"):!1}function Hl({authMode:n,token:t,customHeader:a,transport:s}){const i=String(t||"").trim();if(!i||n==="none")return{};if(n==="custom"){const c=String(a||"").trim();if(!c)throw new Error("Custom header name is required.");return{[c]:i}}return n==="x-api-key"?{"x-api-key":i}:n==="bearer"?{Authorization:`Bearer ${i.replace(/^bearer\s+/i,"").trim()}`}:Es(s)?{"x-api-key":i}:{Authorization:`Bearer ${i.replace(/^bearer\s+/i,"").trim()}`}}function Gl(n,t,a,s){return!String(t||"").trim()||n==="none"?"No auth header will be sent.":n==="custom"?a?`Header preview: ${a}: <token>`:"Set a custom header name.":n==="x-api-key"?"Header preview: x-api-key: <token>":n==="bearer"?"Header preview: Authorization: Bearer <token>":Es(s)?"Auto mode: selected x-api-key for this endpoint":"Auto mode: using Authorization Bearer token"}function da(n,t=""){if(!n||typeof n!="object")return null;const a=n,s=String(a.name||t||"").trim();return s?{name:s,transport:String(a.transport||"").trim(),connected:!!a.connected,enabled:a.enabled!==!1,lastError:String(a.last_error||a.lastError||"").trim(),headers:a.headers&&typeof a.headers=="object"?a.headers:{},toolCache:Array.isArray(a.tool_cache||a.toolCache)?a.tool_cache||a.toolCache:[]}:null}function Vl(n){return Array.isArray(n)?n.map(t=>da(t)).filter(t=>!!t).sort((t,a)=>t.name.localeCompare(a.name)):!n||typeof n!="object"?[]:Array.isArray(n.servers)?n.servers.map(t=>da(t)).filter(t=>!!t).sort((t,a)=>t.name.localeCompare(a.name)):Object.entries(n).map(([t,a])=>da(a&&typeof a=="object"?a:{transport:String(a||"")},t)).filter(t=>!!t).sort((t,a)=>t.name.localeCompare(a.name))}function zl(n){return(Array.isArray(n)?n:Array.isArray(n?.tools)?n.tools:[]).map(a=>typeof a=="string"?a:!a||typeof a!="object"?"":String(a.namespaced_name||a.namespacedName||a.id||a.tool_name||a.toolName||"").trim()).filter(Boolean)}function Yl(n){const t=n&&typeof n=="object"?n:{},a=Array.isArray(t.servers)?t.servers:[];return{generatedAt:String(t.generated_at||"").trim(),count:Number.isFinite(Number(t.count))?Number(t.count):a.length,servers:a.map(s=>!s||typeof s!="object"?null:{slug:String(s.slug||"").trim(),name:String(s.name||s.slug||"").trim(),description:String(s.description||"").trim(),transportUrl:String(s.transport_url||"").trim(),serverConfigName:String(s.server_config_name||s.slug||"").trim(),documentationUrl:String(s.documentation_url||"").trim(),directoryUrl:String(s.directory_url||"").trim(),toolCount:Number.isFinite(Number(s.tool_count))?Number(s.tool_count):0,requiresAuth:s.requires_auth!==!1,requiresSetup:!!s.requires_setup}).filter(s=>!!s&&!!s.slug&&!!s.transportUrl).sort((s,i)=>s.name.localeCompare(i.name))}}function ua(n,t){const a=t&&typeof t=="object"?t:{};return{botToken:"",allowedUsers:Array.isArray(a.allowed_users)?a.allowed_users.join(", "):"",mentionOnly:a.mention_only!==!1&&n==="discord"?!0:!!a.mention_only,guildId:String(a.guild_id||"").trim(),channelId:String(a.channel_id||"").trim(),styleProfile:String(a.style_profile||"default").trim()||"default"}}function Xl(n){return String(n||"").split(",").map(t=>t.trim()).filter(Boolean)}function Zl(n,t){const a=String(n?.catalog_source||"").trim().toLowerCase();return a==="remote"&&t>0?{tone:"ok",text:`${t} models`}:a==="config"&&t>0?{tone:"info",text:"configured models"}:{tone:"warn",text:"manual entry"}}function ec(n,t){const a=String(n?.catalog_message||"").trim();return a||`Default model: ${t||"none"}`}function os({client:n,api:t,toast:a,navigate:s,currentRoute:i,identity:l,themes:c,setTheme:u,themeId:p,refreshProviderStatus:w,refreshIdentityStatus:M}){const b=Lt(),S=wt(null),[q,T]=y({}),[X,z]=y(String(l?.botName||"Tandem")),[J,ne]=y(String(l?.botAvatarUrl||"")),[G,x]=y("Control Center"),[O,B]=y("providers"),[E,D]=y(!1),[F,W]=y(!1),[oe,xe]=y(!1),[Ie,pe]=y({}),[Ne,fe]=y({}),[Oe,se]=y(!1),[I,P]=y(""),[ee,ce]=y(""),[N,ue]=y("none"),[be,Re]=y(""),[Me,Te]=y(""),[st,Ae]=y(!0),[ht,gt]=y(""),[We,Qe]=y("manual"),[ft,bt]=y(""),[He,le]=y(!1),[Be,dt]=y(!1),[ye,Ke]=y(""),[St,$t]=y(""),[Ye,ge]=y(""),[je,Ge]=y("auto"),[De,ut]=y(""),[g,k]=y(""),[ve,ke]=y(!0),[o,d]=y(!1),[C,Q]=y(!0),[qe,Ve]=y(!1),[nt,Et]=y(""),[Zt,ot]=y(""),Ht=wt(null),Mt=async()=>{const r=n?.identity;return r?.get?r.get():t("/api/engine/config/identity",{method:"GET"})},h=async r=>{const f=n?.identity;return f?.patch?f.patch(r):t("/api/engine/config/identity",{method:"PATCH",body:JSON.stringify(r)})},R=j({queryKey:["settings","identity","config"],queryFn:()=>Mt().catch(()=>({identity:{}}))});ie(()=>{const r=R.data?.identity?.bot||{},f=r?.aliases||{},Y=String(r?.canonicalName||r?.canonical_name||l?.botName||"Tandem").trim(),$e=String(r?.avatarUrl||r?.avatar_url||l?.botAvatarUrl||"").trim(),Xe=String(f?.controlPanel||f?.control_panel||"").trim();z(Y||"Tandem"),ne($e),x(Xe||"Control Center")},[l?.botAvatarUrl,l?.botName,R.data]),ie(()=>{i==="mcp"&&B("mcp"),i==="channels"&&B("channels"),i==="bug-monitor"&&B("bug_monitor")},[i]);const v=j({queryKey:["settings","providers","catalog"],queryFn:()=>n.providers.catalog().catch(()=>({all:[],connected:[]}))}),$=j({queryKey:["settings","providers","config"],queryFn:()=>n.providers.config().catch(()=>({default:"",providers:{}}))}),A=j({queryKey:["settings","browser","status"],queryFn:()=>t("/api/engine/browser/status",{method:"GET"}).catch(()=>null),refetchInterval:3e4}),[H,Ce]=y(null),Ue=me({mutationFn:()=>t("/api/engine/browser/install",{method:"POST"}),onSuccess:async()=>{a("ok","Browser sidecar installed on the engine host."),await A.refetch()},onError:r=>a("err",r instanceof Error?r.message:String(r))}),Je=me({mutationFn:()=>t("/api/engine/browser/smoke-test",{method:"POST",body:JSON.stringify({url:"https://example.com"})}),onSuccess:async r=>{Ce(r),a("ok","Browser smoke test passed."),await A.refetch()},onError:r=>{Ce(null),a("err",r instanceof Error?r.message:String(r))}}),rt=j({queryKey:["settings","mcp","servers"],queryFn:()=>n.mcp.list().catch(()=>({})),refetchInterval:1e4}),ze=j({queryKey:["settings","mcp","tools"],queryFn:()=>n.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),et=j({queryKey:["settings","mcp","catalog"],queryFn:()=>t("/api/engine/mcp/catalog",{method:"GET"}).catch(()=>null),refetchInterval:6e4}),at=j({queryKey:["settings","bug-monitor","config"],queryFn:()=>t("/api/engine/config/bug-monitor",{method:"GET"}).catch(()=>({bug_monitor:{}}))}),qt=j({queryKey:["settings","bug-monitor","status"],queryFn:()=>t("/api/engine/bug-monitor/status",{method:"GET"}).catch(()=>({status:{}})),refetchInterval:1e4}),Bt=j({queryKey:["settings","bug-monitor","drafts"],queryFn:()=>t("/api/engine/bug-monitor/drafts?limit=10",{method:"GET"}).catch(()=>({drafts:[]})),refetchInterval:15e3}),Ot=j({queryKey:["settings","bug-monitor","incidents"],queryFn:()=>t("/api/engine/bug-monitor/incidents?limit=10",{method:"GET"}).catch(()=>({incidents:[]})),refetchInterval:1e4}),Ft=j({queryKey:["settings","bug-monitor","posts"],queryFn:()=>t("/api/engine/bug-monitor/posts?limit=10",{method:"GET"}).catch(()=>({posts:[]})),refetchInterval:15e3}),_t=j({queryKey:["settings","bug-monitor","workspace-browser",nt],enabled:qe&&!!nt,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(nt)}`,{method:"GET"})}),Tt=j({queryKey:["settings","channels","config"],queryFn:()=>n.channels.config().catch(()=>({})),refetchInterval:15e3}),we=j({queryKey:["settings","channels","status"],queryFn:()=>n.channels.status().catch(()=>({})),refetchInterval:6e3}),L=me({mutationFn:async({providerId:r,modelId:f})=>n.providers.setDefaults(r,f),onSuccess:async()=>{a("ok","Updated provider defaults."),await Promise.all([b.invalidateQueries({queryKey:["settings","providers"]}),w()])},onError:r=>a("err",r instanceof Error?r.message:String(r))}),lt=me({mutationFn:async()=>t("/api/engine/config/bug-monitor",{method:"PATCH",body:JSON.stringify({bug_monitor:{enabled:He,paused:Be,workspace_root:String(ye||"").trim()||null,repo:String(St||"").trim()||null,mcp_server:String(Ye||"").trim()||null,provider_preference:String(je||"auto").trim(),model_policy:De&&g?{default_model:{provider_id:De,model_id:g}}:null,auto_create_new_issues:ve,require_approval_for_new_issues:o,auto_comment_on_matched_open_issues:C,label_mode:"reporter_only"}})}),onSuccess:async()=>{a("ok","Bug Monitor settings saved."),await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})])},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),he=me({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"]})]),a("ok","Capability bindings refreshed from built-ins.")},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),tt=me({mutationFn:async({draftId:r,decision:f})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(r)}/${f}`,{method:"POST",body:JSON.stringify({reason:`${f}d from control panel settings`})}),onSuccess:async(r,f)=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),a("ok",`Bug Monitor draft ${f.decision==="approve"?"approved":"denied"}.`)},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),yt=me({mutationFn:async({draftId:r})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(r)}/triage-run`,{method:"POST"}),onSuccess:async r=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),a("ok",r?.deduped?`Bug Monitor triage run already exists: ${r?.run?.run_id||"unknown"}`:`Bug Monitor triage run created: ${r?.run?.run_id||"unknown"}`)},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),jt=me({mutationFn:async({action:r})=>t(`/api/engine/bug-monitor/${r}`,{method:"POST"}),onSuccess:async(r,f)=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),a("ok",`Bug Monitor ${f.action==="pause"?"paused":"resumed"}.`)},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),ct=me({mutationFn:async({incidentId:r})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(r)}/replay`,{method:"POST"}),onSuccess:async r=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),a("ok",r?.deduped?`Bug Monitor triage run already exists: ${r?.run?.run_id||"unknown"}`:`Bug Monitor replay queued triage: ${r?.run?.run_id||"unknown"}`)},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),Ct=me({mutationFn:async({draftId:r})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(r)}/publish`,{method:"POST"}),onSuccess:async r=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),a("ok",r?.action==="comment_issue"?`Bug Monitor commented on issue #${r?.draft?.issue_number||"unknown"}.`:`Bug Monitor published issue #${r?.draft?.issue_number||"unknown"}.`)},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),en=me({mutationFn:async({draftId:r})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(r)}/recheck-match`,{method:"POST"}),onSuccess:async r=>{await Promise.all([b.invalidateQueries({queryKey:["settings","bug-monitor"]})]),a("ok",`GitHub match result: ${String(r?.action||"rechecked").replaceAll("_"," ")}.`)},onError:r=>{const f=r instanceof Error?r.message:String(r?.detail||r?.error||r);a("err",f)}}),bn=me({mutationFn:({providerId:r,apiKey:f})=>n.providers.setApiKey(r,f),onSuccess:async()=>{a("ok","API key updated."),await w()},onError:r=>a("err",r instanceof Error?r.message:String(r))}),sn=me({mutationFn:async()=>{const f=(R.data?.identity?.bot||{})?.aliases||{},Y=String(X||"").trim();if(!Y)throw new Error("Bot name is required.");const $e=String(J||"").trim(),Xe=String(G||"").trim();return h({identity:{bot:{canonical_name:Y,avatar_url:$e||null,aliases:{...f,control_panel:Xe||void 0}}}})},onSuccess:async()=>{a("ok","Identity updated."),await Promise.all([b.invalidateQueries({queryKey:["settings","identity"]}),M()])},onError:r=>a("err",r instanceof Error?r.message:String(r))}),yn=Ee(async()=>b.invalidateQueries({queryKey:["settings","channels"]}),[b]),qn=me({mutationFn:async r=>{const f=Ie[r];if(!f)throw new Error(`No draft found for ${r}.`);const Y={allowed_users:Xl(f.allowedUsers),mention_only:!!f.mentionOnly},$e=String(f.botToken||"").trim();if($e&&(Y.bot_token=$e),r==="telegram"&&(Y.style_profile=String(f.styleProfile||"default").trim()||"default"),r==="discord"&&(Y.guild_id=String(f.guildId||"").trim()),r==="slack"){const Xe=String(f.channelId||"").trim();if(!Xe&&!Tt.data?.slack?.channel_id)throw new Error("Slack channel ID is required.");Xe&&(Y.channel_id=Xe)}return n.channels.put(r,Y)},onSuccess:async(r,f)=>{a("ok",`Saved ${f} channel settings.`),fe(Y=>({...Y,[f]:null})),pe(Y=>({...Y,[f]:{...Y[f],botToken:""}})),await yn()},onError:r=>a("err",r instanceof Error?r.message:String(r))}),vn=me({mutationFn:async r=>n.channels.delete(r),onSuccess:async(r,f)=>{a("ok",`Removed ${f} channel settings.`),fe(Y=>({...Y,[f]:null})),pe(Y=>({...Y,[f]:ua(f,null)})),await yn()},onError:r=>a("err",r instanceof Error?r.message:String(r))}),m=me({mutationFn:async r=>{const f=Ie[r],Y={bot_token:String(f?.botToken||"").trim()||void 0};return n.channels.verify(r,Y)},onSuccess:(r,f)=>{fe(Y=>({...Y,[f]:r})),a("ok",`${f} verification complete.`)},onError:r=>a("err",r instanceof Error?r.message:String(r))}),_=Ee(async()=>b.invalidateQueries({queryKey:["settings","mcp"]}),[b]),U=me({mutationFn:async({action:r,server:f})=>{if(!f)throw new Error("No MCP server selected.");if(r==="connect")return n.mcp.connect(f.name);if(r==="disconnect")return n.mcp.disconnect(f.name);if(r==="refresh")return n.mcp.refresh(f.name);if(r==="toggle-enabled")return n.mcp.setEnabled(f.name,!f.enabled);if(r==="delete")return t(`/api/engine/mcp/${encodeURIComponent(f.name)}`,{method:"DELETE"});throw new Error(`Unknown action: ${r}`)},onSuccess:async(r,f)=>{await _(),f.action==="connect"&&a("ok",`Connected ${f.server?.name}.`),f.action==="disconnect"&&a("ok",`Disconnected ${f.server?.name}.`),f.action==="refresh"&&a("ok",`Refreshed ${f.server?.name}.`),f.action==="toggle-enabled"&&a("ok",`${f.server?.enabled?"Disabled":"Enabled"} ${f.server?.name}.`),f.action==="delete"&&a("ok",`Deleted ${f.server?.name}.`)},onError:r=>a("err",r instanceof Error?r.message:String(r))}),de=me({mutationFn:async()=>{const r=String(ee||"").trim(),f=is(r),Y=ba(I||f);if(!r)throw new Error("Transport URL is required.");if(!ka(r)&&!r.startsWith("stdio:"))throw new Error("Transport must be a valid URL or stdio:* transport.");const $e=Hl({authMode:N,token:be,customHeader:Me,transport:r}),Xe={name:Y,transport:r,enabled:!0};Object.keys($e).length&&(Xe.headers=$e);const Dt=String(ht||"").trim();if(Dt&&Dt!==Y&&await t(`/api/engine/mcp/${encodeURIComponent(Dt)}`,{method:"DELETE"}).catch(()=>null),await n.mcp.add(Xe),st&&!(await n.mcp.connect(Xe.name))?.ok)throw new Error(`Added "${Xe.name}" but connect failed.`);return Xe.name},onSuccess:async r=>{await _(),se(!1),P(""),ce(""),ue("none"),Re(""),Te(""),Ae(!0),gt(""),a("ok",`Saved MCP "${r}".`)},onError:r=>a("err",r instanceof Error?r.message:String(r))}),re=r=>{if(!r)return;if(r.size>10*1024*1024){a("err","Avatar image is too large (max 10 MB).");return}const f=new FileReader;f.onload=()=>{const Y=typeof f.result=="string"?f.result:"";if(!Y){a("err","Failed to read avatar image.");return}ne(Y)},f.onerror=()=>a("err","Failed to read avatar image."),f.readAsDataURL(r)},Pe=Array.isArray(v.data?.all)?v.data.all:[],Fe=V(()=>Vl(rt.data),[rt.data]),Nt=V(()=>zl(ze.data),[ze.data]),It=V(()=>Yl(et.data?.catalog||et.data||null),[et.data]),wn=V(()=>new Set(Fe.map(r=>r.name.toLowerCase())),[Fe]),Kt=V(()=>{const r=String(ft||"").trim().toLowerCase();return It.servers.filter(f=>r?f.name.toLowerCase().includes(r)||f.slug.toLowerCase().includes(r)||f.transportUrl.toLowerCase().includes(r):!0).slice(0,36)},[It.servers,ft]),Yt=Fe.filter(r=>r.connected).length,Z=V(()=>qt.data?.status||{},[qt.data]),Yn=V(()=>Array.isArray(Bt.data?.drafts)?Bt.data.drafts||[]:[],[Bt.data]),Xn=V(()=>Array.isArray(Ot.data?.incidents)?Ot.data.incidents||[]:[],[Ot.data]),_a=V(()=>Array.isArray(Ft.data?.posts)?Ft.data.posts||[]:[],[Ft.data]),Xt=V(()=>Fe.find(r=>r.name.toLowerCase()===String(Ye||"").trim().toLowerCase())||null,[Ye,Fe]),Tn=V(()=>Pe.find(r=>String(r?.id||"").toLowerCase()===String(De||"").trim().toLowerCase())||null,[De,Pe]),Zn=V(()=>{const r=Tn&&typeof Tn=="object"?Tn.models||{}:{};return Object.keys(r).sort((f,Y)=>f.localeCompare(Y))},[Tn]),En=Array.isArray(A.data?.blocking_issues)?A.data?.blocking_issues||[]:[],Ca=Array.isArray(A.data?.recommendations)?A.data?.recommendations||[]:[],Ia=Array.isArray(A.data?.install_hints)?A.data?.install_hints||[]:[],xn=["telegram","discord","slack"],ea=xn.filter(r=>!!we.data?.[r]?.connected).length,ta=Array.isArray(_t.data?.directories)?_t.data.directories:[],On=String(Zt||"").trim().toLowerCase(),Aa=V(()=>On?ta.filter(r=>String(r?.name||r?.path||"").trim().toLowerCase().includes(On)):ta,[ta,On]),na=String(_t.data?.parent||"").trim(),Fn=String(_t.data?.dir||nt||"").trim();ie(()=>{const r=at.data?.bug_monitor&&typeof at.data?.bug_monitor=="object"?at.data.bug_monitor:{};le(!!r.enabled),dt(!!r.paused),Ke(String(r.workspace_root||"").trim()),$t(String(r.repo||"").trim()),ge(String(r.mcp_server||"").trim()),Ge(String(r.provider_preference||"auto").trim()||"auto"),ut(String(r.model_policy?.default_model?.provider_id||"").trim()),k(String(r.model_policy?.default_model?.model_id||"").trim()),ke(r.auto_create_new_issues!==!1),d(!!r.require_approval_for_new_issues),Q(r.auto_comment_on_matched_open_issues!==!1)},[at.data]),ie(()=>{const r=Tt.data&&typeof Tt.data=="object"?Tt.data:{};pe(f=>{const Y={...f};for(const $e of xn)Y[$e]||(Y[$e]=ua($e,r[$e]));return Y})},[Tt.data]);const Pa=(r,f)=>{const Y=String(f||"").trim();Y&&L.mutate({providerId:r,modelId:Y})},Dn=r=>{if(r){Qe("manual");const f=r.headers&&typeof r.headers=="object"?r.headers:{},Y=Object.keys(f),$e=Y.find(Dt=>String(Dt).toLowerCase()==="authorization"),Xe=Y.find(Dt=>String(Dt).toLowerCase()==="x-api-key");gt(r.name),P(r.name),ce(r.transport||""),Ae(r.connected||!1),Xe?(ue("x-api-key"),Te(""),Re(String(f[Xe]||"").trim())):$e?(ue("bearer"),Te(""),Re(String(f[$e]||"").replace(/^bearer\s+/i,"").trim())):Y.length===1?(ue("custom"),Te(Y[0]),Re(String(f[Y[0]]||"").trim())):(ue("none"),Te(""),Re(""))}else Qe("catalog"),gt(""),P(""),ce(""),ue("none"),Te(""),Re(""),Ae(!0);se(!0)},Ra=async()=>{const r=await t("/api/engine/bug-monitor/debug",{method:"GET"});await navigator.clipboard.writeText(JSON.stringify(r,null,2)),a("ok","Bug Monitor debug payload copied.")},$a=[{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"}],Ds=V(()=>Gl(N,be,Me,ee),[N,Me,be,ee]);return ie(()=>{const r=S.current;r?dn(r):dn()},[O,He,Be,ye,Ye,Z.readiness?.runtime_ready,Z.runtime?.monitoring_active,Z.runtime?.paused,Z.runtime?.pending_incidents,Z.pending_drafts,Yn.length,Xn.length,he.isPending,jt.isPending,tt.isPending,ct.isPending,yt.isPending,lt.isPending,U.isPending]),e(Mn,{className:"grid gap-4",children:e("div",{ref:S,className:"grid gap-4",children:[e("div",{className:"tcp-settings-tabs",children:$a.map(r=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${O===r.id?"active":""}`,onClick:()=>B(r.id),children:[e("i",{"data-lucide":r.icon}),r.label]},r.id))}),e(In,{main:e(Vi,{className:"grid gap-4",children:[O==="providers"?e(Le,{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(ae,{tone:String($.data?.default||"").trim()?"ok":"warn",children:["Default: ",String($.data?.default||"none")]}),e(ae,{tone:"info",children:[String(v.data?.connected?.length||0)," connected"]}),e("button",{className:"tcp-btn",onClick:()=>w().then(()=>a("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:()=>xe(r=>!r),"aria-expanded":oe,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":oe?"chevron-down":"chevron-right"}),e("span",{children:oe?"Hide provider catalog":"Show provider catalog"})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Pe.length," providers available for configuration. Expand to change models and API keys."]})]}),e(ae,{tone:"info",children:[String(v.data?.connected?.length||0)," connected"]})]})}),e(Ze,{initial:!1,children:oe?e(te.div,{className:"grid gap-3",initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:Pe.length?Pe.map(r=>{const f=String(r?.id||""),Y=Object.keys(r?.models||{}),$e=String($.data?.providers?.[f]?.default_model||Y[0]||""),Xe=String(q[f]??$e).trim(),Dt=Xe.toLowerCase(),mt=Y.filter(At=>Dt?At.toLowerCase().includes(Dt):!0).slice(0,80),vt=Zl(r,Y.length),Us=ec(r,$e),Ma=ws[f]||null,qa=String(Ma?.keyUrl||"").trim();return e(te.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:f}),e("div",{className:"tcp-subtle text-xs",children:Us})]}),e(ae,{tone:vt.tone,children:vt.text})]})}),e("div",{className:"mt-3 grid gap-3",children:[qa?e("div",{className:"flex justify-end",children:e("a",{className:"tcp-btn h-8 px-3 text-xs",href:qa,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Get API key"]})}):null,e("form",{className:"grid gap-2",onSubmit:At=>{At.preventDefault(),Pa(f,Xe)},children:[e("div",{className:"flex gap-2",children:[e("input",{className:"tcp-input",value:Xe,placeholder:`Type model id for ${f}`,onInput:At=>T(un=>({...un,[f]:At.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:mt.length?mt.map(At=>e("button",{type:"button",className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${At===$e?"bg-slate-700/40":""}`,onClick:()=>{T(un=>({...un,[f]:At})),Pa(f,At)},children:At},At)):e("div",{className:"tcp-subtle px-2 py-1 text-xs",children:Y.length?"No matching models.":"No live catalog available. Type a model ID manually."})})]}),e("form",{onSubmit:At=>{At.preventDefault();const un=At.currentTarget.elements.namedItem("apiKey"),Ta=String(un?.value||"").trim();Ta&&(bn.mutate({providerId:f,apiKey:Ta}),un.value="")},className:"flex gap-2",children:[e("input",{name:"apiKey",className:"tcp-input",placeholder:String(Ma?.placeholder||`Set ${f} API key`)}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"save"}),"Save"]})]})]})]},f)}):e(Se,{text:"No providers were detected from the engine catalog."})}):null})]})}):null,O==="identity"?e(Le,{title:"Identity preview",subtitle:"Live preview of how the assistant appears across the panel.",actions:e(Wt,{children:[e("button",{className:"tcp-btn",onClick:()=>M().then(()=>a("ok","Identity refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh identity"]}),e("button",{className:"tcp-btn-primary",onClick:()=>sn.mutate(),disabled:sn.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:J?e("img",{src:J,alt:X||"Bot",className:"block h-full w-full object-cover"}):e("i",{"data-lucide":"cpu"})}),e("div",{children:[e("div",{className:"font-semibold",children:X||"Tandem"}),e("div",{className:"tcp-subtle text-xs",children:G||"Control Center"})]})]}),e(Wt,{children:[e("button",{className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>Ht.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>ne(""),children:e("i",{"data-lucide":"trash-2"})})]})]})}),e("input",{className:"tcp-input",value:X,onInput:r=>z(r.target.value),placeholder:"Bot name"}),e("input",{className:"tcp-input",value:G,onInput:r=>x(r.target.value),placeholder:"Control panel alias"}),e("input",{className:"tcp-input",value:J,onInput:r=>ne(r.target.value),placeholder:"Avatar URL or data URL"}),e("input",{ref:Ht,type:"file",accept:"image/*",className:"hidden",onChange:r=>re(r.target.files?.[0]||null)})]})}):null,O==="theme"?e(Le,{title:"Theme studio",subtitle:"Preview tiles with richer feedback and immediate switching.",children:e(Ql,{themes:c,themeId:p,onChange:u})}):null,O==="channels"?e(Le,{title:"Channel connections",subtitle:"Telegram, Discord, and Slack delivery setup and live listener status.",actions:e(Wt,{children:[e(ae,{tone:ea?"ok":"warn",children:[ea,"/",xn.length," connected"]}),e("button",{className:"tcp-btn",onClick:()=>{yn()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh channels"]})]}),children:e("div",{className:"grid gap-3",children:xn.map(r=>{const f=Tt.data?.[r]||{},Y=we.data?.[r]||{},$e=Ie[r]||ua(r,f),Xe=Ne[r],Dt=!!f?.has_token||!!(Array.isArray(f?.allowed_users)&&f.allowed_users.length)||!!String(f?.guild_id||"").trim()||!!String(f?.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:r}),e("div",{className:"tcp-subtle text-xs",children:r==="telegram"?"Bot token, allowed users, and style profile.":r==="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(ae,{tone:Y.connected?"ok":"warn",children:Y.connected?"Connected":Y.enabled?"Configured":"Disconnected"}),e(ae,{tone:f.has_token?"info":"warn",children:f.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:f.has_token?`Token saved for ${r}. Enter a new token to replace it.`:`Paste ${r} bot token`,value:$e.botToken,onInput:mt=>pe(vt=>({...vt,[r]:{...$e,botToken:mt.target.value}}))}),e("input",{className:"tcp-input",placeholder:"Allowed users (comma separated)",value:$e.allowedUsers,onInput:mt=>pe(vt=>({...vt,[r]:{...$e,allowedUsers:mt.target.value}}))})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[r==="telegram"?e("input",{className:"tcp-input",placeholder:"Style profile",value:$e.styleProfile,onInput:mt=>pe(vt=>({...vt,[r]:{...$e,styleProfile:mt.target.value}}))}):null,r==="discord"?e("input",{className:"tcp-input",placeholder:"Guild ID (optional)",value:$e.guildId,onInput:mt=>pe(vt=>({...vt,[r]:{...$e,guildId:mt.target.value}}))}):null,r==="slack"?e("input",{className:"tcp-input",placeholder:"Default channel ID",value:$e.channelId,onInput:mt=>pe(vt=>({...vt,[r]:{...$e,channelId:mt.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:$e.mentionOnly,onChange:mt=>pe(vt=>({...vt,[r]:{...$e,mentionOnly:mt.target.checked}}))}),"Mention only"]})]}),e("div",{className:"tcp-subtle text-xs",children:["Active sessions: ",Number(Y.active_sessions||0),Y.last_error?` · Last error: ${Y.last_error}`:""]}),Xe?.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:Xe.hints.map((mt,vt)=>e("div",{className:"tcp-subtle",children:mt},`${r}-hint-${vt}`))})]}):null,e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:qn.isPending,onClick:()=>qn.mutate(r),children:[e("i",{"data-lucide":"save"}),"Save"]}),r==="discord"?e("button",{className:"tcp-btn",disabled:m.isPending,onClick:()=>m.mutate("discord"),children:[e("i",{"data-lucide":"shield-check"}),"Verify"]}):null,e("button",{className:"tcp-btn-danger",disabled:vn.isPending||!Dt,onClick:()=>vn.mutate(r),children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},r)})})}):null,O==="mcp"?e(Le,{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(ae,{tone:Yt?"ok":"warn",children:[Yt,"/",Fe.length," connected"]}),e(ae,{tone:"info",children:[Nt.length," tools"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Dn(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]}),e("button",{className:"tcp-btn",onClick:()=>{_()},children:[e("i",{"data-lucide":"refresh-cw"}),"Reload"]})]}),children:e("div",{className:"grid gap-3",children:[Fe.length?Fe.map(r=>{const f=Object.keys(r.headers||{}).filter(Boolean),Y=Array.isArray(r.toolCache)?r.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:r.name}),e("div",{className:"tcp-subtle text-sm",children:r.transport||"No transport set"})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(ae,{tone:r.connected?"ok":"warn",children:r.connected?"Connected":"Disconnected"}),e(ae,{tone:r.enabled?"info":"warn",children:r.enabled?"Enabled":"Disabled"}),e(ae,{tone:"info",children:[Y," tools"]})]})]}),r.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:r.lastError}):null,e("div",{className:"tcp-subtle text-xs",children:f.length?`Auth headers: ${f.join(", ")}`:"No stored auth headers."}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Dn(r),children:"Edit"}),e("button",{className:"tcp-btn",disabled:U.isPending,onClick:()=>U.mutate({action:r.connected?"disconnect":"connect",server:r}),children:r.connected?"Disconnect":"Connect"}),e("button",{className:"tcp-btn",disabled:U.isPending,onClick:()=>U.mutate({action:"refresh",server:r}),children:"Refresh"}),e("button",{className:"tcp-btn",disabled:U.isPending,onClick:()=>U.mutate({action:"toggle-enabled",server:r}),children:r.enabled?"Disable":"Enable"}),e("button",{className:"tcp-btn-danger",disabled:U.isPending,onClick:()=>U.mutate({action:"delete",server:r}),children:"Delete"})]})]},r.name)}):e("div",{className:"grid gap-3",children:[e(Se,{text:"No MCP servers configured."}),e("div",{className:"flex justify-start",children:e("button",{className:"tcp-btn-primary",onClick:()=>Dn(),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:Nt.length?Nt.slice(0,250).join(`
|
|
21
|
-
`):"No MCP tools discovered yet. Connect a server first."})]})]})}):null,O==="bug_monitor"?e(Le,{title:"Bug monitor",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(ae,{tone:Z.runtime?.monitoring_active?Z.readiness?.publish_ready?"ok":"info":Z.readiness?.ingest_ready?"info":"warn",children:Z.runtime?.monitoring_active?Z.readiness?.publish_ready?"Monitoring":"Watching locally":Z.readiness?.ingest_ready?"Ready":"Not ready"}),Be||Z.runtime?.paused?e(ae,{tone:"warn",children:"Paused"}):null,e(ae,{tone:"info",children:[Number(Z.runtime?.pending_incidents||0)," incidents"]}),e(ae,{tone:"info",children:[Number(Z.pending_drafts||0)," pending drafts"]}),e(ae,{tone:"info",children:[Number(Z.pending_posts||0)," post attempts"]}),e("button",{className:"tcp-icon-btn",title:"Reload status","aria-label":"Reload status",onClick:()=>Promise.all([qt.refetch(),Bt.refetch(),Ot.refetch(),Ft.refetch()]).then(()=>a("ok","Bug Monitor status refreshed.")),children:e("i",{"data-lucide":"refresh-cw"})}),e("button",{className:"tcp-icon-btn",title:Be||Z.runtime?.paused?"Resume monitoring":"Pause monitoring","aria-label":Be||Z.runtime?.paused?"Resume monitoring":"Pause monitoring",disabled:jt.isPending,onClick:()=>jt.mutate({action:Be||Z.runtime?.paused?"resume":"pause"}),children:e("i",{"data-lucide":Be||Z.runtime?.paused?"play":"pause"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:he.isPending,onClick:()=>he.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Ra()},children:e("i",{"data-lucide":"copy"})}),e("button",{className:"tcp-icon-btn",title:"Open GitHub MCP guide","aria-label":"Open GitHub MCP guide",onClick:()=>W(!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 ${He?"ring-1 ring-emerald-400/40":""}`,onClick:()=>le(r=>!r),children:[e("div",{className:"font-medium",children:He?Be?"Paused":"Enabled":"Disabled"}),e("div",{className:"tcp-subtle text-xs",children:He?Be?"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 r=String(ye||"/").trim();Et(r||"/"),ot(""),Ve(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,value:ye,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>Ke(""),disabled:!ye,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),e("div",{className:"tcp-subtle text-xs",children:ye?`Reporter analysis root: ${ye}`:"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:r=>$t(r.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:Ye,onChange:r=>ge(r.target.value),children:[e("option",{value:"",children:"Select an MCP server"}),Fe.map(r=>e("option",{value:r.name,children:r.name},r.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:je,onChange:r=>Ge(r.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:De,onChange:r=>{const f=r.target.value;ut(f),k("")},children:[e("option",{value:"",children:"Select a provider"}),Pe.map(r=>e("option",{value:String(r?.id||""),children:String(r?.id||"")},String(r?.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:g,onChange:r=>k(r.target.value),list:"bug-monitor-models",disabled:!De,placeholder:De?"Type or paste a model id":"Choose a provider first",spellCheck:!1}),e("datalist",{id:"bug-monitor-models",children:Zn.map(r=>e("option",{value:r},r))}),e("div",{className:"tcp-subtle text-xs",children:De?Zn.length?`${Zn.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 ${ve&&!o?"ring-1 ring-emerald-400/40":""}`,onClick:()=>{ke(r=>!r),o&&ve&&d(!1)},children:[e("div",{className:"font-medium",children:"Auto-create new issues"}),e("div",{className:"tcp-subtle text-xs",children:ve?"New drafts post to GitHub automatically.":"New drafts stay internal until published manually."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${o?"ring-1 ring-amber-400/40":""}`,onClick:()=>{d(r=>{const f=!r;return f&&ke(!1),f})},children:[e("div",{className:"font-medium",children:"Require approval"}),e("div",{className:"tcp-subtle text-xs",children:o?"New drafts wait for a manual publish click.":"Approval gate disabled."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${C?"ring-1 ring-sky-400/40":""}`,onClick:()=>Q(r=>!r),children:[e("div",{className:"font-medium",children:"Auto-comment matches"}),e("div",{className:"tcp-subtle text-xs",children:C?"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:lt.isPending,title:"Save Bug Monitor settings","aria-label":"Save Bug Monitor settings",onClick:()=>lt.mutate(),children:[e("i",{"data-lucide":"save"}),lt.isPending?"Saving...":null]}),e("button",{className:"tcp-icon-btn",title:"Add MCP server","aria-label":"Add MCP server",onClick:()=>Dn(),children:e("i",{"data-lucide":"plus"})}),e("button",{className:"tcp-icon-btn",title:"Open setup guide","aria-label":"Open setup guide",onClick:()=>W(!0),children:e("i",{"data-lucide":"external-link"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:he.isPending,onClick:()=>he.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Ra()},children:e("i",{"data-lucide":"copy"})}),Xt?e("button",{className:"tcp-icon-btn",title:Xt.connected?"Refresh selected MCP":"Connect selected MCP","aria-label":Xt.connected?"Refresh selected MCP":"Connect selected MCP",disabled:U.isPending,onClick:()=>U.mutate({action:Xt.connected?"refresh":"connect",server:Xt}),children:e("i",{"data-lucide":Xt.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:Z.runtime?.monitoring_active?Z.readiness?.publish_ready?"Monitoring":"Watching locally":Z.runtime?.paused||Be?"Paused":Z.readiness?.ingest_ready?"Ready":"Blocked"}),e("div",{className:"tcp-subtle text-xs",children:Z.runtime?.last_runtime_error||Z.last_error||"No blocking issue reported."}),!Z.readiness?.publish_ready&&Array.isArray(Z.missing_required_capabilities)&&Z.missing_required_capabilities.length?e("div",{className:"tcp-subtle mt-2 text-xs",children:["Missing: ",Z.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:Xt?.name||"None selected"}),e("div",{className:"tcp-subtle text-xs",children:Xt?Xt.connected?"Connected":"Disconnected":"No server selected"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Bindings: ",Z.binding_source_version||"unknown version",Z.bindings_last_merged_at_ms?` · merged ${new Date(Z.bindings_last_merged_at_ms).toLocaleString()}`:""]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Local directory:"," ",ye||String(Z.config?.workspace_root||"").trim()||"engine workspace root"]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last event:"," ",String(Z.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:Z.selected_model?.provider_id&&Z.selected_model?.model_id?`${Z.selected_model.provider_id} / ${Z.selected_model.model_id}`:"No dedicated model selected"}),e("div",{className:"tcp-subtle text-xs",children:Z.readiness?.selected_model_ready?"Available":"Fail-closed when unavailable"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last processed:"," ",Z.runtime?.last_processed_at_ms?new Date(Number(Z.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:"," ",Z.required_capabilities?.github_list_issues?"ready":"missing"]}),e("div",{children:["github.get_issue:"," ",Z.required_capabilities?.github_get_issue?"ready":"missing"]}),e("div",{children:["github.create_issue:"," ",Z.required_capabilities?.github_create_issue?"ready":"missing"]}),e("div",{children:["github.comment_on_issue:"," ",Z.required_capabilities?.github_comment_on_issue?"ready":"missing"]})]}),Array.isArray(Z.resolved_capabilities)&&Z.resolved_capabilities.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:Z.resolved_capabilities.map((r,f)=>e("div",{children:[String(r.capability_id||"unknown"),":"," ",String(r.tool_name||"unresolved")]},`${r.capability_id||"cap"}-${f}`))}):null,Array.isArray(Z.selected_server_binding_candidates)&&Z.selected_server_binding_candidates.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:Z.selected_server_binding_candidates.map((r,f)=>e("div",{children:[String(r.capability_id||"unknown"),":"," ",String(r.binding_tool_name||"unknown"),r.matched?" · matched":" · candidate"]},`${r.capability_id||"candidate"}-${f}`))}):null,Array.isArray(Z.discovered_mcp_tools)&&Z.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:Z.discovered_mcp_tools.join(`
|
|
22
|
-
`)})]}):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:"," ",o?"Manual publish":ve?"Auto-create":"Internal draft only"]}),e("div",{children:["Matched open issues:"," ",C?"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"}),Xn.length?e("div",{className:"grid gap-2",children:Xn.map(r=>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:r.title||r.event_type}),e(ae,{tone:r.last_error?"warn":"info",children:r.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[r.event_type," · seen"," ",Number(r.occurrence_count||0),"x"," · ",r.updated_at_ms?new Date(r.updated_at_ms).toLocaleString():"time unavailable"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:r.workspace_root||"engine workspace root"}),r.last_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:r.last_error}):null,r.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:r.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:ct.isPending,onClick:()=>ct.mutate({incidentId:r.incident_id}),children:e("i",{"data-lucide":"rotate-cw"})}),r.triage_run_id?e("span",{className:"tcp-subtle text-xs",children:["triage run: ",r.triage_run_id]}):null,r.draft_id?e("span",{className:"tcp-subtle text-xs",children:["draft: ",r.draft_id]}):null]})]},r.incident_id))}):e(Se,{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"}),Yn.length?e("div",{className:"grid gap-2",children:Yn.map(r=>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:r.title||r.fingerprint}),e(ae,{tone:r.status==="approval_required"?"warn":"info",children:r.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[r.repo," ·"," ",r.issue_number?`issue #${r.issue_number}`:"draft only"," ","·"," ",r.created_at_ms?new Date(r.created_at_ms).toLocaleString():"time unavailable"]}),r.github_status?e("div",{className:"tcp-subtle mt-1 text-xs",children:["GitHub: ",r.github_status,r.matched_issue_number?` · matched #${r.matched_issue_number}${r.matched_issue_state?` (${r.matched_issue_state})`:""}`:""]}):null,r.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:r.detail}):null,r.last_post_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:r.last_post_error}):null,r.triage_run_id?e("div",{className:"tcp-subtle mt-2 text-xs",children:["triage run: ",r.triage_run_id]}):null,r.status==="approval_required"?e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:tt.isPending,title:"Approve draft","aria-label":"Approve draft",onClick:()=>tt.mutate({draftId:r.draft_id,decision:"approve"}),children:[e("i",{"data-lucide":"check"}),tt.isPending?"Updating...":null]}),e("button",{className:"tcp-icon-btn",title:"Deny draft","aria-label":"Deny draft",disabled:tt.isPending,onClick:()=>tt.mutate({draftId:r.draft_id,decision:"deny"}),children:e("i",{"data-lucide":"x"})})]}):null,r.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:Ct.isPending,onClick:()=>Ct.mutate({draftId:r.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:en.isPending,onClick:()=>en.mutate({draftId:r.draft_id}),children:e("i",{"data-lucide":"refresh-cw"})})]}),(r.github_issue_url||r.github_comment_url)&&e("div",{className:"mt-3 flex flex-wrap gap-2 text-xs",children:[r.github_issue_url?e("a",{className:"tcp-btn",href:r.github_issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,r.github_comment_url?e("a",{className:"tcp-btn",href:r.github_comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]}),(r.status==="draft_ready"||r.status==="triage_queued")&&!r.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:yt.isPending,onClick:()=>yt.mutate({draftId:r.draft_id}),children:e("i",{"data-lucide":"sparkles"})})}):null]},r.draft_id))}):e(Se,{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"}),_a.length?e("div",{className:"grid gap-2",children:_a.map(r=>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:r.operation}),e(ae,{tone:r.status==="posted"?"ok":"warn",children:r.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[r.repo,r.issue_number?` · issue #${r.issue_number}`:"",r.updated_at_ms?` · ${new Date(r.updated_at_ms).toLocaleString()}`:""]}),r.error?e("div",{className:"tcp-subtle mt-1 text-xs",children:r.error}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[r.issue_url?e("a",{className:"tcp-btn",href:r.issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,r.comment_url?e("a",{className:"tcp-btn",href:r.comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]})]},r.post_id))}):e(Se,{text:"No GitHub post attempts yet."})]})]})}):null,O==="browser"?e(Le,{title:"Browser readiness",subtitle:"Operational browser status, diagnostics, and recovery actions.",actions:e(Wt,{children:[e("button",{className:"tcp-btn",onClick:()=>{A.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>Ue.mutate(),disabled:Ue.isPending,children:[e("i",{"data-lucide":"download"}),Ue.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>Je.mutate(),disabled:Je.isPending,children:[e("i",{"data-lucide":"globe"}),Je.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>D(!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:A.data?A.data.runnable?"Ready":A.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",A.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:A.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:A.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:A.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:A.data?.browser?.version||A.data?.browser?.channel||"No version detected"})]})]}),En.length?e("div",{className:"mt-3 grid gap-2",children:En.map((r,f)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:r.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:r.message||"Unknown browser issue."})]},`${r.code||"issue"}-${f}`))}):null,H?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",H.title?`: ${H.title}`:""]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:H.final_url||H.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",H.load_state||"unknown"," · elements:"," ",String(H.element_count??0)," · closed:"," ",H.closed?"yes":"no"]}),H.excerpt?e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words",children:H.excerpt}):null]}):null]}):null]}),aside:e("div",{className:"grid gap-4",children:[e(Le,{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(v.data?.connected?.length||0)," connected, default"," ",String($.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:A.data?A.data.runnable?"Ready":A.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:c.find(r=>r.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:[Yt," connected, ",Nt.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:[Z.readiness?.runtime_ready?"Ready":He?"Enabled but blocked":"Disabled"," · ",Number(Z.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:[ea," connected, ",xn.length," available"]})]})]})}),e(Le,{title:"Quick access",subtitle:"Jump straight to the section you need.",children:e("div",{className:"grid gap-2",children:$a.map(r=>e("button",{className:"tcp-list-item flex items-center justify-between text-left",onClick:()=>B(r.id),children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":r.icon}),r.label]}),O===r.id?e(ae,{tone:"ok",children:"open"}):null]},r.id))})})]})}),e(Hn,{open:F,onClose:()=>W(!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(Ze,{children:qe?e(te.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:()=>{Ve(!1),ot("")}}),e(te.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: ",Fn||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{na&&Et(na)},disabled:!na,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{Fn&&(Ke(Fn),Ve(!1),ot(""),a("ok",`Bug Monitor directory selected: ${Fn}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{Ve(!1),ot("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:Zt,onInput:r=>ot(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:Aa.length?Aa.map(r=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Et(String(r?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(r?.name||r?.path||"")]},String(r?.path||r?.name))):e(Se,{text:On?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e(Hn,{open:E,onClose:()=>D(!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:A.data?A.data.runnable?"Ready":A.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",A.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:A.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:A.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:A.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:A.data?.browser?.version||A.data?.browser?.channel||"No version detected"})]})]}),e(Wt,{children:[e("button",{className:"tcp-btn",onClick:()=>{A.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>Ue.mutate(),disabled:Ue.isPending,children:[e("i",{"data-lucide":"download"}),Ue.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>Je.mutate(),disabled:Je.isPending,children:[e("i",{"data-lucide":"globe"}),Je.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>t("/api/engine/browser/status",{method:"GET"}).then(()=>a("ok","Browser diagnostics refreshed.")).catch(r=>a("err",r instanceof Error?r.message:String(r))),children:[e("i",{"data-lucide":"activity"}),"Re-run diagnostics"]})]}),A.isLoading?e(Se,{text:"Loading browser diagnostics..."}):A.data?e(Qt,{children:[En.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Blocking issues"}),En.map((r,f)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:r.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:r.message||"Unknown browser issue."})]},`${r.code||"issue"}-${f}`))]}):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."}),H?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:H.title||"Smoke test"}),e("div",{className:"tcp-subtle text-xs",children:H.final_url||H.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",H.load_state||"unknown"," · elements:"," ",String(H.element_count??0)," · closed:"," ",H.closed?"yes":"no"]}),H.excerpt?e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:H.excerpt}):null]})]}):null,Ca.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommendations"}),Ca.map((r,f)=>e("div",{className:"tcp-list-item text-sm",children:r},`browser-recommendation-${f}`))]}):null,Ia.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Install hints"}),Ia.map((r,f)=>e("div",{className:"tcp-list-item text-sm",children:r},`browser-install-hint-${f}`))]}):null,A.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: ",A.data.last_error]}):null]}):e(Se,{text:"Browser diagnostics are unavailable."})]})}),e(Ze,{children:Oe?e(te.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:()=>se(!1)}),e(te.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:ht?"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:()=>se(!1),children:e("i",{"data-lucide":"x"})})]}),e("form",{className:"grid gap-3",onSubmit:r=>{r.preventDefault(),de.mutate()},children:[e("div",{className:"tcp-settings-tabs",children:[e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${We==="catalog"?"active":""}`,onClick:()=>Qe("catalog"),children:[e("i",{"data-lucide":"blocks"}),"Built-in packs"]}),e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${We==="manual"?"active":""}`,onClick:()=>Qe("manual"),children:[e("i",{"data-lucide":"square-pen"}),"Manual"]})]}),We==="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:It.generatedAt?`Built-in MCP packs · generated ${It.generatedAt}`:"Built-in MCP packs"}),e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{et.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("input",{className:"tcp-input",value:ft,onInput:r=>bt(r.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:Kt.length?Kt.map(r=>{const f=wn.has(String(r.serverConfigName||r.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:r.name}),e("div",{className:"tcp-subtle text-xs",children:[r.slug,r.requiresSetup?" · setup required":""]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(ae,{tone:"info",children:[r.toolCount," tools"]}),e(ae,{tone:r.requiresAuth?"warn":"ok",children:r.requiresAuth?"Auth":"Authless"})]})]}),e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:r.description||r.transportUrl}),e("div",{className:"tcp-subtle break-all text-xs",children:r.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:()=>{P(ba(r.serverConfigName||r.slug||r.name)),ce(r.transportUrl),Qe("manual"),a("ok",`Loaded ${r.name}. Review and save when ready.`)},children:"Use pack"}),r.documentationUrl?e("a",{className:"tcp-btn h-8 px-3 text-xs",href:r.documentationUrl,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Docs"]}):null,f?e(ae,{tone:"ok",children:"added"}):null]})]},r.slug)}):e(Se,{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:I,onInput:r=>P(r.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:N,onChange:r=>ue(r.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:ee,onInput:r=>{const f=r.target.value;if(ce(f),!String(I||"").trim()||I==="mcp-server"){const Y=is(f);Y&&P(Y)}},placeholder:"https://example.com/mcp"})]}),N==="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:Me,onInput:r=>Te(r.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:be,onInput:r=>Re(r.target.value),placeholder:"token"}),e("div",{className:"tcp-subtle text-xs",children:Ds})]}),e("label",{className:"inline-flex items-center gap-2 text-sm text-slate-200",children:[e("input",{type:"checkbox",className:"accent-slate-400",checked:st,onChange:r=>Ae(r.target.checked)}),"Connect after save"]})]}),e("div",{className:"tcp-confirm-actions mt-2",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>se(!1),children:"Cancel"}),e("button",{type:"submit",className:"tcp-btn-primary",disabled:de.isPending,children:[e("i",{"data-lucide":"save"}),"Save MCP server"]})]})]})]})]}):null})]})})}function tc({routeId:n,pageProps:t}){switch(va(n)){case"chat":return e(Lo,{...t});case"automations":case"agents":case"packs":case"teams":return e(ul,{...t});case"channels":return e(ml,{...t});case"mcp":return e(os,{...t});case"packs-detail":return e(gl,{...t});case"orchestrator":return e(Dl,{...t});case"files":return e(Ll,{...t});case"memory":return e(jl,{...t});case"teams-detail":return e(Kl,{...t});case"feed":return e(Jl,{...t});case"settings":return e(os,{...t});default:return e(mo,{...t})}}const nc={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."},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 ac({identity:n,currentRoute:t,providerLocked:a,navRoutes:s,onNavigate:i,onPaletteOpen:l,onThemeCycle:c,onLogout:u,statusBar:p,routeKey:w,children:M,providerGate:b}){const[S,q]=y(!1),[T,X]=y(!1),z=String(n.botAvatarUrl||"").trim(),J=fs();ie(()=>{q(!1)},[t]),ie(()=>{try{dn()}catch{}},[t,S,p.bugMonitor?.enabled,p.bugMonitor?.monitoringActive,p.bugMonitor?.paused,p.bugMonitor?.pendingIncidents,p.bugMonitor?.blocked]),ie(()=>{X(!1)},[z]);const ne=nc[t]||{title:String(s.find(([F])=>F===t)?.[1]||"Control Panel"),subtitle:"Desktop-inspired operations UI for Tandem."},G=V(()=>s.find(([F])=>F===t)||s[0],[t,s]),x=V(()=>{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]),O=()=>z&&!T?e("img",{src:z,alt:n.botName,className:"block h-full w-full object-cover",onError:()=>X(!0)}):e("span",{className:"text-sm font-semibold uppercase",children:String(n.botName||"T").trim().slice(0,1)||"T"}),B=()=>s.map(([F,W,oe])=>{const xe=t===F,Ie=a&&F!=="settings";return e("button",{type:"button",title:W,disabled:Ie,className:`tcp-rail-icon ${xe?"active":""} ${Ie?"locked":""}`,onClick:()=>i(F),children:[xe?e(te.span,{layoutId:"tcp-icon-indicator",className:"tcp-rail-icon-indicator"}):null,e("i",{"data-lucide":oe})]},F)}),E=(F=!1)=>s.map(([W,oe,xe])=>{const Ie=t===W,pe=a&&W!=="settings";return e("button",{type:"button",disabled:pe,className:`tcp-context-link ${Ie?"active":""} ${pe?"locked":""}`,onClick:()=>{i(W),F&&q(!1)},children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":xe}),e("span",{children:oe})]}),Ie?e("span",{className:"tcp-context-link-dot"}):null]},W)}),D=(F=!1)=>e(Qt,{children:[F?e("div",{className:"tcp-context-hero",children:[e(Qn,{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:O()}),e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:n.controlPanelName||`${n.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:E(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(Jt,{tone:"ok",text:"healthy"}):e(Jt,{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(Jt,{tone:"live",text:String(p.activeRuns)}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"idle"})]}),x?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 ${x.toneClass}`,title:p.bugMonitor?.lastError?`${x.label}: ${p.bugMonitor.lastError}`:x.label,onClick:()=>{i("bug-monitor"),F&&q(!1)},children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:x.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&&q(!1)},children:[e("i",{"data-lucide":"search"}),"Command palette"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{c(),F&&q(!1)},children:[e("i",{"data-lucide":"paint-bucket"}),"Cycle theme"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{u(),F&&q(!1)},children:[e("i",{"data-lucide":"log-out"}),"Logout"]})]})]})]});return e("div",{className:"tcp-shell",children:[e(Qn,{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:()=>i("dashboard"),children:e("div",{className:"tcp-brand-avatar h-10 w-10",children:O()})}),e("nav",{className:"tcp-rail-nav",children:B()}),e("div",{className:"tcp-rail-footer",children:[e(kn,{title:"Command palette",onClick:l,children:e("i",{"data-lucide":"search"})}),e(kn,{title:"Cycle theme",onClick:c,children:e("i",{"data-lucide":"paint-bucket"})}),e(kn,{title:"Logout",onClick:u,children:e("i",{"data-lucide":"log-out"})}),e("div",{className:"mt-2 flex justify-center",children:p.engineHealthy?e(Jt,{tone:"ok"}):e(Jt,{tone:"warn"})})]})]}),e("aside",{className:"tcp-context-rail hidden lg:flex xl:hidden",children:D(!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:()=>q(!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:ne.title}),e("div",{className:"tcp-subtle truncate text-xs",children:G?.[1]||ne.subtitle})]}),x?e("button",{type:"button",className:`tcp-bug-monitor-pill ${x.toneClass}`,title:p.bugMonitor?.lastError?`${x.label}: ${p.bugMonitor.lastError}`:x.label,onClick:()=>i("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"})]}):null,p.activeRuns>0?e(Jt,{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:ne.title}),e("p",{className:"tcp-subtle mt-1 max-w-2xl",children:ne.subtitle})]}),e("div",{className:"tcp-topbar-status",children:[x?e("button",{type:"button",className:`tcp-bug-monitor-pill ${x.toneClass}`,title:p.bugMonitor?.lastError?`${x.label}: ${p.bugMonitor.lastError}`:x.label,onClick:()=>i("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:x.shortLabel})]}):null,e("span",{className:p.providerBadge,children:p.providerText}),p.engineHealthy?e(Jt,{tone:"ok",text:"Engine healthy"}):e(Jt,{tone:"warn",text:"Checking engine"}),p.activeRuns>0?e(Jt,{tone:"live",text:`${p.activeRuns} run`}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"No active runs"})]})]}),e(Ze,{mode:"wait",children:e(te.section,{className:"tcp-main-content",initial:J?!1:{opacity:0,y:18},animate:J?void 0:{opacity:1,y:0},exit:J?void 0:{opacity:0,y:-14},transition:J?void 0:{duration:zt.duration.normal,ease:zt.easing.standard},children:M},w)})]}),e(Ze,{children:S?e(te.div,{className:"tcp-mobile-drawer lg:hidden",initial:J?!1:{opacity:0},animate:J?void 0:{opacity:1},exit:J?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-mobile-drawer-backdrop","aria-label":"Close navigation",onClick:()=>q(!1)}),e(te.aside,{className:"tcp-mobile-drawer-panel",initial:J?!1:{x:"-100%"},animate:J?void 0:{x:0},exit:J?void 0:{x:"-100%"},transition:J?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:n.botName}),e("div",{className:"tcp-subtle text-xs",children:ne.title})]}),e(kn,{title:"Close",onClick:()=>q(!1),children:e("i",{"data-lucide":"x"})})]}),D(!0)]})]}):null}),e(Ze,{children:b||null})]})}function Os(n){const t=String(n||"").trim().toLowerCase();return!!t&&t!=="ollama"&&t!=="local"}function sc(n,t){const a=String(t||"").trim().toLowerCase();if(!a||!n||typeof n!="object")return!1;const s=i=>!i||typeof i!="object"?!1:i.has_key===!0||i.hasKey===!0||i.configured===!0&&!Os(a);return s(n[a])||s(n.providers?.[a])}function rc(n,t,a){const s=String(n?.default||n?.selected_model?.provider_id||"").trim(),i=n?.providers?.[s]||{},l=String(i.default_model||i.defaultModel||n?.selected_model?.model_id||"").trim(),c=Array.isArray(t?.connected)?t.connected:[],u=new Set(c.map(M=>String(M||"").trim().toLowerCase())),p=sc(a,s),w=!!s&&!!l&&u.has(s.toLowerCase())&&(!Os(s)||p);return{ready:w,defaultProvider:s,defaultModel:l,connected:[...u],error:"",needsOnboarding:!w}}function ic(n=!0){return j({queryKey:["system","health"],queryFn:()=>Rt("/api/system/health"),enabled:n,refetchInterval:n?15e3:!1})}function oc(n=!0){return j({queryKey:["swarm","status"],queryFn:()=>Rt("/api/swarm/status"),enabled:n,refetchInterval:n?5e3:!1})}const Sa="tandem_control_panel_token";function ls(){try{return localStorage.getItem(Sa)||""}catch{return""}}function lc(n){try{localStorage.setItem(Sa,n)}catch{}}function cc(){try{localStorage.removeItem(Sa)}catch{}}function dc(n,t){return j({queryKey:["provider","status"],enabled:t&&!!n,refetchInterval:t?15e3:!1,queryFn:async()=>{if(!n)return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:"",needsOnboarding:!1};try{const[a,s,i]=await Promise.all([n.providers.config(),n.providers.catalog(),n.providers.authStatus().catch(()=>({}))]);return rc(a,s,i)}catch(a){return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:a instanceof Error?a.message:String(a),needsOnboarding:!0}}}})}function uc(n,t){return j({queryKey:["identity"],enabled:t&&!!n,refetchInterval:t?3e4:!1,queryFn:async()=>{if(!n)return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"};try{const s=(await Rt("/api/engine/config/identity",{method:"GET"}))?.identity||{},i=String(s?.bot?.canonical_name||s?.bot?.canonicalName||"").trim(),l=s?.bot?.aliases||{},c=String(s?.bot?.avatar_url||s?.bot?.avatarUrl||"").trim(),u=String(l?.control_panel||l?.controlPanel||"").trim(),p=i||"Tandem";return{botName:p,botAvatarUrl:c,controlPanelName:u||`${p} Control Panel`}}catch{return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"}}}})}function mc(n){return j({queryKey:["bug-monitor","status"],enabled:n,refetchInterval:n?1e4:!1,queryFn:async()=>{try{return await Rt("/api/engine/bug-monitor/status",{method:"GET"})}catch{return null}}})}function pc(){const n=Lt(),{toast:t}=co(),{route:a,navigate:s}=oo(),[i,l]=y(Wi()),[c,u]=y(!1),[p,w]=y(!1),M=wt(!1);ie(()=>{Qi(i)},[i]);const S=j({queryKey:["auth","me"],retry:!1,refetchInterval:3e4,queryFn:()=>Rt("/api/auth/me",{method:"GET"})}).isSuccess;ie(()=>{try{dn()}catch{}},[S,a]);const q=V(()=>S?new xi({baseUrl:"/api/engine",token:"session"}):null,[S]),T=dc(q,S),X=uc(q,S),z=ic(S),J=oc(S),ne=mc(S),G=me({mutationFn:async({token:be})=>{await Rt("/api/auth/login",{method:"POST",body:JSON.stringify({token:be})})},onSuccess:(be,Re)=>{Re.remember?lc(Re.token):cc(),n.invalidateQueries({queryKey:["auth","me"]}),t("ok","Signed in."),s("dashboard")},onError:be=>{t("err",be instanceof Error?be.message:String(be))}});ie(()=>{if(S||G.isPending||M.current)return;const be=ls().trim();if(!be){M.current=!0;return}M.current=!0,G.mutate({token:be,remember:!0})},[S,G]);const x=Ee(async()=>{await Rt("/api/auth/logout",{method:"POST"}).catch(()=>{}),n.removeQueries({queryKey:["auth"]}),n.removeQueries({queryKey:["provider"]}),n.removeQueries({queryKey:["identity"]}),n.invalidateQueries({queryKey:["auth","me"]}),t("info","Logged out.")},[n,t]),O=V(()=>new Set(["chat","agents","orchestrator","teams"]),[]),B=!!T.data?.needsOnboarding,E=S&&B;ie(()=>{if(!E){w(!1);return}O.has(a)&&(s("settings"),p||(w(!0),t("info","Set provider + default model first to unlock the control panel.")))},[O,s,p,E,a,t]);const D=E&&O.has(a)?"settings":a,F=Ee(async()=>{await n.invalidateQueries({queryKey:["provider","status"]})},[n]),W=Ee(async()=>{await n.invalidateQueries({queryKey:["identity"]})},[n]),oe=Ee(be=>{const Re=Hi(be);return l(Re.id),Re},[l]),xe=X.data||{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"},Ie={client:q,api:Rt,toast:t,navigate:s,currentRoute:D,providerStatus:{ready:!!T.data?.ready,defaultProvider:T.data?.defaultProvider||"",defaultModel:T.data?.defaultModel||"",connected:T.data?.connected||[],error:T.data?.error||"",needsOnboarding:!!T.data?.needsOnboarding},identity:xe,refreshProviderStatus:F,refreshIdentityStatus:W,providerHints:ws,themes:hn,setTheme:oe,themeId:i},pe=V(()=>{const be=xs.map(([Me,Te])=>({id:`route:${Me}`,label:`Go to ${Te}`,group:"Routes",onSelect:()=>s(Me)})),Re=[{id:"action:new-chat",label:"New chat session",group:"Actions",onSelect:()=>{window.dispatchEvent(new CustomEvent("tcp:new-chat")),s("chat")}},{id:"action:start-engine-check",label:"Check engine health",group:"Actions",onSelect:async()=>{try{const Me=await Rt("/api/system/health"),Te=Me?.engine?.ready||Me?.engine?.healthy?"healthy":"unhealthy";t("info",`Engine ${Te}: ${Me?.engineUrl||"n/a"}`)}catch(Me){t("err",Me instanceof Error?Me.message:String(Me))}}},{id:"action:open-settings",label:"Open provider settings",group:"Actions",onSelect:()=>s("settings")},{id:"action:open-orchestrator",label:"Open orchestrator",group:"Actions",onSelect:()=>s("orchestrator")}];return[...be,...Re]},[s,t]);if(eo(()=>u(be=>!be)),!S)return e(Zi,{loginMutation:G,savedToken:ls(),controlPanelName:xe.controlPanelName,onCheckEngine:async()=>{const be=await Rt("/api/system/health");return`Engine check: ${be?.engine?.ready||be?.engine?.healthy?"healthy":"unhealthy"} at ${be?.engineUrl||"n/a"}`}});const Ne=T.data?.ready?"tcp-badge-ok":"tcp-badge-warn",fe=T.data?.ready?`${T.data?.defaultProvider||"none"}/${T.data?.defaultModel||"none"}`:"provider setup required",Oe=ne.data||null,se=!!Oe?.config?.enabled,I=Number(Oe?.runtime?.pending_incidents||0),P=!!Oe?.runtime?.monitoring_active,ee=!!Oe?.runtime?.paused,ce=!!Oe?.readiness?.ingest_ready,N=!!Oe?.readiness?.publish_ready,ue=String(Oe?.runtime?.last_runtime_error||Oe?.last_error||"").trim();return e(Qt,{children:[e(ac,{identity:xe,currentRoute:D,providerLocked:E,navRoutes:ao,onNavigate:s,onPaletteOpen:()=>u(!0),onThemeCycle:()=>oe(Ji(i)),onLogout:x,statusBar:{engineHealthy:!!(z.data?.engine?.ready||z.data?.engine?.healthy),providerBadge:Ne,providerText:fe,activeRuns:["planning","awaiting_approval","running"].includes(String(J.data?.status||"").toLowerCase())?1:0,bugMonitor:se?{enabled:!0,monitoringActive:P,paused:ee,pendingIncidents:I,blocked:!ce,lastError:P&&!N&&ue?`Watching locally only. ${ue}`:ue}:null},routeKey:D,providerGate:E&&D!=="settings"?e(te.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e(te.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:()=>s("settings"),children:"Open Settings"})})]})}):null,children:e(tc,{routeId:D,pageProps:Ie})}),e(to,{open:c,onClose:()=>u(!1),actions:pe})]})}function hc(){return e(lo,{children:e(pc,{})})}const gc=new oi({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),Fs=document.getElementById("app");if(!Fs)throw new Error("Missing #app host");Ks(Fs).render(e(Js,{children:e(Ws,{client:gc,children:e(hc,{})})}));
|