@frumu/tandem-panel 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import{S as e,_ as t,b as n,g as r,h as i,i as a,m as o,n as s,p as c,r as l,s as u,t as d,v as f,w as p,x as m,y as h}from"./motion-CBnf8hfk.js";import{u as g}from"./preact-vendor-B239Onrg.js";import{a as _,i as v,n as y,r as b,t as x}from"./react-query-_hsOQSt5.js";import{$ as S,$t as C,A as w,At as T,B as E,Bt as D,C as O,Ct as k,D as A,Dt as j,E as M,Et as N,F as P,Ft as F,G as I,Gt as L,H as R,Ht as z,I as ee,It as B,J as V,Jt as H,K as te,Kt as U,L as ne,Lt as re,M as ie,Mt as ae,N as W,Nt as oe,O as se,Ot as ce,P as le,Pt as ue,Q as de,Qt as fe,R as pe,Rt as G,S as K,St as me,T as he,Tt as ge,U as _e,Ut as ve,V as ye,Vt as be,W as xe,Wt as Se,X as Ce,Xt as we,Y as Te,Yt as Ee,Z as De,Zt as Oe,_ as ke,_t as Ae,a as je,an as Me,at as Ne,b as Pe,bt as Fe,c as q,cn as J,ct as Ie,d as Le,dn as Re,dt as ze,en as Be,et as Ve,f as He,fn as Ue,ft as We,g as Ge,gt as Ke,h as qe,ht as Je,i as Ye,in as Xe,it as Ze,j as Qe,jt as $e,k as et,kt as tt,l as nt,ln as rt,lt as it,m as at,mn as ot,mt as st,n as ct,nn as lt,nt as ut,o as dt,on as ft,ot as pt,p as mt,pn as Y,pt as ht,q as gt,qt as _t,r as vt,rn as yt,rt as bt,s as xt,sn as St,st as Ct,t as wt,tn as Tt,tt as Et,u as Dt,un as Ot,ut as kt,v as At,vt as jt,w as Mt,wt as Nt,x as Pt,xt as Ft,y as It,yt as Lt,z as Rt,zt}from"./vendor-DeUDWccs.js";import{n as Bt,t as Vt}from"./markdown-Dd89TVib.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Ht=class extends Error{constructor(e,t,n,r){super(`Tandem API Validation Error [${t}] at ${e}: ${n.length} issues found.`),this.endpoint=e,this.status=t,this.issues=n,this.rawSnippet=r,this.name=`TandemValidationError`}},Ut=Y().or(Re({id:Y().optional(),runID:Y().optional(),runId:Y().optional(),run_id:Y().optional(),sessionID:Y().optional(),sessionId:Y().optional(),session_id:Y().optional(),missionID:Y().optional(),missionId:Y().optional(),mission_id:Y().optional(),instanceID:Y().optional(),instanceId:Y().optional(),instance_id:Y().optional()})).transform(e=>typeof e==`string`?e:e.id||e.runID||e.runId||e.run_id||e.sessionID||e.sessionId||e.session_id||e.missionID||e.missionId||e.mission_id||e.instanceID||e.instanceId||e.instance_id);St().transform(e=>e),Ue(Y(),St()).transform(e=>e);var Wt=Re({ready:rt().optional(),phase:Y().optional(),workspace_root:Y().optional(),workspaceRoot:Y().optional()}).passthrough().transform(e=>({...e,workspaceRoot:e.workspace_root??e.workspaceRoot})),Gt=Re({id:Y(),title:Y(),created_at_ms:Ot().optional(),createdAtMs:Ot().optional(),directory:Y().optional(),workspace_root:Y().optional(),workspaceRoot:Y().optional(),archived:rt().optional()}).passthrough().transform(e=>({...e,createdAtMs:e.created_at_ms??e.createdAtMs??0,workspaceRoot:e.workspace_root??e.workspaceRoot})),Kt=Re({sessions:J(Gt).optional().default([]),count:Ot().optional().default(0)}).passthrough(),qt=Re({active:Re({runID:Y().optional(),runId:Y().optional(),run_id:Y().optional(),attachEventStream:Y().optional()}).passthrough().nullable().optional()}).passthrough().transform(e=>e.active?{active:{...e.active,runId:e.active.runId||e.active.runID||e.active.run_id}}:{active:null}),Jt=Re({ok:rt().optional(),dry_run:rt().optional(),dryRun:rt().optional(),runID:Y().optional(),runId:Y().optional(),run_id:Y().optional(),status:Y().optional()}).passthrough().transform(e=>({...e,dryRun:e.dryRun??e.dry_run,runId:e.runId||e.runID||e.run_id})),Yt=Re({id:Y().optional(),runID:Y().optional(),runId:Y().optional(),run_id:Y().optional(),routine_id:Y().optional(),automation_id:Y().optional(),status:Y().optional(),started_at_ms:Ot().optional(),finished_at_ms:Ot().optional()}).passthrough().transform(e=>({...e,runId:e.runId||e.runID||e.run_id,routineId:e.routine_id,automationId:e.automation_id,startedAtMs:e.started_at_ms,finishedAtMs:e.finished_at_ms})),Xt=Re({ok:rt().default(!0),rev:Ot().optional()}).passthrough(),Zt=Re({key:Y(),value:St(),rev:Ot().optional(),updated_at_ms:Ot().optional(),updated_by:Y().optional()}).passthrough().transform(e=>({...e,updatedAtMs:e.updated_at_ms,updatedBy:e.updated_by})),Qt=Re({items:J(Zt).optional().default([]),count:Ot().optional().default(0)}).passthrough(),$t=Re({items:J(Re({id:Y().optional(),text:Y().optional(),content:Y().optional(),user_id:Y().optional(),userID:Y().optional(),source_type:Y().optional(),sourceType:Y().optional(),tags:J(Y()).optional(),source:Y().optional(),session_id:Y().optional(),sessionID:Y().optional(),run_id:Y().optional(),runID:Y().optional()}).passthrough().transform(e=>({...e,text:e.text||e.content,content:e.content||e.text,userId:e.userID||e.user_id,sourceType:e.sourceType||e.source_type,sessionId:e.session_id||e.sessionID,runId:e.run_id||e.runID}))).optional().default([]),count:Ot().optional().default(0)}).passthrough(),en=Re({results:J(Re({id:Y(),text:Y().optional(),content:Y().optional(),score:Ot().optional(),source_type:Y().optional(),sourceType:Y().optional(),run_id:Y().optional(),runID:Y().optional(),tags:J(Y()).optional()}).passthrough().transform(e=>({...e,text:e.text||e.content,content:e.content||e.text,sourceType:e.sourceType||e.source_type,runId:e.runID||e.run_id}))).optional().default([]),count:Ot().optional().default(0)}).passthrough(),tn=Re({id:Y(),uri:Y(),parent_uri:Y().optional(),node_type:Y(),created_at:Y(),updated_at:Y(),metadata:Ue(Y(),St()).optional()}).passthrough(),nn=Re({l0_preview:Y().optional(),l1_preview:Y().optional(),has_l2:rt()}).passthrough(),rn=Re({node:tn,children:J(St()).optional().default([]),layer_summary:nn.optional()}).passthrough(),an=Re({node:tn.optional()}).passthrough(),on=Re({tree:J(rn).optional().default([])}).passthrough(),sn=Re({ok:rt(),distillation_id:Y().optional(),session_id:Y().optional(),facts_extracted:Ot().optional()}).passthrough(),cn=Re({type:Y(),properties:Ue(Y(),St()).optional().default({}),sessionID:Y().optional(),session_id:Y().optional(),sessionId:Y().optional(),runID:Y().optional(),run_id:Y().optional(),runId:Y().optional(),timestamp:Y().optional()}).passthrough().transform(e=>({...e,properties:e.properties,sessionId:e.sessionId||e.sessionID||e.session_id,runId:e.runId||e.runID||e.run_id}));function ln(e,t,n,r){let i=e.safeParse(t);if(!i.success){let e=JSON.stringify(t).substring(0,200);throw new Ht(n,r,i.error.issues,e)}return i.data}function un(e){let t=e.trim();if(!t||t===`: keep-alive`||t.startsWith(`:`))return null;try{let e=JSON.parse(t),n=cn.safeParse(e);return n.success?n.data:null}catch{return null}}async function*dn(e,t,n){let r=n?.connectTimeoutMs??3e4,i=new AbortController,a=setTimeout(()=>i.abort(),r),o=n?.signal?fn([i.signal,n.signal]):i.signal,s;try{s=await fetch(e,{headers:{Accept:`text/event-stream`,Authorization:`Bearer ${t}`,"Cache-Control":`no-cache`},signal:o})}finally{clearTimeout(a)}if(!s.ok){let e=await s.text().catch(()=>``);throw Error(`SSE connect failed (${s.status} ${s.statusText}): ${e}`)}if(!s.body)throw Error(`SSE response has no body`);let c=new TextDecoder,l=s.body.getReader(),u=``;try{for(;;){let{done:e,value:t}=await l.read();if(e)break;u+=c.decode(t,{stream:!0});let n=u.split(`
2
- `);u=n.pop()??``;let r=``;for(let e of n)if(e.startsWith(`data:`))r+=e.slice(5).trimStart();else if(e===``&&r){let e=un(r);e&&(yield e),r=``}}}finally{l.releaseLock()}}function fn(e){let t=new AbortController;for(let n of e){if(n.aborted){t.abort(n.reason);break}n.addEventListener(`abort`,()=>t.abort(n.reason),{once:!0})}return t.signal}var pn=e=>typeof e==`string`&&e.trim().length>0?e:null,mn=e=>new Promise(t=>setTimeout(t,e)),hn=e=>{try{let t=Ut.parse(e);if(t)return t}catch{let t=e.run||null;if(t)try{let e=Ut.parse(t);if(e)return e}catch{}}throw Error(`Run ID missing in engine response`)},gn=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,``),this.token=e.token,this.timeoutMs=e.timeoutMs??2e4;let t=this._request.bind(this);this.sessions=new Sn(this.baseUrl,this.token,this.timeoutMs,t),this.permissions=new Cn(t),this.questions=new wn(t),this.providers=new Tn(t),this.identity=new En(t),this.channels=new Dn(t),this.mcp=new On(t,this._requestText.bind(this));let n=()=>this.token;this.routines=new Fn(this.baseUrl,n,t),this.automations=new Rn(this.baseUrl,n,t),this.automationsV2=new zn(this.baseUrl,n,t),this.optimizations=new Bn(t),this.workflowPlans=new In(t),this.workflowPlannerSessions=new Ln(t),this.memory=new kn(t),this.skills=new An(t),this.packs=new jn(t),this.capabilities=new Mn(t),this.resources=new Nn(this.baseUrl,n,t),this.browser=new _n(t),this.storage=new vn(t),this.worktrees=new yn(t),this.workflows=new bn(this.baseUrl,n,t),this.bugMonitor=new xn(t),this.coder=new Pn(t),this.agentTeams=new Vn(t),this.missions=new Hn(t)}setToken(e){this.token=e,this.sessions.setToken(e)}async health(){return ln(Wt,await this._request(`/global/health`),`/global/health`,200)}async listToolIds(){return this._request(`/tool/ids`)}async listTools(){let e=await this._request(`/tool`);return Array.isArray(e)?e:[]}async executeTool(e,t){return this._request(`/tool/execute`,{method:`POST`,body:JSON.stringify({tool:e,args:t??{}})})}stream(e,t,n){let r=new URLSearchParams({sessionID:e});return t&&r.set(`runID`,t),dn(`${this.baseUrl}/event?${r.toString()}`,this.token,n)}globalStream(e){return dn(`${this.baseUrl}/global/event`,this.token,e)}async runEvents(e,t){let n=new URLSearchParams;t?.sinceSeq!==void 0&&n.set(`since_seq`,String(t.sinceSeq)),t?.tail!==void 0&&n.set(`tail`,String(t.tail));let r=n.toString()?`?${n.toString()}`:``,i=await this._request(`/run/${encodeURIComponent(e)}/events${r}`);return Array.isArray(i)?i:[]}async _request(e,t={}){let n=t.timeoutMs??this.timeoutMs,r=new AbortController,i=setTimeout(()=>r.abort(),n),a;try{a=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.token}`,...t.headers??{}},signal:r.signal})}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`Request timed out after ${n}ms: ${e}`):t}finally{clearTimeout(i)}if(a.status!==204){if(!a.ok){let t=await a.text().catch(()=>``);throw a.status===524?Error(`Engine timed out while waiting for ${e} to finish.`):Error(`Request failed (${a.status} ${a.statusText}): ${t}`)}return a.json()}}async _requestText(e,t={}){let n=t.timeoutMs??this.timeoutMs,r=new AbortController,i=setTimeout(()=>r.abort(),n),a;try{a=await fetch(`${this.baseUrl}${e}`,{...t,headers:{Authorization:`Bearer ${this.token}`,...t.headers??{}},signal:r.signal})}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`Request timed out after ${n}ms: ${e}`):t}finally{clearTimeout(i)}if(!a.ok){let t=await a.text().catch(()=>``);throw a.status===524?Error(`Engine timed out while waiting for ${e} to finish.`):Error(`Request failed (${a.status} ${a.statusText}): ${t}`)}return a.text()}},_n=class{constructor(e){this.req=e}async status(){return this.req(`/browser/status`)}async install(){return this.req(`/browser/install`,{method:`POST`})}async smokeTest(e){return this.req(`/browser/smoke-test`,{method:`POST`,body:JSON.stringify(e??{})})}},vn=class{constructor(e){this.req=e}async listFiles(e){let t=new URLSearchParams;e?.path&&t.set(`path`,e.path),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return this.req(`/global/storage/files${n}`)}async repair(e){return this.req(`/global/storage/repair`,{method:`POST`,body:JSON.stringify({force:e?.force??!1})})}},yn=class{constructor(e){this.req=e}async cleanup(e){return this.req(`/worktree/cleanup`,{method:`POST`,body:JSON.stringify({repo_root:e?.repoRoot,dry_run:e?.dryRun??!1,remove_orphan_dirs:e?.removeOrphanDirs??!0})})}},bn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(){let e=await this.req(`/workflows`)??{},t=Array.isArray(e.workflows)?e.workflows:[];return{workflows:t,count:typeof e.count==`number`?e.count:t.length}}async get(e){return(await this.req(`/workflows/${encodeURIComponent(e)}`)).workflow??{}}async validate(e){return this.req(`/workflows/validate`,{method:`POST`,body:JSON.stringify(e??{})})}async simulate(e){return this.req(`/workflows/simulate`,{method:`POST`,body:JSON.stringify(e)})}events(e){let t=new URLSearchParams,n=e?.workflow_id??e?.workflowId,r=e?.run_id??e?.runId;n&&t.set(`workflow_id`,n),r&&t.set(`run_id`,r);let i=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/workflows/events${i}`,this.getToken(),{signal:e?.signal})}async listRuns(e){let t=new URLSearchParams,n=e?.workflow_id??e?.workflowId;n&&t.set(`workflow_id`,n),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let r=t.toString()?`?${t.toString()}`:``,i=await this.req(`/workflows/runs${r}`)??{},a=Array.isArray(i.runs)?i.runs:[];return{runs:a,count:typeof i.count==`number`?i.count:a.length}}async getRun(e){return(await this.req(`/workflows/runs/${encodeURIComponent(e)}`)).run??{}}async run(e,t){return this.req(`/workflows/${encodeURIComponent(e)}/run`,{method:`POST`,body:JSON.stringify(t??{})})}async listHooks(e){let t=new URLSearchParams,n=e?.workflow_id??e?.workflowId;n&&t.set(`workflow_id`,n);let r=t.toString()?`?${t.toString()}`:``,i=await this.req(`/workflow-hooks${r}`)??{},a=Array.isArray(i.hooks)?i.hooks:[];return{hooks:a,count:typeof i.count==`number`?i.count:a.length}}async patchHook(e,t){return this.req(`/workflow-hooks/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}},xn=class{constructor(e){this.req=e}async getConfig(){return this.req(`/config/bug-monitor`)}async patchConfig(e){let t=e&&typeof e==`object`&&`bug_monitor`in e?e:{bug_monitor:e};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(e){let t=e?.limit===void 0?``:`?limit=${e.limit}`;return this.req(`/bug-monitor/incidents${t}`)}async getIncident(e){return(await this.req(`/bug-monitor/incidents/${encodeURIComponent(e)}`)).incident??{}}async replayIncident(e,t){return this.req(`/bug-monitor/incidents/${encodeURIComponent(e)}/replay`,{method:`POST`,body:JSON.stringify(t??{})})}async deleteIncident(e){return this.req(`/bug-monitor/incidents/${encodeURIComponent(e)}`,{method:`DELETE`})}async bulkDeleteIncidents(e){return this.req(`/bug-monitor/incidents/bulk-delete`,{method:`POST`,body:JSON.stringify(e)})}async deleteDraft(e){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}`,{method:`DELETE`})}async bulkDeleteDrafts(e){return this.req(`/bug-monitor/drafts/bulk-delete`,{method:`POST`,body:JSON.stringify(e)})}async deletePost(e){return this.req(`/bug-monitor/posts/${encodeURIComponent(e)}`,{method:`DELETE`})}async bulkDeletePosts(e){return this.req(`/bug-monitor/posts/bulk-delete`,{method:`POST`,body:JSON.stringify(e)})}async listDrafts(e){let t=e?.limit===void 0?``:`?limit=${e.limit}`;return this.req(`/bug-monitor/drafts${t}`)}async listPosts(e){let t=e?.limit===void 0?``:`?limit=${e.limit}`;return this.req(`/bug-monitor/posts${t}`)}async getDraft(e){return(await this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}`)).draft??{}}async approveDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t})})}async denyDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t})})}async report(e){let t=e&&typeof e==`object`&&`report`in e?e:{report:e};return this.req(`/bug-monitor/report`,{method:`POST`,body:JSON.stringify(t)})}async createTriageRun(e){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/triage-run`,{method:`POST`})}async createTriageSummary(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/triage-summary`,{method:`POST`,body:JSON.stringify(t)})}async createIssueDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/issue-draft`,{method:`POST`,body:JSON.stringify(t??{})})}async publishDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/publish`,{method:`POST`,body:JSON.stringify(t??{})})}async recheckMatch(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/recheck-match`,{method:`POST`,body:JSON.stringify(t??{})})}},Sn=class{constructor(e,t,n,r){this.baseUrl=e,this.token=t,this.timeoutMs=n,this.req=r}setToken(e){this.token=e}async create(e={}){let t={title:e.title??`Tandem SDK Session`,directory:e.directory??`.`};return e.permissions&&(t.permission=e.permissions),e.model&&e.provider&&(t.model={providerID:e.provider,modelID:e.model},t.provider=e.provider),(await this.req(`/session`,{method:`POST`,body:JSON.stringify(t)})).id}async list(e={}){let t=new URLSearchParams;e.q&&t.set(`q`,e.q),e.page!==void 0&&t.set(`page`,String(e.page)),e.pageSize!==void 0&&t.set(`page_size`,String(e.pageSize)),e.archived!==void 0&&t.set(`archived`,String(e.archived)),e.scope&&t.set(`scope`,e.scope),e.workspace&&t.set(`workspace`,e.workspace);let n=t.toString()?`?${t.toString()}`:``;return ln(Kt,await this.req(`/session${n}`),`/session`,200)}async get(e){return ln(Gt,await this.req(`/session/${encodeURIComponent(e)}`),`/session/${e}`,200)}async update(e,t){return ln(Gt,await this.req(`/session/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),`/session/${e}`,200)}async archive(e){return this.update(e,{archived:!0})}async delete(e){await this.req(`/session/${encodeURIComponent(e)}`,{method:`DELETE`})}async messages(e){return this.req(`/session/${encodeURIComponent(e)}/message`)}async todos(e){let t=await this.req(`/session/${encodeURIComponent(e)}/todo`);return Array.isArray(t)?t:t.todos??[]}async activeRun(e){return ln(qt,await this.req(`/session/${encodeURIComponent(e)}/run`),`/session/${e}/run`,200)}async promptAsync(e,t,n,r){return this.promptAsyncParts(e,[{type:`text`,text:t}],n,r)}async promptAsyncParts(e,t,n,r){let i={parts:t};n?.provider&&n?.model&&(i.model={providerID:n.provider,modelID:n.model}),r?.toolMode&&(i.toolMode=r.toolMode),r?.toolAllowlist?.length&&(i.toolAllowlist=r.toolAllowlist),r?.contextMode&&(i.contextMode=r.contextMode);let a=`/session/${encodeURIComponent(e)}/prompt_async?return=run`,o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs),c;try{c=await fetch(`${this.baseUrl}${a}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.token}`},body:JSON.stringify(i),signal:o.signal})}finally{clearTimeout(s)}if(c.status===409){let e=(await c.json().catch(()=>({}))).activeRun,t=pn(e?.runID)||pn(e?.runId)||pn(e?.run_id);if(t)return{runId:t}}if(!c.ok){let e=await c.text().catch(()=>``);throw Error(`promptAsyncParts failed (${c.status}): ${e}`)}return{runId:hn(await c.json())}}async promptSync(e,t){let n={parts:[{type:`text`,text:t}]},r=await this.req(`/session/${encodeURIComponent(e)}/prompt_sync`,{method:`POST`,body:JSON.stringify(n)});return pn(r.reply)||pn(r.text)||pn(r.output)||``}async abort(e){return this.req(`/session/${encodeURIComponent(e)}/abort`,{method:`POST`,body:JSON.stringify({})})}async cancel(e){return this.req(`/session/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({})})}async cancelRun(e,t){return this.req(`/session/${encodeURIComponent(e)}/run/${encodeURIComponent(t)}/cancel`,{method:`POST`,body:JSON.stringify({})})}async fork(e){return ln(Gt,await this.req(`/session/${encodeURIComponent(e)}/fork`,{method:`POST`,body:JSON.stringify({})}),`/session/${e}/fork`,200)}async diff(e){return this.req(`/session/${encodeURIComponent(e)}/diff`)}async revert(e){return this.req(`/session/${encodeURIComponent(e)}/revert`,{method:`POST`,body:JSON.stringify({})})}async unrevert(e){return this.req(`/session/${encodeURIComponent(e)}/unrevert`,{method:`POST`,body:JSON.stringify({})})}async children(e){return ln(Kt,await this.req(`/session/${encodeURIComponent(e)}/children`),`/session/${e}/children`,200).sessions}async summarize(e){return this.req(`/session/${encodeURIComponent(e)}/summarize`,{method:`POST`,body:JSON.stringify({})})}async attach(e,t){return this.req(`/session/${encodeURIComponent(e)}/attach`,{method:`POST`,body:JSON.stringify({target_workspace:t})})}},Cn=class{constructor(e){this.req=e}async list(){return this.req(`/permission`)}async reply(e,t){let n=await this.req(`/permission/${encodeURIComponent(e)}/reply`,{method:`POST`,body:JSON.stringify({reply:t})});if(!n.ok)throw Error(`Permission reply rejected: ${n.error??e}`);return{ok:!0}}},wn=class{constructor(e){this.req=e}async list(){let e=await this.req(`/question`);return Array.isArray(e)?{questions:e}:e}async reply(e,t){return this.req(`/question/${encodeURIComponent(e)}/reply`,{method:`POST`,body:JSON.stringify({answer:t})})}async reject(e){return this.req(`/question/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify({})})}},Tn=class{constructor(e){this.req=e}async catalog(){return this.req(`/provider`)}async config(){return this.req(`/config/providers`)}async setDefaults(e,t){await this.req(`/config`,{method:`PATCH`,body:JSON.stringify({default_provider:e,providers:{[e]:{default_model:t}}})})}async setApiKey(e,t){await this.req(`/auth/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({apiKey:t})})}async oauthAuthorize(e){return this.req(`/provider/${encodeURIComponent(e)}/oauth/authorize`,{method:`POST`})}async oauthStatus(e,t){let n=t?`?session_id=${encodeURIComponent(t)}`:``;return this.req(`/provider/${encodeURIComponent(e)}/oauth/status${n}`)}async oauthUseLocalSession(e){return this.req(`/provider/${encodeURIComponent(e)}/oauth/session/local`,{method:`POST`})}async oauthDisconnect(e){return this.req(`/provider/${encodeURIComponent(e)}/oauth/session`,{method:`DELETE`})}async authStatus(){return this.req(`/provider/auth`)}},En=class{constructor(e){this.req=e}async get(){return this.req(`/config/identity`)}async patch(e){return this.req(`/config/identity`,{method:`PATCH`,body:JSON.stringify(e)})}},Dn=class{constructor(e){this.req=e}async config(){return this.req(`/channels/config`)}async status(){return this.req(`/channels/status`)}async put(e,t){return this.req(`/channels/${e}`,{method:`PUT`,body:JSON.stringify(t)})}async delete(e){return this.req(`/channels/${e}`,{method:`DELETE`})}async verify(e,t={}){return this.req(`/channels/${e}/verify`,{method:`POST`,body:JSON.stringify(t)})}async toolPreferences(e){return this.req(`/channels/${e}/tool-preferences`)}async setToolPreferences(e,t){return this.req(`/channels/${e}/tool-preferences`,{method:`PUT`,body:JSON.stringify(t)})}},On=class{constructor(e,t){this.req=e,this.reqText=t}async list(){return this.req(`/mcp`)}async listTools(){return this.req(`/mcp/tools`)}async listResources(){let e=await this.req(`/mcp/resources`);return Array.isArray(e)?e:[]}async add(e){return this.req(`/mcp`,{method:`POST`,body:JSON.stringify(e)})}async connect(e){return this.req(`/mcp/${encodeURIComponent(e)}/connect`,{method:`POST`})}async disconnect(e){return this.req(`/mcp/${encodeURIComponent(e)}/disconnect`,{method:`POST`})}async refresh(e){return this.req(`/mcp/${encodeURIComponent(e)}/refresh`,{method:`POST`})}async patch(e,t){return this.req(`/mcp/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t??{})})}async setEnabled(e,t){return this.patch(e,{enabled:t})}async delete(e){return this.req(`/mcp/${encodeURIComponent(e)}`,{method:`DELETE`})}async auth(e,t){return this.req(`/mcp/${encodeURIComponent(e)}/auth`,{method:`POST`,body:JSON.stringify(t??{})})}async deleteAuth(e){return this.req(`/mcp/${encodeURIComponent(e)}/auth`,{method:`DELETE`})}async authCallback(e,t){return this.req(`/mcp/${encodeURIComponent(e)}/auth/callback`,{method:`POST`,body:JSON.stringify(t)})}async authenticate(e,t){return this.req(`/mcp/${encodeURIComponent(e)}/auth/authenticate`,{method:`POST`,body:JSON.stringify(t??{})})}async catalogToml(e){if(!this.reqText)throw Error(`Text request helper unavailable`);return this.reqText(`/mcp/catalog/${encodeURIComponent(e)}/toml`)}},kn=class{constructor(e){this.req=e}async put(e){return this.req(`/memory/put`,{method:`POST`,body:JSON.stringify(e)})}async search(e){return ln(en,await this.req(`/memory/search`,{method:`POST`,body:JSON.stringify(e)}),`/memory/search`,200)}async importPath(e){let t={source:{kind:`path`,path:e.path},format:e.format??`directory`,tier:e.tier??`project`,project_id:e.projectId,session_id:e.sessionId,sync_deletes:e.syncDeletes??!1};return this.req(`/memory/import`,{method:`POST`,body:JSON.stringify(t)})}async list(e){let t=new URLSearchParams;e?.q&&t.set(`q`,e.q),e?.limit!==void 0&&t.set(`limit`,String(e.limit)),e?.offset!==void 0&&t.set(`offset`,String(e.offset)),e?.userId&&t.set(`user_id`,e.userId);let n=t.toString()?`?${t.toString()}`:``;return ln($t,await this.req(`/memory${n}`),`/memory`,200)}async delete(e){return this.req(`/memory/${encodeURIComponent(e)}`,{method:`DELETE`})}async promote(e){return this.req(`/memory/promote`,{method:`POST`,body:JSON.stringify(e)})}async demote(e){let t={id:e.id,run_id:e.runId};return this.req(`/memory/demote`,{method:`POST`,body:JSON.stringify(t)})}async audit(e){let t=new URLSearchParams;e?.run_id&&t.set(`run_id`,e.run_id),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``,r=await this.req(`/memory/audit${n}`);return Array.isArray(r)?{entries:r,count:r.length}:r}async contextResolveUri(e){return ln(an,await this.req(`/memory/context/resolve`,{method:`POST`,body:JSON.stringify({uri:e})}),`/memory/context/resolve`,200)}async contextTree(e,t){let n=new URLSearchParams;n.set(`uri`,e),t!==void 0&&n.set(`max_depth`,String(t));let r=n.toString()?`?${n.toString()}`:``;return ln(on,await this.req(`/memory/context/tree${r}`),`/memory/context/tree`,200)}async contextGenerateLayers(e){return this.req(`/memory/context/layers/generate`,{method:`POST`,body:JSON.stringify({node_id:e})})}async contextDistill(e,t){return ln(sn,await this.req(`/memory/context/distill`,{method:`POST`,body:JSON.stringify({session_id:e,conversation:t})}),`/memory/context/distill`,200)}},An=class{constructor(e){this.req=e}async list(e){let t=e?`?location=${encodeURIComponent(e)}`:``,n=await this.req(`/skills${t}`);return Array.isArray(n)?{skills:n,count:n.length}:n}async get(e){return this.req(`/skills/${encodeURIComponent(e)}`)}async import(e){let t={content:e.content,file_or_path:e.file_or_path??e.fileOrPath,location:e.location,namespace:e.namespace,conflict_policy:e.conflict_policy??e.conflictPolicy};return this.req(`/skills/import`,{method:`POST`,body:JSON.stringify(t)})}async preview(e){let t={content:e.content,file_or_path:e.file_or_path??e.fileOrPath,location:e.location,namespace:e.namespace,conflict_policy:e.conflict_policy??e.conflictPolicy};return this.req(`/skills/import/preview`,{method:`POST`,body:JSON.stringify(t)})}async templates(){let e=await this.req(`/skills/templates`);return Array.isArray(e)?{templates:e,count:e.length}:e}async catalog(){let e=await this.req(`/skills/catalog`),t=Array.isArray(e)?e:[];return{skills:t,count:t.length}}async validate(e){let t={content:e.content,file_or_path:e.file_or_path??e.fileOrPath};return this.req(`/skills/validate`,{method:`POST`,body:JSON.stringify(t)})}async match(e){let t={goal:e.goal,max_matches:e.max_matches??e.maxMatches,threshold:e.threshold};return this.req(`/skills/router/match`,{method:`POST`,body:JSON.stringify(t)})}async evalBenchmark(e){let t={threshold:e.threshold,cases:e.cases.map(e=>({prompt:e.prompt,expected_skill:e.expected_skill??e.expectedSkill}))};return this.req(`/skills/evals/benchmark`,{method:`POST`,body:JSON.stringify(t)})}async evalTriggers(e){let t={skill_name:e.skill_name??e.skillName,prompts:e.prompts,threshold:e.threshold};return this.req(`/skills/evals/triggers`,{method:`POST`,body:JSON.stringify(t)})}async compile(e){let t={skill_name:e.skill_name??e.skillName,goal:e.goal,threshold:e.threshold,max_matches:e.max_matches??e.maxMatches,schedule:e.schedule};return this.req(`/skills/compile`,{method:`POST`,body:JSON.stringify(t)})}async generate(e){return this.req(`/skills/generate`,{method:`POST`,body:JSON.stringify(e)})}async generateInstall(e){let t={prompt:e.prompt,threshold:e.threshold,location:e.location,conflict_policy:e.conflictPolicy,artifacts:e.artifacts?{"SKILL.md":e.artifacts[`SKILL.md`],"workflow.yaml":e.artifacts[`workflow.yaml`],"automation.example.yaml":e.artifacts[`automation.example.yaml`]}:void 0};return this.req(`/skills/generate/install`,{method:`POST`,body:JSON.stringify(t)})}},jn=class{constructor(e){this.req=e}async list(){return this.req(`/packs`)}async inspect(e){return this.req(`/packs/${encodeURIComponent(e)}`)}async install(e){return this.req(`/packs/install`,{method:`POST`,body:JSON.stringify(e)})}async installFromAttachment(e){return this.req(`/packs/install_from_attachment`,{method:`POST`,body:JSON.stringify(e)})}async uninstall(e){return this.req(`/packs/uninstall`,{method:`POST`,body:JSON.stringify(e)})}async export(e){return this.req(`/packs/export`,{method:`POST`,body:JSON.stringify(e)})}async detect(e){return this.req(`/packs/detect`,{method:`POST`,body:JSON.stringify(e)})}async updates(e){let t=await this.req(`/packs/${encodeURIComponent(e)}/updates`)||{},n=Array.isArray(t.updates)?t.updates:[];return{pack_id:pn(t.pack_id)??void 0,name:pn(t.name)??void 0,current_version:pn(t.current_version)??void 0,updates:n}}async update(e,t){let n=await this.req(`/packs/${encodeURIComponent(e)}/update`,{method:`POST`,body:JSON.stringify(t??{})});return{updated:!!n.updated,pack_id:pn(n.pack_id)??void 0,name:pn(n.name)??void 0,current_version:pn(n.current_version)??void 0,target_version:pn(n.target_version)??void 0,reason:pn(n.reason)??void 0}}},Mn=class{constructor(e){this.req=e}async getBindings(){return(await this.req(`/capabilities/bindings`)).bindings}async setBindings(e){return this.req(`/capabilities/bindings`,{method:`PUT`,body:JSON.stringify(e)})}async discovery(){return this.req(`/capabilities/discovery`)}async resolve(e){return this.req(`/capabilities/resolve`,{method:`POST`,body:JSON.stringify(e)})}async readiness(e){return this.req(`/capabilities/readiness`,{method:`POST`,body:JSON.stringify(e)})}},Nn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(e){let t=new URLSearchParams;e?.prefix&&t.set(`prefix`,e.prefix),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return ln(Qt,await this.req(`/resource${n}`),`/resource`,200)}async write(e){return this.req(`/resource`,{method:`PUT`,body:JSON.stringify(e)})}async get(e){return ln(Zt,await this.req(`/resource/${encodeURIComponent(e)}`),`/resource/${e}`,200)}async putKey(e,t,n){return ln(Xt,await this.req(`/resource/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({value:t,...n??{}})}),`/resource/${e}`,200)}async patchKey(e,t){return ln(Xt,await this.req(`/resource/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),`/resource/${e}`,200)}async delete(e,t){return this.req(`/resource`,{method:`DELETE`,body:JSON.stringify({key:e,...t})})}async deleteKey(e){return this.req(`/resource/${encodeURIComponent(e)}`,{method:`DELETE`})}events(e){let t=new URLSearchParams;e?.sinceSeq!==void 0&&t.set(`since_seq`,String(e.sinceSeq)),e?.tail!==void 0&&t.set(`tail`,String(e.tail));let n=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/resource/events${n}`,this.getToken())}},Pn=class{constructor(e){this.req=e}async createRun(e){return this.req(`/coder/runs`,{method:`POST`,body:JSON.stringify(e)})}async listRuns(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=e?.workflow_mode??e?.workflowMode,r=e?.repo_slug??e?.repoSlug;n&&t.set(`workflow_mode`,n),r&&t.set(`repo_slug`,r);let i=t.toString()?`?${t.toString()}`:``,a=await this.req(`/coder/runs${i}`)??{},o=Array.isArray(a.runs)?a.runs:[];return{runs:o,count:typeof a.count==`number`?a.count:o.length}}async getRun(e){let t=await this.req(`/coder/runs/${encodeURIComponent(e)}`)??{};return{...t,coderRun:t.coder_run??void 0,coder_run:t.coder_run??void 0,run:t.run??void 0}}async getProjectBinding(e){let t=await this.req(`/coder/projects/${encodeURIComponent(e)}/bindings`)??{};return{...t,binding:t.binding??null}}async putProjectBinding(e,t){let n=await this.req(`/coder/projects/${encodeURIComponent(e)}/bindings`,{method:`PUT`,body:JSON.stringify(t)})??{};return{...n,binding:n.binding}}async getProjectGithubInbox(e){let t=await this.req(`/coder/projects/${encodeURIComponent(e)}/github-project/inbox`)??{};return{...t,items:Array.isArray(t.items)?t.items:[],binding:t.binding,project_id:String(t.project_id||t.projectId||``),schema_drift:!!(t.schema_drift??t.schemaDrift),live_schema_fingerprint:String(t.live_schema_fingerprint||t.liveSchemaFingerprint||``)}}async intakeProjectItem(e,t){let n=await this.req(`/coder/projects/${encodeURIComponent(e)}/github-project/intake`,{method:`POST`,body:JSON.stringify(t)})??{};return{...n,coder_run:n.coder_run??void 0,coderRun:n.coder_run??void 0,run:n.run??void 0}}async executeNext(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/execute-next`,{method:`POST`,body:JSON.stringify(t??{})})}async executeAll(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/execute-all`,{method:`POST`,body:JSON.stringify(t??{})})}async createFollowOnRun(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/follow-on-run`,{method:`POST`,body:JSON.stringify(t)})}async approveRun(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t})})}async cancelRun(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({reason:t})})}async listArtifacts(e){let t=await this.req(`/coder/runs/${encodeURIComponent(e)}/artifacts`)??{},n=Array.isArray(t.artifacts)?t.artifacts:[];return{...t,artifacts:n,count:typeof t.count==`number`?t.count:n.length}}async getMemoryHits(e,t){let n=new URLSearchParams;t?.query&&n.set(`q`,t.query),t?.limit!==void 0&&n.set(`limit`,String(t.limit));let r=n.toString()?`?${n.toString()}`:``,i=await this.req(`/coder/runs/${encodeURIComponent(e)}/memory-hits${r}`)??{},a=Array.isArray(i.hits)?i.hits:[];return{...i,hits:a,count:typeof i.count==`number`?i.count:a.length}}async createTriageInspectionReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/triage-inspection-report`,{method:`POST`,body:JSON.stringify(t)})}async createTriageReproductionReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/triage-reproduction-report`,{method:`POST`,body:JSON.stringify(t)})}async createTriageSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/triage-summary`,{method:`POST`,body:JSON.stringify(t)})}async createPrReviewEvidence(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-review-evidence`,{method:`POST`,body:JSON.stringify(t)})}async createPrReviewSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-review-summary`,{method:`POST`,body:JSON.stringify(t)})}async createIssueFixValidationReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/issue-fix-validation-report`,{method:`POST`,body:JSON.stringify(t)})}async createIssueFixSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/issue-fix-summary`,{method:`POST`,body:JSON.stringify(t)})}async createPrDraft(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-draft`,{method:`POST`,body:JSON.stringify(t??{})})}async submitPr(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-submit`,{method:`POST`,body:JSON.stringify(t??{})})}async createMergeReadinessReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/merge-readiness-report`,{method:`POST`,body:JSON.stringify(t)})}async createMergeRecommendationSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/merge-recommendation-summary`,{method:`POST`,body:JSON.stringify(t)})}async listMemoryCandidates(e){let t=await this.req(`/coder/runs/${encodeURIComponent(e)}/memory-candidates`)??{},n=Array.isArray(t.candidates)?t.candidates:[];return{...t,candidates:n,count:typeof t.count==`number`?t.count:n.length}}async createMemoryCandidate(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/memory-candidates`,{method:`POST`,body:JSON.stringify(t)})}async promoteMemoryCandidate(e,t,n){return this.req(`/coder/runs/${encodeURIComponent(e)}/memory-candidates/${encodeURIComponent(t)}/promote`,{method:`POST`,body:JSON.stringify(n??{})})}},Fn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(){return this.req(`/routines`)}async create(e){let t={...e};return`prompt`in t&&!(`entrypoint`in t)&&(t.entrypoint=t.prompt),this.req(`/routines`,{method:`POST`,body:JSON.stringify(t)})}async update(e,t){return this.req(`/routines/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}async delete(e){await this.req(`/routines/${encodeURIComponent(e)}`,{method:`DELETE`})}async runNow(e){return ln(Jt,await this.req(`/routines/${encodeURIComponent(e)}/run_now`,{method:`POST`,body:JSON.stringify({})}),`/routines/${e}/run_now`,200)}async listRuns(e){let t=new URLSearchParams;e?.routine_id&&t.set(`routine_id`,e.routine_id),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return this.req(`/routines/runs${n}`)}async getRunsForRoutine(e,t=25){return this.req(`/routines/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e){return ln(Yt,await this.req(`/routines/runs/${encodeURIComponent(e)}`),`/routines/runs/${e}`,200)}async listArtifacts(e){return this.req(`/routines/runs/${encodeURIComponent(e)}/artifacts`)}async approveRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async denyRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async pauseRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resumeRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async history(e,t){let n=t===void 0?``:`?limit=${t}`,r=await this.req(`/routines/${encodeURIComponent(e)}/history${n}`);return Array.isArray(r)?{history:r,count:r.length}:r}events(e){let t=new URLSearchParams,n=e?.routine_id??e?.routineId;n&&t.set(`routine_id`,n);let r=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/routines/events${r}`,this.getToken(),{signal:e?.signal})}addArtifact(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/artifacts`,{method:`POST`,body:JSON.stringify(t)})}},In=class{constructor(e){this.req=e,this.planSessionIds=new Map,this.chatProjectSlug=`workflow-plans-chat`}plannerSessions(){return new Ln(this.req)}rememberSession(e,t){let n=pn(e),r=pn(t?.session_id);!n||!r||this.planSessionIds.set(n,r)}chatSessionTitle(e){let t=e.trim().replace(/\s+/g,` `);return t?t.length>80?`${t.slice(0,77)}...`:t:`Workflow planner chat`}async ensureChatSession(e){let t=pn(e);if(!t)throw Error(`Workflow planner plan ID is required`);let n=this.planSessionIds.get(t);if(n)return n;let r=await this.get(t),i=await this.plannerSessions().create({projectSlug:this.chatProjectSlug,project_slug:this.chatProjectSlug,title:pn(r.plan?.title)??`Workflow planner chat`,goal:pn(r.plan?.title)??``,plan_source:`workflow_plans_chat`,plan:r.plan,conversation:r.conversation,planner_diagnostics:r.planner_diagnostics??void 0,plan_revision:Number(r.plan?.plan_revision??1)||1,last_success_materialization:null}),a=pn(i.session?.session_id);if(!a)throw Error(`Workflow planner session creation failed`);return this.rememberSession(t,i.session),a}async preview(e){return this.req(`/workflow-plans/preview`,{method:`POST`,body:JSON.stringify({prompt:e.prompt,schedule:e.schedule,plan_source:e.plan_source??e.planSource,allowed_mcp_servers:e.allowed_mcp_servers??e.allowedMcpServers,workspace_root:e.workspace_root??e.workspaceRoot,operator_preferences:e.operator_preferences??e.operatorPreferences})})}async apply(e){return this.req(`/workflow-plans/apply`,{method:`POST`,body:JSON.stringify({plan_id:e.plan_id??e.planId,plan:e.plan,creator_id:e.creator_id??e.creatorId,pack_builder_export:e.pack_builder_export??e.packBuilderExport,overlap_decision:e.overlap_decision??e.overlapDecision})})}async chatStart(e){let t=pn((await this.plannerSessions().create({projectSlug:this.chatProjectSlug,project_slug:this.chatProjectSlug,title:this.chatSessionTitle(e.prompt),workspace_root:e.workspace_root??e.workspaceRoot,goal:e.prompt,plan_source:e.plan_source??e.planSource??`workflow_plans_chat`,allowed_mcp_servers:e.allowed_mcp_servers??e.allowedMcpServers,operator_preferences:e.operator_preferences??e.operatorPreferences})).session?.session_id);if(!t)throw Error(`Workflow planner session creation failed`);let n=await this.plannerSessions().start(t,e);return this.rememberSession(n.plan?.plan_id,n.session),n}async get(e){return this.req(`/workflow-plans/${encodeURIComponent(e)}`)}async chatMessage(e){let t=e.plan_id??e.planId,n=await this.ensureChatSession(t??``),r=await this.plannerSessions().message(n,{message:e.message});return this.rememberSession(r.plan?.plan_id??t,r.session),r}async chatReset(e){let t=e.plan_id??e.planId,n=await this.ensureChatSession(t??``),r=await this.plannerSessions().reset(n);return this.rememberSession(r.plan?.plan_id??t,r.session),r}async importPreview(e){return this.req(`/workflow-plans/import/preview`,{method:`POST`,body:JSON.stringify({bundle:e.bundle,creator_id:e.creator_id??e.creatorId,project_slug:e.project_slug??e.projectSlug,title:e.title})})}async importPlan(e){return this.req(`/workflow-plans/import`,{method:`POST`,body:JSON.stringify({bundle:e.bundle,creator_id:e.creator_id??e.creatorId,project_slug:e.project_slug??e.projectSlug,title:e.title})})}},Ln=class{constructor(e){this.req=e,this.kickoffTimeoutMs=2e4,this.operationTimeoutMs=62e4,this.operationPollIntervalMs=1500}async awaitOperation(e,t){let n=pn(e);if(!n)throw Error(`Workflow planner session ID is required`);let r=Date.now()+this.operationTimeoutMs;for(;Date.now()<r;){let e=(await this.get(n)).session,r=e?.operation;if(!r){await mn(this.operationPollIntervalMs);continue}let i=pn(r.request_id);if(t&&i&&i!==t)throw Error(`Workflow planner session was replaced by a newer operation`);let a=(pn(r.status)??``).toLowerCase();if(a===`completed`){let t=r.response;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Workflow planner completed without a usable response payload`);return Object.assign({},t,{session:e})}if(a===`failed`)throw Error(pn(r.error)??`Workflow planner failed during background execution`);await mn(this.operationPollIntervalMs)}throw Error(`Workflow planner timed out before completion`)}async list(e){let t=new URLSearchParams,n=e?.project_slug??e?.projectSlug;n&&t.set(`project_slug`,n);let r=t.toString()?`?${t.toString()}`:``;return this.req(`/workflow-plans/sessions${r}`)}async create(e){return this.req(`/workflow-plans/sessions`,{method:`POST`,body:JSON.stringify({project_slug:e.project_slug??e.projectSlug,title:e.title,workspace_root:e.workspace_root??e.workspaceRoot,goal:e.goal,notes:e.notes,planner_provider:e.planner_provider??e.plannerProvider,planner_model:e.planner_model??e.plannerModel,plan_source:e.plan_source??e.planSource,plan:e.plan,conversation:e.conversation,planner_diagnostics:e.planner_diagnostics??e.plannerDiagnostics,plan_revision:e.plan_revision??e.planRevision,last_success_materialization:e.last_success_materialization??e.lastSuccessMaterialization,allowed_mcp_servers:e.allowed_mcp_servers??e.allowedMcpServers,operator_preferences:e.operator_preferences??e.operatorPreferences,planning:e.planning})})}async get(e){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}`)}async patch(e,t){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify({title:t.title,workspace_root:t.workspace_root??t.workspaceRoot,goal:t.goal,notes:t.notes,planner_provider:t.planner_provider??t.plannerProvider,planner_model:t.planner_model??t.plannerModel,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,operator_preferences:t.operator_preferences??t.operatorPreferences,planning:t.planning,current_plan_id:t.current_plan_id??t.currentPlanId,draft:t.draft,published_at_ms:t.published_at_ms??t.publishedAtMs,published_tasks:t.published_tasks??t.publishedTasks})})}async duplicate(e,t){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/duplicate`,{method:`POST`,body:JSON.stringify({title:t?.title})})}async delete(e){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}`,{method:`DELETE`})}async start(e,t){let n=await this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/start-async`,{method:`POST`,timeoutMs:this.kickoffTimeoutMs,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})});return this.awaitOperation(e,n.session?.operation?.request_id??null)}async message(e,t){let n=await this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/message-async`,{method:`POST`,timeoutMs:this.kickoffTimeoutMs,body:JSON.stringify({message:t.message})});return this.awaitOperation(e,n.session?.operation?.request_id??null)}async reset(e){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/reset`,{method:`POST`})}},Rn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(){return this.req(`/automations`)}async create(e){return this.req(`/automations`,{method:`POST`,body:JSON.stringify(e)})}async update(e,t){return this.req(`/automations/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}async delete(e){await this.req(`/automations/${encodeURIComponent(e)}`,{method:`DELETE`})}async runNow(e){return ln(Jt,await this.req(`/automations/${encodeURIComponent(e)}/run_now`,{method:`POST`,body:JSON.stringify({})}),`/automations/${e}/run_now`,200)}async listRuns(e){let t=new URLSearchParams;e?.automation_id&&t.set(`automation_id`,e.automation_id),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return this.req(`/automations/runs${n}`)}async getRunsForAutomation(e,t=25){return this.req(`/automations/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e){return ln(Yt,await this.req(`/automations/runs/${encodeURIComponent(e)}`),`/automations/runs/${e}`,200)}async listArtifacts(e){return this.req(`/automations/runs/${encodeURIComponent(e)}/artifacts`)}async approveRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async denyRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async pauseRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resumeRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async history(e,t){let n=t===void 0?``:`?limit=${t}`,r=await this.req(`/automations/${encodeURIComponent(e)}/history${n}`);return Array.isArray(r)?{history:r,count:r.length}:r}events(e){let t=new URLSearchParams,n=e?.automation_id??e?.automationId,r=e?.run_id??e?.runId;n&&t.set(`automation_id`,n),r&&t.set(`run_id`,r);let i=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/automations/events${i}`,this.getToken(),{signal:e?.signal})}addArtifact(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/artifacts`,{method:`POST`,body:JSON.stringify(t)})}},zn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async create(e){return this.req(`/automations/v2`,{method:`POST`,body:JSON.stringify(e)})}async list(){return this.req(`/automations/v2`)}async get(e){return this.req(`/automations/v2/${encodeURIComponent(e)}`)}async update(e,t){return this.req(`/automations/v2/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}async delete(e){return this.req(`/automations/v2/${encodeURIComponent(e)}`,{method:`DELETE`})}async runNow(e,t){return this.req(`/automations/v2/${encodeURIComponent(e)}/run_now`,{method:`POST`,body:JSON.stringify({dry_run:t?.dryRun===!0})})}async pause(e,t){return this.req(`/automations/v2/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resume(e){return this.req(`/automations/v2/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({})})}async listRuns(e,t=50){return this.req(`/automations/v2/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}`)}async pauseRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resumeRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async recoverRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/recover`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async repairRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/repair`,{method:`POST`,body:JSON.stringify(t)})}async retryTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/retry`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async previewTaskReset(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/reset_preview`)}async continueTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/continue`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async requeueTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/requeue`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async claimBacklogTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/backlog/tasks/${encodeURIComponent(t)}/claim`,{method:`POST`,body:JSON.stringify(n||{})})}async requeueBacklogTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/backlog/tasks/${encodeURIComponent(t)}/requeue`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async cancelRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async gateDecide(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/gate`,{method:`POST`,body:JSON.stringify(t)})}async listHandoffs(e){return this.req(`/automations/v2/${encodeURIComponent(e)}/handoffs`)}events(e){let t=new URLSearchParams,n=e?.automation_id??e?.automationId,r=e?.run_id??e?.runId;n&&t.set(`automation_id`,n),r&&t.set(`run_id`,r);let i=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/automations/v2/events${i}`,this.getToken(),{signal:e?.signal})}},Bn=class{constructor(e){this.req=e}async list(){return this.req(`/optimizations`)}async create(e){return this.req(`/optimizations`,{method:`POST`,body:JSON.stringify(e)})}async get(e){return this.req(`/optimizations/${encodeURIComponent(e)}`)}async action(e,t){return this.req(`/optimizations/${encodeURIComponent(e)}/actions`,{method:`POST`,body:JSON.stringify(t)})}async listExperiments(e){return this.req(`/optimizations/${encodeURIComponent(e)}/experiments`)}async getExperiment(e,t){return this.req(`/optimizations/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`)}async applyWinner(e,t){return this.req(`/optimizations/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`,{method:`POST`,body:JSON.stringify({})})}},Vn=class{constructor(e){this.req=e}async listTemplates(e){let t=new URLSearchParams,n=String(e?.workspaceRoot||``).trim();n&&t.set(`workspaceRoot`,n);let r=t.toString()?`?${t.toString()}`:``;return this.req(`/agent-team/templates${r}`)}async createTemplate(e,t){let n=new URLSearchParams,r=String(t?.workspaceRoot||``).trim();r&&n.set(`workspaceRoot`,r);let i=n.toString()?`?${n.toString()}`:``;return this.req(`/agent-team/templates${i}`,{method:`POST`,body:JSON.stringify(e)})}async updateTemplate(e,t,n){let r=new URLSearchParams,i=String(n?.workspaceRoot||``).trim();i&&r.set(`workspaceRoot`,i);let a=r.toString()?`?${r.toString()}`:``;return this.req(`/agent-team/templates/${encodeURIComponent(e)}${a}`,{method:`PATCH`,body:JSON.stringify(t)})}async deleteTemplate(e,t){let n=new URLSearchParams,r=String(t?.workspaceRoot||``).trim();r&&n.set(`workspaceRoot`,r);let i=n.toString()?`?${n.toString()}`:``;return this.req(`/agent-team/templates/${encodeURIComponent(e)}${i}`,{method:`DELETE`})}async composeStandup(e){return this.req(`/agent-standup/compose`,{method:`POST`,body:JSON.stringify({name:e.name,workspace_root:e.workspaceRoot,schedule:e.schedule,participant_template_ids:e.participantTemplateIds,report_path_template:e.reportPathTemplate,model_policy:e.modelPolicy})})}async listInstances(e){let t=new URLSearchParams;e?.missionID&&t.set(`missionID`,e.missionID),e?.parentInstanceID&&t.set(`parentInstanceID`,e.parentInstanceID),e?.status&&t.set(`status`,e.status);let n=t.toString()?`?${t.toString()}`:``;return this.req(`/agent-team/instances${n}`)}async listMissions(){return this.req(`/agent-team/missions`)}async listApprovals(){return this.req(`/agent-team/approvals`)}async spawn(e){return this.req(`/agent-team/spawn`,{method:`POST`,body:JSON.stringify(e)})}async approveSpawn(e,t){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async denySpawn(e,t){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t??``})})}},Hn=class{constructor(e){this.req=e}async list(){return this.req(`/mission`)}async create(e){return this.req(`/mission`,{method:`POST`,body:JSON.stringify(e)})}async get(e){return this.req(`/mission/${encodeURIComponent(e)}`)}async applyEvent(e,t){return this.req(`/mission/${encodeURIComponent(e)}/event`,{method:`POST`,body:JSON.stringify({event:t})})}},Un=`electric_blue`,Wn={"--radius":`0px`,"--border-width":`1px`,"--border-width-strong":`2px`,"--shadow-offset":`2px 2px 0 rgba(0, 0, 0, 0.32)`,"--shadow-offset-lg":`4px 4px 0 rgba(0, 0, 0, 0.32)`,"--clip-primary-cta":`polygon(10% 0, 100% 0, 100% 100%, 0 100%, 0 25%)`},Gn=[{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)`}}],Kn={duration:{fast:.14,normal:.22,slow:.38},easing:{standard:[.22,1,.36,1],soft:[.33,1,.68,1],exit:[.4,0,1,1]},spring:{gentle:{type:`spring`,stiffness:220,damping:26,mass:.9},snappy:{type:`spring`,stiffness:320,damping:30,mass:.82},modal:{type:`spring`,stiffness:280,damping:28,mass:.95},drawer:{type:`spring`,stiffness:340,damping:34,mass:.82}}};function qn(e){let t=String(e||``).trim()||`electric_blue`;return t===`web_control`&&(t=Un),Gn.find(e=>e.id===t)||Gn[0]}function Jn(e){let t=qn(e).id,n=Gn.findIndex(e=>e.id===t);return n<0?Un:Gn[(n+1)%Gn.length].id}function Yn(e,t=typeof document<`u`?document.documentElement:null){let n=qn(e);if(!t)return n;for(let[e,n]of Object.entries(Wn))t.style.setProperty(e,n);for(let[e,r]of Object.entries(n.cssVars))r!=null&&t.style.setProperty(e,r);return t.dataset.theme=n.id,t.style.colorScheme=n.id===`porcelain`?`light`:`dark`,n}function Xn(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}var Zn=`tandem.themeId`;function Qn(){try{return qn(localStorage.getItem(Zn)).id}catch{return Un}}function $n(e){return Yn(e)}function er(e){let t=Yn(e);try{localStorage.setItem(Zn,t.id)}catch{}return t}function tr(){let[e,t]=r(()=>Xn());return m(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),n=()=>t(e.matches);return n(),typeof e.addEventListener==`function`?(e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}function nr(e,t,n){return Math.min(n,Math.max(t,e))}function rr({className:e=``,children:t}){return a(`div`,{className:`tcp-glow-layer ${e}`.trim(),children:t})}function ir({className:e=``,children:t}){let n=tr();return a(s.div,{className:e,initial:n?!1:{opacity:0,y:14},animate:n?void 0:{opacity:1,y:0},exit:n?void 0:{opacity:0,y:-10},transition:n?void 0:{duration:Kn.duration.normal,ease:Kn.easing.standard},children:t})}function ar({className:e=``,children:t}){let n=tr();return a(s.div,{className:e,initial:n?!1:`hidden`,animate:n?void 0:`show`,variants:n?void 0:{hidden:{},show:{transition:{staggerChildren:.06,delayChildren:.02}}},children:t})}function or({className:e=``,children:t,as:n=`div`}){let r=tr();return a(n===`section`?s.section:n===`article`?s.article:s.div,{className:e,variants:r?void 0:{hidden:{opacity:0,y:12,scale:.985},show:{opacity:1,y:0,scale:1,transition:{duration:Kn.duration.normal,ease:Kn.easing.standard}}},initial:r?!1:`hidden`,animate:r?void 0:`show`,children:t})}function sr({value:e,format:t=e=>String(e),className:n=``}){let i=tr(),[o,s]=r(()=>Number(e||0)),l=c(Number(e||0));return m(()=>{let t=Number(e||0);if(!Number.isFinite(t)){s(0),l.current=0;return}if(i){s(t),l.current=t;return}let n=l.current,r=t-n;if(!r){s(t),l.current=t;return}let a=performance.now(),o=0,c=e=>{let i=nr((e-a)/420,0,1);s(n+r*(1-(1-i)**3)),i<1?o=window.requestAnimationFrame(c):l.current=t};return o=window.requestAnimationFrame(c),()=>window.cancelAnimationFrame(o)},[i,e]),a(`span`,{className:n,children:t(Number.isFinite(o)?o:0)})}function cr({tone:e=`ok`,text:t,className:n=``}){return a(`span`,{className:`tcp-status-pulse ${e} ${n}`.trim(),children:[a(`span`,{className:`tcp-status-pulse-dot`,"aria-hidden":`true`}),t?a(`span`,{children:t}):null]})}function lr({className:e=``,children:t}){return a(`div`,{className:`tcp-toolbar ${e}`.trim(),children:t})}function ur({className:e=``,title:t,children:n,...r}){return a(`button`,{type:`button`,title:t,className:`tcp-icon-btn ${e}`.trim(),...r,children:n})}function X({tone:e=`info`,className:t=``,children:n}){return a(`span`,{className:`${e===`ok`?`tcp-badge-ok`:e===`warn`?`tcp-badge-warn`:e===`err`?`tcp-badge-err`:e===`ghost`?`tcp-badge tcp-badge-ghost`:`tcp-badge-info`} ${t}`.trim(),children:n})}function dr({title:e,subtitle:t,actions:n,className:r=``,fullHeight:i,children:o}){return a(or,{as:`section`,className:`tcp-panel-card ${i?`flex flex-col h-full`:``} ${r}`.trim(),children:[e||t||n?a(`div`,{className:`tcp-panel-card-head shrink-0`,children:[a(`div`,{className:`min-w-0`,children:[e?a(`h3`,{className:`tcp-title`,children:e}):null,t?a(`p`,{className:`tcp-subtle mt-1`,children:t}):null]}),n?a(`div`,{className:`shrink-0`,children:n}):null]}):null,a(`div`,{className:i?`flex-1 flex flex-col min-h-0`:``,children:o})]})}function fr({text:e,title:t=`Nothing here yet`,action:n,className:r=``}){return a(`div`,{className:`tcp-empty-state ${r}`.trim(),children:[a(`div`,{className:`tcp-empty-state-orb`}),a(`div`,{className:`relative z-10`,children:[a(`div`,{className:`tcp-empty-state-title`,children:t}),a(`p`,{className:`tcp-subtle mt-1`,children:e}),n?a(`div`,{className:`mt-3`,children:n}):null]})]})}function pr({eyebrow:e,title:t,subtitle:n,badges:r,actions:i,className:o=``}){return a(or,{className:`tcp-page-header ${o}`.trim(),children:[a(rr,{className:`tcp-page-header-glow`}),a(`div`,{className:`relative z-10 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between`,children:[a(`div`,{className:`min-w-0`,children:[e?a(`div`,{className:`tcp-page-eyebrow`,children:e}):null,a(`h1`,{className:`tcp-page-title`,children:t}),n?a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:n}):null,r?a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:r}):null]}),i?a(lr,{className:`justify-start lg:justify-end`,children:i}):null]})]})}function mr({className:e=``,mainClassName:t=``,asideClassName:n=``,main:r,aside:i}){return a(`div`,{className:`tcp-split-view ${i?``:`tcp-split-view--solo`} ${e}`.trim(),children:[a(`div`,{className:`min-w-0 ${t}`.trim(),children:r}),i?a(`div`,{className:`min-w-0 ${n}`.trim(),children:i}):null]})}function hr({open:e,title:t,onClose:n,children:r}){let i=tr();return a(l,{children:e?a(s.div,{className:`tcp-drawer-root`,initial:i?!1:{opacity:0},animate:i?void 0:{opacity:1},exit:i?void 0:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-drawer-backdrop`,"aria-label":`Close`,onClick:n}),a(s.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:Kn.spring.drawer,children:[a(`div`,{className:`tcp-drawer-head`,children:[a(`div`,{className:`min-w-0`,children:t?a(`h3`,{className:`tcp-title`,children:t}):null}),a(ur,{title:`Close drawer`,onClick:n,children:a(`i`,{"data-lucide":`x`})})]}),a(`div`,{className:`min-h-0 flex-1 overflow-auto p-4`,children:r})]})]}):null})}function gr({loginMutation:e,savedToken:t,onCheckEngine:n,controlPanelName:i,controlPanelMode:o,controlPanelModeReason:s}){let[c,l]=r(t),[u,d]=r(!0),[f,p]=r(``),[m,h]=r(!1);return a(`main`,{className:`relative min-h-screen overflow-hidden px-5 py-8`,children:[a(rr,{className:`tcp-shell-background`,children:[a(`div`,{className:`tcp-shell-glow tcp-shell-glow-a`}),a(`div`,{className:`tcp-shell-glow tcp-shell-glow-b`})]}),a(`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:[a(`section`,{className:`grid gap-4`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Tandem Control`}),a(`h1`,{className:`tcp-page-title max-w-3xl`,children:`Sign in to continue.`}),a(`p`,{className:`tcp-subtle max-w-2xl text-base`,children:`Enter your engine token to access chat, task board, automations, runs, memory, and settings.`})]}),a(dr,{title:i,subtitle:o===`aca`?`ACA install detected. Authenticate against your Tandem engine to continue.`:`Standalone install detected. Authenticate against your Tandem engine to continue.`,children:a(`form`,{className:`grid gap-3`,onSubmit:t=>{if(t.preventDefault(),!c.trim()){h(!1),p(`Token is required.`);return}e.mutate({token:c.trim(),remember:u})},children:[a(`label`,{className:`text-sm tcp-subtle`,children:`Engine token`}),a(`input`,{className:`tcp-input`,type:`password`,value:c,onInput:e=>l(e.target.value),placeholder:`tk_...`,autoComplete:`off`}),a(`label`,{className:`inline-flex items-center gap-2 text-xs tcp-subtle`,children:[a(`input`,{type:`checkbox`,className:`h-4 w-4 accent-slate-400`,checked:u,onChange:e=>d(e.target.checked)}),`Remember token on this browser`]}),a(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[a(`button`,{disabled:e.isPending,type:`submit`,className:`tcp-btn-primary w-full`,children:[a(`i`,{"data-lucide":`key-round`}),`Sign in`]}),a(`button`,{type:`button`,className:`tcp-btn w-full`,onClick:async()=>{try{let e=await n();h(!0),p(e)}catch(e){h(!1),p(e instanceof Error?e.message:String(e))}},children:[a(`i`,{"data-lucide":`activity`}),`Check engine`]})]}),a(`div`,{className:`min-h-[1.2rem] text-sm ${m?`text-lime-300`:`text-rose-300`}`,children:e.error?.message||f}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-950/30 p-3`,children:[a(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[a(`div`,{className:`font-medium`,children:`Readiness`}),a(cr,{tone:m?`ok`:`warn`,text:m?`Engine reachable`:`Waiting`})]}),a(`p`,{className:`tcp-subtle text-xs`,children:`Connectivity checks are non-destructive and help verify the local panel can reach the engine before authentication.`}),s?a(`p`,{className:`tcp-subtle mt-2 text-xs`,children:s}):null]})]})})]})]})}function _r(e){m(()=>{let t=t=>{(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()===`k`&&(t.preventDefault(),e())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e])}function vr({open:e,onClose:t,actions:n}){let[i,c]=r(``);m(()=>{e||c(``)},[e]),m(()=>{if(!e)return;let n=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]);let u=o(()=>{let e=i.trim().toLowerCase();return e?n.filter(t=>`${t.label} ${t.group}`.toLowerCase().includes(e)):n},[n,i]);return a(l,{children:e?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:a(s.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:e=>e.stopPropagation(),children:[a(`div`,{className:`tcp-doc-header`,children:[a(`h3`,{className:`tcp-doc-title`,children:`Command Palette`}),a(`kbd`,{className:`tcp-subtle text-xs`,children:`Ctrl/Cmd + K`})]}),a(`div`,{className:`p-3`,children:[a(`input`,{autoFocus:!0,value:i,onInput:e=>c(e.target.value),placeholder:`Jump to route or action`,className:`tcp-input`}),a(`div`,{className:`mt-3 grid max-h-[50vh] gap-2 overflow-auto`,children:[u.map(e=>a(`button`,{type:`button`,className:`tcp-btn w-full justify-between`,onClick:()=>{e.onSelect(),t()},children:[a(`span`,{className:`inline-flex items-center gap-1.5`,children:[a(`i`,{"data-lucide":`list`}),a(`span`,{children:e.label})]}),a(`span`,{className:`tcp-subtle text-xs`,children:e.group})]},e.id)),u.length?null:a(`p`,{className:`tcp-subtle px-1 py-2`,children:`No matching action.`})]})]})]})}):null})}var yr=[[`dashboard`,`Dashboard`,`home`],[`chat`,`Chat`,`message-square`],[`planner`,`Planner`,`compass`],[`workflows`,`Workflows`,`network`],[`marketplace`,`Marketplace`,`globe`],[`studio`,`Studio`,`blocks`],[`automations`,`Automations`,`bot`],[`experiments`,`Experiments`,`flask-conical`],[`coding`,`Coder`,`code`],[`agents`,`Agents`,`users`],[`orchestrator`,`Task Board`,`workflow`],[`files`,`Files`,`folder`],[`memory`,`Memory`,`database`],[`runs`,`Runs`,`activity`],[`approvals`,`Approvals`,`shield-check`],[`settings`,`Settings`,`settings`],[`packs`,`Packs`,`package`],[`teams`,`Teams`,`users`],[`channels`,`Channels`,`message-circle`],[`mcp`,`MCP`,`link`],[`bug-monitor`,`Bug Monitor`,`bug-play`],[`packs-detail`,`Packs`,`package`],[`teams-detail`,`Teams`,`users`]],br=[`dashboard`,`chat`,`planner`,`workflows`,`marketplace`,`studio`,`automations`,`experiments`,`coding`,`agents`,`orchestrator`,`bug-monitor`,`files`,`memory`,`runs`,`approvals`,`settings`].map(e=>{let t=yr.find(([t])=>t===e);if(!t)throw Error(`Missing navigation route: ${e}`);return t}),xr={openai:{label:`OpenAI`,keyUrl:`https://platform.openai.com/api-keys`,placeholder:`sk-proj-...`},"openai-codex":{label:`Codex Account`,keyUrl:``,placeholder:`Browser sign-in required`,authMode:`oauth`,description:`Use your ChatGPT/Codex subscription on this machine without pasting a separate API key.`},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_...`},llama_cpp:{label:`llama.cpp`,keyUrl:``,placeholder:`No key required`},ollama:{label:`Ollama`,keyUrl:``,placeholder:`No key required`}},Sr=yr,Cr=br,wr=new Map([[`packs`,`automations`],[`teams`,`automations`],[`feed`,`runs`],[`swarm`,`orchestrator`],[`failure-reporter`,`bug-monitor`]]),Tr=new Set(Sr.map(([e])=>e));function Er(e,t=`dashboard`){return wr.get(String(e||``).trim())||(Tr.has(e)?e:t)}function Dr(e=`dashboard`){return Er((window.location.hash||`#/${e}`).replace(/^#\//,``).split(`?`)[0].split(`/`)[0].trim(),e)}function Or(e){window.location.hash=`#/${e}`}function kr(e={}){let[t,n]=r(()=>Dr()),i=c(t),a=c(e.canNavigate);m(()=>{i.current=t},[t]),m(()=>{a.current=e.canNavigate},[e.canNavigate]),m(()=>{let e=Dr(i.current);window.location.hash!==`#/${e}`&&Or(e)},[]);let o=h((e,t)=>{let r=i.current;return e===r?window.location.hash===`#/${r}`?(n(r),!0):(Or(r),!0):!a.current||a.current(e,r)?window.location.hash===`#/${e}`?(n(e),!0):(Or(e),!0):(t===`hashchange`&&window.location.hash!==`#/${r}`&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}#/${r}`),!1)},[]);return m(()=>{let e=()=>{o(Dr(),`hashchange`)};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[o]),{route:t,navigate:h(e=>{o(Er(e),`navigate`)},[o])}}var Ar=e({toast:()=>void 0});function jr({children:e}){let[t,n]=r([]),i=h((e,t)=>{let r=Math.random().toString(36).slice(2);n(n=>[...n,{id:r,kind:e,text:t}].slice(-4)),window.setTimeout(()=>{n(e=>e.filter(e=>e.id!==r))},3500)},[]),c=o(()=>({toast:i}),[i]);return a(Ar.Provider,{value:c,children:[e,a(`div`,{className:`toasts`,"aria-live":`polite`,"aria-atomic":`true`,children:a(l,{children:t.map(e=>a(s.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-${e.kind}`,children:e.text},e.id))})})]})}function Mr(){return n(Ar)}function Nr({title:e,subtitle:t,children:n,actions:r,className:i,fullHeight:o}){return a(dr,{title:e,subtitle:t,actions:r,className:i||``,fullHeight:o,children:n})}function Pr({text:e,title:t,action:n}){return a(fr,{text:e,title:t,action:n})}function Fr(e){return JSON.stringify(e,null,2)}function Ir(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Lr({value:e,label:t=`Show raw JSON`,className:n=``,preClassName:i=`tcp-code mt-2 max-h-64 overflow-auto text-[11px]`,hint:s}){let[c,l]=r(!1),u=o(()=>c?Ir(e):``,[c,e]);return a(`details`,{className:n,onToggle:e=>l(e.currentTarget.open),children:[a(`summary`,{className:`cursor-pointer select-none text-xs text-slate-400 hover:text-slate-200`,children:[t,s?a(`span`,{className:`ml-2 text-[10px] text-slate-500`,children:s}):null]}),c?a(`pre`,{className:i,children:u}):null]})}function Rr({value:e,open:t,className:n=`tcp-code mt-2 max-h-32 overflow-auto text-[11px]`}){let r=o(()=>t?Ir(e):``,[t,e]);return t?a(`pre`,{className:n,children:r}):null}function zr(e){return new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(Number(e||0))}function Br(e){return new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,maximumFractionDigits:4}).format(Number(e||0))}function Vr(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function Hr(e){return String(e||``).trim().replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase()}function Ur(e){return e.ready?e.defaultProvider===`openai-codex`?e.defaultProviderManagedBy===`codex-upload`?`Imported auth.json on hosted server`:e.defaultProviderManagedBy===`codex-cli`?`Mirrored from local Codex CLI`:e.defaultProviderAuthKind===`oauth`?`Codex account session active`:``:e.defaultProviderAuthKind===`oauth`?`OAuth session active`:e.defaultProviderSource===`env`?`Env-managed credentials`:e.defaultProviderSource===`persisted`?`Stored credentials`:``:``}function Wr(e){let{api:t,client:n,navigate:i,providerStatus:s}=e,[c,l]=r(``),[u,d]=r(`day`),f=new Set([`workflow`,`bug_monitor_triage`]),p=y({queryKey:[`dashboard`,`health`],queryFn:()=>t(`/api/system/health`),refetchInterval:15e3}),m=y({queryKey:[`dashboard`,`sessions`],queryFn:()=>n.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),h=y({queryKey:[`dashboard`,`routines`],queryFn:()=>n.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),g=y({queryKey:[`dashboard`,`automation-v2-runs`],queryFn:()=>t(`/api/engine/automations/v2/runs?limit=200`).catch(()=>({runs:[]})),refetchInterval:15e3}),_=y({queryKey:[`dashboard`,`swarm`],queryFn:()=>t(`/api/swarm/status`).catch(()=>({status:`unknown`,activeRuns:0})),refetchInterval:6e3}),v=y({queryKey:[`dashboard`,`workflow-context-runs`],queryFn:()=>t(`/api/engine/context/runs?limit=12`).catch(()=>({runs:[]})),refetchInterval:6e3}),b=y({queryKey:[`dashboard`,`workflow-context-run`,c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}`).catch(()=>({run:null}))}),x=y({queryKey:[`dashboard`,`workflow-context-blackboard`,c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}/blackboard`).catch(()=>({blackboard:null}))}),S=Vr(m.data,`sessions`),C=Vr(h.data,`routines`),w=Vr(g.data,`runs`),T=Vr(v.data,`runs`).filter(e=>f.has(String(e?.run_type||``).trim().toLowerCase())),E=!!(p.data?.engine?.ready||p.data?.engine?.healthy),D=String(_.data?.status||`unknown`),O=[`planning`,`awaiting_approval`,`running`,`executing`].includes(D.toLowerCase()),k=w.filter(e=>[`queued`,`running`,`pausing`,`awaiting_approval`,`blocked`].includes(Hr(e?.status))),A=w.filter(e=>{let t=Number(e?.total_tokens||0),n=Number(e?.estimated_cost_usd||0);return t>0||n>0}),j=w.reduce((e,t)=>({prompt:e.prompt+Number(t?.prompt_tokens||0),completion:e.completion+Number(t?.completion_tokens||0),total:e.total+Number(t?.total_tokens||0),cost:e.cost+Number(t?.estimated_cost_usd||0)}),{prompt:0,completion:0,total:0,cost:0}),M=T.filter(e=>[`queued`,`planning`,`running`,`awaiting_approval`].includes(String(e?.status||``).trim().toLowerCase())),N=Ur(s),P=o(()=>{let e=new Map,t=Date.now(),n,r,i,a;u===`day`?(n=336*60*60*1e3,r=14,i=e=>e.toISOString().slice(0,10),a=e=>{let[,t,n]=e.split(`-`);return`${t}/${n}`}):u===`week`?(n=1344*60*60*1e3,r=8,i=e=>{let t=new Date(e);return t.setDate(e.getDate()-(e.getDay()+6)%7),t.toISOString().slice(0,10)},a=e=>{let[,t,n]=e.split(`-`);return`w/${t}/${n}`}):(n=4320*60*60*1e3,r=6,i=e=>e.toISOString().slice(0,7),a=e=>{let[t,n]=e.split(`-`);return`${n}/${t.slice(2)}`});let o=t-n;for(let t of w){let n=Number(t?.created_at_ms||t?.updated_at_ms||0);if(!n||n<o)continue;let r=new Date(n),s=i(r),c=e.get(s)??{label:a(s),runs:0,tokens:0,cost:0};c.runs+=1,c.tokens+=Number(t?.total_tokens||0),c.cost+=Number(t?.estimated_cost_usd||0),e.set(s,c)}let s=[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0])),c=Math.max(1,...s.map(([,e])=>e.tokens));return{buckets:s.map(([,e])=>e),maxTokens:c,bucketCount:r}},[w,u]),F=o(()=>[{label:`Recent sessions`,value:S.length,tone:`info`,helper:`Latest active conversation surfaces`},{label:`Stored runs`,value:w.length,tone:`ok`,helper:`Persisted automation-v2 history`},{label:`Live runs`,value:k.length,tone:k.length?`warn`:`ghost`,helper:`Queued, running, blocked, awaiting approval`},{label:`Tracked tokens`,value:j.total,tone:j.total?`info`:`ghost`,helper:`${A.length} runs with usage`},{label:`Estimated spend`,value:j.cost,tone:j.cost?`ok`:`ghost`,helper:`Summed from stored run records`,format:Br},{label:`Context runs`,value:T.length,tone:M.length?`warn`:`info`,helper:M.length?`${M.length} active`:`Workflow + triage visibility`}],[M.length,w.length,j.cost,j.total,k.length,S.length,T.length,A.length]);return a(ir,{className:`grid gap-4`,children:[a(dr,{className:`overflow-hidden`,children:[a(`div`,{className:`grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start`,children:a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Overview`}),a(`h1`,{className:`tcp-page-title`,children:`Command center`}),a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:`A higher-signal home screen with animated state and a clearer read on what the system is doing right now.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(X,{tone:E?`ok`:`warn`,children:E?`Engine healthy`:`Engine checking`}),a(X,{tone:s.ready?`ok`:`warn`,children:s.ready?s.defaultProvider:`Provider setup required`}),N?a(X,{tone:`info`,children:N}):null,O?a(cr,{tone:`live`,text:`Swarm ${D}`}):a(X,{tone:`ghost`,children:[`Swarm `,D]})]})]})}),a(`div`,{className:`mt-5`,children:[a(`div`,{className:`dashboard-kpis`,children:F.map(e=>a(`div`,{children:[a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`span`,{className:`dashboard-kpi-label`,children:e.label}),a(X,{tone:e.tone,children:e.helper})]}),a(`strong`,{children:a(sr,{value:e.value,format:e.format??zr})})]},e.label))}),a(`p`,{className:`tcp-subtle mt-3 text-xs`,children:`Usage totals are aggregated from stored automation-v2 run history, so they reflect real executions instead of inferred activity.`}),a(`div`,{className:`mt-4 dashboard-bars`,children:[a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{children:`Engine readiness`}),a(`span`,{className:`dashboard-bar-count`,children:E?`100%`:`45%`})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill completed`,style:{width:E?`100%`:`45%`}})})]}),a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{children:`Provider confidence`}),a(`span`,{className:`dashboard-bar-count`,children:s.ready?`100%`:`30%`})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill ${s.ready?`running`:`queued`}`,style:{width:s.ready?`100%`:`30%`}})})]}),a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{children:`Automation activity`}),a(`span`,{className:`dashboard-bar-count`,children:[k.length,` live`]})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill ${k.length?`running`:`manual`}`,style:{width:`${w.length?Math.min(100,Math.max(12,k.length/w.length*100)):12}%`}})})]})]})]})]}),a(dr,{children:[a(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Usage`}),a(`h2`,{className:`font-semibold`,children:`Token usage over time`})]}),a(`div`,{className:`flex gap-1`,children:[`day`,`week`,`month`].map(e=>a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-xs capitalize ${u===e?`tcp-btn-active`:``}`,onClick:()=>d(e),children:e},e))})]}),P.buckets.length===0?a(`p`,{className:`tcp-subtle text-xs`,children:`No token data in this window yet.`}):a(`div`,{className:`grid gap-2`,children:P.buckets.map(e=>a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{className:`font-mono text-xs`,children:e.label}),a(`span`,{className:`dashboard-bar-count`,children:[zr(e.tokens),` tok`,e.cost>0?` · ${Br(e.cost)}`:``,` · `,a(`span`,{className:`tcp-subtle`,children:[e.runs,` run`,e.runs===1?``:`s`]})]})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill ${e.tokens>0?`running`:`manual`}`,style:{width:`${Math.max(4,e.tokens/P.maxTokens*100)}%`}})})]},e.label))})]}),a(mr,{main:a(dr,{title:`Recent sessions`,subtitle:`Latest conversations, ready to reopen.`,children:a(`div`,{className:`grid gap-2`,children:S.length?S.map(e=>a(`button`,{className:`tcp-list-item text-left`,onClick:()=>i(`chat`),children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`messages-square`}),String(e.title||e.id||`Session`)]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(e.id||e.session_id||``)})]},String(e.id||e.session_id||Math.random()))):a(Pr,{text:`Start a conversation to populate recent sessions here.`})})}),aside:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`Context visibility`,subtitle:`Recent workflow and failure-triage context runs with their current projection state.`,children:[a(lr,{className:`mb-3`,children:[a(X,{tone:M.length?`warn`:`info`,children:[T.length,` recent`]}),a(`button`,{className:`tcp-btn`,onClick:()=>i(`orchestrator`),children:[a(`i`,{"data-lucide":`workflow`}),`Open task board`]})]}),a(`div`,{className:`grid gap-2`,children:T.length?T.slice(0,5).map(e=>a(`button`,{className:`tcp-list-item text-left`,onClick:()=>l(String(e?.run_id||``).trim()),children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:String(e?.objective||e?.run_id||`Context run`)}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(X,{tone:`ghost`,children:String(e?.run_type||`context`)}),a(X,{tone:[`failed`,`cancelled`].includes(String(e?.status||``).toLowerCase())?`err`:[`running`,`queued`,`planning`].includes(String(e?.status||``).toLowerCase())?`warn`:`ok`,children:String(e?.status||`unknown`)})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:String(e?.run_id||``)}),a(`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()))):a(Pr,{text:`Workflow and failure-triage context runs will appear here once they execute.`})})]}),a(dr,{title:`Automation snapshot`,subtitle:`Schedules and run-ready routines.`,children:[a(lr,{className:`mb-3`,children:[a(X,{tone:`info`,children:[C.length,` loaded`]}),a(`button`,{className:`tcp-btn`,onClick:()=>i(`automations`),children:[a(`i`,{"data-lucide":`bot`}),`Manage`]})]}),a(`div`,{className:`grid gap-2`,children:C.length?C.slice(0,4).map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:String(e.name||e.id||`Routine`)}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(e.schedule||e.status||`manual`)})]},String(e.id||e.routine_id||Math.random()))):a(Pr,{text:`No routines are configured yet.`})})]}),a(dr,{title:`Health notes`,subtitle:`Direct links for the next likely action.`,children:a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`activity`}),`Engine endpoint`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(p.data?.engineUrl||`Unavailable`)})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`radio`}),`Swarm`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[`Status: `,D]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`database`}),`Memory & runs`]}),a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>i(`memory`),children:`Open memory`}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>i(`runs`),children:`Open runs`})]})]})]})})]})}),a(hr,{open:!!c,onClose:()=>l(``),title:c||`Workflow context run`,children:c?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:String(b.data?.run?.objective||c)}),a(X,{tone:`info`,children:String(b.data?.run?.status||`unknown`)})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`type: `,String(b.data?.run?.run_type||`workflow`)]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium mb-2`,children:`Projected blackboard`}),a(`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]})]}),a(Lr,{value:{run:b.data?.run||null,blackboard:x.data?.blackboard||null},label:`Show run + blackboard`})]}):null})]})}var Gr={Activity:ft,Archive:Me,ArrowDown:Xe,ArrowLeftToLine:yt,ArrowRight:lt,ArrowUpCircle:z,BadgeCheck:Tt,Binary:Be,Blocks:C,Bot:Oe,BookOpen:fe,Bug:Ee,BugPlay:we,Calendar:H,Check:_t,ChevronDown:U,ChevronLeft:L,ChevronRight:Se,ChevronUp:ve,ClipboardList:D,Clock:G,Clock3:zt,Code:re,Compass:B,CornerUpLeft:oe,Copy:ue,CopyPlus:F,Cpu:ae,Database:T,DatabaseZap:$e,Download:tt,Eraser:ce,ExternalLink:j,FilePlus:ge,FileText:k,FileInput:N,Files:Ft,FileSearch:Nt,FileUp:me,Filter:We,FilterX:ht,FlaskConical:Fe,Folder:Je,FolderCode:Lt,FolderOpen:jt,FolderPlus:Ae,FolderUp:Ke,Fullscreen:st,Globe:ze,HardDrive:kt,History:it,Home:Ie,Info:Ct,KeyRound:pt,Layers:Ne,Link:Ze,List:Et,ListChecks:bt,ListX:ut,LoaderCircle:Ve,LogOut:S,Menu:de,MessageCircle:De,MessageSquare:Ce,MessagesSquare:Te,MonitorCog:V,Network:gt,Package:I,PackagePlus:te,PaintBucket:xe,PanelLeft:_e,Paperclip:R,Pause:ye,Pencil:E,Play:Rt,PlugZap:pe,Plus:ne,Radio:P,Radar:ee,RefreshCw:le,Rocket:W,RotateCcw:ie,RotateCw:Qe,Save:w,Search:et,Send:se,Settings:M,Settings2:A,Share2:he,Shield:K,ShieldAlert:Mt,ShieldCheck:O,Siren:Pt,SkipForward:Pe,SlidersHorizontal:It,Sparkles:At,Square:qe,SquareCheckBig:ke,SquarePen:Ge,Star:at,Trash2:mt,TriangleAlert:He,Unlink:Le,Upload:Dt,UserPlus:nt,Users:q,Workflow:xt,X:dt,XCircle:be},Kr=new Set,qr=0;function Jr(){qr=0;let e=[...Kr];Kr.clear();for(let t of e)je({icons:Gr,attrs:{width:`16`,height:`16`,"stroke-width":`1.8`},...t?{root:t}:{}})}function Yr(e){Kr.add(e||null),!qr&&(qr=window.requestAnimationFrame(Jr))}Vt.setOptions({gfm:!0,breaks:!0});function Xr(e){let t=String(e||``),n=Vt.parse(t,{async:!1});return Bt.sanitize(n)}function Zr({messages:e,emptyText:t,inputValue:n,inputPlaceholder:r,sendLabel:i,onInputChange:o,onSend:u,sendDisabled:f=!1,inputDisabled:p=!1,statusTitle:h=``,statusDetail:g=``,questionTitle:_=``,questionText:v=``,quickReplies:y=[],onQuickReply:b,questionHint:x=``,botIdentity:S,streamingText:C=``,showThinking:w=!1,thinkingText:T=`Thinking`,autoFocusKey:E,attachments:D=[],onOpenAttachment:O,onRemoveAttachment:k,onAttach:A,attachDisabled:j=!1,className:M=``}){let N=!!d(),P=c(null),F=c(null),I=c(null),L=c(!0),R=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=24;m(()=>{let e=F.current;e&&L.current&&(e.scrollTop=e.scrollHeight)},[e,C,w]),m(()=>{let e=I.current;e&&(e.style.height=`0px`,e.style.height=`${Math.min(e.scrollHeight,180)}px`)},[n]),m(()=>{if(E==null||p)return;let e=I.current;if(e){e.focus();try{let t=e.value.length;e.setSelectionRange(t,t)}catch{}}},[E,p]),m(()=>{P.current&&Yr(P.current)},[D,n,e,y,f,w,C]);let z=S?.botName||`Assistant`;return a(`div`,{ref:P,className:`rounded-2xl border border-white/10 bg-black/20 p-3 flex min-h-0 flex-1 flex-col ${M}`,children:[v?a(`div`,{className:`mb-3 rounded-xl border border-sky-500/40 bg-sky-950/30 p-3`,children:[a(`div`,{className:`text-xs uppercase tracking-wide text-sky-200`,children:_||`Planner question`}),a(`div`,{className:`mt-1 text-sm font-medium text-sky-100`,children:v}),y.length?a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:y.map(e=>a(`button`,{type:`button`,className:`tcp-btn text-sm`,disabled:p,onClick:()=>b?.(e),children:e.label},e.id))}):null,x?a(`div`,{className:`mt-2 text-xs text-sky-200/80`,children:x}):null]}):null,a(`div`,{ref:F,className:`chat-messages mb-2 min-h-0 min-w-0 flex-1 overflow-auto p-2 space-y-2`,onScroll:()=>{let e=F.current;e&&(L.current=R(e))},children:[e.length?a(l,{initial:!1,children:e.map(e=>{let t=e.role===`assistant`||e.role===`system`;return a(s.article,{className:`chat-msg ${t?`assistant`:`user`}`,initial:N?!1:{opacity:0,y:4},animate:N?void 0:{opacity:1,y:0},exit:N?void 0:{opacity:0,y:-4},children:[a(`div`,{className:`chat-msg-role`,children:t?a(`span`,{className:`inline-flex items-center gap-2`,children:[S?.botAvatarUrl?a(`img`,{src:S.botAvatarUrl,alt:z,className:`chat-avatar-ring h-5 w-5 rounded-full object-cover`}):null,a(`span`,{children:e.displayRole||z})]}):e.displayRole||e.role}),e.markdown?a(`div`,{className:`tcp-markdown tcp-markdown-ai`,dangerouslySetInnerHTML:{__html:Xr(e.text||``)}}):a(`pre`,{className:`chat-msg-pre`,children:e.text||` `})]},e.id)})}):a(`div`,{className:`chat-empty-state`,children:a(`p`,{className:`chat-rail-empty`,children:t})}),w||C?a(`article`,{className:`chat-msg assistant`,children:[a(`div`,{className:`chat-msg-role`,children:a(`span`,{className:`inline-flex items-center gap-2`,children:[S?.botAvatarUrl?a(`img`,{src:S.botAvatarUrl,alt:z,className:`chat-avatar-ring h-5 w-5 rounded-full object-cover`}):null,a(`span`,{children:z})]})}),w&&!C?a(`div`,{className:`tcp-thinking`,"aria-live":`polite`,children:[a(`span`,{children:T}),a(`i`,{}),a(`i`,{}),a(`i`,{})]}):null,C?a(`pre`,{className:`chat-msg-pre`,children:C}):null]}):null]}),h?a(`div`,{className:`mb-2 rounded-xl border border-sky-500/30 bg-sky-950/20 p-3 text-sm text-sky-100`,children:[a(`div`,{className:`flex items-center gap-2 font-medium`,children:[a(`span`,{className:`inline-block h-4 w-4 animate-spin rounded-full border-2 border-sky-200 border-t-transparent`,"aria-hidden":`true`}),h]}),g?a(`div`,{className:`mt-1 text-xs text-sky-200/80`,children:g}):null]}):null,a(`div`,{className:`chat-composer shrink-0`,children:[D.length?a(`div`,{className:`chat-attach-row mb-2 flex flex-wrap items-center gap-2`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:[D.length,` attached`]}),a(`div`,{className:`flex flex-wrap gap-1`,children:D.map((e,t)=>a(`span`,{className:`chat-file-pill min-w-0`,children:[a(`span`,{className:`chat-file-pill-name`,title:e.path,children:e.name||e.path}),e.size==null?null:a(`span`,{className:`chat-file-pill-size`,children:e.size<1024?`${e.size}B`:e.size<1024*1024?`${(e.size/1024).toFixed(1)}KB`:`${(e.size/1024/1024).toFixed(1)}MB`}),O?a(`button`,{type:`button`,className:`chat-file-pill-btn`,title:`Open in Files`,onClick:()=>O(t),children:a(`i`,{"data-lucide":`folder-open`})}):null,k?a(`button`,{type:`button`,className:`chat-file-pill-btn chat-file-pill-btn-danger`,title:`Remove from list`,onClick:()=>k(t),children:a(`i`,{"data-lucide":`x`})}):null]},`${e.path}-${t}`))})]}):null,a(`div`,{className:`chat-input-wrap`,children:[A?a(`button`,{type:`button`,className:`chat-icon-btn chat-icon-btn-inner`,title:`Attach files`,disabled:j,onClick:A,children:a(`i`,{"data-lucide":`paperclip`})}):null,a(`textarea`,{ref:I,rows:1,value:n,className:`tcp-input chat-input-with-clip chat-input-modern resize-none`,placeholder:r,disabled:p,onInput:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),f||u())}}),a(`button`,{type:`button`,className:`chat-send-btn`,title:i,disabled:f,onClick:u,children:a(`i`,{"data-lucide":`send`})})]})]})]})}var Qr=`tcp.chat.session`;function $r(e){return String(e?.id||e?.session_id||e?.sessionID||``).trim()}function ei(e){let t=String(e?.title||e?.name||``).trim();if(t)return t;let n=$r(e);return n?`Session ${n.slice(0,8)}`:`Session`}function ti(e){return Array.isArray(e)?e:Array.isArray(e?.sessions)?e.sessions:[]}function ni(e){return String(e?.title||``).trim().toLowerCase().startsWith(`__provider_test__`)}function ri(e){return ti(e).filter(e=>!ni(e)).map(e=>({id:$r(e),title:ei(e),raw:e})).filter(e=>!!e.id)}async function ii(e,t){try{let t=ri(await e.sessions.list({pageSize:50}));if(t.length>0)return t}catch{}try{return ri(await t(`/api/engine/session?page_size=50`,{method:`GET`}))}catch{return[]}}function ai(){try{return localStorage.getItem(`tcp.chat.session`)||``}catch{return``}}function oi(e){try{e?localStorage.setItem(Qr,e):localStorage.removeItem(Qr)}catch{}}function si(e){return Array.isArray(e)?e.map(e=>e?typeof e==`string`?e:typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:typeof e.content==`string`?e.content:``:``).filter(Boolean).join(`
2
+ `);u=n.pop()??``;let r=``;for(let e of n)if(e.startsWith(`data:`))r+=e.slice(5).trimStart();else if(e===``&&r){let e=un(r);e&&(yield e),r=``}}}finally{l.releaseLock()}}function fn(e){let t=new AbortController;for(let n of e){if(n.aborted){t.abort(n.reason);break}n.addEventListener(`abort`,()=>t.abort(n.reason),{once:!0})}return t.signal}var pn=e=>typeof e==`string`&&e.trim().length>0?e:null,mn=e=>new Promise(t=>setTimeout(t,e)),hn=e=>{try{let t=Ut.parse(e);if(t)return t}catch{let t=e.run||null;if(t)try{let e=Ut.parse(t);if(e)return e}catch{}}throw Error(`Run ID missing in engine response`)},gn=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,``),this.token=e.token,this.timeoutMs=e.timeoutMs??2e4;let t=this._request.bind(this);this.sessions=new Sn(this.baseUrl,this.token,this.timeoutMs,t),this.permissions=new Cn(t),this.questions=new wn(t),this.providers=new Tn(t),this.identity=new En(t),this.channels=new Dn(t),this.mcp=new On(t,this._requestText.bind(this));let n=()=>this.token;this.routines=new Fn(this.baseUrl,n,t),this.automations=new Rn(this.baseUrl,n,t),this.automationsV2=new zn(this.baseUrl,n,t),this.optimizations=new Bn(t),this.workflowPlans=new In(t),this.workflowPlannerSessions=new Ln(t),this.memory=new kn(t),this.skills=new An(t),this.packs=new jn(t),this.capabilities=new Mn(t),this.resources=new Nn(this.baseUrl,n,t),this.browser=new _n(t),this.storage=new vn(t),this.worktrees=new yn(t),this.workflows=new bn(this.baseUrl,n,t),this.bugMonitor=new xn(t),this.coder=new Pn(t),this.agentTeams=new Vn(t),this.missions=new Hn(t)}setToken(e){this.token=e,this.sessions.setToken(e)}async health(){return ln(Wt,await this._request(`/global/health`),`/global/health`,200)}async listToolIds(){return this._request(`/tool/ids`)}async listTools(){let e=await this._request(`/tool`);return Array.isArray(e)?e:[]}async executeTool(e,t){return this._request(`/tool/execute`,{method:`POST`,body:JSON.stringify({tool:e,args:t??{}})})}stream(e,t,n){let r=new URLSearchParams({sessionID:e});return t&&r.set(`runID`,t),dn(`${this.baseUrl}/event?${r.toString()}`,this.token,n)}globalStream(e){return dn(`${this.baseUrl}/global/event`,this.token,e)}async runEvents(e,t){let n=new URLSearchParams;t?.sinceSeq!==void 0&&n.set(`since_seq`,String(t.sinceSeq)),t?.tail!==void 0&&n.set(`tail`,String(t.tail));let r=n.toString()?`?${n.toString()}`:``,i=await this._request(`/run/${encodeURIComponent(e)}/events${r}`);return Array.isArray(i)?i:[]}async _request(e,t={}){let n=t.timeoutMs??this.timeoutMs,r=new AbortController,i=setTimeout(()=>r.abort(),n),a;try{a=await fetch(`${this.baseUrl}${e}`,{...t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.token}`,...t.headers??{}},signal:r.signal})}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`Request timed out after ${n}ms: ${e}`):t}finally{clearTimeout(i)}if(a.status!==204){if(!a.ok){let t=await a.text().catch(()=>``);throw a.status===524?Error(`Engine timed out while waiting for ${e} to finish.`):Error(`Request failed (${a.status} ${a.statusText}): ${t}`)}return a.json()}}async _requestText(e,t={}){let n=t.timeoutMs??this.timeoutMs,r=new AbortController,i=setTimeout(()=>r.abort(),n),a;try{a=await fetch(`${this.baseUrl}${e}`,{...t,headers:{Authorization:`Bearer ${this.token}`,...t.headers??{}},signal:r.signal})}catch(t){throw t instanceof Error&&t.name===`AbortError`?Error(`Request timed out after ${n}ms: ${e}`):t}finally{clearTimeout(i)}if(!a.ok){let t=await a.text().catch(()=>``);throw a.status===524?Error(`Engine timed out while waiting for ${e} to finish.`):Error(`Request failed (${a.status} ${a.statusText}): ${t}`)}return a.text()}},_n=class{constructor(e){this.req=e}async status(){return this.req(`/browser/status`)}async install(){return this.req(`/browser/install`,{method:`POST`})}async smokeTest(e){return this.req(`/browser/smoke-test`,{method:`POST`,body:JSON.stringify(e??{})})}},vn=class{constructor(e){this.req=e}async listFiles(e){let t=new URLSearchParams;e?.path&&t.set(`path`,e.path),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return this.req(`/global/storage/files${n}`)}async repair(e){return this.req(`/global/storage/repair`,{method:`POST`,body:JSON.stringify({force:e?.force??!1})})}},yn=class{constructor(e){this.req=e}async cleanup(e){return this.req(`/worktree/cleanup`,{method:`POST`,body:JSON.stringify({repo_root:e?.repoRoot,dry_run:e?.dryRun??!1,remove_orphan_dirs:e?.removeOrphanDirs??!0})})}},bn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(){let e=await this.req(`/workflows`)??{},t=Array.isArray(e.workflows)?e.workflows:[];return{workflows:t,count:typeof e.count==`number`?e.count:t.length}}async get(e){return(await this.req(`/workflows/${encodeURIComponent(e)}`)).workflow??{}}async validate(e){return this.req(`/workflows/validate`,{method:`POST`,body:JSON.stringify(e??{})})}async simulate(e){return this.req(`/workflows/simulate`,{method:`POST`,body:JSON.stringify(e)})}events(e){let t=new URLSearchParams,n=e?.workflow_id??e?.workflowId,r=e?.run_id??e?.runId;n&&t.set(`workflow_id`,n),r&&t.set(`run_id`,r);let i=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/workflows/events${i}`,this.getToken(),{signal:e?.signal})}async listRuns(e){let t=new URLSearchParams,n=e?.workflow_id??e?.workflowId;n&&t.set(`workflow_id`,n),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let r=t.toString()?`?${t.toString()}`:``,i=await this.req(`/workflows/runs${r}`)??{},a=Array.isArray(i.runs)?i.runs:[];return{runs:a,count:typeof i.count==`number`?i.count:a.length}}async getRun(e){return(await this.req(`/workflows/runs/${encodeURIComponent(e)}`)).run??{}}async run(e,t){return this.req(`/workflows/${encodeURIComponent(e)}/run`,{method:`POST`,body:JSON.stringify(t??{})})}async listHooks(e){let t=new URLSearchParams,n=e?.workflow_id??e?.workflowId;n&&t.set(`workflow_id`,n);let r=t.toString()?`?${t.toString()}`:``,i=await this.req(`/workflow-hooks${r}`)??{},a=Array.isArray(i.hooks)?i.hooks:[];return{hooks:a,count:typeof i.count==`number`?i.count:a.length}}async patchHook(e,t){return this.req(`/workflow-hooks/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}},xn=class{constructor(e){this.req=e}async getConfig(){return this.req(`/config/bug-monitor`)}async patchConfig(e){let t=e&&typeof e==`object`&&`bug_monitor`in e?e:{bug_monitor:e};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(e){let t=e?.limit===void 0?``:`?limit=${e.limit}`;return this.req(`/bug-monitor/incidents${t}`)}async getIncident(e){return(await this.req(`/bug-monitor/incidents/${encodeURIComponent(e)}`)).incident??{}}async replayIncident(e,t){return this.req(`/bug-monitor/incidents/${encodeURIComponent(e)}/replay`,{method:`POST`,body:JSON.stringify(t??{})})}async deleteIncident(e){return this.req(`/bug-monitor/incidents/${encodeURIComponent(e)}`,{method:`DELETE`})}async bulkDeleteIncidents(e){return this.req(`/bug-monitor/incidents/bulk-delete`,{method:`POST`,body:JSON.stringify(e)})}async deleteDraft(e){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}`,{method:`DELETE`})}async bulkDeleteDrafts(e){return this.req(`/bug-monitor/drafts/bulk-delete`,{method:`POST`,body:JSON.stringify(e)})}async deletePost(e){return this.req(`/bug-monitor/posts/${encodeURIComponent(e)}`,{method:`DELETE`})}async bulkDeletePosts(e){return this.req(`/bug-monitor/posts/bulk-delete`,{method:`POST`,body:JSON.stringify(e)})}async listDrafts(e){let t=e?.limit===void 0?``:`?limit=${e.limit}`;return this.req(`/bug-monitor/drafts${t}`)}async listPosts(e){let t=e?.limit===void 0?``:`?limit=${e.limit}`;return this.req(`/bug-monitor/posts${t}`)}async listIntakeKeys(){return this.req(`/bug-monitor/intake/keys`)}async createIntakeKey(e){return this.req(`/bug-monitor/intake/keys`,{method:`POST`,body:JSON.stringify(e)})}async disableIntakeKey(e){return this.req(`/bug-monitor/intake/keys/${encodeURIComponent(e)}/disable`,{method:`POST`})}async resetLogSourceOffset(e,t){return this.req(`/bug-monitor/log-sources/${encodeURIComponent(e)}/${encodeURIComponent(t)}/reset-offset`,{method:`POST`})}async replayLatestLogSourceCandidate(e,t){return this.req(`/bug-monitor/log-sources/${encodeURIComponent(e)}/${encodeURIComponent(t)}/replay-latest`,{method:`POST`})}async getDraft(e){return(await this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}`)).draft??{}}async approveDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t})})}async denyDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t})})}async report(e){let t=e&&typeof e==`object`&&`report`in e?e:{report:e};return this.req(`/bug-monitor/report`,{method:`POST`,body:JSON.stringify(t)})}async createTriageRun(e){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/triage-run`,{method:`POST`})}async createTriageSummary(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/triage-summary`,{method:`POST`,body:JSON.stringify(t)})}async createIssueDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/issue-draft`,{method:`POST`,body:JSON.stringify(t??{})})}async publishDraft(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/publish`,{method:`POST`,body:JSON.stringify(t??{})})}async recheckMatch(e,t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(e)}/recheck-match`,{method:`POST`,body:JSON.stringify(t??{})})}},Sn=class{constructor(e,t,n,r){this.baseUrl=e,this.token=t,this.timeoutMs=n,this.req=r}setToken(e){this.token=e}async create(e={}){let t={title:e.title??`Tandem SDK Session`,directory:e.directory??`.`};return e.permissions&&(t.permission=e.permissions),e.model&&e.provider&&(t.model={providerID:e.provider,modelID:e.model},t.provider=e.provider),(await this.req(`/session`,{method:`POST`,body:JSON.stringify(t)})).id}async list(e={}){let t=new URLSearchParams;e.q&&t.set(`q`,e.q),e.page!==void 0&&t.set(`page`,String(e.page)),e.pageSize!==void 0&&t.set(`page_size`,String(e.pageSize)),e.archived!==void 0&&t.set(`archived`,String(e.archived)),e.scope&&t.set(`scope`,e.scope),e.workspace&&t.set(`workspace`,e.workspace);let n=t.toString()?`?${t.toString()}`:``;return ln(Kt,await this.req(`/session${n}`),`/session`,200)}async get(e){return ln(Gt,await this.req(`/session/${encodeURIComponent(e)}`),`/session/${e}`,200)}async update(e,t){return ln(Gt,await this.req(`/session/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),`/session/${e}`,200)}async archive(e){return this.update(e,{archived:!0})}async delete(e){await this.req(`/session/${encodeURIComponent(e)}`,{method:`DELETE`})}async messages(e){return this.req(`/session/${encodeURIComponent(e)}/message`)}async todos(e){let t=await this.req(`/session/${encodeURIComponent(e)}/todo`);return Array.isArray(t)?t:t.todos??[]}async activeRun(e){return ln(qt,await this.req(`/session/${encodeURIComponent(e)}/run`),`/session/${e}/run`,200)}async promptAsync(e,t,n,r){return this.promptAsyncParts(e,[{type:`text`,text:t}],n,r)}async promptAsyncParts(e,t,n,r){let i={parts:t};n?.provider&&n?.model&&(i.model={providerID:n.provider,modelID:n.model}),r?.toolMode&&(i.toolMode=r.toolMode),r?.toolAllowlist?.length&&(i.toolAllowlist=r.toolAllowlist),r?.contextMode&&(i.contextMode=r.contextMode);let a=`/session/${encodeURIComponent(e)}/prompt_async?return=run`,o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs),c;try{c=await fetch(`${this.baseUrl}${a}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.token}`},body:JSON.stringify(i),signal:o.signal})}finally{clearTimeout(s)}if(c.status===409){let e=(await c.json().catch(()=>({}))).activeRun,t=pn(e?.runID)||pn(e?.runId)||pn(e?.run_id);if(t)return{runId:t}}if(!c.ok){let e=await c.text().catch(()=>``);throw Error(`promptAsyncParts failed (${c.status}): ${e}`)}return{runId:hn(await c.json())}}async promptSync(e,t){let n={parts:[{type:`text`,text:t}]},r=await this.req(`/session/${encodeURIComponent(e)}/prompt_sync`,{method:`POST`,body:JSON.stringify(n)});return pn(r.reply)||pn(r.text)||pn(r.output)||``}async abort(e){return this.req(`/session/${encodeURIComponent(e)}/abort`,{method:`POST`,body:JSON.stringify({})})}async cancel(e){return this.req(`/session/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({})})}async cancelRun(e,t){return this.req(`/session/${encodeURIComponent(e)}/run/${encodeURIComponent(t)}/cancel`,{method:`POST`,body:JSON.stringify({})})}async fork(e){return ln(Gt,await this.req(`/session/${encodeURIComponent(e)}/fork`,{method:`POST`,body:JSON.stringify({})}),`/session/${e}/fork`,200)}async diff(e){return this.req(`/session/${encodeURIComponent(e)}/diff`)}async revert(e){return this.req(`/session/${encodeURIComponent(e)}/revert`,{method:`POST`,body:JSON.stringify({})})}async unrevert(e){return this.req(`/session/${encodeURIComponent(e)}/unrevert`,{method:`POST`,body:JSON.stringify({})})}async children(e){return ln(Kt,await this.req(`/session/${encodeURIComponent(e)}/children`),`/session/${e}/children`,200).sessions}async summarize(e){return this.req(`/session/${encodeURIComponent(e)}/summarize`,{method:`POST`,body:JSON.stringify({})})}async attach(e,t){return this.req(`/session/${encodeURIComponent(e)}/attach`,{method:`POST`,body:JSON.stringify({target_workspace:t})})}},Cn=class{constructor(e){this.req=e}async list(){return this.req(`/permission`)}async reply(e,t){let n=await this.req(`/permission/${encodeURIComponent(e)}/reply`,{method:`POST`,body:JSON.stringify({reply:t})});if(!n.ok)throw Error(`Permission reply rejected: ${n.error??e}`);return{ok:!0}}},wn=class{constructor(e){this.req=e}async list(){let e=await this.req(`/question`);return Array.isArray(e)?{questions:e}:e}async reply(e,t){return this.req(`/question/${encodeURIComponent(e)}/reply`,{method:`POST`,body:JSON.stringify({answer:t})})}async reject(e){return this.req(`/question/${encodeURIComponent(e)}/reject`,{method:`POST`,body:JSON.stringify({})})}},Tn=class{constructor(e){this.req=e}async catalog(){return this.req(`/provider`)}async config(){return this.req(`/config/providers`)}async setDefaults(e,t){await this.req(`/config`,{method:`PATCH`,body:JSON.stringify({default_provider:e,providers:{[e]:{default_model:t}}})})}async setApiKey(e,t){await this.req(`/auth/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({apiKey:t})})}async oauthAuthorize(e){return this.req(`/provider/${encodeURIComponent(e)}/oauth/authorize`,{method:`POST`})}async oauthStatus(e,t){let n=t?`?session_id=${encodeURIComponent(t)}`:``;return this.req(`/provider/${encodeURIComponent(e)}/oauth/status${n}`)}async oauthUseLocalSession(e){return this.req(`/provider/${encodeURIComponent(e)}/oauth/session/local`,{method:`POST`})}async oauthDisconnect(e){return this.req(`/provider/${encodeURIComponent(e)}/oauth/session`,{method:`DELETE`})}async authStatus(){return this.req(`/provider/auth`)}},En=class{constructor(e){this.req=e}async get(){return this.req(`/config/identity`)}async patch(e){return this.req(`/config/identity`,{method:`PATCH`,body:JSON.stringify(e)})}},Dn=class{constructor(e){this.req=e}async config(){return this.req(`/channels/config`)}async status(){return this.req(`/channels/status`)}async put(e,t){return this.req(`/channels/${e}`,{method:`PUT`,body:JSON.stringify(t)})}async delete(e){return this.req(`/channels/${e}`,{method:`DELETE`})}async verify(e,t={}){return this.req(`/channels/${e}/verify`,{method:`POST`,body:JSON.stringify(t)})}async toolPreferences(e){return this.req(`/channels/${e}/tool-preferences`)}async setToolPreferences(e,t){return this.req(`/channels/${e}/tool-preferences`,{method:`PUT`,body:JSON.stringify(t)})}},On=class{constructor(e,t){this.req=e,this.reqText=t}async list(){return this.req(`/mcp`)}async listTools(){return this.req(`/mcp/tools`)}async listResources(){let e=await this.req(`/mcp/resources`);return Array.isArray(e)?e:[]}async add(e){return this.req(`/mcp`,{method:`POST`,body:JSON.stringify(e)})}async connect(e){return this.req(`/mcp/${encodeURIComponent(e)}/connect`,{method:`POST`})}async disconnect(e){return this.req(`/mcp/${encodeURIComponent(e)}/disconnect`,{method:`POST`})}async refresh(e){return this.req(`/mcp/${encodeURIComponent(e)}/refresh`,{method:`POST`})}async patch(e,t){return this.req(`/mcp/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t??{})})}async setEnabled(e,t){return this.patch(e,{enabled:t})}async delete(e){return this.req(`/mcp/${encodeURIComponent(e)}`,{method:`DELETE`})}async auth(e,t){return this.req(`/mcp/${encodeURIComponent(e)}/auth`,{method:`POST`,body:JSON.stringify(t??{})})}async deleteAuth(e){return this.req(`/mcp/${encodeURIComponent(e)}/auth`,{method:`DELETE`})}async authCallback(e,t){return this.req(`/mcp/${encodeURIComponent(e)}/auth/callback`,{method:`POST`,body:JSON.stringify(t)})}async authenticate(e,t){return this.req(`/mcp/${encodeURIComponent(e)}/auth/authenticate`,{method:`POST`,body:JSON.stringify(t??{})})}async catalogToml(e){if(!this.reqText)throw Error(`Text request helper unavailable`);return this.reqText(`/mcp/catalog/${encodeURIComponent(e)}/toml`)}},kn=class{constructor(e){this.req=e}async put(e){return this.req(`/memory/put`,{method:`POST`,body:JSON.stringify(e)})}async search(e){return ln(en,await this.req(`/memory/search`,{method:`POST`,body:JSON.stringify(e)}),`/memory/search`,200)}async importPath(e){let t={source:{kind:`path`,path:e.path},format:e.format??`directory`,tier:e.tier??`project`,project_id:e.projectId,session_id:e.sessionId,sync_deletes:e.syncDeletes??!1};return this.req(`/memory/import`,{method:`POST`,body:JSON.stringify(t)})}async list(e){let t=new URLSearchParams;e?.q&&t.set(`q`,e.q),e?.limit!==void 0&&t.set(`limit`,String(e.limit)),e?.offset!==void 0&&t.set(`offset`,String(e.offset)),e?.userId&&t.set(`user_id`,e.userId);let n=t.toString()?`?${t.toString()}`:``;return ln($t,await this.req(`/memory${n}`),`/memory`,200)}async delete(e){return this.req(`/memory/${encodeURIComponent(e)}`,{method:`DELETE`})}async promote(e){return this.req(`/memory/promote`,{method:`POST`,body:JSON.stringify(e)})}async demote(e){let t={id:e.id,run_id:e.runId};return this.req(`/memory/demote`,{method:`POST`,body:JSON.stringify(t)})}async audit(e){let t=new URLSearchParams;e?.run_id&&t.set(`run_id`,e.run_id),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``,r=await this.req(`/memory/audit${n}`);return Array.isArray(r)?{entries:r,count:r.length}:r}async contextResolveUri(e){return ln(an,await this.req(`/memory/context/resolve`,{method:`POST`,body:JSON.stringify({uri:e})}),`/memory/context/resolve`,200)}async contextTree(e,t){let n=new URLSearchParams;n.set(`uri`,e),t!==void 0&&n.set(`max_depth`,String(t));let r=n.toString()?`?${n.toString()}`:``;return ln(on,await this.req(`/memory/context/tree${r}`),`/memory/context/tree`,200)}async contextGenerateLayers(e){return this.req(`/memory/context/layers/generate`,{method:`POST`,body:JSON.stringify({node_id:e})})}async contextDistill(e,t){return ln(sn,await this.req(`/memory/context/distill`,{method:`POST`,body:JSON.stringify({session_id:e,conversation:t})}),`/memory/context/distill`,200)}},An=class{constructor(e){this.req=e}async list(e){let t=e?`?location=${encodeURIComponent(e)}`:``,n=await this.req(`/skills${t}`);return Array.isArray(n)?{skills:n,count:n.length}:n}async get(e){return this.req(`/skills/${encodeURIComponent(e)}`)}async import(e){let t={content:e.content,file_or_path:e.file_or_path??e.fileOrPath,location:e.location,namespace:e.namespace,conflict_policy:e.conflict_policy??e.conflictPolicy};return this.req(`/skills/import`,{method:`POST`,body:JSON.stringify(t)})}async preview(e){let t={content:e.content,file_or_path:e.file_or_path??e.fileOrPath,location:e.location,namespace:e.namespace,conflict_policy:e.conflict_policy??e.conflictPolicy};return this.req(`/skills/import/preview`,{method:`POST`,body:JSON.stringify(t)})}async templates(){let e=await this.req(`/skills/templates`);return Array.isArray(e)?{templates:e,count:e.length}:e}async catalog(){let e=await this.req(`/skills/catalog`),t=Array.isArray(e)?e:[];return{skills:t,count:t.length}}async validate(e){let t={content:e.content,file_or_path:e.file_or_path??e.fileOrPath};return this.req(`/skills/validate`,{method:`POST`,body:JSON.stringify(t)})}async match(e){let t={goal:e.goal,max_matches:e.max_matches??e.maxMatches,threshold:e.threshold};return this.req(`/skills/router/match`,{method:`POST`,body:JSON.stringify(t)})}async evalBenchmark(e){let t={threshold:e.threshold,cases:e.cases.map(e=>({prompt:e.prompt,expected_skill:e.expected_skill??e.expectedSkill}))};return this.req(`/skills/evals/benchmark`,{method:`POST`,body:JSON.stringify(t)})}async evalTriggers(e){let t={skill_name:e.skill_name??e.skillName,prompts:e.prompts,threshold:e.threshold};return this.req(`/skills/evals/triggers`,{method:`POST`,body:JSON.stringify(t)})}async compile(e){let t={skill_name:e.skill_name??e.skillName,goal:e.goal,threshold:e.threshold,max_matches:e.max_matches??e.maxMatches,schedule:e.schedule};return this.req(`/skills/compile`,{method:`POST`,body:JSON.stringify(t)})}async generate(e){return this.req(`/skills/generate`,{method:`POST`,body:JSON.stringify(e)})}async generateInstall(e){let t={prompt:e.prompt,threshold:e.threshold,location:e.location,conflict_policy:e.conflictPolicy,artifacts:e.artifacts?{"SKILL.md":e.artifacts[`SKILL.md`],"workflow.yaml":e.artifacts[`workflow.yaml`],"automation.example.yaml":e.artifacts[`automation.example.yaml`]}:void 0};return this.req(`/skills/generate/install`,{method:`POST`,body:JSON.stringify(t)})}},jn=class{constructor(e){this.req=e}async list(){return this.req(`/packs`)}async inspect(e){return this.req(`/packs/${encodeURIComponent(e)}`)}async install(e){return this.req(`/packs/install`,{method:`POST`,body:JSON.stringify(e)})}async installFromAttachment(e){return this.req(`/packs/install_from_attachment`,{method:`POST`,body:JSON.stringify(e)})}async uninstall(e){return this.req(`/packs/uninstall`,{method:`POST`,body:JSON.stringify(e)})}async export(e){return this.req(`/packs/export`,{method:`POST`,body:JSON.stringify(e)})}async detect(e){return this.req(`/packs/detect`,{method:`POST`,body:JSON.stringify(e)})}async updates(e){let t=await this.req(`/packs/${encodeURIComponent(e)}/updates`)||{},n=Array.isArray(t.updates)?t.updates:[];return{pack_id:pn(t.pack_id)??void 0,name:pn(t.name)??void 0,current_version:pn(t.current_version)??void 0,updates:n}}async update(e,t){let n=await this.req(`/packs/${encodeURIComponent(e)}/update`,{method:`POST`,body:JSON.stringify(t??{})});return{updated:!!n.updated,pack_id:pn(n.pack_id)??void 0,name:pn(n.name)??void 0,current_version:pn(n.current_version)??void 0,target_version:pn(n.target_version)??void 0,reason:pn(n.reason)??void 0}}},Mn=class{constructor(e){this.req=e}async getBindings(){return(await this.req(`/capabilities/bindings`)).bindings}async setBindings(e){return this.req(`/capabilities/bindings`,{method:`PUT`,body:JSON.stringify(e)})}async discovery(){return this.req(`/capabilities/discovery`)}async resolve(e){return this.req(`/capabilities/resolve`,{method:`POST`,body:JSON.stringify(e)})}async readiness(e){return this.req(`/capabilities/readiness`,{method:`POST`,body:JSON.stringify(e)})}},Nn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(e){let t=new URLSearchParams;e?.prefix&&t.set(`prefix`,e.prefix),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return ln(Qt,await this.req(`/resource${n}`),`/resource`,200)}async write(e){return this.req(`/resource`,{method:`PUT`,body:JSON.stringify(e)})}async get(e){return ln(Zt,await this.req(`/resource/${encodeURIComponent(e)}`),`/resource/${e}`,200)}async putKey(e,t,n){return ln(Xt,await this.req(`/resource/${encodeURIComponent(e)}`,{method:`PUT`,body:JSON.stringify({value:t,...n??{}})}),`/resource/${e}`,200)}async patchKey(e,t){return ln(Xt,await this.req(`/resource/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)}),`/resource/${e}`,200)}async delete(e,t){return this.req(`/resource`,{method:`DELETE`,body:JSON.stringify({key:e,...t})})}async deleteKey(e){return this.req(`/resource/${encodeURIComponent(e)}`,{method:`DELETE`})}events(e){let t=new URLSearchParams;e?.sinceSeq!==void 0&&t.set(`since_seq`,String(e.sinceSeq)),e?.tail!==void 0&&t.set(`tail`,String(e.tail));let n=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/resource/events${n}`,this.getToken())}},Pn=class{constructor(e){this.req=e}async createRun(e){return this.req(`/coder/runs`,{method:`POST`,body:JSON.stringify(e)})}async listRuns(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=e?.workflow_mode??e?.workflowMode,r=e?.repo_slug??e?.repoSlug;n&&t.set(`workflow_mode`,n),r&&t.set(`repo_slug`,r);let i=t.toString()?`?${t.toString()}`:``,a=await this.req(`/coder/runs${i}`)??{},o=Array.isArray(a.runs)?a.runs:[];return{runs:o,count:typeof a.count==`number`?a.count:o.length}}async getRun(e){let t=await this.req(`/coder/runs/${encodeURIComponent(e)}`)??{};return{...t,coderRun:t.coder_run??void 0,coder_run:t.coder_run??void 0,run:t.run??void 0}}async getProjectBinding(e){let t=await this.req(`/coder/projects/${encodeURIComponent(e)}/bindings`)??{};return{...t,binding:t.binding??null}}async putProjectBinding(e,t){let n=await this.req(`/coder/projects/${encodeURIComponent(e)}/bindings`,{method:`PUT`,body:JSON.stringify(t)})??{};return{...n,binding:n.binding}}async getProjectGithubInbox(e){let t=await this.req(`/coder/projects/${encodeURIComponent(e)}/github-project/inbox`)??{};return{...t,items:Array.isArray(t.items)?t.items:[],binding:t.binding,project_id:String(t.project_id||t.projectId||``),schema_drift:!!(t.schema_drift??t.schemaDrift),live_schema_fingerprint:String(t.live_schema_fingerprint||t.liveSchemaFingerprint||``)}}async intakeProjectItem(e,t){let n=await this.req(`/coder/projects/${encodeURIComponent(e)}/github-project/intake`,{method:`POST`,body:JSON.stringify(t)})??{};return{...n,coder_run:n.coder_run??void 0,coderRun:n.coder_run??void 0,run:n.run??void 0}}async executeNext(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/execute-next`,{method:`POST`,body:JSON.stringify(t??{})})}async executeAll(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/execute-all`,{method:`POST`,body:JSON.stringify(t??{})})}async createFollowOnRun(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/follow-on-run`,{method:`POST`,body:JSON.stringify(t)})}async approveRun(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t})})}async cancelRun(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({reason:t})})}async listArtifacts(e){let t=await this.req(`/coder/runs/${encodeURIComponent(e)}/artifacts`)??{},n=Array.isArray(t.artifacts)?t.artifacts:[];return{...t,artifacts:n,count:typeof t.count==`number`?t.count:n.length}}async getMemoryHits(e,t){let n=new URLSearchParams;t?.query&&n.set(`q`,t.query),t?.limit!==void 0&&n.set(`limit`,String(t.limit));let r=n.toString()?`?${n.toString()}`:``,i=await this.req(`/coder/runs/${encodeURIComponent(e)}/memory-hits${r}`)??{},a=Array.isArray(i.hits)?i.hits:[];return{...i,hits:a,count:typeof i.count==`number`?i.count:a.length}}async createTriageInspectionReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/triage-inspection-report`,{method:`POST`,body:JSON.stringify(t)})}async createTriageReproductionReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/triage-reproduction-report`,{method:`POST`,body:JSON.stringify(t)})}async createTriageSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/triage-summary`,{method:`POST`,body:JSON.stringify(t)})}async createPrReviewEvidence(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-review-evidence`,{method:`POST`,body:JSON.stringify(t)})}async createPrReviewSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-review-summary`,{method:`POST`,body:JSON.stringify(t)})}async createIssueFixValidationReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/issue-fix-validation-report`,{method:`POST`,body:JSON.stringify(t)})}async createIssueFixSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/issue-fix-summary`,{method:`POST`,body:JSON.stringify(t)})}async createPrDraft(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-draft`,{method:`POST`,body:JSON.stringify(t??{})})}async submitPr(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/pr-submit`,{method:`POST`,body:JSON.stringify(t??{})})}async createMergeReadinessReport(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/merge-readiness-report`,{method:`POST`,body:JSON.stringify(t)})}async createMergeRecommendationSummary(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/merge-recommendation-summary`,{method:`POST`,body:JSON.stringify(t)})}async listMemoryCandidates(e){let t=await this.req(`/coder/runs/${encodeURIComponent(e)}/memory-candidates`)??{},n=Array.isArray(t.candidates)?t.candidates:[];return{...t,candidates:n,count:typeof t.count==`number`?t.count:n.length}}async createMemoryCandidate(e,t){return this.req(`/coder/runs/${encodeURIComponent(e)}/memory-candidates`,{method:`POST`,body:JSON.stringify(t)})}async promoteMemoryCandidate(e,t,n){return this.req(`/coder/runs/${encodeURIComponent(e)}/memory-candidates/${encodeURIComponent(t)}/promote`,{method:`POST`,body:JSON.stringify(n??{})})}},Fn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(){return this.req(`/routines`)}async create(e){let t={...e};return`prompt`in t&&!(`entrypoint`in t)&&(t.entrypoint=t.prompt),this.req(`/routines`,{method:`POST`,body:JSON.stringify(t)})}async update(e,t){return this.req(`/routines/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}async delete(e){await this.req(`/routines/${encodeURIComponent(e)}`,{method:`DELETE`})}async runNow(e){return ln(Jt,await this.req(`/routines/${encodeURIComponent(e)}/run_now`,{method:`POST`,body:JSON.stringify({})}),`/routines/${e}/run_now`,200)}async listRuns(e){let t=new URLSearchParams;e?.routine_id&&t.set(`routine_id`,e.routine_id),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return this.req(`/routines/runs${n}`)}async getRunsForRoutine(e,t=25){return this.req(`/routines/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e){return ln(Yt,await this.req(`/routines/runs/${encodeURIComponent(e)}`),`/routines/runs/${e}`,200)}async listArtifacts(e){return this.req(`/routines/runs/${encodeURIComponent(e)}/artifacts`)}async approveRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async denyRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async pauseRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resumeRun(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async history(e,t){let n=t===void 0?``:`?limit=${t}`,r=await this.req(`/routines/${encodeURIComponent(e)}/history${n}`);return Array.isArray(r)?{history:r,count:r.length}:r}events(e){let t=new URLSearchParams,n=e?.routine_id??e?.routineId;n&&t.set(`routine_id`,n);let r=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/routines/events${r}`,this.getToken(),{signal:e?.signal})}addArtifact(e,t){return this.req(`/routines/runs/${encodeURIComponent(e)}/artifacts`,{method:`POST`,body:JSON.stringify(t)})}},In=class{constructor(e){this.req=e,this.planSessionIds=new Map,this.chatProjectSlug=`workflow-plans-chat`}plannerSessions(){return new Ln(this.req)}rememberSession(e,t){let n=pn(e),r=pn(t?.session_id);!n||!r||this.planSessionIds.set(n,r)}chatSessionTitle(e){let t=e.trim().replace(/\s+/g,` `);return t?t.length>80?`${t.slice(0,77)}...`:t:`Workflow planner chat`}async ensureChatSession(e){let t=pn(e);if(!t)throw Error(`Workflow planner plan ID is required`);let n=this.planSessionIds.get(t);if(n)return n;let r=await this.get(t),i=await this.plannerSessions().create({projectSlug:this.chatProjectSlug,project_slug:this.chatProjectSlug,title:pn(r.plan?.title)??`Workflow planner chat`,goal:pn(r.plan?.title)??``,plan_source:`workflow_plans_chat`,plan:r.plan,conversation:r.conversation,planner_diagnostics:r.planner_diagnostics??void 0,plan_revision:Number(r.plan?.plan_revision??1)||1,last_success_materialization:null}),a=pn(i.session?.session_id);if(!a)throw Error(`Workflow planner session creation failed`);return this.rememberSession(t,i.session),a}async preview(e){return this.req(`/workflow-plans/preview`,{method:`POST`,body:JSON.stringify({prompt:e.prompt,schedule:e.schedule,plan_source:e.plan_source??e.planSource,allowed_mcp_servers:e.allowed_mcp_servers??e.allowedMcpServers,workspace_root:e.workspace_root??e.workspaceRoot,operator_preferences:e.operator_preferences??e.operatorPreferences})})}async apply(e){return this.req(`/workflow-plans/apply`,{method:`POST`,body:JSON.stringify({plan_id:e.plan_id??e.planId,plan:e.plan,creator_id:e.creator_id??e.creatorId,pack_builder_export:e.pack_builder_export??e.packBuilderExport,overlap_decision:e.overlap_decision??e.overlapDecision})})}async chatStart(e){let t=pn((await this.plannerSessions().create({projectSlug:this.chatProjectSlug,project_slug:this.chatProjectSlug,title:this.chatSessionTitle(e.prompt),workspace_root:e.workspace_root??e.workspaceRoot,goal:e.prompt,plan_source:e.plan_source??e.planSource??`workflow_plans_chat`,allowed_mcp_servers:e.allowed_mcp_servers??e.allowedMcpServers,operator_preferences:e.operator_preferences??e.operatorPreferences})).session?.session_id);if(!t)throw Error(`Workflow planner session creation failed`);let n=await this.plannerSessions().start(t,e);return this.rememberSession(n.plan?.plan_id,n.session),n}async get(e){return this.req(`/workflow-plans/${encodeURIComponent(e)}`)}async chatMessage(e){let t=e.plan_id??e.planId,n=await this.ensureChatSession(t??``),r=await this.plannerSessions().message(n,{message:e.message});return this.rememberSession(r.plan?.plan_id??t,r.session),r}async chatReset(e){let t=e.plan_id??e.planId,n=await this.ensureChatSession(t??``),r=await this.plannerSessions().reset(n);return this.rememberSession(r.plan?.plan_id??t,r.session),r}async importPreview(e){return this.req(`/workflow-plans/import/preview`,{method:`POST`,body:JSON.stringify({bundle:e.bundle,creator_id:e.creator_id??e.creatorId,project_slug:e.project_slug??e.projectSlug,title:e.title})})}async importPlan(e){return this.req(`/workflow-plans/import`,{method:`POST`,body:JSON.stringify({bundle:e.bundle,creator_id:e.creator_id??e.creatorId,project_slug:e.project_slug??e.projectSlug,title:e.title})})}},Ln=class{constructor(e){this.req=e,this.kickoffTimeoutMs=2e4,this.operationTimeoutMs=62e4,this.operationPollIntervalMs=1500}async awaitOperation(e,t){let n=pn(e);if(!n)throw Error(`Workflow planner session ID is required`);let r=Date.now()+this.operationTimeoutMs;for(;Date.now()<r;){let e=(await this.get(n)).session,r=e?.operation;if(!r){await mn(this.operationPollIntervalMs);continue}let i=pn(r.request_id);if(t&&i&&i!==t)throw Error(`Workflow planner session was replaced by a newer operation`);let a=(pn(r.status)??``).toLowerCase();if(a===`completed`){let t=r.response;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`Workflow planner completed without a usable response payload`);return Object.assign({},t,{session:e})}if(a===`failed`)throw Error(pn(r.error)??`Workflow planner failed during background execution`);await mn(this.operationPollIntervalMs)}throw Error(`Workflow planner timed out before completion`)}async list(e){let t=new URLSearchParams,n=e?.project_slug??e?.projectSlug;n&&t.set(`project_slug`,n);let r=t.toString()?`?${t.toString()}`:``;return this.req(`/workflow-plans/sessions${r}`)}async create(e){return this.req(`/workflow-plans/sessions`,{method:`POST`,body:JSON.stringify({project_slug:e.project_slug??e.projectSlug,title:e.title,workspace_root:e.workspace_root??e.workspaceRoot,goal:e.goal,notes:e.notes,planner_provider:e.planner_provider??e.plannerProvider,planner_model:e.planner_model??e.plannerModel,plan_source:e.plan_source??e.planSource,plan:e.plan,conversation:e.conversation,planner_diagnostics:e.planner_diagnostics??e.plannerDiagnostics,plan_revision:e.plan_revision??e.planRevision,last_success_materialization:e.last_success_materialization??e.lastSuccessMaterialization,allowed_mcp_servers:e.allowed_mcp_servers??e.allowedMcpServers,operator_preferences:e.operator_preferences??e.operatorPreferences,planning:e.planning})})}async get(e){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}`)}async patch(e,t){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify({title:t.title,workspace_root:t.workspace_root??t.workspaceRoot,goal:t.goal,notes:t.notes,planner_provider:t.planner_provider??t.plannerProvider,planner_model:t.planner_model??t.plannerModel,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,operator_preferences:t.operator_preferences??t.operatorPreferences,planning:t.planning,current_plan_id:t.current_plan_id??t.currentPlanId,draft:t.draft,published_at_ms:t.published_at_ms??t.publishedAtMs,published_tasks:t.published_tasks??t.publishedTasks})})}async duplicate(e,t){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/duplicate`,{method:`POST`,body:JSON.stringify({title:t?.title})})}async delete(e){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}`,{method:`DELETE`})}async start(e,t){let n=await this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/start-async`,{method:`POST`,timeoutMs:this.kickoffTimeoutMs,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})});return this.awaitOperation(e,n.session?.operation?.request_id??null)}async message(e,t){let n=await this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/message-async`,{method:`POST`,timeoutMs:this.kickoffTimeoutMs,body:JSON.stringify({message:t.message})});return this.awaitOperation(e,n.session?.operation?.request_id??null)}async reset(e){return this.req(`/workflow-plans/sessions/${encodeURIComponent(e)}/reset`,{method:`POST`})}},Rn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async list(){return this.req(`/automations`)}async create(e){return this.req(`/automations`,{method:`POST`,body:JSON.stringify(e)})}async update(e,t){return this.req(`/automations/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}async delete(e){await this.req(`/automations/${encodeURIComponent(e)}`,{method:`DELETE`})}async runNow(e){return ln(Jt,await this.req(`/automations/${encodeURIComponent(e)}/run_now`,{method:`POST`,body:JSON.stringify({})}),`/automations/${e}/run_now`,200)}async listRuns(e){let t=new URLSearchParams;e?.automation_id&&t.set(`automation_id`,e.automation_id),e?.limit!==void 0&&t.set(`limit`,String(e.limit));let n=t.toString()?`?${t.toString()}`:``;return this.req(`/automations/runs${n}`)}async getRunsForAutomation(e,t=25){return this.req(`/automations/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e){return ln(Yt,await this.req(`/automations/runs/${encodeURIComponent(e)}`),`/automations/runs/${e}`,200)}async listArtifacts(e){return this.req(`/automations/runs/${encodeURIComponent(e)}/artifacts`)}async approveRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async denyRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async pauseRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resumeRun(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async history(e,t){let n=t===void 0?``:`?limit=${t}`,r=await this.req(`/automations/${encodeURIComponent(e)}/history${n}`);return Array.isArray(r)?{history:r,count:r.length}:r}events(e){let t=new URLSearchParams,n=e?.automation_id??e?.automationId,r=e?.run_id??e?.runId;n&&t.set(`automation_id`,n),r&&t.set(`run_id`,r);let i=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/automations/events${i}`,this.getToken(),{signal:e?.signal})}addArtifact(e,t){return this.req(`/automations/runs/${encodeURIComponent(e)}/artifacts`,{method:`POST`,body:JSON.stringify(t)})}},zn=class{constructor(e,t,n){this.baseUrl=e,this.getToken=t,this.req=n}async create(e){return this.req(`/automations/v2`,{method:`POST`,body:JSON.stringify(e)})}async list(){return this.req(`/automations/v2`)}async get(e){return this.req(`/automations/v2/${encodeURIComponent(e)}`)}async update(e,t){return this.req(`/automations/v2/${encodeURIComponent(e)}`,{method:`PATCH`,body:JSON.stringify(t)})}async delete(e){return this.req(`/automations/v2/${encodeURIComponent(e)}`,{method:`DELETE`})}async runNow(e,t){return this.req(`/automations/v2/${encodeURIComponent(e)}/run_now`,{method:`POST`,body:JSON.stringify({dry_run:t?.dryRun===!0})})}async pause(e,t){return this.req(`/automations/v2/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resume(e){return this.req(`/automations/v2/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({})})}async listRuns(e,t=50){return this.req(`/automations/v2/${encodeURIComponent(e)}/runs?limit=${t}`)}async getRun(e){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}`)}async pauseRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/pause`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async resumeRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/resume`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async recoverRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/recover`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async repairRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/repair`,{method:`POST`,body:JSON.stringify(t)})}async retryTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/retry`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async previewTaskReset(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/reset_preview`)}async continueTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/continue`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async requeueTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/tasks/${encodeURIComponent(t)}/requeue`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async claimBacklogTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/backlog/tasks/${encodeURIComponent(t)}/claim`,{method:`POST`,body:JSON.stringify(n||{})})}async requeueBacklogTask(e,t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/backlog/tasks/${encodeURIComponent(t)}/requeue`,{method:`POST`,body:JSON.stringify({reason:n??``})})}async cancelRun(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/cancel`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async gateDecide(e,t){return this.req(`/automations/v2/runs/${encodeURIComponent(e)}/gate`,{method:`POST`,body:JSON.stringify(t)})}async listHandoffs(e){return this.req(`/automations/v2/${encodeURIComponent(e)}/handoffs`)}events(e){let t=new URLSearchParams,n=e?.automation_id??e?.automationId,r=e?.run_id??e?.runId;n&&t.set(`automation_id`,n),r&&t.set(`run_id`,r);let i=t.toString()?`?${t.toString()}`:``;return dn(`${this.baseUrl}/automations/v2/events${i}`,this.getToken(),{signal:e?.signal})}},Bn=class{constructor(e){this.req=e}async list(){return this.req(`/optimizations`)}async create(e){return this.req(`/optimizations`,{method:`POST`,body:JSON.stringify(e)})}async get(e){return this.req(`/optimizations/${encodeURIComponent(e)}`)}async action(e,t){return this.req(`/optimizations/${encodeURIComponent(e)}/actions`,{method:`POST`,body:JSON.stringify(t)})}async listExperiments(e){return this.req(`/optimizations/${encodeURIComponent(e)}/experiments`)}async getExperiment(e,t){return this.req(`/optimizations/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`)}async applyWinner(e,t){return this.req(`/optimizations/${encodeURIComponent(e)}/experiments/${encodeURIComponent(t)}`,{method:`POST`,body:JSON.stringify({})})}},Vn=class{constructor(e){this.req=e}async listTemplates(e){let t=new URLSearchParams,n=String(e?.workspaceRoot||``).trim();n&&t.set(`workspaceRoot`,n);let r=t.toString()?`?${t.toString()}`:``;return this.req(`/agent-team/templates${r}`)}async createTemplate(e,t){let n=new URLSearchParams,r=String(t?.workspaceRoot||``).trim();r&&n.set(`workspaceRoot`,r);let i=n.toString()?`?${n.toString()}`:``;return this.req(`/agent-team/templates${i}`,{method:`POST`,body:JSON.stringify(e)})}async updateTemplate(e,t,n){let r=new URLSearchParams,i=String(n?.workspaceRoot||``).trim();i&&r.set(`workspaceRoot`,i);let a=r.toString()?`?${r.toString()}`:``;return this.req(`/agent-team/templates/${encodeURIComponent(e)}${a}`,{method:`PATCH`,body:JSON.stringify(t)})}async deleteTemplate(e,t){let n=new URLSearchParams,r=String(t?.workspaceRoot||``).trim();r&&n.set(`workspaceRoot`,r);let i=n.toString()?`?${n.toString()}`:``;return this.req(`/agent-team/templates/${encodeURIComponent(e)}${i}`,{method:`DELETE`})}async composeStandup(e){return this.req(`/agent-standup/compose`,{method:`POST`,body:JSON.stringify({name:e.name,workspace_root:e.workspaceRoot,schedule:e.schedule,participant_template_ids:e.participantTemplateIds,report_path_template:e.reportPathTemplate,model_policy:e.modelPolicy})})}async listInstances(e){let t=new URLSearchParams;e?.missionID&&t.set(`missionID`,e.missionID),e?.parentInstanceID&&t.set(`parentInstanceID`,e.parentInstanceID),e?.status&&t.set(`status`,e.status);let n=t.toString()?`?${t.toString()}`:``;return this.req(`/agent-team/instances${n}`)}async listMissions(){return this.req(`/agent-team/missions`)}async listApprovals(){return this.req(`/agent-team/approvals`)}async spawn(e){return this.req(`/agent-team/spawn`,{method:`POST`,body:JSON.stringify(e)})}async approveSpawn(e,t){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(e)}/approve`,{method:`POST`,body:JSON.stringify({reason:t??``})})}async denySpawn(e,t){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(e)}/deny`,{method:`POST`,body:JSON.stringify({reason:t??``})})}},Hn=class{constructor(e){this.req=e}async list(){return this.req(`/mission`)}async create(e){return this.req(`/mission`,{method:`POST`,body:JSON.stringify(e)})}async get(e){return this.req(`/mission/${encodeURIComponent(e)}`)}async applyEvent(e,t){return this.req(`/mission/${encodeURIComponent(e)}/event`,{method:`POST`,body:JSON.stringify({event:t})})}},Un=`electric_blue`,Wn={"--radius":`0px`,"--border-width":`1px`,"--border-width-strong":`2px`,"--shadow-offset":`2px 2px 0 rgba(0, 0, 0, 0.32)`,"--shadow-offset-lg":`4px 4px 0 rgba(0, 0, 0, 0.32)`,"--clip-primary-cta":`polygon(10% 0, 100% 0, 100% 100%, 0 100%, 0 25%)`},Gn=[{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)`}}],Kn={duration:{fast:.14,normal:.22,slow:.38},easing:{standard:[.22,1,.36,1],soft:[.33,1,.68,1],exit:[.4,0,1,1]},spring:{gentle:{type:`spring`,stiffness:220,damping:26,mass:.9},snappy:{type:`spring`,stiffness:320,damping:30,mass:.82},modal:{type:`spring`,stiffness:280,damping:28,mass:.95},drawer:{type:`spring`,stiffness:340,damping:34,mass:.82}}};function qn(e){let t=String(e||``).trim()||`electric_blue`;return t===`web_control`&&(t=Un),Gn.find(e=>e.id===t)||Gn[0]}function Jn(e){let t=qn(e).id,n=Gn.findIndex(e=>e.id===t);return n<0?Un:Gn[(n+1)%Gn.length].id}function Yn(e,t=typeof document<`u`?document.documentElement:null){let n=qn(e);if(!t)return n;for(let[e,n]of Object.entries(Wn))t.style.setProperty(e,n);for(let[e,r]of Object.entries(n.cssVars))r!=null&&t.style.setProperty(e,r);return t.dataset.theme=n.id,t.style.colorScheme=n.id===`porcelain`?`light`:`dark`,n}function Xn(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}var Zn=`tandem.themeId`;function Qn(){try{return qn(localStorage.getItem(Zn)).id}catch{return Un}}function $n(e){return Yn(e)}function er(e){let t=Yn(e);try{localStorage.setItem(Zn,t.id)}catch{}return t}function tr(){let[e,t]=r(()=>Xn());return m(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(`(prefers-reduced-motion: reduce)`),n=()=>t(e.matches);return n(),typeof e.addEventListener==`function`?(e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)):(e.addListener(n),()=>e.removeListener(n))},[]),e}function nr(e,t,n){return Math.min(n,Math.max(t,e))}function rr({className:e=``,children:t}){return a(`div`,{className:`tcp-glow-layer ${e}`.trim(),children:t})}function ir({className:e=``,children:t}){let n=tr();return a(s.div,{className:e,initial:n?!1:{opacity:0,y:14},animate:n?void 0:{opacity:1,y:0},exit:n?void 0:{opacity:0,y:-10},transition:n?void 0:{duration:Kn.duration.normal,ease:Kn.easing.standard},children:t})}function ar({className:e=``,children:t}){let n=tr();return a(s.div,{className:e,initial:n?!1:`hidden`,animate:n?void 0:`show`,variants:n?void 0:{hidden:{},show:{transition:{staggerChildren:.06,delayChildren:.02}}},children:t})}function or({className:e=``,children:t,as:n=`div`}){let r=tr();return a(n===`section`?s.section:n===`article`?s.article:s.div,{className:e,variants:r?void 0:{hidden:{opacity:0,y:12,scale:.985},show:{opacity:1,y:0,scale:1,transition:{duration:Kn.duration.normal,ease:Kn.easing.standard}}},initial:r?!1:`hidden`,animate:r?void 0:`show`,children:t})}function sr({value:e,format:t=e=>String(e),className:n=``}){let i=tr(),[o,s]=r(()=>Number(e||0)),l=c(Number(e||0));return m(()=>{let t=Number(e||0);if(!Number.isFinite(t)){s(0),l.current=0;return}if(i){s(t),l.current=t;return}let n=l.current,r=t-n;if(!r){s(t),l.current=t;return}let a=performance.now(),o=0,c=e=>{let i=nr((e-a)/420,0,1);s(n+r*(1-(1-i)**3)),i<1?o=window.requestAnimationFrame(c):l.current=t};return o=window.requestAnimationFrame(c),()=>window.cancelAnimationFrame(o)},[i,e]),a(`span`,{className:n,children:t(Number.isFinite(o)?o:0)})}function cr({tone:e=`ok`,text:t,className:n=``}){return a(`span`,{className:`tcp-status-pulse ${e} ${n}`.trim(),children:[a(`span`,{className:`tcp-status-pulse-dot`,"aria-hidden":`true`}),t?a(`span`,{children:t}):null]})}function lr({className:e=``,children:t}){return a(`div`,{className:`tcp-toolbar ${e}`.trim(),children:t})}function ur({className:e=``,title:t,children:n,...r}){return a(`button`,{type:`button`,title:t,className:`tcp-icon-btn ${e}`.trim(),...r,children:n})}function X({tone:e=`info`,className:t=``,children:n}){return a(`span`,{className:`${e===`ok`?`tcp-badge-ok`:e===`warn`?`tcp-badge-warn`:e===`err`?`tcp-badge-err`:e===`ghost`?`tcp-badge tcp-badge-ghost`:`tcp-badge-info`} ${t}`.trim(),children:n})}function dr({title:e,subtitle:t,actions:n,className:r=``,fullHeight:i,children:o}){return a(or,{as:`section`,className:`tcp-panel-card ${i?`flex flex-col h-full`:``} ${r}`.trim(),children:[e||t||n?a(`div`,{className:`tcp-panel-card-head shrink-0`,children:[a(`div`,{className:`min-w-0`,children:[e?a(`h3`,{className:`tcp-title`,children:e}):null,t?a(`p`,{className:`tcp-subtle mt-1`,children:t}):null]}),n?a(`div`,{className:`shrink-0`,children:n}):null]}):null,a(`div`,{className:i?`flex-1 flex flex-col min-h-0`:``,children:o})]})}function fr({text:e,title:t=`Nothing here yet`,action:n,className:r=``}){return a(`div`,{className:`tcp-empty-state ${r}`.trim(),children:[a(`div`,{className:`tcp-empty-state-orb`}),a(`div`,{className:`relative z-10`,children:[a(`div`,{className:`tcp-empty-state-title`,children:t}),a(`p`,{className:`tcp-subtle mt-1`,children:e}),n?a(`div`,{className:`mt-3`,children:n}):null]})]})}function pr({eyebrow:e,title:t,subtitle:n,badges:r,actions:i,className:o=``}){return a(or,{className:`tcp-page-header ${o}`.trim(),children:[a(rr,{className:`tcp-page-header-glow`}),a(`div`,{className:`relative z-10 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between`,children:[a(`div`,{className:`min-w-0`,children:[e?a(`div`,{className:`tcp-page-eyebrow`,children:e}):null,a(`h1`,{className:`tcp-page-title`,children:t}),n?a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:n}):null,r?a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:r}):null]}),i?a(lr,{className:`justify-start lg:justify-end`,children:i}):null]})]})}function mr({className:e=``,mainClassName:t=``,asideClassName:n=``,main:r,aside:i}){return a(`div`,{className:`tcp-split-view ${i?``:`tcp-split-view--solo`} ${e}`.trim(),children:[a(`div`,{className:`min-w-0 ${t}`.trim(),children:r}),i?a(`div`,{className:`min-w-0 ${n}`.trim(),children:i}):null]})}function hr({open:e,title:t,onClose:n,children:r}){let i=tr();return a(l,{children:e?a(s.div,{className:`tcp-drawer-root`,initial:i?!1:{opacity:0},animate:i?void 0:{opacity:1},exit:i?void 0:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-drawer-backdrop`,"aria-label":`Close`,onClick:n}),a(s.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:Kn.spring.drawer,children:[a(`div`,{className:`tcp-drawer-head`,children:[a(`div`,{className:`min-w-0`,children:t?a(`h3`,{className:`tcp-title`,children:t}):null}),a(ur,{title:`Close drawer`,onClick:n,children:a(`i`,{"data-lucide":`x`})})]}),a(`div`,{className:`min-h-0 flex-1 overflow-auto p-4`,children:r})]})]}):null})}function gr({loginMutation:e,savedToken:t,onCheckEngine:n,controlPanelName:i,controlPanelMode:o,controlPanelModeReason:s}){let[c,l]=r(t),[u,d]=r(!0),[f,p]=r(``),[m,h]=r(!1);return a(`main`,{className:`relative min-h-screen overflow-hidden px-5 py-8`,children:[a(rr,{className:`tcp-shell-background`,children:[a(`div`,{className:`tcp-shell-glow tcp-shell-glow-a`}),a(`div`,{className:`tcp-shell-glow tcp-shell-glow-b`})]}),a(`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:[a(`section`,{className:`grid gap-4`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Tandem Control`}),a(`h1`,{className:`tcp-page-title max-w-3xl`,children:`Sign in to continue.`}),a(`p`,{className:`tcp-subtle max-w-2xl text-base`,children:`Enter your engine token to access chat, task board, automations, runs, memory, and settings.`})]}),a(dr,{title:i,subtitle:o===`aca`?`ACA install detected. Authenticate against your Tandem engine to continue.`:`Standalone install detected. Authenticate against your Tandem engine to continue.`,children:a(`form`,{className:`grid gap-3`,onSubmit:t=>{if(t.preventDefault(),!c.trim()){h(!1),p(`Token is required.`);return}e.mutate({token:c.trim(),remember:u})},children:[a(`label`,{className:`text-sm tcp-subtle`,children:`Engine token`}),a(`input`,{className:`tcp-input`,type:`password`,value:c,onInput:e=>l(e.target.value),placeholder:`tk_...`,autoComplete:`off`}),a(`label`,{className:`inline-flex items-center gap-2 text-xs tcp-subtle`,children:[a(`input`,{type:`checkbox`,className:`h-4 w-4 accent-slate-400`,checked:u,onChange:e=>d(e.target.checked)}),`Remember token on this browser`]}),a(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[a(`button`,{disabled:e.isPending,type:`submit`,className:`tcp-btn-primary w-full`,children:[a(`i`,{"data-lucide":`key-round`}),`Sign in`]}),a(`button`,{type:`button`,className:`tcp-btn w-full`,onClick:async()=>{try{let e=await n();h(!0),p(e)}catch(e){h(!1),p(e instanceof Error?e.message:String(e))}},children:[a(`i`,{"data-lucide":`activity`}),`Check engine`]})]}),a(`div`,{className:`min-h-[1.2rem] text-sm ${m?`text-lime-300`:`text-rose-300`}`,children:e.error?.message||f}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-950/30 p-3`,children:[a(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[a(`div`,{className:`font-medium`,children:`Readiness`}),a(cr,{tone:m?`ok`:`warn`,text:m?`Engine reachable`:`Waiting`})]}),a(`p`,{className:`tcp-subtle text-xs`,children:`Connectivity checks are non-destructive and help verify the local panel can reach the engine before authentication.`}),s?a(`p`,{className:`tcp-subtle mt-2 text-xs`,children:s}):null]})]})})]})]})}function _r(e){m(()=>{let t=t=>{(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()===`k`&&(t.preventDefault(),e())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e])}function vr({open:e,onClose:t,actions:n}){let[i,c]=r(``);m(()=>{e||c(``)},[e]),m(()=>{if(!e)return;let n=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]);let u=o(()=>{let e=i.trim().toLowerCase();return e?n.filter(t=>`${t.label} ${t.group}`.toLowerCase().includes(e)):n},[n,i]);return a(l,{children:e?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:a(s.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:e=>e.stopPropagation(),children:[a(`div`,{className:`tcp-doc-header`,children:[a(`h3`,{className:`tcp-doc-title`,children:`Command Palette`}),a(`kbd`,{className:`tcp-subtle text-xs`,children:`Ctrl/Cmd + K`})]}),a(`div`,{className:`p-3`,children:[a(`input`,{autoFocus:!0,value:i,onInput:e=>c(e.target.value),placeholder:`Jump to route or action`,className:`tcp-input`}),a(`div`,{className:`mt-3 grid max-h-[50vh] gap-2 overflow-auto`,children:[u.map(e=>a(`button`,{type:`button`,className:`tcp-btn w-full justify-between`,onClick:()=>{e.onSelect(),t()},children:[a(`span`,{className:`inline-flex items-center gap-1.5`,children:[a(`i`,{"data-lucide":`list`}),a(`span`,{children:e.label})]}),a(`span`,{className:`tcp-subtle text-xs`,children:e.group})]},e.id)),u.length?null:a(`p`,{className:`tcp-subtle px-1 py-2`,children:`No matching action.`})]})]})]})}):null})}var yr=[[`dashboard`,`Dashboard`,`home`],[`chat`,`Chat`,`message-square`],[`planner`,`Planner`,`compass`],[`workflows`,`Workflows`,`network`],[`marketplace`,`Marketplace`,`globe`],[`studio`,`Studio`,`blocks`],[`automations`,`Automations`,`bot`],[`experiments`,`Experiments`,`flask-conical`],[`coding`,`Coder`,`code`],[`agents`,`Agents`,`users`],[`orchestrator`,`Task Board`,`workflow`],[`files`,`Files`,`folder`],[`memory`,`Memory`,`database`],[`runs`,`Runs`,`activity`],[`approvals`,`Approvals`,`shield-check`],[`settings`,`Settings`,`settings`],[`packs`,`Packs`,`package`],[`teams`,`Teams`,`users`],[`channels`,`Channels`,`message-circle`],[`mcp`,`MCP`,`link`],[`bug-monitor`,`Bug Monitor`,`bug-play`],[`packs-detail`,`Packs`,`package`],[`teams-detail`,`Teams`,`users`]],br=[`dashboard`,`chat`,`planner`,`workflows`,`marketplace`,`studio`,`automations`,`experiments`,`coding`,`agents`,`orchestrator`,`bug-monitor`,`files`,`memory`,`runs`,`approvals`,`settings`].map(e=>{let t=yr.find(([t])=>t===e);if(!t)throw Error(`Missing navigation route: ${e}`);return t}),xr={openai:{label:`OpenAI`,keyUrl:`https://platform.openai.com/api-keys`,placeholder:`sk-proj-...`},"openai-codex":{label:`Codex Account`,keyUrl:``,placeholder:`Browser sign-in required`,authMode:`oauth`,description:`Use your ChatGPT/Codex subscription on this machine without pasting a separate API key.`},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_...`},llama_cpp:{label:`llama.cpp`,keyUrl:``,placeholder:`No key required`},ollama:{label:`Ollama`,keyUrl:``,placeholder:`No key required`}},Sr=yr,Cr=br,wr=new Map([[`packs`,`automations`],[`teams`,`automations`],[`feed`,`runs`],[`swarm`,`orchestrator`],[`failure-reporter`,`bug-monitor`]]),Tr=new Set(Sr.map(([e])=>e));function Er(e,t=`dashboard`){return wr.get(String(e||``).trim())||(Tr.has(e)?e:t)}function Dr(e=`dashboard`){return Er((window.location.hash||`#/${e}`).replace(/^#\//,``).split(`?`)[0].split(`/`)[0].trim(),e)}function Or(e){window.location.hash=`#/${e}`}function kr(e={}){let[t,n]=r(()=>Dr()),i=c(t),a=c(e.canNavigate);m(()=>{i.current=t},[t]),m(()=>{a.current=e.canNavigate},[e.canNavigate]),m(()=>{let e=Dr(i.current);window.location.hash!==`#/${e}`&&Or(e)},[]);let o=h((e,t)=>{let r=i.current;return e===r?window.location.hash===`#/${r}`?(n(r),!0):(Or(r),!0):!a.current||a.current(e,r)?window.location.hash===`#/${e}`?(n(e),!0):(Or(e),!0):(t===`hashchange`&&window.location.hash!==`#/${r}`&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}#/${r}`),!1)},[]);return m(()=>{let e=()=>{o(Dr(),`hashchange`)};return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[o]),{route:t,navigate:h(e=>{o(Er(e),`navigate`)},[o])}}var Ar=e({toast:()=>void 0});function jr({children:e}){let[t,n]=r([]),i=h((e,t)=>{let r=Math.random().toString(36).slice(2);n(n=>[...n,{id:r,kind:e,text:t}].slice(-4)),window.setTimeout(()=>{n(e=>e.filter(e=>e.id!==r))},3500)},[]),c=o(()=>({toast:i}),[i]);return a(Ar.Provider,{value:c,children:[e,a(`div`,{className:`toasts`,"aria-live":`polite`,"aria-atomic":`true`,children:a(l,{children:t.map(e=>a(s.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-${e.kind}`,children:e.text},e.id))})})]})}function Mr(){return n(Ar)}function Nr({title:e,subtitle:t,children:n,actions:r,className:i,fullHeight:o}){return a(dr,{title:e,subtitle:t,actions:r,className:i||``,fullHeight:o,children:n})}function Pr({text:e,title:t,action:n}){return a(fr,{text:e,title:t,action:n})}function Fr(e){return JSON.stringify(e,null,2)}function Ir(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Lr({value:e,label:t=`Show raw JSON`,className:n=``,preClassName:i=`tcp-code mt-2 max-h-64 overflow-auto text-[11px]`,hint:s}){let[c,l]=r(!1),u=o(()=>c?Ir(e):``,[c,e]);return a(`details`,{className:n,onToggle:e=>l(e.currentTarget.open),children:[a(`summary`,{className:`cursor-pointer select-none text-xs text-slate-400 hover:text-slate-200`,children:[t,s?a(`span`,{className:`ml-2 text-[10px] text-slate-500`,children:s}):null]}),c?a(`pre`,{className:i,children:u}):null]})}function Rr({value:e,open:t,className:n=`tcp-code mt-2 max-h-32 overflow-auto text-[11px]`}){let r=o(()=>t?Ir(e):``,[t,e]);return t?a(`pre`,{className:n,children:r}):null}function zr(e){return new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(Number(e||0))}function Br(e){return new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`,maximumFractionDigits:4}).format(Number(e||0))}function Vr(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function Hr(e){return String(e||``).trim().replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase()}function Ur(e){return e.ready?e.defaultProvider===`openai-codex`?e.defaultProviderManagedBy===`codex-upload`?`Imported auth.json on hosted server`:e.defaultProviderManagedBy===`codex-cli`?`Mirrored from local Codex CLI`:e.defaultProviderAuthKind===`oauth`?`Codex account session active`:``:e.defaultProviderAuthKind===`oauth`?`OAuth session active`:e.defaultProviderSource===`env`?`Env-managed credentials`:e.defaultProviderSource===`persisted`?`Stored credentials`:``:``}function Wr(e){let{api:t,client:n,navigate:i,providerStatus:s}=e,[c,l]=r(``),[u,d]=r(`day`),f=new Set([`workflow`,`bug_monitor_triage`]),p=y({queryKey:[`dashboard`,`health`],queryFn:()=>t(`/api/system/health`),refetchInterval:15e3}),m=y({queryKey:[`dashboard`,`sessions`],queryFn:()=>n.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),h=y({queryKey:[`dashboard`,`routines`],queryFn:()=>n.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),g=y({queryKey:[`dashboard`,`automation-v2-runs`],queryFn:()=>t(`/api/engine/automations/v2/runs?limit=200`).catch(()=>({runs:[]})),refetchInterval:15e3}),_=y({queryKey:[`dashboard`,`swarm`],queryFn:()=>t(`/api/swarm/status`).catch(()=>({status:`unknown`,activeRuns:0})),refetchInterval:6e3}),v=y({queryKey:[`dashboard`,`workflow-context-runs`],queryFn:()=>t(`/api/engine/context/runs?limit=12`).catch(()=>({runs:[]})),refetchInterval:6e3}),b=y({queryKey:[`dashboard`,`workflow-context-run`,c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}`).catch(()=>({run:null}))}),x=y({queryKey:[`dashboard`,`workflow-context-blackboard`,c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}/blackboard`).catch(()=>({blackboard:null}))}),S=Vr(m.data,`sessions`),C=Vr(h.data,`routines`),w=Vr(g.data,`runs`),T=Vr(v.data,`runs`).filter(e=>f.has(String(e?.run_type||``).trim().toLowerCase())),E=!!(p.data?.engine?.ready||p.data?.engine?.healthy),D=String(_.data?.status||`unknown`),O=[`planning`,`awaiting_approval`,`running`,`executing`].includes(D.toLowerCase()),k=w.filter(e=>[`queued`,`running`,`pausing`,`awaiting_approval`,`blocked`].includes(Hr(e?.status))),A=w.filter(e=>{let t=Number(e?.total_tokens||0),n=Number(e?.estimated_cost_usd||0);return t>0||n>0}),j=w.reduce((e,t)=>({prompt:e.prompt+Number(t?.prompt_tokens||0),completion:e.completion+Number(t?.completion_tokens||0),total:e.total+Number(t?.total_tokens||0),cost:e.cost+Number(t?.estimated_cost_usd||0)}),{prompt:0,completion:0,total:0,cost:0}),M=T.filter(e=>[`queued`,`planning`,`running`,`awaiting_approval`].includes(String(e?.status||``).trim().toLowerCase())),N=Ur(s),P=o(()=>{let e=new Map,t=Date.now(),n,r,i,a;u===`day`?(n=336*60*60*1e3,r=14,i=e=>e.toISOString().slice(0,10),a=e=>{let[,t,n]=e.split(`-`);return`${t}/${n}`}):u===`week`?(n=1344*60*60*1e3,r=8,i=e=>{let t=new Date(e);return t.setDate(e.getDate()-(e.getDay()+6)%7),t.toISOString().slice(0,10)},a=e=>{let[,t,n]=e.split(`-`);return`w/${t}/${n}`}):(n=4320*60*60*1e3,r=6,i=e=>e.toISOString().slice(0,7),a=e=>{let[t,n]=e.split(`-`);return`${n}/${t.slice(2)}`});let o=t-n;for(let t of w){let n=Number(t?.created_at_ms||t?.updated_at_ms||0);if(!n||n<o)continue;let r=new Date(n),s=i(r),c=e.get(s)??{label:a(s),runs:0,tokens:0,cost:0};c.runs+=1,c.tokens+=Number(t?.total_tokens||0),c.cost+=Number(t?.estimated_cost_usd||0),e.set(s,c)}let s=[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0])),c=Math.max(1,...s.map(([,e])=>e.tokens));return{buckets:s.map(([,e])=>e),maxTokens:c,bucketCount:r}},[w,u]),F=o(()=>[{label:`Recent sessions`,value:S.length,tone:`info`,helper:`Latest active conversation surfaces`},{label:`Stored runs`,value:w.length,tone:`ok`,helper:`Persisted automation-v2 history`},{label:`Live runs`,value:k.length,tone:k.length?`warn`:`ghost`,helper:`Queued, running, blocked, awaiting approval`},{label:`Tracked tokens`,value:j.total,tone:j.total?`info`:`ghost`,helper:`${A.length} runs with usage`},{label:`Estimated spend`,value:j.cost,tone:j.cost?`ok`:`ghost`,helper:`Summed from stored run records`,format:Br},{label:`Context runs`,value:T.length,tone:M.length?`warn`:`info`,helper:M.length?`${M.length} active`:`Workflow + triage visibility`}],[M.length,w.length,j.cost,j.total,k.length,S.length,T.length,A.length]);return a(ir,{className:`grid gap-4`,children:[a(dr,{className:`overflow-hidden`,children:[a(`div`,{className:`grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start`,children:a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Overview`}),a(`h1`,{className:`tcp-page-title`,children:`Command center`}),a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:`A higher-signal home screen with animated state and a clearer read on what the system is doing right now.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(X,{tone:E?`ok`:`warn`,children:E?`Engine healthy`:`Engine checking`}),a(X,{tone:s.ready?`ok`:`warn`,children:s.ready?s.defaultProvider:`Provider setup required`}),N?a(X,{tone:`info`,children:N}):null,O?a(cr,{tone:`live`,text:`Swarm ${D}`}):a(X,{tone:`ghost`,children:[`Swarm `,D]})]})]})}),a(`div`,{className:`mt-5`,children:[a(`div`,{className:`dashboard-kpis`,children:F.map(e=>a(`div`,{children:[a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`span`,{className:`dashboard-kpi-label`,children:e.label}),a(X,{tone:e.tone,children:e.helper})]}),a(`strong`,{children:a(sr,{value:e.value,format:e.format??zr})})]},e.label))}),a(`p`,{className:`tcp-subtle mt-3 text-xs`,children:`Usage totals are aggregated from stored automation-v2 run history, so they reflect real executions instead of inferred activity.`}),a(`div`,{className:`mt-4 dashboard-bars`,children:[a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{children:`Engine readiness`}),a(`span`,{className:`dashboard-bar-count`,children:E?`100%`:`45%`})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill completed`,style:{width:E?`100%`:`45%`}})})]}),a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{children:`Provider confidence`}),a(`span`,{className:`dashboard-bar-count`,children:s.ready?`100%`:`30%`})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill ${s.ready?`running`:`queued`}`,style:{width:s.ready?`100%`:`30%`}})})]}),a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{children:`Automation activity`}),a(`span`,{className:`dashboard-bar-count`,children:[k.length,` live`]})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill ${k.length?`running`:`manual`}`,style:{width:`${w.length?Math.min(100,Math.max(12,k.length/w.length*100)):12}%`}})})]})]})]})]}),a(dr,{children:[a(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Usage`}),a(`h2`,{className:`font-semibold`,children:`Token usage over time`})]}),a(`div`,{className:`flex gap-1`,children:[`day`,`week`,`month`].map(e=>a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-xs capitalize ${u===e?`tcp-btn-active`:``}`,onClick:()=>d(e),children:e},e))})]}),P.buckets.length===0?a(`p`,{className:`tcp-subtle text-xs`,children:`No token data in this window yet.`}):a(`div`,{className:`grid gap-2`,children:P.buckets.map(e=>a(`div`,{className:`dashboard-bar-row`,children:[a(`div`,{className:`dashboard-bar-meta`,children:[a(`span`,{className:`font-mono text-xs`,children:e.label}),a(`span`,{className:`dashboard-bar-count`,children:[zr(e.tokens),` tok`,e.cost>0?` · ${Br(e.cost)}`:``,` · `,a(`span`,{className:`tcp-subtle`,children:[e.runs,` run`,e.runs===1?``:`s`]})]})]}),a(`div`,{className:`dashboard-bar-track`,children:a(`span`,{className:`dashboard-bar-fill ${e.tokens>0?`running`:`manual`}`,style:{width:`${Math.max(4,e.tokens/P.maxTokens*100)}%`}})})]},e.label))})]}),a(mr,{main:a(dr,{title:`Recent sessions`,subtitle:`Latest conversations, ready to reopen.`,children:a(`div`,{className:`grid gap-2`,children:S.length?S.map(e=>a(`button`,{className:`tcp-list-item text-left`,onClick:()=>i(`chat`),children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`messages-square`}),String(e.title||e.id||`Session`)]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(e.id||e.session_id||``)})]},String(e.id||e.session_id||Math.random()))):a(Pr,{text:`Start a conversation to populate recent sessions here.`})})}),aside:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`Context visibility`,subtitle:`Recent workflow and failure-triage context runs with their current projection state.`,children:[a(lr,{className:`mb-3`,children:[a(X,{tone:M.length?`warn`:`info`,children:[T.length,` recent`]}),a(`button`,{className:`tcp-btn`,onClick:()=>i(`orchestrator`),children:[a(`i`,{"data-lucide":`workflow`}),`Open task board`]})]}),a(`div`,{className:`grid gap-2`,children:T.length?T.slice(0,5).map(e=>a(`button`,{className:`tcp-list-item text-left`,onClick:()=>l(String(e?.run_id||``).trim()),children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:String(e?.objective||e?.run_id||`Context run`)}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(X,{tone:`ghost`,children:String(e?.run_type||`context`)}),a(X,{tone:[`failed`,`cancelled`].includes(String(e?.status||``).toLowerCase())?`err`:[`running`,`queued`,`planning`].includes(String(e?.status||``).toLowerCase())?`warn`:`ok`,children:String(e?.status||`unknown`)})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:String(e?.run_id||``)}),a(`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()))):a(Pr,{text:`Workflow and failure-triage context runs will appear here once they execute.`})})]}),a(dr,{title:`Automation snapshot`,subtitle:`Schedules and run-ready routines.`,children:[a(lr,{className:`mb-3`,children:[a(X,{tone:`info`,children:[C.length,` loaded`]}),a(`button`,{className:`tcp-btn`,onClick:()=>i(`automations`),children:[a(`i`,{"data-lucide":`bot`}),`Manage`]})]}),a(`div`,{className:`grid gap-2`,children:C.length?C.slice(0,4).map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:String(e.name||e.id||`Routine`)}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(e.schedule||e.status||`manual`)})]},String(e.id||e.routine_id||Math.random()))):a(Pr,{text:`No routines are configured yet.`})})]}),a(dr,{title:`Health notes`,subtitle:`Direct links for the next likely action.`,children:a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`activity`}),`Engine endpoint`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(p.data?.engineUrl||`Unavailable`)})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`radio`}),`Swarm`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[`Status: `,D]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":`database`}),`Memory & runs`]}),a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>i(`memory`),children:`Open memory`}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>i(`runs`),children:`Open runs`})]})]})]})})]})}),a(hr,{open:!!c,onClose:()=>l(``),title:c||`Workflow context run`,children:c?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:String(b.data?.run?.objective||c)}),a(X,{tone:`info`,children:String(b.data?.run?.status||`unknown`)})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`type: `,String(b.data?.run?.run_type||`workflow`)]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium mb-2`,children:`Projected blackboard`}),a(`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]})]}),a(Lr,{value:{run:b.data?.run||null,blackboard:x.data?.blackboard||null},label:`Show run + blackboard`})]}):null})]})}var Gr={Activity:ft,Archive:Me,ArrowDown:Xe,ArrowLeftToLine:yt,ArrowRight:lt,ArrowUpCircle:z,BadgeCheck:Tt,Binary:Be,Blocks:C,Bot:Oe,BookOpen:fe,Bug:Ee,BugPlay:we,Calendar:H,Check:_t,ChevronDown:U,ChevronLeft:L,ChevronRight:Se,ChevronUp:ve,ClipboardList:D,Clock:G,Clock3:zt,Code:re,Compass:B,CornerUpLeft:oe,Copy:ue,CopyPlus:F,Cpu:ae,Database:T,DatabaseZap:$e,Download:tt,Eraser:ce,ExternalLink:j,FilePlus:ge,FileText:k,FileInput:N,Files:Ft,FileSearch:Nt,FileUp:me,Filter:We,FilterX:ht,FlaskConical:Fe,Folder:Je,FolderCode:Lt,FolderOpen:jt,FolderPlus:Ae,FolderUp:Ke,Fullscreen:st,Globe:ze,HardDrive:kt,History:it,Home:Ie,Info:Ct,KeyRound:pt,Layers:Ne,Link:Ze,List:Et,ListChecks:bt,ListX:ut,LoaderCircle:Ve,LogOut:S,Menu:de,MessageCircle:De,MessageSquare:Ce,MessagesSquare:Te,MonitorCog:V,Network:gt,Package:I,PackagePlus:te,PaintBucket:xe,PanelLeft:_e,Paperclip:R,Pause:ye,Pencil:E,Play:Rt,PlugZap:pe,Plus:ne,Radio:P,Radar:ee,RefreshCw:le,Rocket:W,RotateCcw:ie,RotateCw:Qe,Save:w,Search:et,Send:se,Settings:M,Settings2:A,Share2:he,Shield:K,ShieldAlert:Mt,ShieldCheck:O,Siren:Pt,SkipForward:Pe,SlidersHorizontal:It,Sparkles:At,Square:qe,SquareCheckBig:ke,SquarePen:Ge,Star:at,Trash2:mt,TriangleAlert:He,Unlink:Le,Upload:Dt,UserPlus:nt,Users:q,Workflow:xt,X:dt,XCircle:be},Kr=new Set,qr=0;function Jr(){qr=0;let e=[...Kr];Kr.clear();for(let t of e)je({icons:Gr,attrs:{width:`16`,height:`16`,"stroke-width":`1.8`},...t?{root:t}:{}})}function Yr(e){Kr.add(e||null),!qr&&(qr=window.requestAnimationFrame(Jr))}Vt.setOptions({gfm:!0,breaks:!0});function Xr(e){let t=String(e||``),n=Vt.parse(t,{async:!1});return Bt.sanitize(n)}function Zr({messages:e,emptyText:t,inputValue:n,inputPlaceholder:r,sendLabel:i,onInputChange:o,onSend:u,sendDisabled:f=!1,inputDisabled:p=!1,statusTitle:h=``,statusDetail:g=``,questionTitle:_=``,questionText:v=``,quickReplies:y=[],onQuickReply:b,questionHint:x=``,botIdentity:S,streamingText:C=``,showThinking:w=!1,thinkingText:T=`Thinking`,autoFocusKey:E,attachments:D=[],onOpenAttachment:O,onRemoveAttachment:k,onAttach:A,attachDisabled:j=!1,className:M=``}){let N=!!d(),P=c(null),F=c(null),I=c(null),L=c(!0),R=e=>e.scrollHeight-e.scrollTop-e.clientHeight<=24;m(()=>{let e=F.current;e&&L.current&&(e.scrollTop=e.scrollHeight)},[e,C,w]),m(()=>{let e=I.current;e&&(e.style.height=`0px`,e.style.height=`${Math.min(e.scrollHeight,180)}px`)},[n]),m(()=>{if(E==null||p)return;let e=I.current;if(e){e.focus();try{let t=e.value.length;e.setSelectionRange(t,t)}catch{}}},[E,p]),m(()=>{P.current&&Yr(P.current)},[D,n,e,y,f,w,C]);let z=S?.botName||`Assistant`;return a(`div`,{ref:P,className:`rounded-2xl border border-white/10 bg-black/20 p-3 flex min-h-0 flex-1 flex-col ${M}`,children:[v?a(`div`,{className:`mb-3 rounded-xl border border-sky-500/40 bg-sky-950/30 p-3`,children:[a(`div`,{className:`text-xs uppercase tracking-wide text-sky-200`,children:_||`Planner question`}),a(`div`,{className:`mt-1 text-sm font-medium text-sky-100`,children:v}),y.length?a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:y.map(e=>a(`button`,{type:`button`,className:`tcp-btn text-sm`,disabled:p,onClick:()=>b?.(e),children:e.label},e.id))}):null,x?a(`div`,{className:`mt-2 text-xs text-sky-200/80`,children:x}):null]}):null,a(`div`,{ref:F,className:`chat-messages mb-2 min-h-0 min-w-0 flex-1 overflow-auto p-2 space-y-2`,onScroll:()=>{let e=F.current;e&&(L.current=R(e))},children:[e.length?a(l,{initial:!1,children:e.map(e=>{let t=e.role===`assistant`||e.role===`system`;return a(s.article,{className:`chat-msg ${t?`assistant`:`user`}`,initial:N?!1:{opacity:0,y:4},animate:N?void 0:{opacity:1,y:0},exit:N?void 0:{opacity:0,y:-4},children:[a(`div`,{className:`chat-msg-role`,children:t?a(`span`,{className:`inline-flex items-center gap-2`,children:[S?.botAvatarUrl?a(`img`,{src:S.botAvatarUrl,alt:z,className:`chat-avatar-ring h-5 w-5 rounded-full object-cover`}):null,a(`span`,{children:e.displayRole||z})]}):e.displayRole||e.role}),e.markdown?a(`div`,{className:`tcp-markdown tcp-markdown-ai`,dangerouslySetInnerHTML:{__html:Xr(e.text||``)}}):a(`pre`,{className:`chat-msg-pre`,children:e.text||` `})]},e.id)})}):a(`div`,{className:`chat-empty-state`,children:a(`p`,{className:`chat-rail-empty`,children:t})}),w||C?a(`article`,{className:`chat-msg assistant`,children:[a(`div`,{className:`chat-msg-role`,children:a(`span`,{className:`inline-flex items-center gap-2`,children:[S?.botAvatarUrl?a(`img`,{src:S.botAvatarUrl,alt:z,className:`chat-avatar-ring h-5 w-5 rounded-full object-cover`}):null,a(`span`,{children:z})]})}),w&&!C?a(`div`,{className:`tcp-thinking`,"aria-live":`polite`,children:[a(`span`,{children:T}),a(`i`,{}),a(`i`,{}),a(`i`,{})]}):null,C?a(`pre`,{className:`chat-msg-pre`,children:C}):null]}):null]}),h?a(`div`,{className:`mb-2 rounded-xl border border-sky-500/30 bg-sky-950/20 p-3 text-sm text-sky-100`,children:[a(`div`,{className:`flex items-center gap-2 font-medium`,children:[a(`span`,{className:`inline-block h-4 w-4 animate-spin rounded-full border-2 border-sky-200 border-t-transparent`,"aria-hidden":`true`}),h]}),g?a(`div`,{className:`mt-1 text-xs text-sky-200/80`,children:g}):null]}):null,a(`div`,{className:`chat-composer shrink-0`,children:[D.length?a(`div`,{className:`chat-attach-row mb-2 flex flex-wrap items-center gap-2`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:[D.length,` attached`]}),a(`div`,{className:`flex flex-wrap gap-1`,children:D.map((e,t)=>a(`span`,{className:`chat-file-pill min-w-0`,children:[a(`span`,{className:`chat-file-pill-name`,title:e.path,children:e.name||e.path}),e.size==null?null:a(`span`,{className:`chat-file-pill-size`,children:e.size<1024?`${e.size}B`:e.size<1024*1024?`${(e.size/1024).toFixed(1)}KB`:`${(e.size/1024/1024).toFixed(1)}MB`}),O?a(`button`,{type:`button`,className:`chat-file-pill-btn`,title:`Open in Files`,onClick:()=>O(t),children:a(`i`,{"data-lucide":`folder-open`})}):null,k?a(`button`,{type:`button`,className:`chat-file-pill-btn chat-file-pill-btn-danger`,title:`Remove from list`,onClick:()=>k(t),children:a(`i`,{"data-lucide":`x`})}):null]},`${e.path}-${t}`))})]}):null,a(`div`,{className:`chat-input-wrap`,children:[A?a(`button`,{type:`button`,className:`chat-icon-btn chat-icon-btn-inner`,title:`Attach files`,disabled:j,onClick:A,children:a(`i`,{"data-lucide":`paperclip`})}):null,a(`textarea`,{ref:I,rows:1,value:n,className:`tcp-input chat-input-with-clip chat-input-modern resize-none`,placeholder:r,disabled:p,onInput:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),f||u())}}),a(`button`,{type:`button`,className:`chat-send-btn`,title:i,disabled:f,onClick:u,children:a(`i`,{"data-lucide":`send`})})]})]})]})}var Qr=`tcp.chat.session`;function $r(e){return String(e?.id||e?.session_id||e?.sessionID||``).trim()}function ei(e){let t=String(e?.title||e?.name||``).trim();if(t)return t;let n=$r(e);return n?`Session ${n.slice(0,8)}`:`Session`}function ti(e){return Array.isArray(e)?e:Array.isArray(e?.sessions)?e.sessions:[]}function ni(e){return String(e?.title||``).trim().toLowerCase().startsWith(`__provider_test__`)}function ri(e){return ti(e).filter(e=>!ni(e)).map(e=>({id:$r(e),title:ei(e),raw:e})).filter(e=>!!e.id)}async function ii(e,t){try{let t=ri(await e.sessions.list({pageSize:50}));if(t.length>0)return t}catch{}try{return ri(await t(`/api/engine/session?page_size=50`,{method:`GET`}))}catch{return[]}}function ai(){try{return localStorage.getItem(`tcp.chat.session`)||``}catch{return``}}function oi(e){try{e?localStorage.setItem(Qr,e):localStorage.removeItem(Qr)}catch{}}function si(e){return Array.isArray(e)?e.map(e=>e?typeof e==`string`?e:typeof e.text==`string`?e.text:typeof e.delta==`string`?e.delta:typeof e.content==`string`?e.content:``:``).filter(Boolean).join(`
3
3
  `).trim():``}function ci(e){return String(e?.info?.role||e?.role||e?.message_role||e?.type||e?.author||`assistant`).trim().toLowerCase()}function li(e){let t=si(e?.parts);if(t)return t;let n=[e?.content,e?.text,e?.message,e?.delta,e?.body].map(e=>typeof e==`string`?e:``).find(e=>e.trim().length>0);if(n)return n.trim();let r=e?.content;if(Array.isArray(r)){let e=r.map(e=>e?typeof e==`string`?e:typeof e?.text==`string`?e.text:typeof e?.content==`string`?e.content:``:``).filter(Boolean);if(e.length)return e.join(`
4
4
  `).trim()}return``}function ui(e,t){return e===`assistant`?t||`Assistant`:e===`user`?`User`:e===`system`?`System`:e||`Assistant`}function di(e,t,n){let r=ci(e),i=li(e),a=r===`assistant`||r===`system`;return{id:String(e?.id||e?.messageID||e?.message_id||e?.event_id||`${r}-${t}`).trim()||`${r}-${t}`,role:r,displayRole:ui(r,n),text:i,markdown:a}}function fi(e,t){return(Array.isArray(e)?e:Array.isArray(e?.messages)?e.messages:[]).map((e,n)=>di(e,n,t))}var pi=`tandem_control_panel_files_explorer_handoff`,mi=new Set([`uploads`,`artifacts`,`exports`]),hi=`control-panel`;function gi(e){let t=String(e||``).trim().replace(/\\/g,`/`);if(!t)return``;let n=t.lastIndexOf(`/channel_uploads/`),r=(n>=0?t.slice(n+17):t.startsWith(`channel_uploads/`)?t.slice(16):t.replace(/^\/+/,``)).replace(/\/+$/,``);if(!r)return``;let i=r.split(`/`).filter(Boolean);if(!i.length||i.some(e=>e===`.`||e===`..`))return``;let[a,...o]=i;return a===hi?[`uploads`,...o].join(`/`):mi.has(a)?[a,...o].join(`/`):``}function _i(e){return gi(e)}function vi(e){let t=gi(e);if(!t)return``;let n=t.lastIndexOf(`/`);return n<0?``:t.slice(0,n)}function yi(e){try{sessionStorage.setItem(pi,JSON.stringify(e))}catch{}}function bi(e){return gi(e)}function xi(e){return vi(e)}function Si(e){let t=gi(e.path||``);yi({dir:_i(e.dir||``)||(t?mi.has(t)?t:vi(t):``)||void 0,path:t||void 0,atMs:Date.now()})}function Ci(){try{let e=sessionStorage.getItem(pi);if(!e)return null;sessionStorage.removeItem(pi);let t=JSON.parse(e),n=gi(t?.path||``);return{dir:_i(t?.dir||``)||void 0,path:n||void 0,atMs:Number(t?.atMs||0)||Date.now()}}catch{return null}}function wi(e,t){let n=gi(t.path||``),r=_i(t.dir||``)||(n?mi.has(n)?n:vi(n):``);return!n&&!r?!1:(Si({dir:r||void 0,path:n||void 0}),e(`files`),!0)}var Ti=new Set([`tool.called`,`tool_call.started`,`session.tool_call`]),Ei=new Set([`tool.result`,`tool_call.completed`,`tool_call.failed`,`session.tool_result`]),Di=new Set([`run.complete`,`run.completed`,`session.run.finished`,`session.run.completed`]),Oi=new Set([`run.failed`,`session.run.failed`,`run.cancelled`,`run.canceled`,`session.run.cancelled`,`session.run.canceled`]);function ki(e){return String(e||``).trim().replace(/\s+/g,` `).replace(/[<>]/g,``)}function Ai(e){let t=e||{},n=t.call||t.toolCall||t.part||{};return ki(t.tool||t.name||t.toolName||t.tool_id||t.toolID||n.tool||n.name||n.toolName||``)}function ji(e){let t=e||{},n=t.call||t.toolCall||t.part||{};return String(t.callID||t.toolCallID||t.tool_call_id||t.id||n.callID||n.toolCallID||n.tool_call_id||n.id||``).trim()}function Mi(e,t=``){let n=e?.properties||{};return String(e?.runId||e?.runID||e?.run_id||n.runID||n.runId||n.run_id||n.run?.id||t).trim()}function Ni(e){if(!e)return null;let t=e.request||e.approval||e.permission||{},n=String(e.id||e.requestID||e.requestId||e.approvalID||t.id||t.requestID||``).trim();return n?{id:n,tool:ki(e.tool||t.tool||t.name||`tool`)||`tool`,permission:String(e.permission||t.permission||``).trim(),pattern:String(e.pattern||t.pattern||``).trim(),sessionId:String(e.sessionId||e.sessionID||e.session_id||t.sessionId||t.sessionID||``).trim(),status:String(e.status||t.status||``).trim().toLowerCase()}:null}function Pi(e){let t=String(e||``).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 Fi(e,t){let n=t&&typeof t==`object`?t:{},r=String(e||``).trim()||`pack.event`,i=String(n.path||``).trim(),a=String(n.attachment_id||n.attachmentId||``).trim(),o=String(n.connector||``).trim(),s=String(n.channel_id||n.channelId||``).trim(),c=String(n.sender_id||n.senderId||``).trim(),l=String(n.name||``).trim(),u=String(n.version||``).trim(),d=String(n.error||``).trim(),f=[];l&&f.push(l),u&&f.push(u),i&&f.push(i),o&&f.push(o),s&&f.push(`channel=${s}`),c&&f.push(`sender=${c}`);let p=f.join(` · `);return{id:`${r}:${a||i||l||`event`}`,type:r,path:i,attachmentId:a,connector:o,channelId:s,senderId:c,error:d,summary:p||r,at:Date.now()}}var Ii=new Map,Li={channels_open:0,channels_total:0,events_received:0,errors_total:0},Ri=1e3,zi=15e3;function Bi(e,t){return`${t?`cred`:`anon`}:${e}`}function Vi(){let e=0;for(let t of Ii.values())t.closed||(e+=1);Li.channels_open=e,Li.channels_total=Ii.size}function Hi(e){e.reconnectTimer!==null&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null)}function Ui(e,t){Li.events_received+=1;let n={data:t};for(let t of[...e.listeners])try{t(n)}catch{}}function Wi(e,t){Li.errors_total+=1;for(let n of[...e.errorListeners])try{n(t)}catch{}}function Gi(e,t){let n=String(t||``).trim();!n||n===`: keep-alive`||n.startsWith(`:`)||Ui(e,n)}async function Ki(e,t,n){let r=t.getReader(),i=new TextDecoder,a=``,o=``;try{for(;!(n.aborted||e.closed||e.refs===0);){let{done:t,value:n}=await r.read();if(t)break;a+=i.decode(n,{stream:!0});let s=a.split(`
5
5
  `);a=s.pop()??``;for(let t of s){let n=t.replace(/\r$/,``);if(n.startsWith(`data:`)){o+=n.slice(5).trimStart();continue}n===``&&(o&&=(Gi(e,o),``))}}o&&Gi(e,o)}finally{r.releaseLock()}}async function qi(e,t,n,r){if(e.closed||e.refs===0||e.running)return;e.running=!0,Hi(e);let i=new AbortController;e.controller=i;let a=!1;try{let r=await fetch(t,{credentials:n?`include`:`omit`,headers:{Accept:`text/event-stream`,"Cache-Control":`no-cache`},signal:i.signal});if(e.closed||e.refs===0||i.signal.aborted)return;if(!r.ok){let t=await r.text().catch(()=>``);Wi(e,Error(`SSE connect failed (${r.status} ${r.statusText}): ${t}`)),a=!0;return}if(!String(r.headers.get(`content-type`)||``).toLowerCase().includes(`text/event-stream`)||!r.body){a=!0;return}e.reconnectDelayMs=Ri,await Ki(e,r.body,i.signal)}catch(t){!e.closed&&e.refs>0&&!i.signal.aborted&&(Wi(e,t),a=!0)}finally{if(e.controller===i&&(e.controller=null),e.running=!1,!e.closed&&e.refs>0){let i=a?e.reconnectDelayMs:Ri;a?e.reconnectDelayMs=Math.min(Math.max(i,Ri)*2,zi):e.reconnectDelayMs=Ri,e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=null,qi(e,t,n,r)},i)}else Ii.delete(r),Vi()}}function Ji(e,t=!0){let n=Bi(e,t),r=Ii.get(n);if(r&&!r.closed)return r;let i={controller:null,errorListeners:new Set,listeners:new Set,reconnectDelayMs:Ri,reconnectTimer:null,refs:0,closed:!1,running:!1};return Ii.set(n,i),Vi(),i}function Yi(e,t,n={}){let r=n.withCredentials!==!1,i=Bi(e,r),a=Ji(e,r);return a.refs+=1,a.listeners.add(t),typeof n.onError==`function`&&a.errorListeners.add(n.onError),qi(a,e,r,i),()=>{let e=Ii.get(i);e&&(e.listeners.delete(t),typeof n.onError==`function`&&e.errorListeners.delete(n.onError),e.refs=Math.max(0,e.refs-1),e.refs===0&&(e.closed=!0,e.controller?.abort(),Hi(e),Ii.delete(i),Vi()))}}var Xi=`uploads`,Zi=`tandem_control_panel_chat_auto_approve_tools`,Qi=`tandem.automations.plannerSeed`,$i=`tandem.workflow.plannerSeed`,ea={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 ta(e=``){return ea[String(e).toLowerCase().split(`.`).pop()||``]||`application/octet-stream`}function na(e=``,t=``){return!e||!t?t||``:`${String(e).replace(/[\\/]+$/,``)}/${String(t).replace(/^[\\/]+/,``)}`}function ra(e,t){return!e||!t?!0:String(e).trim()===String(t).trim()}function ia(e){let t=String(e||``).trim();return t!==`server.connected`&&t!==`engine.lifecycle.ready`}function aa(e){return e===`completed`?`chat-tool-chip-ok`:e===`failed`?`chat-tool-chip-failed`:`chat-tool-chip-running`}function oa(){try{return localStorage.getItem(Zi)===`1`}catch{return!1}}function sa(e){try{localStorage.setItem(Zi,e?`1`:`0`)}catch{}}function ca(e){try{let t=String(e?.prompt||e?.goal||``).trim();if(!t)return;sessionStorage.setItem(Qi,JSON.stringify({prompt:t,plan_source:String(e?.plan_source||`chat_setup`).trim()||`chat_setup`}))}catch{}}function la(e){try{let t=String(e?.prompt||e?.goal||``).trim();if(!t)return;sessionStorage.setItem($i,JSON.stringify({prompt:t,plan_source:String(e?.plan_source||`chat_setup`).trim()||`chat_setup`,session_id:String(e?.session_id||``).trim()||``,source_platform:String(e?.source_platform||``).trim()||``,source_channel:String(e?.source_channel||``).trim()||``,workspace_root:String(e?.workspace_root||``).trim()||``}))}catch{}}function ua(e){return e instanceof Error?e.message:String(e)}function da(e){if(e.decision===`pass_through`)return null;if(e.intent_kind===`provider_setup`)return{title:`Provider setup`,body:`Configure ${e.slots.provider_ids[0]||`a provider`} in Providers.`,cta:`Open Providers`,actionType:`open_provider_setup`,payload:e.proposed_action.payload||{}};if(e.intent_kind===`integration_setup`)return{title:`Tool connection`,body:`Connect ${e.slots.integration_targets[0]||`the matching tool`} through MCP.`,cta:`Open MCP`,actionType:`open_mcp_setup`,payload:e.proposed_action.payload||{}};if(e.intent_kind===`automation_create`)return{title:`Automation setup`,body:e.slots.goal||`Create an automation from this request.`,cta:`Open Automations`,actionType:`open_automations`,payload:e.proposed_action.payload||{}};if(e.intent_kind===`workflow_planner_create`){let t={...e.proposed_action.payload||{},prompt:String(e.proposed_action.payload?.prompt||e.slots.goal||``).trim()||void 0,plan_source:String(e.proposed_action.payload?.plan_source||``).trim()||`chat_setup`};return{title:e.decision===`clarify`?`Workflow planning questions`:`Workflow planning`,body:e.clarifier?.question||e.slots.goal||`Open the planner to draft a governed workflow plan.`,cta:`Open Planner`,actionType:`open_planner`,payload:t,clarifier:e.clarifier||void 0}}return{title:`Setup help`,body:e.clarifier?.question||`Choose a setup path.`,cta:`Open Providers`,actionType:`open_provider_setup`,payload:e.proposed_action.payload||{},clarifier:e.clarifier||void 0}}function fa({client:e,api:t,toast:n,providerStatus:i,identity:u,navigate:f}){let p=_(),g=!!d(),v=c(null),y=c(null),b=c(null),x=c(null),S=c(null),C=c(!0),w=c(null),T=c(null),[E,D]=r([]),[O,k]=r(!1),[A,j]=r(ai()),[M,N]=r([]),[P,F]=r(!1),[I,L]=r(``),[R,z]=r([]),[ee,B]=r([]),[V,H]=r(!1),[te,U]=r(``),[ne,re]=r(!1),[ie,ae]=r([]),[W,oe]=r(new Set),[se,ce]=r([]),[le,ue]=r(new Set),[de,fe]=r([]),[pe,G]=r(new Set),[K,me]=r(oa()),[he,ge]=r(!1),[_e,ve]=r([]),[ye,be]=r(null),[xe,Se]=r(null),Ce=o(()=>E.find(e=>e.id===A)?.title||`Chat`,[A,E]);m(()=>(C.current=!0,()=>{C.current=!1,S.current?.abort(),w.current&&window.clearTimeout(w.current),T.current&&window.clearTimeout(T.current)}),[]),m(()=>{let e=v.current;e&&Yr(e)},[E,R,ee,de,ie,se,M,O,ne,te]),m(()=>{oi(A)},[A]),m(()=>{let e=y.current;e&&(e.style.height=`0px`,e.style.height=`${Math.min(e.scrollHeight,180)}px`)},[I]),m(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)},[M,te,ne]);let we=h(async()=>{let n=await ii(e,t);C.current&&(D(n),j(e=>{if(e&&n.some(t=>t.id===e))return e;let t=ai();return t&&n.some(e=>e.id===t)?t:n[0]?.id||``}))},[t,e]),Te=h(async()=>{let t=String(i.defaultProvider||``).trim(),n=String(i.defaultModel||``).trim();if(t&&n)return{providerID:t,modelID:n};try{let t=await e.providers.config(),n=String(t?.default||``).trim(),r=String(t?.providers?.[n]?.defaultModel||``).trim();if(n&&r)return{providerID:n,modelID:r}}catch{}return null},[e.providers,i.defaultModel,i.defaultProvider]),Ee=h(async()=>{let t=await Te(),n={title:`Chat ${new Date().toLocaleTimeString()}`};t&&(n.provider=t.providerID,n.model=t.modelID);let r=await e.sessions.create(n),i=String(r||``).trim();if(!i)throw Error(`Failed to create session.`);return j(i),await we(),i},[e.sessions,we,Te]),De=h(e=>{N(fi(e,u.botName||`Assistant`))},[u.botName]),Oe=h(async()=>{if(!A){N([]);return}F(!0);try{let t=await e.sessions.messages(A).catch(()=>({messages:[]}));if(!C.current)return;De(t)}finally{C.current&&F(!1)}},[e.sessions,De,A]),ke=h(()=>{ae([]),oe(new Set)},[]),Ae=h(()=>{ce([]),ue(new Set)},[]),je=h((e,t,n=``)=>{let r=String(e||``).trim();if(!r)return;let i=!0;n&&(oe(e=>{if(e.has(n))return i=!1,e;let t=new Set(e);return t.add(n),t.size>1e3?new Set([n]):t}),!i)||ae(e=>[{id:`${r}:${t}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:r,status:t,at:Date.now()},...e].slice(0,80))},[]),Me=h((e,t)=>{let n=Fi(e,t);if(!String(n.type).toLowerCase().startsWith(`pack.`))return;let r=!0;ue(e=>{if(e.has(n.id))return r=!1,e;let t=new Set(e);return t.add(n.id),t.size>400?new Set([n.id]):t}),r&&ce(e=>[n,...e].slice(0,80))},[]),Ne=h(e=>{Pi(e?.status||``)&&fe(t=>{let n=t.findIndex(t=>t.id===e.id);if(n>=0){let r=[...t];return r[n]={...r[n],...e},r}return[e,...t]})},[]),Pe=h(e=>{fe(t=>t.filter(t=>t.id!==e))},[]),Fe=h(async()=>{let t=await e.permissions.list().catch(()=>({requests:[]})),n=(Array.isArray(t?.requests)?t.requests:[]).map(e=>Ni(e)).filter(e=>!!e).filter(e=>ra(e.sessionId,A)).filter(e=>Pi(e.status));C.current&&fe(n.slice(0,80))},[e.permissions,A]),q=h(async(t,r,i=!1)=>{if(t&&!pe.has(t)){G(e=>{let n=new Set(e);return n.add(t),n});try{await e.permissions.reply(t,r),Pe(t),i||n(`ok`,`Permission ${r===`deny`?`denied`:`approved`} (${t}).`)}catch(e){i||n(`err`,ua(e))}finally{G(e=>{let n=new Set(e);return n.delete(t),n}),Fe()}}},[e.permissions,pe,Fe,Pe,n]),J=h(async()=>{if(!(!K||he||de.length===0)){ge(!0);try{for(let e of[...de])await q(e.id,`always`,!0)}finally{C.current&&ge(!1)}}},[K,he,de,q]),Ie=h(e=>(Array.isArray(e)?e:Array.isArray(e?.tools)?e.tools:[]).map(e=>{if(typeof e==`string`)return e;let t=e||{};return String(t.name||t.id||t.tool||``).trim()}).filter(Boolean),[]),Le=h(async()=>{try{let n=Ie(await e.listTools?.().catch(()=>null)||[]);n.length||(n=Ie(await t(`/api/engine/tool`,{method:`GET`}).catch(()=>[])||[])),C.current&&ve([...new Set(n)].sort((e,t)=>e.localeCompare(t)))}catch{C.current&&ve([])}},[t,e,Ie]),Re=h(e=>new Promise((t,n)=>{let r=`${Date.now()}-${Math.random().toString(16).slice(2)}`;B(t=>[...t,{id:r,name:e.name,progress:0,error:``}]);let i=new XMLHttpRequest;i.open(`POST`,`/api/files/upload?dir=${encodeURIComponent(Xi)}`),i.withCredentials=!0,i.responseType=`json`,i.setRequestHeader(`x-file-name`,encodeURIComponent(e.name)),i.upload.onprogress=e=>{if(!e.lengthComputable)return;let t=e.loaded/e.total*100;B(e=>e.map(e=>e.id===r?{...e,progress:t}:e))},i.onerror=()=>{B(e=>e.map(e=>e.id===r?{...e,error:`Network error`}:e)),window.setTimeout(()=>{B(e=>e.filter(e=>e.id!==r))},1200),n(Error(`Upload failed: ${e.name}`))},i.onload=()=>{let e=i.response||{};if(i.status<200||i.status>=300||e?.ok===!1){let t=String(e?.error||`Upload failed (${i.status})`);B(e=>e.map(e=>e.id===r?{...e,error:t}:e)),window.setTimeout(()=>{B(e=>e.filter(e=>e.id!==r))},1600),n(Error(t));return}B(e=>e.filter(e=>e.id!==r)),t(e)},i.send(e)}),[]),ze=h(async e=>{let t=[...e||[]];if(!t.length)return;let r=0;for(let e of t)try{let t=await Re(e);z(n=>[{name:String(t?.name||e.name),path:String(t?.path||e.name),size:Number(t?.size||e.size||0),mime:e.type||ta(String(t?.name||e.name)),url:String(t?.absPath||na(t?.root,t?.path)||t?.path||e.name)},...n]),r+=1}catch(e){n(`err`,ua(e))}r>0&&n(`ok`,`Uploaded ${r} file${r===1?``:`s`}.`)},[n,Re]),Be=h(async t=>{await e.sessions.delete(t),D(e=>e.filter(e=>e.id!==t)),be(null),n(`ok`,`Session deleted.`),A===t&&j(E.find(e=>e.id!==t)?.id||await Ee())},[e.sessions,Ee,A,E,n]),Ve=h((e,t)=>{let n=String(e||``).trim();if(!n)return;let r=t>0?`\n\n${t} attachment${t===1?``:`s`}`:``;N(e=>[...e,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`user`,displayRole:`User`,text:`${n}${r}`,markdown:!1}])},[]),He=h(async()=>{if(V)return;let r=I.trim(),i=[...R],a=r||(i.length?`Please analyze the attached file(s).`:``);if(a){try{let e=await t(`/api/engine/setup/understand`,{method:`POST`,body:JSON.stringify({surface:`control_panel_chat`,session_id:A||void 0,text:a,channel:null,trigger:{source:`direct_message`,is_direct_message:!0,was_explicitly_mentioned:!1,is_reply_to_bot:!1},scope:{kind:`direct`,id:A||`control-panel-chat`}})});if(e.decision!==`pass_through`){let t=da(e);if(t){Se(t),L(``);return}}}catch{}L(``),H(!0),Ve(a,i.length);try{let t=A;if(t||=await Ee(),!t)throw Error(`No active session.`);let n=await Te();if(!n)throw Error(`No default provider/model configured. Set it in Settings before sending chat.`);let r=i.map(e=>({type:`file`,mime:e.mime||ta(e.name||e.path),filename:e.name||e.path||`attachment`,url:e.url||e.path}));r.push({type:`text`,text:a});let o=async()=>{let e=await fetch(`/api/engine/session/${encodeURIComponent(t)}/run`,{method:`GET`,credentials:`include`});if(!e.ok)return``;let n=await e.json().catch(()=>({}));return n?.active?.runID||n?.active?.runId||n?.active?.run_id||``},s=async()=>{let e=await o().catch(()=>``);e&&await fetch(`/api/engine/session/${encodeURIComponent(t)}/run/${encodeURIComponent(e)}/cancel`,{method:`POST`,credentials:`include`,headers:{"content-type":`application/json`},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent(t)}/cancel`,{method:`POST`,credentials:`include`,headers:{"content-type":`application/json`},body:JSON.stringify({})}).catch(()=>{});for(let e=0;e<50;e+=1){if(!await o().catch(()=>``))return!0;await new Promise(e=>window.setTimeout(e,200))}return!1},c=async()=>fetch(`/api/engine/session/${encodeURIComponent(t)}/prompt_async?return=run`,{method:`POST`,credentials:`include`,headers:{"content-type":`application/json`},body:JSON.stringify({parts:r,model:{providerID:n.providerID,modelID:n.modelID}})}),l=await c(),u=``;if(l.status===409){if(!await s())throw Error(`Session has a stuck active run. Cancel it and retry.`);if(l=await c(),l.ok){let e=await l.json().catch(()=>({}));u=e?.runID||e?.runId||e?.run_id||``}else if(l.status===409)throw Error(`Session is still busy with another run. Retry in a moment.`);else{let e=await l.text().catch(()=>``);throw Error(`prompt_async retry failed (${l.status}): ${e}`)}}else if(l.ok){let e=await l.json().catch(()=>({}));u=e?.runID||e?.runId||e?.run_id||``}else{let e=await l.text().catch(()=>``);throw Error(`prompt_async failed (${l.status}): ${e}`)}if(!u)throw Error(`No run ID returned from engine.`);i.length&&z([]),U(``),re(!0);let d=new AbortController;S.current?.abort(),S.current=d;let f=!1,m=!1,h=``,g=async(e,t)=>{let n=Date.now();for(;Date.now()-n<t;){let t=await o().catch(()=>e);if(await Oe(),!t||t!==e)return!0;await new Promise(e=>window.setTimeout(e,350))}return!1},_=()=>{w.current&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{m=!0,h=`no-events-timeout`,d.abort(`no-events-timeout`)},3e4)};_(),T.current&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{m=!0,h=`max-stream-window`,d.abort(`max-stream-window`)},18e4);try{for await(let n of e.stream(t,u,{signal:d.signal})){let e=n;if(ia(e.type)&&_(),e.type===`approval.requested`||e.type===`permission.request`||e.type===`permission.asked`){let n=Ni(e.properties||{});n&&ra(n.sessionId,t)?(Ne(n),J()):Fe()}if(e.type===`approval.resolved`||e.type===`permission.resolved`||e.type===`permission.replied`){let t=Ni(e.properties||{});t?.id&&Pe(t.id),Fe()}String(e.type||``).toLowerCase().startsWith(`pack.`)&&Me(e.type,e.properties||{});let r=Mi(e);if(!(r&&r!==u)){if(e.type===`session.response`){let t=String(e.properties?.delta||``);if(!t)continue;f=!0,re(!1),U(e=>`${e}${t}`)}if(Ti.has(e.type)){let t=Ai(e.properties)||`tool`;je(t,`started`,`${ji(e.properties)||r||u}:${t}:started`)}if(Ei.has(e.type)){let t=Ai(e.properties)||`tool`,n=ji(e.properties),i=String(e.properties?.status||e.properties?.state||``).toLowerCase(),a=e.type===`tool_call.failed`||i.includes(`fail`)||i.includes(`error`)||!!e.properties?.error;je(t,a?`failed`:`completed`,`${n||r||u}:${t}:${a?`failed`:`completed`}`)}if(e.type===`message.part.updated`){let t=e.properties?.part||{},n=String(t.type||``).trim().toLowerCase().replace(/_/g,`-`),i=Ai(t)||Ai(e.properties),a=ji(t),o=t?.state,s=String((o&&typeof o==`object`?o.status:o)||t.status||``).trim().toLowerCase(),c=!!t.error||!!(o&&typeof o==`object`&&o.error)||s.includes(`fail`)||s.includes(`error`)||s.includes(`deny`)||s.includes(`reject`)||s.includes(`cancel`),l=!!t.result||!!t.output||!!(o&&typeof o==`object`&&(o.output||o.result))||s.includes(`done`)||s.includes(`complete`)||s.includes(`success`);if(i&&(n===`tool`||n===`tool-invocation`)){let e=c?`failed`:l?`completed`:`started`;je(i,e,`${a||r||u}:${i}:${e}`)}i&&n===`tool-result`&&je(i,c?`failed`:`completed`,`${a||r||u}:${i}:${c?`failed`:`completed`}`)}if(Oi.has(e.type))throw Error(String(e.properties?.error||`Run failed.`));if((e.type===`session.updated`||e.type===`session.status`)&&String(e.properties?.status||``).toLowerCase()===`idle`||Di.has(e.type))break}}}catch(e){let t=String(e?.message||e||``).toLowerCase();if(!(m||t.includes(`abort`)||t.includes(`terminated`)||t.includes(`networkerror`)))throw e}finally{w.current&&window.clearTimeout(w.current),T.current&&window.clearTimeout(T.current)}if(m){let e=await g(u,45e3);if(await Oe(),!e)throw Error(`Run stream timed out and the run is still active. Check logs and retry.`)}if(f||re(!0),await Oe(),await new Promise(e=>window.setTimeout(e,180)),await Oe(),await new Promise(e=>window.setTimeout(e,220)),await Oe(),!f&&await o().catch(()=>``)===u)if(await g(u,3e4))await Oe();else throw Error(`Run ${u} is still active without a final response (${h||`stream-ended`}).`);U(``),re(!1),await we(),await p.invalidateQueries({queryKey:[`chat`]}).catch(()=>{})}catch(e){let t=ua(e);n(`err`,t.includes(`no-events-timeout`)||t.includes(`max-stream-window`)||t.includes(`AbortError`)||t.toLowerCase().includes(`terminated`)?`Run stream timed out before events were received. Check engine/provider logs and retry.`:t),await Oe()}finally{C.current&&(H(!1),re(!1))}}},[t,Ve,J,e,Ee,I,p,Me,je,Oe,Fe,we,Pe,Te,A,V,n,R,Ne]);return m(()=>{we(),Le();let e=async()=>{let e=await Ee().catch(()=>``);e&&j(e),k(!1)};window.addEventListener(`tcp:new-chat`,e);let t=window.setInterval(()=>{we()},8e3);return()=>{window.removeEventListener(`tcp:new-chat`,e),window.clearInterval(t)}},[Ee,Le,we]),m(()=>{A&&(S.current?.abort(),k(!1),ke(),Ae(),Fe(),Oe())},[Oe,Fe,Ae,ke,A]),m(()=>{A||N([])},[A]),m(()=>{!A&&E.length===0&&Ee().catch(()=>{})},[Ee,A,E.length]),m(()=>{sa(K),K&&J()},[K,J]),m(()=>{let e=window.setInterval(()=>{A&&Fe()},2500);return()=>window.clearInterval(e)},[Fe,A]),m(()=>{let e=Yi(`/api/global/event`,e=>{let t=null;try{t=JSON.parse(String(e.data||`{}`))}catch{return}let n=String(t?.type||``).trim();if(!n)return;let r=t?.properties||{},i=Ni(r);if(i&&ra(i.sessionId,A)&&((n===`approval.requested`||n===`permission.request`||n===`permission.asked`)&&Ne(i),(n===`approval.resolved`||n===`permission.resolved`||n===`permission.replied`)&&Pe(i.id)),n.toLowerCase().startsWith(`pack.`)&&Me(n,r),Ti.has(n)){let e=Ai(r)||`tool`,n=ji(r),i=Mi(t,`global`);je(e,`started`,`${n||i}:${e}:started`)}if(Ei.has(n)){let e=Ai(r)||`tool`,i=ji(r),a=Mi(t,`global`),o=String(r?.status||r?.state||``).toLowerCase(),s=n===`tool_call.failed`||o.includes(`fail`)||!!r?.error;je(e,s?`failed`:`completed`,`${i||a}:${e}:${s?`failed`:`completed`}`)}},{withCredentials:!0});return()=>e()},[Me,je,Pe,A,Ne]),R.length,!P&&M.length,a(`div`,{ref:v,className:`chat-layout chat-layout-fill min-w-0 min-h-0 h-full w-full flex-1`,children:[a(s.aside,{className:`chat-sessions-panel ${O?`open`:``}`,initial:!1,animate:g?{x:O?0:`-104%`}:{x:O?0:`-104%`,transition:{duration:.18,ease:`easeOut`}},children:[a(`div`,{className:`chat-sessions-header`,children:[a(`h3`,{className:`chat-sessions-title`,children:[a(`i`,{"data-lucide":`history`}),`Sessions`]}),a(`div`,{className:`flex items-center gap-1`,children:[a(`button`,{type:`button`,className:`tcp-btn h-8 px-2.5 text-xs`,onClick:()=>{Ee().catch(e=>n(`err`,ua(e))),k(!1)},children:[a(`i`,{"data-lucide":`plus`}),`New`]}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-2.5 text-xs`,onClick:()=>void we(),children:a(`i`,{"data-lucide":`refresh-cw`})})]})]}),a(`div`,{className:`chat-session-list`,children:[a(l,{children:E.map(e=>a(s.div,{className:`chat-session-row`,initial:g?!1:{opacity:0,y:6},animate:g?void 0:{opacity:1,y:0},exit:g?void 0:{opacity:0,y:-6},children:[a(`button`,{type:`button`,className:`chat-session-btn ${e.id===A?`active`:``}`,title:e.id,onClick:()=>{j(e.id),k(!1)},children:a(`span`,{className:`block truncate`,children:e.title})}),a(`button`,{type:`button`,className:`chat-session-del`,title:`Delete session`,onClick:()=>be({id:e.id,title:e.title}),children:a(`i`,{"data-lucide":`trash-2`})})]},e.id))}),E.length?null:a(`p`,{className:`chat-rail-empty px-1 py-2`,children:`No sessions yet.`})]})]}),a(l,{children:O?a(s.button,{type:`button`,className:`chat-scrim open`,"aria-label":`Close sessions`,initial:g?!1:{opacity:0},animate:g?void 0:{opacity:1},exit:g?void 0:{opacity:0},onClick:()=>k(!1)}):null}),a(`div`,{className:`chat-workspace min-h-0 min-w-0`,children:[a(`section`,{className:`chat-main-shell flex min-h-0 min-w-0 flex-col overflow-hidden`,children:[a(`header`,{className:`chat-main-header shrink-0`,children:[a(`button`,{type:`button`,className:`chat-icon-btn h-8 w-8`,title:`Sessions`,onClick:()=>k(e=>!e),children:a(`i`,{"data-lucide":`history`})}),a(`div`,{className:`chat-main-dot`}),a(`h3`,{className:`tcp-title chat-main-title`,children:Ce}),_e.length?a(`span`,{className:`chat-main-tools`,children:[_e.length,` tools`]}):null]}),xe?a(`div`,{className:`mx-3 mb-2 rounded-xl border border-amber-500/30 bg-amber-500/8 p-3`,children:[a(`div`,{className:`mb-2 flex items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`tcp-title text-sm`,children:xe.title}),a(`div`,{className:`tcp-subtle text-sm`,children:xe.body})]}),a(`button`,{type:`button`,className:`tcp-btn tcp-btn-ghost`,onClick:()=>Se(null),children:`Dismiss`})]}),xe.clarifier?a(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:xe.clarifier.options.map(e=>a(`button`,{type:`button`,className:`tcp-btn tcp-btn-ghost`,onClick:()=>{let t=e.id.startsWith(`workflow_planner_`);Se({title:e.id===`provider_setup`?`Provider setup`:e.id===`integration_setup`?`Tool connection`:t?`Workflow planning`:`Automation setup`,body:e.id===`provider_setup`?`Open Providers to configure a provider.`:e.id===`integration_setup`?`Open MCP to connect the tool you need.`:t?`Open the planner to answer the missing workflow details.`:`Open Automations to build the workflow.`,cta:e.id===`provider_setup`?`Open Providers`:e.id===`integration_setup`?`Open MCP`:t?`Open Planner`:`Open Automations`,actionType:e.id===`provider_setup`?`open_provider_setup`:e.id===`integration_setup`?`open_mcp_setup`:t?`open_planner`:`open_automations`,payload:xe.payload})},children:e.label},e.id))}):null,a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>{xe.actionType===`open_provider_setup`?f(`settings`):xe.actionType===`open_mcp_setup`?f(`mcp`):xe.actionType===`open_planner`?(la(xe.payload),f(`planner`)):xe.actionType===`open_automations`&&(ca(xe.payload),f(`automations`))},children:xe.cta})]}):null,a(Zr,{messages:M.map(e=>({id:e.id,role:e.role,displayRole:e.displayRole,text:e.text,markdown:e.markdown})),emptyText:`No messages yet. Send a prompt to start.`,inputValue:I,inputPlaceholder:`Ask anything... (Enter to send, Shift+Enter newline)`,sendLabel:`Send`,onInputChange:L,onSend:()=>void He(),sendDisabled:V,inputDisabled:V,botIdentity:{botName:u.botName,botAvatarUrl:u.botAvatarUrl},streamingText:te,showThinking:ne,thinkingText:`Thinking`,attachments:R.map(e=>({path:e.path,name:e.path,size:e.size})),onOpenAttachment:e=>{let t=R[e];t?.path&&wi(f,{path:t.path})},onRemoveAttachment:e=>z(t=>t.filter((t,n)=>n!==e)),onAttach:()=>b.current?.click(),attachDisabled:V,statusTitle:V?`Sending…`:``}),a(`input`,{ref:b,type:`file`,className:`hidden`,multiple:!0,onChange:e=>{ze(e.target.files),e.target.value=``}})]}),a(`aside`,{className:`chat-right-rail hidden min-h-0 flex-col gap-3 overflow-hidden xl:flex`,children:[a(`section`,{className:`min-h-0`,children:[a(`div`,{className:`mb-2 flex items-center justify-between`,children:[a(`p`,{className:`chat-rail-label`,children:`Tools`}),a(`span`,{className:`chat-rail-count`,children:_e.length})]}),a(`div`,{className:`chat-tools-list`,children:_e.length?_e.slice(0,32).map(e=>a(`button`,{type:`button`,className:`chat-tool-pill`,title:`Insert ${e}`,onClick:()=>{L(t=>t.trim()?`${t} ${e}`:e),y.current?.focus()},children:e},e)):a(`p`,{className:`chat-rail-empty`,children:`No tools loaded.`})})]}),a(`section`,{className:`min-h-0`,children:[a(`div`,{className:`mb-2 flex items-center justify-between`,children:[a(`p`,{className:`chat-rail-label`,children:`Approvals`}),a(`span`,{className:`chat-rail-count`,children:de.length})]}),a(`div`,{className:`mb-2 flex items-center gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-[11px]`,disabled:!de.length||he,onClick:async()=>{let e=de.map(e=>e.id).filter(Boolean);if(!e.length)return;for(let t of e)await q(t,`once`,!0);await Fe();let t=e.filter(e=>de.some(t=>String(t.id||``).trim()===e)).length;t>0?n(`warn`,`${t} request${t===1?``:`s`} still pending (likely stale/expired).`):n(`ok`,`Approved ${e.length} pending request${e.length===1?``:`s`}.`)},children:`Approve all`}),a(`label`,{className:`chat-auto-approve-label`,children:[a(`input`,{type:`checkbox`,className:`chat-auto-approve-checkbox`,checked:K,onChange:e=>me(e.target.checked)}),`Auto`]})]}),a(`div`,{className:`chat-tools-activity`,children:de.length?de.slice(0,20).map(e=>{let t=pe.has(e.id),n=[e.permission,e.pattern].filter(Boolean).join(` `);return a(`article`,{className:`chat-pack-event-card`,children:[a(`div`,{className:`chat-pack-event-title truncate`,title:e.id,children:e.tool}),a(`div`,{className:`chat-pack-event-summary mt-0.5`,children:n||e.id}),a(`div`,{className:`mt-1 flex gap-1`,children:[a(`button`,{className:`tcp-btn h-6 px-1.5 text-[10px]`,disabled:t,onClick:()=>void q(e.id,`once`),children:`Allow`}),a(`button`,{className:`tcp-btn h-6 px-1.5 text-[10px]`,disabled:t,onClick:()=>void q(e.id,`always`),children:`Always`}),a(`button`,{className:`tcp-btn-danger h-6 px-1.5 text-[10px]`,disabled:t,onClick:()=>void q(e.id,`deny`),children:`Deny`})]})]},e.id)}):a(`p`,{className:`chat-rail-empty`,children:`No pending approvals.`})})]}),a(`section`,{className:`min-h-0 flex-1`,children:[a(`div`,{className:`mb-2 flex items-center justify-between`,children:[a(`p`,{className:`chat-rail-label`,children:`Pack Events`}),a(`div`,{className:`flex items-center gap-2`,children:[a(`span`,{className:`chat-rail-count`,children:se.length}),a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-[11px]`,onClick:()=>{Ae()},children:[a(`i`,{"data-lucide":`trash-2`}),`Clear`]})]})]}),a(`div`,{className:`chat-tools-activity`,children:se.length?se.slice(0,20).map(e=>a(s.article,{className:`chat-pack-event-card`,initial:g?!1:{opacity:0,y:6},animate:g?void 0:{opacity:1,y:0},children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`chat-pack-event-title truncate`,title:e.type,children:e.type}),a(`span`,{className:`chat-pack-event-time`,children:new Date(e.at).toLocaleTimeString()})]}),a(`div`,{className:`chat-pack-event-summary mt-0.5`,children:e.summary}),e.error?a(`div`,{className:`chat-pack-event-error mt-1`,children:e.error}):null,a(`div`,{className:`mt-1 flex flex-wrap gap-1`,children:[a(`button`,{type:`button`,className:`tcp-btn h-6 px-1.5 text-[10px]`,onClick:()=>f(`packs-detail`),children:[a(`i`,{"data-lucide":`package`}),`Packs`]}),e.path?a(`button`,{type:`button`,className:`tcp-btn h-6 px-1.5 text-[10px]`,onClick:async()=>{try{let r=await t(`/api/engine/packs/install`,{method:`POST`,body:JSON.stringify({path:e.path,source:{kind:`control_panel_chat`,event:`pack.detected`}})});n(`ok`,`Installed ${r?.installed?.name||`pack`} ${r?.installed?.version||``}`.trim())}catch(e){n(`err`,`Install failed: ${ua(e)}`)}},children:[a(`i`,{"data-lucide":`download`}),`Install path`]}):null,e.path&&e.attachmentId?a(`button`,{type:`button`,className:`tcp-btn h-6 px-1.5 text-[10px]`,onClick:async()=>{try{let r=await t(`/api/engine/packs/install-from-attachment`,{method:`POST`,body:JSON.stringify({attachment_id:e.attachmentId,path:e.path,connector:e.connector||void 0,channel_id:e.channelId||void 0,sender_id:e.senderId||void 0})});n(`ok`,`Installed ${r?.installed?.name||`pack`} ${r?.installed?.version||``}`.trim())}catch(e){n(`err`,`Install failed: ${ua(e)}`)}},children:[a(`i`,{"data-lucide":`paperclip`}),`Install attach`]}):null]})]},`${e.id}-${e.at}`)):a(`p`,{className:`chat-rail-empty`,children:`No pack events yet.`})})]}),a(`section`,{className:`min-h-0 flex-1`,children:[a(`div`,{className:`mb-2 flex items-center justify-between`,children:[a(`p`,{className:`chat-rail-label`,children:`Tool Activity`}),a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-[11px]`,onClick:ke,children:[a(`i`,{"data-lucide":`trash-2`}),`Clear`]})]}),a(`div`,{className:`chat-tools-activity`,children:ie.length?ie.slice(0,24).map(e=>a(`div`,{className:`chat-tool-chip ${aa(e.status)}`,children:[e.tool,`: `,e.status]},e.id)):a(`p`,{className:`chat-rail-empty`,children:`No tool events yet.`})})]})]})]}),a(l,{children:ye?a(s.div,{className:`tcp-confirm-overlay`,initial:g?!1:{opacity:0},animate:g?void 0:{opacity:1},exit:g?void 0:{opacity:0},onClick:()=>be(null),children:a(s.div,{className:`tcp-confirm-dialog`,initial:g?!1:{opacity:0,y:8,scale:.98},animate:g?void 0:{opacity:1,y:0,scale:1},exit:g?void 0:{opacity:0,y:6,scale:.98},onClick:e=>e.stopPropagation(),children:[a(`h3`,{className:`tcp-confirm-title`,children:`Delete session`}),a(`p`,{className:`tcp-confirm-message`,children:[`This will permanently remove `,a(`strong`,{children:ye.title}),` and all its messages.`]}),a(`div`,{className:`tcp-confirm-actions`,children:[a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>be(null),children:[a(`i`,{"data-lucide":`x`}),`Cancel`]}),a(`button`,{type:`button`,className:`tcp-btn-danger`,onClick:()=>void Be(ye.id).catch(e=>n(`err`,ua(e))),children:[a(`i`,{"data-lucide":`trash-2`}),`Delete session`]})]})]})}):null})]})}function pa(e,t){let n=new Set,r=[];for(let i of[t,...e]){let e=String(i||``).trim();!e||n.has(e)||(n.add(e),r.push(e))}return r}function ma({providerLabel:e,modelLabel:t,draft:n,providers:r,onChange:i,inheritLabel:o=`Workspace default`,disabled:s=!1}){let c=pa(r.find(e=>e.id===n.provider)?.models||[],n.model).filter(e=>{let t=String(n.model||``).trim().toLowerCase();return!t||e.toLowerCase().includes(t)}).slice(0,80);return a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`block text-sm`,children:[a(`div`,{className:`mb-1 flex items-center gap-2 font-medium text-slate-200`,children:[a(`i`,{"data-lucide":`cpu`}),a(`span`,{children:e})]}),a(`select`,{value:n.provider,onInput:e=>{let t=e.target.value;i({provider:t,model:(r.find(e=>e.id===t)?.models||[])[0]||``})},className:`tcp-select h-10 w-full`,disabled:s,children:[a(`option`,{value:``,children:o}),pa(r.map(e=>e.id),n.provider).map(e=>a(`option`,{value:e,children:[e,r.find(t=>t.id===e)?.configured===!1?` (not configured)`:``]},e))]})]}),a(`label`,{className:`block text-sm`,children:[a(`div`,{className:`mb-1 flex items-center gap-2 font-medium text-slate-200`,children:[a(`i`,{"data-lucide":`sparkles`}),a(`span`,{children:t})]}),a(`input`,{className:`tcp-input h-10 w-full`,value:n.model,onInput:e=>i({...n,model:e.target.value}),placeholder:n.provider?`Type to filter models`:o,disabled:s||!n.provider}),a(`div`,{className:`mt-2 max-h-48 overflow-auto rounded-xl border border-slate-700/60 bg-slate-900/20 p-1`,children:n.provider?c.length?c.map(e=>a(`button`,{type:`button`,className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${e===n.model?`bg-slate-700/40`:``}`,onClick:()=>i({...n,model:e}),disabled:s,children:e},e)):a(`div`,{className:`tcp-subtle px-2 py-1 text-xs`,children:`No matching models. Type a model id manually.`}):a(`div`,{className:`tcp-subtle px-2 py-1 text-xs`,children:o})})]})]})}function ha({value:e,error:t=``,open:n,browseDir:r,search:i,parentDir:o,currentDir:s,directories:c,label:l=`Workspace root`,helperText:u=`Select the local workspace folder the planner should inspect.`,onOpen:d,onClose:f,onClear:m,onSearchChange:h,onBrowseParent:g,onBrowseDirectory:_,onSelectDirectory:v}){let y=String(i||``).trim().toLowerCase();return a(p,{children:[a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:l}),a(`div`,{className:`grid gap-2 md:grid-cols-[auto_1fr_auto]`,children:[a(`button`,{className:`tcp-btn h-10 px-3`,type:`button`,onClick:d,children:`Browse`}),a(`input`,{className:`tcp-input text-sm ${t?`border-red-500/70 text-red-100`:``}`,value:e,readOnly:!0,placeholder:`Select a local directory with Browse`}),a(`button`,{className:`tcp-btn h-10 px-3`,type:`button`,onClick:m,disabled:!e,children:`Clear`})]}),a(`span`,{className:`text-xs ${t?`text-red-300`:`tcp-subtle`}`,children:t||u})]}),n?a(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center p-4`,children:[a(`button`,{type:`button`,className:`tcp-confirm-backdrop`,"aria-label":`Close workspace directory dialog`,onClick:f}),a(`div`,{className:`tcp-confirm-dialog max-w-2xl`,children:[a(`h3`,{className:`tcp-confirm-title`,children:`Select Workspace Folder`}),a(`p`,{className:`tcp-confirm-message`,children:[`Current: `,s||r||`n/a`]}),a(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,type:`button`,onClick:g,disabled:!o,children:`Up`}),a(`button`,{className:`tcp-btn-primary`,type:`button`,onClick:v,disabled:!s,children:`Select This Folder`}),a(`button`,{className:`tcp-btn`,type:`button`,onClick:f,children:`Close`})]}),a(`div`,{className:`mb-2`,children:a(`input`,{className:`tcp-input`,placeholder:`Type to filter folders...`,value:i,onInput:e=>h(e.target.value)})}),a(`div`,{className:`max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2`,children:c.length?c.map(e=>a(`button`,{className:`tcp-list-item mb-1 w-full text-left`,type:`button`,onClick:()=>_(String(e?.path||``)),children:a(`span`,{children:String(e?.name||e?.path||``)})},String(e?.path||e?.name))):a(fr,{text:y?`No folders match your search.`:`No subdirectories in this folder.`})})]})]}):null]})}function ga(...e){let t=new Set,n=[];for(let r of e)for(let e of r){let r=ya(e);!r||t.has(r)||(t.add(r),n.push(r))}return n}function _a(e){if(Array.isArray(e))return e.map(e=>ya(e)).filter(Boolean);if(e&&typeof e==`object`)return Object.keys(e).map(e=>ya(e)).filter(Boolean);let t=ya(e);return t?[t]:[]}function va(e){let t=ya(e).toLowerCase();return t.startsWith(`mcp_header::`)||t.startsWith(`channel::`)}function ya(e){return String(e||``).trim()}function ba(e){let t=ya(e);if(!t)return``;let n=(t.split(/\r?\n/).map(e=>e.trim()).find(Boolean)||t).replace(/\s+/g,` `).trim();return n.length<=180?n:`${n.slice(0,177).trimEnd()}...`}function xa(e){let t=Number(e||0);if(!t)return`unknown`;let n=Date.now()-t,r=Math.max(1,Math.round(n/6e4));if(r<60)return`${r}m ago`;let i=Math.round(r/60);return i<24?`${i}h ago`:`${Math.round(i/24)}d ago`}function Sa(e,t=96){let n=ya(e);return n?n.length>t?`${n.slice(0,Math.max(0,t-1)).trimEnd()}…`:n:``}function Ca(e){return Array.isArray(e?.messages)?e.messages:[]}function wa(e){switch(e){case`waiting_for_clarification`:return`Waiting for clarification`;case`ready_to_publish`:return`Ready to publish`;case`published`:return`Published`;case`published_with_new_edits`:return`Published with new edits`;default:return`Draft`}}function Ta(e){switch(e){case`published`:return`ok`;case`ready_to_publish`:return`info`;case`published_with_new_edits`:case`waiting_for_clarification`:return`warn`;default:return`ghost`}}function Ea(e){let t=Number(e.publishedAtMs||0),n=Number(e.updatedAtMs||0);return!t||!n?!1:n>t}function Da(e){let t=e.session||{},n=e.draft||null,r=[...Ca(n?.conversation||t?.draft?.conversation||null)].reverse(),i=r.find(e=>ya(e?.role).toLowerCase()===`assistant`),a=r.find(e=>ya(e?.role).toLowerCase()===`user`);if(e.clarificationState?.status===`waiting`)return Sa(e.clarificationState.question||`Planner needs clarification.`);let o=ya(n?.current_plan?.title||n?.currentPlan?.title||t?.current_plan?.title||t?.plan?.title||t?.title);if(i?.text)return Sa(i.text);if(a?.text)return Sa(a.text);if(o)return Sa(o);let s=ya(t?.goal||n?.goal);return s?Sa(s):`No plan activity yet.`}function Oa(e){let t=e.session||{},n=e.draft||t?.draft||null,r=n?.current_plan||n?.currentPlan||t?.current_plan||null,i=ya(t?.session_id||t?.sessionId),a=Number(t?.updated_at_ms||t?.updatedAtMs||0)||0,o=Number(t?.published_at_ms||t?.publishedAtMs||n?.published_at_ms||0)||null,s=ya(t?.current_plan_id||t?.currentPlanId||r?.plan_id||r?.planId),c=Number(n?.plan_revision||n?.planRevision||r?.plan_revision||r?.planRevision||t?.plan_revision||t?.planRevision||+!!s),l=Ea({publishedAtMs:o,updatedAtMs:a}),u=`draft`;return e.clarificationState?.status===`waiting`?u=`waiting_for_clarification`:o&&l?u=`published_with_new_edits`:o?u=`published`:s&&(u=`ready_to_publish`),{id:i,title:ya(t?.title||r?.title||`Untitled plan`),projectSlug:ya(t?.project_slug||t?.projectSlug),workspaceRoot:ya(t?.workspace_root||t?.workspaceRoot),currentPlanId:s,goal:ya(t?.goal||n?.goal),plannerProvider:ya(t?.planner_provider||t?.plannerProvider),plannerModel:ya(t?.planner_model||t?.plannerModel),updatedAtMs:a,updatedAtLabel:xa(a),previewText:Da({session:t,draft:n,clarificationState:e.clarificationState||null}),status:u,statusLabel:wa(u),statusTone:Ta(u),revisionCount:Number.isFinite(c)?c:+!!s,publishedAtMs:o,hasUnpublishedChanges:l}}function ka(e){let t=Array.isArray(e.providerCatalog?.all)?e.providerCatalog.all:Array.isArray(e.providerCatalog?.providers)?e.providerCatalog.providers:[],n=e.providerConfig?.providers||{},r=new Map;for(let[e,t]of Object.entries(n)){let n=ya(e);!n||va(n)||r.set(n.toLowerCase(),{id:n,value:t})}let i=new Set;if(Array.isArray(e.providerCatalog?.connected))for(let t of e.providerCatalog.connected){let e=ya(t).toLowerCase();e&&i.add(e)}let a=e.providerAuthStatus;if(a&&typeof a==`object`){let e=a.providers,t=e&&typeof e==`object`?e:a;if(t&&typeof t==`object`)for(let[e,n]of Object.entries(t)){let t=ya(e).toLowerCase();if(!t||!n||typeof n!=`object`)continue;let r=ya(n.status).toLowerCase();(n.connected===!0||r===`connected`||r===`configured`||n.has_key===!0||n.hasKey===!0)&&i.add(t)}}let o=e.includeUnconfiguredProviders===!0,s=new Map;for(let e of t){let t=ya(e?.id);if(!t||va(t))continue;let n=t.toLowerCase(),a=r.get(n),c=!!a,l=a?.value||{},u=ga(_a(e?.models),_a(l?.models),_a(l?.default_model||l?.defaultModel));(o||c||i.has(n))&&s.set(n,{id:t,models:u,configured:!!c||i.has(n)})}for(let{id:e,value:t}of r.values()){let n=e.toLowerCase();s.has(n)||s.set(n,{id:e,models:ga(_a(t?.models),_a(t?.default_model||t?.defaultModel)),configured:!0})}for(let e of i)s.has(e)||r.has(e)||va(e)||s.set(e,{id:e,models:[],configured:!0});return[...s.values()].sort((e,t)=>e.id.localeCompare(t.id))}function Aa(e){let t=ba(e);return{knowledge:{enabled:!0,reuse_mode:`preflight`,trust_floor:`promoted`,read_spaces:[{scope:`project`}],promote_spaces:[{scope:`project`}],...t?{subject:t}:{}}}}function ja(e){return{rollout:{rollout_mode:`project_first_pilot`,guardrails:[`Start in one project space before widening scope.`,`Keep reuse_mode at preflight and trust_floor at promoted by default.`,`Promote only validated outcomes; do not treat raw run output as shared truth.`,`Use approved_default sparingly, only for reviewed default guidance.`,`Watch reuse_reason, skip_reason, and freshness_reason during the pilot.`,`Expand namespaces only after the pilot demonstrates stable reuse.`],recommended_sequence:[`Run one workflow once to seed working knowledge.`,`Promote validated outcomes into the project knowledge space.`,`Run a second workflow with the same subject to verify reuse.`,`Check that unrelated workflows still miss the same knowledge key.`],subject:ya(e)||null}}}function Ma(e,t=!0){return(Array.isArray(e?.messages)?e.messages:[]).map((e,n)=>({id:String(e?.created_at_ms||e?.createdAtMs||`${n}`),role:ya(e?.role||`assistant`).toLowerCase(),displayRole:ya(e?.role||`assistant`),text:ya(e?.text||``)||` `,markdown:t}))}var Na=[{id:`automation`,label:`Workflow automation`,detail:`Package the result into a governed automation draft.`},{id:`mission`,label:`Mission execution`,detail:`Shape a mission-style plan with multi-agent handoff and runtime review.`},{id:`coding`,label:`Coder`,detail:`Turn intent into repo-aware work that can publish into coding flows.`},{id:`orchestrator`,label:`Orchestrator`,detail:`Prepare an execution-ready plan for orchestration and approvals.`}],Pa=[{id:`same_day`,label:`Same day`,detail:`Split work into waves that should complete in a single day.`},{id:`multi_day`,label:`Multi-day`,detail:`Break the mission into a plan that spans several days.`},{id:`weekly`,label:`Weekly recurring`,detail:`Plan recurring work that should execute on a weekly cadence.`},{id:`monthly`,label:`Monthly recurring`,detail:`Plan recurring synthesis or review across a monthly cycle.`},{id:`mixed`,label:`Mixed cadence`,detail:`Blend one-time setup work with recurring follow-on work.`}],Fa=[`Plan a week-long multi-agent launch workflow`,`Turn this outcome into a phased mission with approvals`,`Break this into daily work waves and recurring follow-up`];function Ia(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t].sort((e,t)=>e.localeCompare(t))}function La(e){return String(e||``).trim()}function Ra({draft:e,onChange:t,providerOptions:n,plannerCanUseLlm:i,basePlannerLabel:o,availableMcpServers:s,workspaceRootError:c=``,workspaceBrowserOpen:l,workspaceBrowserDir:u,workspaceBrowserSearch:d,workspaceBrowserParentDir:f,workspaceBrowserCurrentDir:p,workspaceBrowserDirectories:h,onOpenWorkspaceBrowser:g,onCloseWorkspaceBrowser:_,onClearWorkspaceRoot:v,onWorkspaceBrowserSearchChange:y,onWorkspaceBrowserParent:b,onWorkspaceBrowserDirectory:x,onSelectWorkspaceDirectory:S,onReset:C,disabled:w=!1}){let[T,E]=r(!1);m(()=>{try{Yr()}catch{}});let D=Na.find(t=>t.id===e.targetSurface),O=Pa.find(t=>t.id===e.planningHorizon),k=Aa(e.goal).knowledge,A=ja(e.goal).rollout,j=La(k.subject||e.goal);return a(`div`,{className:`grid gap-4 min-h-0`,children:[a(`div`,{className:`rounded-2xl border border-emerald-500/10 bg-emerald-500/5 p-3`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(X,{tone:`ok`,children:`planner workbench`}),a(X,{tone:i?`ok`:`warn`,children:i?`model ready`:`model missing`}),a(`div`,{className:`flex-1`}),a(`button`,{type:`button`,className:`tcp-btn h-6 px-2 text-[10px]`,onClick:C,title:`Start a new mission and clear the current planner state`,disabled:w,children:[a(`i`,{"data-lucide":`plus`,className:`mr-1 h-3 w-3`}),`New mission`]})]}),a(`p`,{className:`tcp-subtle mt-2 text-xs`,children:`The planner turns your intent into a structured workflow. Describe the full system — connected agents, schedules, and handoffs — and the planner will decompose it.`})]}),a(`div`,{className:`rounded-2xl border border-cyan-500/10 bg-cyan-500/5 p-3`,children:[a(`div`,{className:`text-xs uppercase tracking-wide text-cyan-200/80`,children:`Knowledge defaults`}),a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(X,{tone:`info`,children:`project scope`}),a(X,{tone:`info`,children:`preflight reuse`}),a(X,{tone:`info`,children:`promoted trust floor`}),j?null:a(X,{tone:`warn`,children:`subject inferred later`})]}),j?a(`div`,{className:`mt-3 rounded border border-white/5 bg-black/20 p-2 text-xs tcp-subtle break-words`,children:[a(`strong`,{className:`text-emerald-500/80 uppercase tracking-wide mr-1`,children:`Subject:`}),a(`span`,{className:`line-clamp-3`,children:j})]}):null,a(`p`,{className:`tcp-subtle mt-2 text-xs`,children:`The planner will start from project-scoped promoted knowledge and reuse prior work before it recomputes. Raw working notes stay local unless they are promoted later.`})]}),a(`div`,{className:`rounded-2xl border border-amber-500/15 bg-amber-500/5 p-3`,children:[a(`div`,{className:`text-xs uppercase tracking-wide text-amber-200/80`,children:`Rollout guardrails`}),a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(X,{tone:`warn`,children:`project-first pilot`}),a(X,{tone:`warn`,children:`promoted only`}),a(X,{tone:`warn`,children:`approved_default rare`})]}),a(`ul`,{className:`tcp-subtle mt-2 space-y-1 text-xs`,children:A.guardrails.map(e=>a(`li`,{children:[`• `,e]},e))})]}),a(ha,{value:e.workspaceRoot,error:c,open:l,browseDir:u,search:d,parentDir:f,currentDir:p,directories:h,helperText:`This folder is required. The planner uses it to inspect the repo and generate the plan.`,onOpen:g,onClose:_,onClear:v,onSearchChange:y,onBrowseParent:b,onBrowseDirectory:x,onSelectDirectory:S}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:`Intent`}),a(`textarea`,{className:`tcp-input min-h-32 text-sm`,value:e.goal,onInput:n=>t({...e,goal:n.target.value}),placeholder:`Describe the long-horizon outcome you want, including what success looks like.`,disabled:w}),a(`div`,{className:`flex flex-wrap gap-2`,children:Fa.map(n=>a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>t({...e,goal:n}),disabled:w,children:n},n))}),a(`span`,{className:`tcp-subtle text-xs`,children:`Keep this high-level. The planner should turn the goal into structure after the first draft.`})]}),a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:`Optional guidance`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Leave this collapsed if you want the planner to infer the setup from your intent.`})]}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>E(e=>!e),disabled:w,children:T?`Hide guidance`:`Add guidance`})]}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`span`,{className:`tcp-badge-info`,children:D?.label||`Mission execution`}),a(`span`,{className:`tcp-badge-info`,children:O?.label||`Mixed cadence`}),a(`span`,{className:`tcp-badge-info`,children:e.selectedMcpServers.length?`${e.selectedMcpServers.length} MCP source${e.selectedMcpServers.length===1?``:`s`}`:`all connected MCP sources`})]}),T?a(`div`,{className:`mt-4 grid gap-4`,children:[a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:`Target surface`}),a(`select`,{className:`tcp-input text-sm`,value:e.targetSurface,onChange:n=>t({...e,targetSurface:n.target.value}),disabled:w,children:Na.map(e=>a(`option`,{value:e.id,children:e.label},e.id))}),a(`div`,{className:`tcp-subtle text-xs`,children:D?.detail})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:`Planning horizon`}),a(`select`,{className:`tcp-input text-sm`,value:e.planningHorizon,onChange:n=>t({...e,planningHorizon:n.target.value}),disabled:w,children:Pa.map(e=>a(`option`,{value:e.id,children:e.label},e.id))}),a(`div`,{className:`tcp-subtle text-xs`,children:O?.detail})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-wide text-slate-500`,children:`Outputs or constraints`}),a(`textarea`,{className:`tcp-input min-h-28 text-sm`,value:[e.outputExpectations,e.constraints].filter(Boolean).join(`
@@ -2893,7 +2893,7 @@ flow:
2893
2893
  `)}function r_(e,t,n){return[`# Task Plan`,``,`- Project: ${n.projectSlug||`unbound`}`,`- Workspace root: ${n.workspaceRoot||`engine workspace root`}`,n.goal?`- Goal: ${n.goal}`:`- Goal: (none)`,`- Planner provider: ${n.plannerProvider||`workspace default`}`,`- Planner model: ${n.plannerModel||`workspace default`}`,n.notes?`- Rework notes: ${n.notes}`:``,e?.title?`- Plan title: ${e.title}`:``,``,`## Tasks`,...t.flatMap((e,t)=>[`### ${t+1}. ${e.title}`,``,e.objective||``,``,e.outputContract?`- Expected result: ${e.outputContract}`:``,e.dependsOn.length?`- Depends on: ${e.dependsOn.join(`, `)}`:``,``]),``,`## Raw Plan`,"```json",JSON.stringify(e||{},null,2),"```"].filter(Boolean).join(`
2894
2894
  `)}function i_(e){let t=Gg(e.defaultProvider),n=Gg(e.defaultModel),r=Gg(e.plannerProvider),i=Gg(e.plannerModel),a={};return t&&n&&(a.model_provider=t,a.model_id=n),r&&i&&(a.role_models={planner:{provider_id:r,model_id:i}}),Object.assign(a,Aa(e.goal)),Object.assign(a,ja(e.goal)),a}function a_({client:e,api:t,toast:n,selectedProjectSlug:i,selectedProject:s,githubProjectBoardSnapshot:l,taskSourceType:u,workspaceRootSeed:d,connectedMcpServers:f,engineHealthy:p,providerStatus:g}){let v=c(null),b=_(),[x,S]=r([]),[C,w]=r({}),[T,E]=r(``),[D,O]=r(!1),[k,A]=r(``),[j,M]=r(``),[N,P]=r(``),[F,I]=r(``),[L,R]=r(``),[z,ee]=r(``),[B,V]=r(null),[H,te]=r(null),[U,ne]=r([]),[re,ie]=r(``),[ae,W]=r(null),[oe,se]=r(!1),[ce,le]=r(!1),[ue,de]=r(!1),[fe,pe]=r(`idle`),[G,K]=r({status:`none`}),[me,he]=r(null),[ge,_e]=r(null),[ve,ye]=r(``),[be,xe]=r(``),[Se,Ce]=r(null),[we,Te]=r(null),[Ee,De]=r([]),Oe=c(``),ke=y({queryKey:[`coding-workflows`,`control-panel-config`,i],queryFn:()=>t(`/api/control-panel/config`)}),Ae=y({queryKey:[`coding-workflows`,`providers`,`catalog`],queryFn:()=>e.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),je=y({queryKey:[`coding-workflows`,`providers`,`config`],queryFn:()=>e.providers.config().catch(()=>({})),refetchInterval:3e4}),Me=o(()=>$g(B),[B]),Ne=String(u||``).trim()===`github_project`,Pe=o(()=>ka({providerCatalog:Ae.data,providerConfig:je.data,defaultProvider:g.defaultProvider,defaultModel:g.defaultModel}),[g.defaultModel,g.defaultProvider,Ae.data,je.data]),Fe=Gg(ke.data?.config?.repository?.path||ke.data?.config?.repository?.worktree_root||``),q=o(()=>Ne?Fe||qg(s)||d||``:String(u||``).trim()===`kanban_board`||String(u||``).trim()===`local_backlog`?Gg(s?.taskSource?.path||d||``):d||``,[Fe,Ne,s,u,d]),J=Ne&&!!Gg(s?.taskSource?.owner)&&!!Gg(s?.taskSource?.repo)&&Number.isFinite(Number(s?.taskSource?.project||0)),Ie=!!(Gg(g.defaultProvider)&&Gg(g.defaultModel)),Le=!!(Gg(L)&&Gg(z)),Re=Gg(L)===Gg(g.defaultProvider)&&Gg(z)===Gg(g.defaultModel),ze=Ie||Le,Be=fe===`generating`,Ve=fe===`clarifying`,He=fe!==`idle`,Ue=Gg(ae?.fallback_reason||ae?.fallbackReason),We=Ue===`clarification_needed`,Ge=Gg(Array.isArray(H?.messages)?[...H.messages].reverse().find(e=>Gg(e?.role).toLowerCase()===`assistant`)?.text:``),Ke=/timed out before completion/i.test(Gg(re))||/timed out before completion/i.test(Ge),qe=o(()=>Ma(H,!1),[H]),Je=He?Be?`Generating task plan…`:Ve?`Waiting for planner…`:`Revising task plan…`:``,Ye=Ve?`The planner is thinking. You'll be able to answer its question shortly.`:`The request is running against the engine now. Repo-aware planning can take a bit longer while the model inspects files and drafts the task breakdown.`,Xe=B?`Send a follow-up message or revision request to the planner. (Enter to send, Shift+Enter newline)`:`Describe the outcome you want and send to planner. (Enter to send, Shift+Enter newline)`,Ze=Me.length===1&&Gg(Me[0]?.id)===`execute_goal`&&(!!Ue||/fallback draft/i.test(Gg(B?.description))),Qe=Ze?[]:Me;m(()=>{Oe.current=T},[T]);let $e=o(()=>{let e=x.find(e=>e.id===T);if(!e)return null;let t=C[e.id];return Zg(e,{...t||{session:null,draft:null,clarification:{status:`none`},planPreview:null,planningConversation:null,planningChangeSummary:[],plannerDiagnostics:null,publishedTasks:[]},clarification:T===e.id?G:t?.clarification||{status:`none`}})},[G,C,x,T]),et=o(()=>x.map(e=>Zg(e,C[e.id])),[C,x]),tt=h(e=>{let t=Oe.current;t&&t!==e&&Ig(i,t,F),E(e),O(!1)},[F,i]),nt=h(e=>{let t=Oe.current;if(!t)return;let{session:n,...r}=e;w(e=>({...e,[t]:{...Qg(),...e[t]||{},session:n?{...e[t]?.session||{},...n||{}}:e[t]?.session||null,...r}}))},[]),rt=e=>{if(e){A(e.goal),M(e.workspaceRoot||q||d||``),P(e.notes),R(e.plannerProvider||g.defaultProvider||``),ee(e.plannerModel||g.defaultModel||``),V(e.plan),te(e.conversation),ne(e.changeSummary||[]),ie(e.plannerError||``),W(e.plannerDiagnostics||null),xe(e.publishedAtMs?`Last published ${new Date(e.publishedAtMs).toLocaleString()}`:``),Te(e.publishedAtMs||null),Ce(e.updatedAtMs||e.publishedAtMs||null),De(e.publishedTasks||[]),K({status:`none`});return}A(``),I(``),M(q||d||``),P(``),R(g.defaultProvider||``),ee(g.defaultModel||``),V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),xe(``),Ce(null),Te(null),De([]),I(``)},it=h(e=>{if(!e)return null;let t=e?.draft||null,n=t?.current_plan||t?.currentPlan||null;return{goal:Gg(e?.goal||n?.title||``),workspaceRoot:Gg(e?.workspace_root||e?.workspaceRoot||``),notes:Gg(e?.notes||``),plannerProvider:Gg(e?.planner_provider||e?.plannerProvider||``),plannerModel:Gg(e?.planner_model||e?.plannerModel||``),plan:n,conversation:t?.conversation||null,changeSummary:[],plannerError:``,plannerDiagnostics:t?.planner_diagnostics||t?.plannerDiagnostics||null,publishedAtMs:Number(e?.published_at_ms||e?.publishedAtMs||0)||null,updatedAtMs:Number(e?.updated_at_ms||e?.updatedAtMs||0)||Date.now(),publishedTasks:Array.isArray(e?.published_tasks||e?.publishedTasks)?e?.published_tasks||e?.publishedTasks:[]}},[q,g.defaultModel,g.defaultProvider,d]),at=h(async()=>{if(!e?.workflowPlannerSessions?.list)return[];let t=await e.workflowPlannerSessions.list({project_slug:i}),n=Array.isArray(t?.sessions)?t.sessions:[];return S(n.map(Yg).filter(e=>e.id).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)),n},[e?.workflowPlannerSessions?.list,i]),ot=h(async t=>{if(!e?.workflowPlannerSessions?.get||!t)return;let n=(await e.workflowPlannerSessions.get(t))?.session||null;if(!n)return;let r=it(n);rt(r),I(Fg(i,t)),xe(n.published_at_ms?`Last published ${new Date(n.published_at_ms).toLocaleString()}`:``),Te(Number(n.published_at_ms||0)||null),Ce(Number(n.updated_at_ms||0)||null),w(e=>({...e,[t]:{session:n,draft:r,clarification:e[t]?.clarification||{status:`none`},planPreview:e[t]?.planPreview||null,planningConversation:e[t]?.planningConversation||null,planningChangeSummary:e[t]?.planningChangeSummary||[],plannerDiagnostics:e[t]?.plannerDiagnostics||null,publishedTasks:e[t]?.publishedTasks||r?.publishedTasks||[]}})),S(e=>{let t=e.filter(e=>e.id!==n.session_id);return t.unshift(Xg(n)),t.sort((e,t)=>t.updatedAtMs-e.updatedAtMs)})},[e?.workflowPlannerSessions?.get,it,i]),st=h(async t=>{if(!(!T||!e?.workflowPlannerSessions?.patch))try{let n=t,r=(await e.workflowPlannerSessions.patch(T,n))?.session;r?.session_id&&(S(e=>{let t=e.filter(e=>e.id!==r.session_id);return t.unshift(Xg(r)),t.sort((e,t)=>t.updatedAtMs-e.updatedAtMs)}),w(e=>({...e,[r.session_id]:{...e[r.session_id]||{session:null,draft:null,clarification:{status:`none`},planPreview:null,planningConversation:null,planningChangeSummary:[],plannerDiagnostics:null,publishedTasks:[]},session:r,draft:n.draft?n.draft:e[r.session_id]?.draft||null,publishedTasks:Array.isArray(n.published_tasks||n.publishedTasks)?n.published_tasks||n.publishedTasks:e[r.session_id]?.publishedTasks||[]}})))}catch{}},[e?.workflowPlannerSessions?.patch,T]);m(()=>{let e=!1;return de(!0),(async()=>{try{let e=await at(),t=jg(i),n=Oe.current,r=!!n&&e.some(e=>Gg(e?.session_id||e?.sessionId)===n),a=!!t&&e.some(e=>Gg(e?.session_id||e?.sessionId)===t),o=r?n:a?t:Gg(e[0]?.session_id||e[0]?.sessionId||``);o&&o!==n?E(o):o||(E(``),Ng(i))}catch{}finally{e||de(!1)}})(),()=>{e=!0}},[e?.workflowPlannerSessions,at,i]),m(()=>{if(!T){rt(null),I(``);return}Mg(i,T);let e=!1;return de(!0),(async()=>{try{if(await ot(T),e)return}catch{e||rt(null)}finally{e||de(!1)}})(),()=>{e=!0}},[ot,i,T]),m(()=>{if(!T)return;let e=!1;return de(!0),(async()=>{try{await ot(T)}catch{rt(null)}finally{e||de(!1)}})(),()=>{e=!0}},[T,ot,q,d,g.defaultProvider,g.defaultModel]),m(()=>{if(!(typeof sessionStorage>`u`))try{let t=sessionStorage.getItem(Wg);if(!t)return;sessionStorage.removeItem(Wg);let n=JSON.parse(t);if(!e?.workflowPlannerSessions?.create)return;(async()=>{let t=(await e.workflowPlannerSessions.create({project_slug:i,title:Jg({goal:n?.goal,plan:n?.plan,fallbackTime:Date.now()}),workspace_root:Gg(n?.workspaceRoot||n?.workspace_root||d),goal:Gg(n?.goal),notes:Gg(n?.notes),planner_provider:Gg(n?.plannerProvider||n?.planner_provider),planner_model:Gg(n?.plannerModel||n?.planner_model),plan_source:`coding_task_planning`,plan:n?.plan??null,conversation:n?.conversation??null,planner_diagnostics:n?.plannerDiagnostics??null,plan_revision:n?.plan?.plan_revision??1,last_success_materialization:n?.lastSuccessMaterialization??null,allowed_mcp_servers:Array.isArray(n?.allowedMcpServers)?n.allowedMcpServers:f,operator_preferences:n?.operatorPreferences??null}))?.session;t?.session_id&&(S(e=>[Xg(t),...e.filter(e=>e.id!==t.session_id)].sort((e,t)=>t.updatedAtMs-e.updatedAtMs)),E(t.session_id),rt(it(t)),xe(`Planner handoff loaded from Planner page.`))})()}catch{}},[e?.workflowPlannerSessions?.create,f,it,i,d]),m(()=>{!j&&q&&M(q)},[q,j]),m(()=>{ie(``),W(null),ye(``)},[L,z]),m(()=>{if(ue||!T)return;let e=B||null,t=Gg(e?.plan_id||``),n=e&&e.plan_id?{initial_plan:e,current_plan:e,plan_revision:Number(e.plan_revision||1)||1,conversation:H||{conversation_id:`wfchat-${T}`,plan_id:e.plan_id,created_at_ms:Date.now(),updated_at_ms:Date.now(),messages:[]},planner_diagnostics:ae,last_success_materialization:null}:void 0;st({title:Jg({goal:k,plan:e,fallbackTime:Se||Date.now()}),workspace_root:j,goal:k,notes:N,planner_provider:L,planner_model:z,plan_source:`coding_task_planning`,allowed_mcp_servers:f,operator_preferences:i_({plannerProvider:L,plannerModel:z,defaultProvider:g.defaultProvider,defaultModel:g.defaultModel,selectedProjectSlug:i,taskSourceType:u,selectedProject:s,goal:k,notes:N}),current_plan_id:t||void 0,draft:n,published_at_ms:we||void 0,published_tasks:Ee.length?Ee:void 0})},[f,k,Se,ue,N,B,ae,re,U,H,Ee,we,i,T,u,z,L,st,j,g.defaultProvider,g.defaultModel,s]);let ct=async()=>{if(e?.workflowPlannerSessions?.create)try{Oe.current&&Ig(i,Oe.current,F);let t=Oe.current?``:F,r=(await e.workflowPlannerSessions.create({project_slug:i,title:Jg({goal:``,fallbackTime:Date.now()}),workspace_root:q||d||j||``,goal:``,notes:``,planner_provider:L,planner_model:z,plan_source:`coding_task_planning`,allowed_mcp_servers:f,operator_preferences:i_({plannerProvider:L,plannerModel:z,defaultProvider:g.defaultProvider,defaultModel:g.defaultModel,selectedProjectSlug:i,taskSourceType:u,selectedProject:s,goal:``,notes:``})}))?.session;r?.session_id&&(S(e=>[Xg(r),...e.filter(e=>e.id!==r.session_id)].sort((e,t)=>t.updatedAtMs-e.updatedAtMs)),Lg(i,r.session_id),tt(r.session_id),rt(it(r)),I(t||Fg(i,r.session_id)),n(`ok`,`Started a new planner session.`))}catch(e){n(`err`,e instanceof Error?e.message:String(e))}},lt=async t=>{let n=x.find(e=>e.id===t);!n||!e?.workflowPlannerSessions?.patch||he({sessionId:t,value:n.title||`Untitled plan`})},ut=async()=>{let t=me;if(!t||!e?.workflowPlannerSessions?.patch)return;let r=Gg(t.value);if(!r){n(`warn`,`Enter a session name.`);return}try{let i=(await e.workflowPlannerSessions.patch(t.sessionId,{title:r}))?.session;i?.session_id&&(S(e=>e.filter(e=>e.id!==i.session_id).concat(Xg(i)).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)),w(e=>({...e,[i.session_id]:{...e[i.session_id]||{session:null,draft:null,clarification:{status:`none`},planPreview:null,planningConversation:null,planningChangeSummary:[],plannerDiagnostics:null,publishedTasks:[]},session:i}})),Oe.current===t.sessionId&&tt(i.session_id)),he(null),n(`ok`,`Planner session renamed.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}},dt=async t=>{let r=x.find(e=>e.id===t);if(!(!r||!e?.workflowPlannerSessions?.duplicate))try{let a=(await e.workflowPlannerSessions.duplicate(t,{title:`Copy of ${r.title||`Untitled plan`}`}))?.session;a?.session_id&&(S(e=>e.filter(e=>e.id!==a.session_id).concat(Xg(a)).sort((e,t)=>t.updatedAtMs-e.updatedAtMs)),Lg(i,a.session_id),tt(a.session_id)),n(`ok`,`Planner session duplicated.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}},ft=async e=>{let t=x.find(t=>t.id===e);t&&_e({sessionId:e,title:t.title||`Untitled plan`})},pt=async()=>{let t=ge;if(t)try{await e.workflowPlannerSessions.delete(t.sessionId);let r=x.filter(e=>e.id!==t.sessionId);if(S(r),w(e=>{let n={...e};return delete n[t.sessionId],n}),Lg(i,t.sessionId),Oe.current===t.sessionId){let e=r[0]?.id||``;e?tt(e):ct()}_e(null),n(`ok`,`Planner session deleted.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}},mt=async t=>{let r=Gg(t??F??k),a=Gg(j);if(!r){n(`warn`,`Describe the goal you want to turn into tasks.`);return}if(!a){n(`warn`,`Workspace root is required so the planner can inspect the repo.`);return}if(!a.startsWith(`/`)){n(`warn`,`Workspace root must be an absolute path.`);return}if(!T){n(`warn`,`Start a planner session first.`);return}if(!e?.workflowPlannerSessions?.start){n(`err`,`This control panel build is missing workflow planner support.`);return}ye(``),ie(``),W(null),A(r);let o=`idle`;pe(`generating`);try{let t=await e.workflowPlannerSessions.start(T,{prompt:[`Create a Tandem workflow plan for the repo at ${a} to implement this goal: ${r}`,`Use small ordered implementation steps.`,`Prefer step objectives that mention likely files, modules, or repo areas to inspect or change.`,`If the target or desired outcome is ambiguous, return a clarification question instead of guessing.`,Gg(s?.repoUrl)?`Repo URL: ${Gg(s?.repoUrl)}`:``,i?`Selected project: ${i}`:``,N?`User feedback / revision notes:\n${N}`:``].filter(Boolean).join(`
2895
2895
  `),plan_source:`coding_task_planning`,workspace_root:a,allowed_mcp_servers:f,operator_preferences:i_({plannerProvider:L,plannerModel:z,defaultProvider:g.defaultProvider,defaultModel:g.defaultModel,selectedProjectSlug:i,taskSourceType:u,selectedProject:s,goal:r,notes:N})});V(t?.plan||null),te(t?.conversation||null),ne([]),W(t?.planner_diagnostics||t?.plannerDiagnostics||null);let c=typeof t?.clarifier?.question==`string`?String(t.clarifier.question):``,l=Array.isArray(t?.clarifier?.options)?t.clarifier.options.map(e=>({id:String(e?.id||``),label:String(e?.label||``)})).filter(e=>e.id&&e.label):[];ie(c),c&&l.length>0?(K({status:`waiting`,question:c,options:l}),o=`clarifying`):K({status:`none`}),Ce(Date.now()),De([]),ye(`Plan synced to session.`),I(``),Lg(i,T),nt({session:t?.session||null,draft:t?.session?it(t.session):null,clarification:c&&l.length>0?{status:`waiting`,question:c,options:l}:{status:`none`},planPreview:t?.plan||null,planningConversation:t?.conversation||null,planningChangeSummary:[],plannerDiagnostics:t?.planner_diagnostics||t?.plannerDiagnostics||null,publishedTasks:[]}),n(`ok`,typeof t?.clarifier?.question==`string`?`Planner needs clarification before it can draft richer tasks.`:`Planner generated a task draft.`)}catch(e){let t=e instanceof Error?e.message:String(e);if(Kg(t)){V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),n(`info`,`The previous planner session expired. Starting a fresh planning chat.`),await mt(r);return}ie(t),K({status:`none`}),ye(t.includes(`Request timed out after`)?`The panel timed out before the planner finished. The engine may still be working, so wait a moment before retrying.`:``),n(`err`,t)}finally{pe(o)}},Y=async t=>{if(!e?.workflowPlannerSessions?.message||!T){n(`warn`,`Generate a plan first before revising it.`);return}let r=Gg(t??F??N);if(!r){n(`warn`,`Add a message for the planner first.`);return}ye(``),ie(``),W(null),P(r);let a=`idle`;pe(`revising`);try{let t=await e.workflowPlannerSessions.message(T,{message:We?r:[`Revise the workflow plan for repo ${Gg(j)}.`,`Goal: ${Gg(k)}`,i?`Selected project: ${i}`:``,`Keep the workflow valid and machine-parseable.`,`Prefer concrete repo-aware implementation steps.`,`If the request is ambiguous, return a clarification question.`,``,`Revision notes:`,r].filter(Boolean).join(`
2896
- `)});V(t?.plan||null),te(t?.conversation||null),ne(Array.isArray(t?.change_summary)?t.change_summary.map(e=>Gg(e)).filter(Boolean):[]),W(t?.planner_diagnostics||t?.plannerDiagnostics||null);let o=typeof t?.clarifier?.question==`string`?String(t.clarifier.question):``,s=Array.isArray(t?.clarifier?.options)?t.clarifier.options.map(e=>({id:String(e?.id||``),label:String(e?.label||``)})).filter(e=>e.id&&e.label):[];ie(o),o&&s.length>0?(K({status:`waiting`,question:o,options:s}),a=`clarifying`):K({status:`none`}),Ce(Date.now()),De([]),ye(`Revision synced to session.`),I(``),Lg(i,T),nt({session:t?.session||null,draft:t?.session?it(t.session):null,clarification:o&&s.length>0?{status:`waiting`,question:o,options:s}:{status:`none`},planPreview:t?.plan||null,planningConversation:t?.conversation||null,planningChangeSummary:Array.isArray(t?.change_summary)?t.change_summary.map(e=>Gg(e)).filter(Boolean):[],plannerDiagnostics:t?.planner_diagnostics||t?.plannerDiagnostics||null,publishedTasks:[]}),n(`ok`,`Plan revised.`)}catch(e){let t=e instanceof Error?e.message:String(e);if(Kg(t)){V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),n(`info`,`The previous planner session expired. Starting a fresh planning chat.`),await mt(r);return}ie(t),K({status:`none`}),ye(t.includes(`Request timed out after`)?`The panel timed out before the planner revision finished. The engine may still be working, so wait a moment before retrying.`:``),n(`err`,t)}finally{pe(a)}},ht=async()=>{if(!e?.workflowPlannerSessions?.reset||!T){A(``),I(``),P(``),V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),xe(``),Te(null),Ce(null),ye(`Draft cleared.`);return}le(!0);try{let t=await e.workflowPlannerSessions.reset(T);V(t?.plan||null),te(t?.conversation||null),I(``),ne([]),ie(``),W(t?.planner_diagnostics||t?.plannerDiagnostics||null),De([]),xe(``),Te(null),ye(`Plan reset.`),Ce(Date.now()),Lg(i,T),nt({session:t?.session?{...t.session,published_at_ms:null}:null,draft:t?.session?it(t.session):null,clarification:{status:`none`},planPreview:t?.plan||null,planningConversation:t?.conversation||null,planningChangeSummary:[],plannerDiagnostics:t?.planner_diagnostics||t?.plannerDiagnostics||null,publishedTasks:[]}),n(`ok`,`Plan reset.`)}catch(e){let t=e instanceof Error?e.message:String(e);if(Kg(t)){A(``),I(``),P(``),V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),xe(``),Te(null),Ce(null),ye(`The expired planner session was cleared locally.`),n(`info`,`The previous planner session had expired, so the local draft was reset.`);return}ie(t),n(`err`,t)}finally{le(!1)}},gt=async()=>{let r=Me.length?Me:k.trim()?[{id:`task-1`,title:k.trim(),objective:k.trim(),kind:`task`,dependsOn:[],inputRefs:[],outputContract:``}]:[];if(!r.length){n(`warn`,`Generate a plan before publishing tasks.`);return}se(!0),xe(``);try{if(Ne&&J){let a=s?.taskSource||{},o=Gg(a.owner),c=Gg(a.repo),d=Number(a.project),f=l,p=Number(f?.status_field_id||f?.statusFieldId||0),m=Gg(f?.status_option_map?.ready||f?.statusOptionMap?.ready||f?.status_option_map?.Ready||f?.statusOptionMap?.Ready||``);if((!p||!m)&&Gg(i))try{f=await t(`/api/aca/projects/${encodeURIComponent(i)}/board?refresh=true`)}catch{}let h=[];for(let t=0;t<r.length;t+=1){let n=r[t],a=n_(B,n,t,{goal:k,workspaceRoot:j,projectSlug:i,taskSourceType:u,selectedProject:s,notes:N,plannerProvider:L,plannerModel:z}),l=e_(await e.executeTool(`mcp.github.issue_write`,{method:`create`,owner:o,repo:c,title:n.title,body:a,labels:[`tandem`,`planned-task`,`ready`]}));if(!l)throw Error(`Created GitHub issue for "${n.title}" but could not determine the issue number from the engine response.`);let f=t_(await e.executeTool(`mcp.github.projects_write`,{method:`add_project_item`,owner:o,project_number:d,item_type:`issue`,item_owner:o,item_repo:c,issue_number:l}));f&&p&&m&&await e.executeTool(`mcp.github.projects_write`,{method:`update_project_item`,owner:o,project_number:d,item_id:f,updated_field:{id:p,value:m}}),h.push({title:n.title,issueNumber:l,issueUrl:`https://github.com/${o}/${c}/issues/${l}`,publishedAtMs:Date.now()})}let g=Date.now();De(h),xe(`Published ${h.length} GitHub tasks into Ready.`),Te(g),Ce(g),nt({session:{published_at_ms:g,published_tasks:h},publishedTasks:h}),await Promise.all([b.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-board`,i]}),b.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-tasks`,i]}),b.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]})]),n(`ok`,`Published ${h.length} task(s) to the GitHub Project.`)}else{let e=r_(B,r,{goal:k,workspaceRoot:j,projectSlug:i,notes:N,plannerProvider:L,plannerModel:z}),t=Date.now();De(r.map(e=>({title:e.title,publishedAtMs:t}))),xe(`Saved a local task bundle. Use the exported markdown to update your kanban file.`),Te(t),Ce(t),nt({session:{published_at_ms:t,published_tasks:r},publishedTasks:r.map(e=>({title:e.title,publishedAtMs:t}))}),navigator.clipboard?.writeText&&await navigator.clipboard.writeText(e),n(`ok`,`Saved a local task bundle. The plan markdown has been copied to your clipboard.`)}}catch(e){let t=e instanceof Error?e.message:String(e);xe(t),n(`err`,t)}finally{se(!1)}},_t=o(()=>r_(B,Me,{goal:k,workspaceRoot:j,projectSlug:i,notes:N,plannerProvider:L,plannerModel:z}),[k,N,B,Me,z,L,i,j]),vt=Ne?`GitHub Project task planning`:`Local kanban task planning`,yt=!!B||!!ae||U.length>0||Array.isArray(H?.messages)&&H.messages.length>0;return m(()=>{v.current&&Yr(v.current)},[G.status,Qe.length,yt,He,re,B,U.length,H,et.length,T,D,be,ve]),a(Ug,{rootRef:v,session:{plannerSessions:x,selectedSessionId:T,sessionsOpen:D,plannerSessionSummaries:et,activePlannerSessionSummary:$e,plannerTitle:vt},planner:{goal:k,workspaceRoot:j,notes:N,plannerInput:F,plannerProvider:L,plannerModel:z,planPreview:B,planningConversation:H,planningChangeSummary:U,plannerError:re,plannerDiagnostics:ae,publishing:oe,resetting:ce,clarification:G,saveStatus:ve,publishStatus:be,lastSavedAtMs:Se,publishedAtMs:we,publishedTasks:Ee,plannerChatMessages:qe,plannerInputPlaceholder:Xe,plannerStatusTitle:Je,plannerStatusDetail:Ye,exportMarkdown:_t,plannerFallbackReason:Ue,hasPlannerResponse:yt,displayTasks:Qe},status:{isGitHubProject:Ne,taskSourceType:u,engineHealthy:p,plannerCanUseLlm:ze,hasExplicitPlannerOverride:Le,hasBasePlannerModel:Ie,plannerSelectionMatchesWorkspaceDefault:Re,resolvedWorkspaceRoot:q,canPublishToGitHub:J,plannerTimedOut:Ke,clarificationNeeded:We,planIsFallbackOnly:Ze,isPlanning:He},provider:{providerOptions:Pe,providerStatus:g,selectedProjectSlug:i,selectedProject:s,githubProjectBoardSnapshot:l,connectedMcpServers:f},actions:{activatePlannerSession:tt,createNewPlannerSession:ct,renamePlannerSession:lt,duplicatePlannerSession:dt,deletePlannerSession:ft,setSessionsOpen:O,previewMutation:mt,reviseMutation:Y,resetMutation:ht,patchActivePlannerSession:st,setPlannerInput:I,setGoal:A,setWorkspaceRoot:M,setNotes:P,setPlannerProvider:R,setPlannerModel:ee,setPlannerError:ie,setPlannerDiagnostics:W,setClarification:K,setSaveStatus:ye,publishTasks:gt,plannerOperatorPreferences:i_,plannerSessionTitle:Jg},dialogs:{renameSessionDialog:me,deleteSessionDialog:ge,confirmRenamePlannerSession:ut,confirmDeletePlannerSession:pt,setRenameSessionDialog:he,setDeleteSessionDialog:_e}})}function o_(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function s_(e){return(Array.isArray(e)?e:Array.isArray(e?.servers)?e.servers:e&&typeof e==`object`?Object.entries(e).map(([e,t])=>({name:e,...t})):[]).map(e=>({name:String(e?.name||``).trim(),connected:!!e?.connected,enabled:e?.enabled!==!1,transport:String(e?.transport||``).trim(),lastError:String(e?.last_error||e?.lastError||``).trim()})).filter(e=>e.name).sort((e,t)=>e.name.localeCompare(t.name))}function c_(e){return(Array.isArray(e)?e:Array.isArray(e?.tools)?e.tools:[]).map(e=>typeof e==`string`?e:String(e?.namespaced_name||e?.namespacedName||e?.id||``).trim()).filter(Boolean)}function l_(e){let t=Array.isArray(e)?e:e&&typeof e==`object`?Object.entries(e).map(([e,t])=>({slug:e,...t})):[],n=new Map;for(let e of t){let t=e?.task_source||e?.taskSource||{},r=String(t?.type||``).trim(),i=e?.repo||{},a=String(e?.repo_url||e?.repoUrl||i?.clone_url||i?.cloneUrl||``).trim(),o=r===`github_project`&&String(t?.owner||``).trim()&&String(t?.repo||``).trim()&&String(t?.project||``).trim()?`github:${String(t.owner).trim().toLowerCase()}/${String(t.repo).trim().toLowerCase()}#${String(t.project).trim()}`:a?`repo:${a.toLowerCase()}`:`slug:${e.slug}`,s=n.get(o);if(!s){n.set(o,e);continue}let c=s?.repo||{},l=String(s?.repo_url||s?.repoUrl||c?.clone_url||c?.cloneUrl||``).trim(),u=(s.implicit?0:10)+ +!!l;(e.implicit?0:10)+ +!!a>u&&n.set(o,e)}return Array.from(n.values()).map(e=>{let t=e?.repo||{},n=e?.task_source||e?.taskSource||{};return{slug:String(e?.slug||``).trim(),name:String(e?.name||e?.display_name||e?.displayName||e?.slug||``).trim(),repoUrl:String(e?.repo_url||e?.repoUrl||t?.clone_url||t?.cloneUrl||``).trim(),repoPath:String(t?.path||e?.repo_path||e?.repoPath||``).trim(),worktreeRoot:String(t?.worktree_root||e?.worktree_root||e?.worktreeRoot||``).trim(),defaultBranch:String(t?.default_branch||e?.default_branch||e?.defaultBranch||`main`).trim(),remoteName:String(t?.remote_name||e?.remote_name||e?.remoteName||`origin`).trim(),credentialFile:String(t?.credential_file||e?.credential_file||e?.credentialFile||``).trim(),taskSource:n,implicit:e?.implicit===!0}}).filter(e=>e.slug).sort((e,t)=>e.implicit===t.implicit?e.slug.localeCompare(t.slug):e.implicit?1:-1)}function u_(e){return{items:Array.isArray(e?.items)?e.items.map((e,t)=>({id:String(e?.id||e?.project_item_id||`item-${t}`).trim(),projectItemId:String(e?.project_item_id||e?.projectItemId||``).trim(),title:String(e?.title||`Untitled item`).trim(),statusKey:String(e?.status_key||e?.statusKey||`unknown`).trim(),statusName:String(e?.status_name||e?.statusName||`Unknown`).trim(),issueNumber:e?.issue_number||e?.issueNumber||null,issueUrl:String(e?.issue_url||e?.issueUrl||``).trim(),repoName:String(e?.repo_name||e?.repoName||``).trim(),actionable:e?.actionable===!0,selector:String(e?.project_item_id||e?.projectItemId||e?.issue_number||e?.issueNumber||e?.id||``).trim()})).filter(e=>e.id):[],source:String(e?.source||``).trim(),warning:String(e?.warning||``).trim(),isStale:e?.is_stale===!0,lastSyncedAtMs:Number(e?.last_synced_at_ms||e?.lastSyncedAtMs||0)}}function d_(e,t){return String(e?.run_id||e?.runId||e?.id||`run-${t}`).trim()}function f_(e){return String(e?.title||e?.summary||e?.run_id||e?.runId||`Untitled run`).trim()}function p_(e){let t=Number(e?.updated_at_ms||e?.created_at_ms||e?.snapshot?.updated_at_ms||e?.snapshot?.created_at_ms||0);return Number.isFinite(t)?t:0}function m_(e){return String(e?.status||e?.snapshot?.status||e?.status?.run?.status||`unknown`).trim().toLowerCase()}function h_(e){return String(e?.phase?.name||e?.snapshot?.phase?.name||e?.status?.phase?.name||``).trim().toLowerCase()}function g_(e){return String(e||`unknown`).replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var __=1800*1e3,v_=15*1e3;function y_(e){return e?.is_running===!0||e?.snapshot?.is_running===!0}function b_(e){let t=m_(e);if([`completed`,`done`,`failed`,`cancelled`,`blocked`,`archived`].includes(t))return!1;if(y_(e))return!0;let n=p_(e);return n?Date.now()-n<__:!1}function x_(e,t){let n=e?.blackboard?.task||e?.snapshot?.blackboard?.task||{},r=n?.source||{},i=n?.repo||{};return String(r?.issue_url||r?.url||r?.item_url||r?.project_item_id||r?.card_id||n?.task_id||`${i?.slug||e?.project_slug||`project`}:${f_(e)}:${t}`).trim()}function S_(e){return String(e?.issueUrl||e?.projectItemId||e?.id||``).trim()}function C_(e){let t=String(e?.statusKey||``).trim().toLowerCase();return!e?.selector||t===`in_review`||t===`done`?!1:e?.actionable===!0||[`ready`,`backlog`,`todo`].includes(t)}function w_(e){let t=new Map;return e.forEach((e,n)=>{let r=x_(e,n),i=t.get(r);(!i||p_(e)>=p_(i))&&t.set(r,e)}),Array.from(t.values()).sort((e,t)=>p_(t)-p_(e))}function T_(e){let t=String(e||``).trim();if(!t)return null;let n=e=>{let t=e.replace(/^\/+/,``).replace(/\.git$/i,``).split(`/`).map(e=>e.trim()).filter(Boolean);if(t.length<2)return null;let[n,r]=t;return!n||!r?null:{owner:n,repo:r,slug:`${n}/${r}`}},r=t.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);if(r?.[1]&&r?.[2])return n(`${r[1]}/${r[2]}`);try{let e=new URL(t);return e.hostname.toLowerCase()===`github.com`?n(e.pathname):null}catch{return n(t)}}function E_(e,{prompt:t,path:n,repoRef:r,projectNumber:i}){return e===`manual`?{type:`manual`,prompt:t.trim()}:e===`kanban_board`?{type:`kanban_board`,path:n.trim()}:e===`local_backlog`?{type:`local_backlog`,path:n.trim()}:{type:`github_project`,owner:r?.owner||``,repo:r?.repo||``,project:i.trim()}}function D_(e){let t=String(e||``).trim().replace(/\\/g,`/`);if(!t)return!0;if(t.startsWith(`/`)||/^[A-Za-z]:/.test(t))return!1;let n=t.split(`/`).filter(Boolean);return n.length>0&&!n.some(e=>e===`.`||e===`..`)}function O_(e){try{let t=JSON.parse(String(e||`{}`));return t&&typeof t==`object`?t:null}catch{return null}}function k_({api:e,client:t,toast:n,providerStatus:i,navigate:s}){let c=_(),[l,u]=r(`overview`),[d,f]=r(``),[h,g]=r(``),[v,b]=r(``),[x,S]=r(``),[C,w]=r(``),[T,E]=r(``),[D,O]=r(``),[k,A]=r(``),[j,M]=r(`main`),[N,P]=r(`origin`),[F,I]=r(``),[L,R]=r(`github_project`),[z,ee]=r(``),[B,V]=r(``),[H,te]=r(``),[U,ne]=r(``),[re,ie]=r(``),[ae,W]=r(``),[oe,se]=r(!1),[ce,le]=r(!1),[ue,de]=r(``),[fe,pe]=r(``),[G,K]=r(null),[me,he]=r(null),[ge,_e]=r(!1),[ve,ye]=r(null),[be,xe]=r(!1),[Se,Ce]=r(!1),[we,Te]=r([]),[Ee,De]=r({}),[Oe,ke]=r(!1),Ae=Oc(),je=Ae.data?.aca_integration===!0,Me=Ae.data?.engine_healthy===!0,Ne=Ae.data?.hosted_managed===!0,Pe=je||Me,Fe=y({queryKey:[`coding-workflows`,`health`],queryFn:()=>e(`/api/system/health`),refetchInterval:15e3}),q=y({queryKey:[`coding-workflows`,`aca-health`],queryFn:()=>e(`/api/aca/health`),enabled:je}),J=y({queryKey:[`coding-workflows`,`aca-overview`],queryFn:()=>e(`/api/aca/overview`),enabled:je,refetchInterval:je?3e4:!1}),Ie=y({queryKey:[`coding-workflows`,`aca-projects`],queryFn:()=>e(`/api/aca/projects`),enabled:je}),Le=y({queryKey:[`coding-workflows`,`aca-workspace-guide`],queryFn:()=>e(`/api/aca/workspace/guide`),enabled:je}),Re=y({queryKey:[`coding-workflows`,`aca-runs`],queryFn:()=>e(`/api/aca/runs`),enabled:je}),ze=y({queryKey:[`coding-workflows`,`coder-runs`],queryFn:()=>e(`/api/aca/operator/coder-runs`),enabled:je,refetchInterval:je?15e3:!1}),Be=y({queryKey:[`coding-workflows`,`aca-project-tasks`,d],queryFn:()=>e(`/api/aca/projects/${encodeURIComponent(d)}/tasks`),enabled:je&&!!d}),Ve=y({queryKey:[`coding-workflows`,`aca-project-board`,d],queryFn:()=>e(`/api/aca/projects/${encodeURIComponent(d)}/board`),enabled:je&&!!d&&l_(Ie.data).some(e=>e.slug===d&&String(e?.taskSource?.type||``).trim()===`github_project`),refetchInterval:je&&d&&l_(Ie.data).some(e=>e.slug===d&&String(e?.taskSource?.type||``).trim()===`github_project`)?12e4:!1}),He=y({queryKey:[`coding-workflows`,`aca-run-detail`,h],queryFn:()=>e(`/api/aca/runs/${encodeURIComponent(h)}`),enabled:je&&!!h}),Ue=y({queryKey:[`coding-workflows`,`aca-run-logs`,h],queryFn:()=>e(`/api/aca/runs/${encodeURIComponent(h)}/logs`),enabled:je&&!!h}),We=y({queryKey:[`coding-workflows`,`aca-run-log-tail`,h,v],queryFn:()=>e(`/api/aca/runs/${encodeURIComponent(h)}/logs/${encodeURIComponent(v)}?tail=120`),enabled:je&&!!h&&!!v}),Ge=y({queryKey:[`coding-workflows`,`mcp-servers`],queryFn:()=>t.mcp.list().catch(()=>({})),refetchInterval:Pe?1e4:!1,enabled:Pe}),Ke=y({queryKey:[`coding-workflows`,`mcp-tools`],queryFn:()=>t.mcp.listTools().catch(()=>[]),refetchInterval:Pe?15e3:!1,enabled:Pe}),qe=y({queryKey:[`coding-workflows`,`providers`,`catalog`],queryFn:()=>t.providers.catalog().catch(()=>({all:[]})),refetchInterval:Pe?3e4:!1,enabled:Pe}),Je=y({queryKey:[`coding-workflows`,`providers`,`config`],queryFn:()=>t.providers.config().catch(()=>({})),refetchInterval:Pe?3e4:!1,enabled:Pe}),Ye=o(()=>s_(Ge.data),[Ge.data]),Xe=o(()=>c_(Ke.data),[Ke.data]),Ze=o(()=>l_(Ie.data),[Ie.data]),Qe=o(()=>o_(Re.data,`runs`),[Re.data]),$e=o(()=>o_(ze.data,`coder_runs`),[ze.data]),et=o(()=>u_(Ve.data),[Ve.data]),tt=o(()=>ka({providerCatalog:qe.data,providerConfig:Je.data,defaultProvider:i.defaultProvider,defaultModel:i.defaultModel}),[i.defaultModel,i.defaultProvider,qe.data,Je.data]),nt=o(()=>T_(T),[T]);m(()=>{Ze.length&&(!d||!Ze.some(e=>e.slug===d))&&f(Ze[0].slug)},[Ze,d]);let rt=o(()=>d?Qe.filter(e=>String(e?.project_slug||``).trim()===d):Qe,[Qe,d]),it=o(()=>w_(rt),[rt]),at=o(()=>it.filter(b_),[it]);m(()=>{if(!it.length){g(``);return}let e=at.map((e,t)=>d_(e,t)),t=it.some((e,t)=>d_(e,t)===h),n=e.includes(h);if(e.length&&(!h||!n)){g(e[0]);return}(!h||!t)&&g(d_(it[0],0))},[at,h,it]);let ot=o(()=>o_(Ue.data,`logs`),[Ue.data]);m(()=>{if(!ot.length){b(``);return}(!v||!ot.some(e=>String(e?.name||``)===v))&&b(String(ot[0]?.name||``))},[ot,v]);let st=!!(Fe.data?.engine?.ready||Fe.data?.engine?.healthy),ct=Ye.some(e=>e.name.toLowerCase().includes(`github`)),lt=Ze.find(e=>e.slug===d)||null,ut=lt?.repo||{},dt=String(lt?.taskSource?.type||``).trim(),ft=String(Fe.data?.workspaceRoot||Fe.data?.workspace_root||(dt===`kanban_board`||dt===`local_backlog`)&&lt?.taskSource?.path||``).trim(),pt=Ye.filter(e=>e.connected).map(e=>e.name),mt=o(()=>et.items.filter(e=>we.includes(String(e.id||``))),[et.items,we]),Y=o(()=>et.items.filter(e=>C_(e)),[et.items]),ht=o(()=>new Set(Object.keys(Ee)),[Ee]),gt=i.defaultProvider&&i.defaultModel?`ACA default (${i.defaultProvider} / ${i.defaultModel})`:`ACA default`,_t=(e=!1)=>a(`div`,{className:`grid gap-2`,children:[a(ma,{providerLabel:`ACA provider`,modelLabel:`ACA model`,draft:{provider:re,model:ae},providers:tt,onChange:({provider:e,model:t})=>{ie(e),W(t)},inheritLabel:gt,disabled:e}),a(`div`,{className:`tcp-subtle text-xs`,children:`Leave blank to inherit the base ACA provider and model for this run.`})]}),vt=o(()=>new Set(at.map((e,t)=>x_(e,t)).map(e=>String(e||``).trim()).filter(Boolean)),[at]),yt=it.find((e,t)=>d_(e,t)===h)||null,bt=String(He.data?.summary||``).trim(),xt=He.data?.blackboard||null;m(()=>{pe(``)},[h]),m(()=>{if(!je)return;let e=Yi(`/api/aca/events`,e=>{let t=O_(String(e?.data||``));if(!t||t.event_type===`ping`)return;de(String(t.event_type||`event`).trim()),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-overview`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]}),d&&(c.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-board`,d]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-tasks`,d]}));let n=String(t?.payload?.run_id||t?.payload?.event?.run_id||``).trim();h&&n&&n===h&&c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-detail`,h]})});return()=>e()},[je,c,d,h]),m(()=>{if(!je||!h||!yt?.is_running)return;let e=Yi(`/api/aca/runs/${encodeURIComponent(h)}/events`,e=>{let t=O_(String(e?.data||``));!t||t.event_type===`ping`||(pe(String(t.event_type||`event`).trim()),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-detail`,h]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-logs`,h]}),v&&c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-log-tail`,h,v]}))});return()=>e()},[je,c,v,yt?.is_running,h]),m(()=>{Be.data&&K(Date.now())},[Be.data]),m(()=>{Ve.data&&he(Number(Ve.data?.last_synced_at_ms||Date.now()))},[Ve.data]),m(()=>{Te([])},[d]),m(()=>{De({})},[d]),m(()=>{let e=Object.entries(Ee);if(!e.length)return;let t=e.map(([e,t])=>{let n=Date.now()-Number(t||0),r=Math.max(0,v_-n);return window.setTimeout(()=>{De(t=>{if(!t[e])return t;let n={...t};return delete n[e],n})},r)});return()=>{t.forEach(e=>window.clearTimeout(e))}},[Ee]),m(()=>{!Object.keys(Ee).length||!et.items.length||De(e=>{let t=!1,n={...e};return et.items.forEach(e=>{let r=String(e?.id||``).trim();!r||n[r]===void 0||vt.has(S_(e))&&(delete n[r],t=!0)}),t?n:e})},[vt,et.items,Ee]),m(()=>{let e=new Set(et.items.map(e=>String(e.id||``)));Te(t=>t.filter(t=>e.has(t)))},[et.items]);let St=[{id:`overview`,label:`Overview`,icon:`layout-dashboard`},{id:`board`,label:`Intake`,icon:`list-checks`},{id:`planning`,label:`Planning`,icon:`clipboard-list`},{id:`manual`,label:`Manual tasks`,icon:`code`},{id:`integrations`,label:`Integrations`,icon:`plug-zap`}];async function Ct(t){let r=String(t||``).trim();if(r)try{await e(`/api/aca/operator/coder-runs/${encodeURIComponent(r)}/reconcile`,{method:`POST`}),await c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),n(`ok`,`Reconciled coder run ${r}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function wt(t){let r=String(t||``).trim();if(r&&window.confirm(`Cancel coder run ${r}?`))try{await e(`/api/aca/operator/coder-runs/${encodeURIComponent(r)}/cancel`,{method:`POST`,body:JSON.stringify({reason:`cancelled from Tandem Control Panel Coder view`})}),await c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),n(`ok`,`Cancelled coder run ${r}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function Tt(){let t=T_(T),r=x.trim()||L===`github_project`&&t?.slug||``,i=C.trim(),a=T.trim(),o=D.trim(),s=k.trim(),l=j.trim(),u=N.trim(),d=F.trim();if(L===`github_project`&&!t){n(`warn`,`Paste a GitHub repository URL like https://github.com/owner/repo.`);return}if(!r){n(`warn`,`Project slug is required.`);return}if(o&&!D_(o)||s&&!D_(s)){n(`warn`,`Repo paths must stay within the managed workspace root.`);return}let p=E_(L,{prompt:z,path:B,repoRef:t,projectNumber:H});if(p.type===`manual`&&!p.prompt){n(`warn`,`Manual task source requires a prompt.`);return}if([`kanban_board`,`local_backlog`].includes(p.type)&&!p.path){n(`warn`,`This task source requires a path.`);return}if(p.type===`github_project`&&(!p.owner||!p.repo||!p.project)){n(`warn`,`GitHub Project task sources require a repo URL and project number.`);return}se(!0);try{let t=new URLSearchParams({slug:r});a&&t.set(`repo_url`,a),i&&t.set(`name`,i),o&&t.set(`repo_path`,o),s&&t.set(`worktree_root`,s),l&&t.set(`default_branch`,l),u&&t.set(`remote_name`,u),d&&t.set(`credential_file`,d),await e(`/api/aca/projects?${t.toString()}`,{method:`POST`,body:JSON.stringify(p)}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-workspace-guide`]}),f(r),S(``),w(``),E(``),O(``),A(``),M(`main`),P(`origin`),I(``),n(`ok`,`Registered ACA project ${r}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{se(!1)}}async function Et(){if(!d){n(`warn`,`Select a project before triggering a run.`);return}let t={};re.trim()&&(t.ACA_PROVIDER=re.trim()),ae.trim()&&(t.ACA_MODEL=ae.trim()),le(!0);try{let r=new URLSearchParams({project_slug:d});U.trim()&&r.set(`item`,U.trim());let i=await e(`/api/aca/runs/trigger?${r.toString()}`,{method:`POST`,body:JSON.stringify(t)});await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]});let a=String(i?.run_id||``).trim();a&&(g(a),u(`board`)),n(`ok`,`ACA run started${a?`: ${a}`:`.`}`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{le(!1)}}function Dt(e){Te(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}function Ot(){Te(et.items.filter(e=>C_(e)&&!vt.has(S_(e))&&!ht.has(String(e.id||``))).map(e=>String(e.id||``)))}function kt(){Te([])}async function At(t){if(!d){n(`warn`,`Select a project before starting ACA runs.`);return}let r=t.filter(e=>C_(e)&&!vt.has(S_(e))&&!ht.has(String(e.id||``))),i=r.map(e=>String(e?.selector||``).trim()).filter(Boolean);if(!i.length){n(`warn`,`Those GitHub items are already running or are not launchable from ACA intake.`);return}let a={};re.trim()&&(a.ACA_PROVIDER=re.trim()),ae.trim()&&(a.ACA_MODEL=ae.trim()),De(e=>{let t={...e},n=Date.now();return r.forEach(e=>{let r=String(e?.id||``).trim();r&&(t[r]=n)}),t}),ke(!0);try{let t=await e(`/api/aca/runs/trigger-batch`,{method:`POST`,body:JSON.stringify({project_slug:d,items:i,overrides:a})});await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]});let r=o_(t,`runs`),o=String(r?.[0]?.run_id||``).trim();o&&(g(o),u(`board`)),n(`ok`,`Started ${i.length} ACA run${i.length===1?``:`s`}.`),Te([])}catch(e){De(e=>{let t={...e};return r.forEach(e=>{let n=String(e?.id||``).trim();n&&delete t[n]}),t}),n(`err`,e instanceof Error?e.message:String(e))}finally{ke(!1)}}async function jt(){if(!d){n(`warn`,`Select a project before refreshing GitHub intake.`);return}try{await Be.refetch(),K(Date.now()),n(`ok`,`Refreshed task intake from GitHub MCP.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function Mt(){if(!d){n(`warn`,`Select a GitHub-backed project before refreshing the board.`);return}try{let t=await e(`/api/aca/projects/${encodeURIComponent(d)}/board?refresh=true`);c.setQueryData([`coding-workflows`,`aca-project-board`,d],t),he(Number(t?.last_synced_at_ms||Date.now())),n(`ok`,`Refreshed GitHub Project items through Tandem MCP.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function Nt(){if(!d){n(`warn`,`Select a project before syncing its repository.`);return}_e(!0),ye(null);try{let t=await e(`/api/aca/projects/${encodeURIComponent(d)}/repo/sync`,{method:`POST`});ye(t),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-workspace-guide`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-tasks`,d]}),n(`ok`,`Repository ready at ${String(t?.repo?.path||`managed checkout`)}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{_e(!1)}}return je?a(ir,{className:`grid gap-4`,children:[a(dr,{className:`overflow-hidden`,children:a(`div`,{className:`grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Coder`}),a(`h1`,{className:`tcp-page-title`,children:`Coder project intake and run dashboard`}),a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:`This view talks to the ACA control plane for project registration, task preview, durable coder runs, live logs, and final handoff artifacts.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(X,{tone:q.data?.status===`healthy`?`ok`:`warn`,children:q.data?.status===`healthy`?`ACA healthy`:`ACA checking`}),a(X,{tone:st?`ok`:`warn`,children:st?`Engine healthy`:`Engine checking`}),a(X,{tone:ct?`ok`:`warn`,children:ct?`GitHub MCP connected`:`GitHub MCP pending`}),a(cr,{tone:at.length?`live`:`info`,text:`${at.length} active runs`}),ue?a(X,{tone:`ghost`,children:[`Live `,g_(ue)]}):null]})]}),a(`div`,{className:`grid gap-3 rounded-2xl border border-white/10 bg-black/20 p-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-sm font-semibold text-slate-100`,children:`Repository`}),a(`div`,{className:`tcp-subtle mt-1 truncate text-xs`,children:d?String(ut?.path||ut?.clone_url||lt?.repo_url||d):`Select a project to sync its checkout.`})]}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:Nt,disabled:!d||ge,children:[a(`i`,{"data-lucide":ge?`loader-circle`:`refresh-cw`}),ge?`Syncing`:`Sync repo`]})]}),a(`div`,{className:`grid gap-2 text-xs`,children:[a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:ut?.clone_url?`ok`:`ghost`,children:ut?.clone_url?`remote git`:`local git`}),a(X,{tone:`ghost`,children:String(ut?.default_branch||`main`)}),ve?.repo?.dirty?a(X,{tone:`warn`,children:`dirty`}):null]}),ve?.repo?.commit?a(`div`,{className:`tcp-subtle truncate`,children:[`Ready at `,String(ve.repo.path),` ·`,` `,String(ve.repo.commit).slice(0,7)]}):null]})]})]})}),a(`div`,{className:`tcp-settings-tabs`,children:St.map(e=>a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${l===e.id?`active`:``}`,onClick:()=>u(e.id),children:[a(`i`,{"data-lucide":e.icon}),e.label]},e.id))}),l===`overview`?a(Tg,{projects:Ze,selectedProjectSlug:d,setSelectedProjectSlug:f,selectedProject:lt,acaOverview:J,projectTasksQuery:Be,refreshTaskPreview:jt,taskPreviewRefreshAt:G,coderRuns:$e,coderRunsQuery:ze,reconcileCoderRun:Ct,cancelCoderRun:wt,visibleRunsCount:rt.length,activeRunsCount:at.length,connectedMcpServersCount:Ye.length,registeredToolsCount:Xe.length}):null,l===`board`?a(`div`,{className:`grid gap-4`,children:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`GitHub Project intake`,subtitle:`GitHub items ACA can launch`,children:[a(`div`,{className:`mb-4`,children:a(`select`,{className:`tcp-input`,value:d,onChange:e=>f(e.target.value),children:[Ze.length?null:a(`option`,{value:``,children:`No ACA projects found`}),Ze.map(e=>a(`option`,{value:e.slug,children:e.name?`${e.name} · ${e.slug}`:e.slug},e.slug))]})}),String(lt?.taskSource?.type||``).trim()===`github_project`?Ve.isLoading?a(`div`,{className:`tcp-subtle text-sm`,children:`Loading GitHub Project items...`}):Ve.isError?a(`div`,{className:`rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-200`,children:Ve.error instanceof Error?Ve.error.message:`Could not load the GitHub Project items.`}):a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-white/10 bg-black/20 p-3`,children:[a(`div`,{className:`tcp-subtle text-xs`,children:[`Items are listed by ACA launchability with direct run controls.`,me?` Last synced ${new Date(me).toLocaleTimeString()}.`:``]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(X,{tone:et.isStale?`warn`:`ok`,children:et.isStale?`Cached snapshot`:g_(et.source||`live`)}),a(`button`,{type:`button`,className:`tcp-btn tcp-btn-secondary`,onClick:Mt,disabled:Ve.isFetching,children:Ve.isFetching?`Refreshing...`:`Refresh from GitHub`})]})]}),a(`div`,{className:`flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-cyan-500/20 bg-cyan-500/10 p-3`,children:[a(`div`,{className:`tcp-subtle text-xs`,children:`Select GitHub items here to start ACA runs directly from the board. This creates one ACA run per selected item and starts them immediately.`}),a(`div`,{className:`min-w-[320px] flex-1`,children:_t(Oe)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn tcp-btn-secondary`,onClick:Ot,disabled:!Y.length||Oe,children:`Select actionable`}),a(`button`,{type:`button`,className:`tcp-btn tcp-btn-secondary`,onClick:kt,disabled:!we.length||Oe,children:`Clear selection`}),a(`button`,{type:`button`,className:`tcp-btn-primary`,onClick:()=>At(mt),disabled:!mt.length||Oe,children:Oe?`Starting...`:`Run selected${mt.length?` (${mt.length})`:``}`})]})]}),et.warning?a(`div`,{className:`rounded-2xl border border-yellow-500/20 bg-yellow-500/10 p-4 text-sm text-yellow-100`,children:et.warning}):null,et.items.length?a(`div`,{className:`grid gap-3`,children:et.items.map(e=>{let t=C_(e),n=String(e.id||``),r=t&&vt.has(S_(e)),i=ht.has(n),o=r||i||Oe;return a(`div`,{className:`rounded-2xl border px-4 py-3 transition ${we.includes(n)?`border-cyan-400/60 bg-cyan-500/10`:`border-white/10 bg-black/20`}`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{className:`flex min-w-0 flex-1 items-start gap-3`,children:[a(`input`,{type:`checkbox`,className:`mt-1 h-4 w-4 shrink-0`,checked:we.includes(n),disabled:!t||o,onChange:()=>Dt(n)}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`break-words text-sm font-semibold leading-5`,children:String(e.title||`Untitled item`)}),a(`div`,{className:`tcp-subtle mt-1 break-words text-xs leading-5`,children:[e.repoName?String(e.repoName):d,e.issueNumber?` #${String(e.issueNumber)}`:``]})]})]}),a(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[e.actionable?a(X,{tone:`ok`,children:`Actionable`}):null,a(X,{tone:`ghost`,children:g_(String(e.statusName||e.statusKey||`Unknown`))}),r?a(X,{tone:`info`,children:`Run active`}):null,i&&!r?a(X,{tone:`warn`,children:`Starting`}):null]})]}),a(`div`,{className:`mt-3 flex flex-wrap gap-2 pl-7`,children:[e.issueUrl?a(`a`,{className:`tcp-btn h-8 px-3 text-xs`,href:e.issueUrl,target:`_blank`,rel:`noreferrer`,children:`Open in GitHub`}):null,a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>At([e]),disabled:!t||o,children:t?r?`Already running`:i?`Starting...`:`Run task`:`Not launchable`})]})]},n)})}):a(Pr,{text:`No GitHub Project items returned for this project.`})]}):a(Pr,{text:`The selected project is not backed by a GitHub Project task source.`})]}),a(dr,{title:`ACA execution history`,subtitle:`Recent runs for the selected project`,children:it.length?a(`div`,{className:`grid gap-2`,children:it.map((e,t)=>{let n=d_(e,t);return a(`button`,{type:`button`,className:`rounded-2xl border px-3 py-3 text-left transition ${n===h?`border-cyan-400/60 bg-cyan-500/10`:`border-white/10 bg-black/20 hover:border-white/20`}`,onClick:()=>g(n),children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:f_(e)}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[String(e?.project_slug||`unknown`),e?.branch?` · ${String(e.branch)}`:``]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:b_(e)?`info`:`ok`,children:g_(m_(e))}),h_(e)?a(X,{tone:`ghost`,children:g_(h_(e))}):null]})]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:n})]},n)})}):a(Pr,{text:`No ACA runs for this project yet.`})}),a(dr,{title:`Run detail`,subtitle:h?`ACA detail for ${h}`:`Select a run`,actions:a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>xe(e=>!e),children:[a(`i`,{"data-lucide":be?`chevron-down`:`chevron-right`}),be?`Collapse`:`Expand`]}),children:be?h?He.isLoading?a(`div`,{className:`tcp-subtle text-sm`,children:`Loading run detail...`}):He.isError?a(`div`,{className:`rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-200`,children:He.error instanceof Error?He.error.message:`Could not load run detail.`}):a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-sm font-semibold`,children:String(He.data?.status?.task?.title||yt?.title||h)}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(He.data?.project_slug||yt?.project_slug||`unknown`)})]}),a(X,{tone:He.data?.is_running?`info`:`ok`,children:g_(String(He.data?.status?.run?.status||yt?.status||`unknown`))})]}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[He.data?.status?.phase?.name?a(X,{tone:`info`,children:[`Phase `,g_(String(He.data.status.phase.name))]}):null,fe?a(X,{tone:`ghost`,children:[`Latest `,g_(fe)]}):null,He.data?.snapshot?.summary_available?a(X,{tone:`ok`,children:`Summary ready`}):null,He.data?.error?a(X,{tone:`warn`,children:`Has error`}):null]})]}),bt?a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`mb-2 text-sm font-semibold`,children:`Summary`}),a(`pre`,{className:`max-h-56 overflow-auto whitespace-pre-wrap text-xs leading-6 text-slate-200`,children:bt})]}):null,a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`mb-2 text-sm font-semibold`,children:`Blackboard`}),a(Lr,{value:xt||{},label:`Show blackboard`,preClassName:`max-h-72 overflow-auto whitespace-pre-wrap text-xs leading-6 text-slate-200`})]})]}):a(Pr,{text:`Select a run from the board to inspect its status, summary, and blackboard.`}):null}),a(dr,{title:`Live logs`,subtitle:`Tail ACA worker and manager logs`,actions:a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>Ce(e=>!e),children:[a(`i`,{"data-lucide":Se?`chevron-down`:`chevron-right`}),Se?`Collapse`:`Expand`]}),children:Se?h?a(`div`,{className:`grid gap-3`,children:[ot.length?a(`select`,{className:`tcp-input`,value:v,onChange:e=>b(e.target.value),children:ot.map(e=>a(`option`,{value:String(e?.name||``),children:String(e?.name||``)},String(e?.name||``)))}):a(`div`,{className:`tcp-subtle text-sm`,children:`No logs available yet.`}),v&&We.data?.lines?a(`pre`,{className:`max-h-80 overflow-auto rounded-2xl border border-white/10 bg-black/30 p-4 text-xs leading-6 text-slate-200`,children:o_(We.data,`lines`).join(`
2896
+ `)});V(t?.plan||null),te(t?.conversation||null),ne(Array.isArray(t?.change_summary)?t.change_summary.map(e=>Gg(e)).filter(Boolean):[]),W(t?.planner_diagnostics||t?.plannerDiagnostics||null);let o=typeof t?.clarifier?.question==`string`?String(t.clarifier.question):``,s=Array.isArray(t?.clarifier?.options)?t.clarifier.options.map(e=>({id:String(e?.id||``),label:String(e?.label||``)})).filter(e=>e.id&&e.label):[];ie(o),o&&s.length>0?(K({status:`waiting`,question:o,options:s}),a=`clarifying`):K({status:`none`}),Ce(Date.now()),De([]),ye(`Revision synced to session.`),I(``),Lg(i,T),nt({session:t?.session||null,draft:t?.session?it(t.session):null,clarification:o&&s.length>0?{status:`waiting`,question:o,options:s}:{status:`none`},planPreview:t?.plan||null,planningConversation:t?.conversation||null,planningChangeSummary:Array.isArray(t?.change_summary)?t.change_summary.map(e=>Gg(e)).filter(Boolean):[],plannerDiagnostics:t?.planner_diagnostics||t?.plannerDiagnostics||null,publishedTasks:[]}),n(`ok`,`Plan revised.`)}catch(e){let t=e instanceof Error?e.message:String(e);if(Kg(t)){V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),n(`info`,`The previous planner session expired. Starting a fresh planning chat.`),await mt(r);return}ie(t),K({status:`none`}),ye(t.includes(`Request timed out after`)?`The panel timed out before the planner revision finished. The engine may still be working, so wait a moment before retrying.`:``),n(`err`,t)}finally{pe(a)}},ht=async()=>{if(!e?.workflowPlannerSessions?.reset||!T){A(``),I(``),P(``),V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),xe(``),Te(null),Ce(null),ye(`Draft cleared.`);return}le(!0);try{let t=await e.workflowPlannerSessions.reset(T);V(t?.plan||null),te(t?.conversation||null),I(``),ne([]),ie(``),W(t?.planner_diagnostics||t?.plannerDiagnostics||null),De([]),xe(``),Te(null),ye(`Plan reset.`),Ce(Date.now()),Lg(i,T),nt({session:t?.session?{...t.session,published_at_ms:null}:null,draft:t?.session?it(t.session):null,clarification:{status:`none`},planPreview:t?.plan||null,planningConversation:t?.conversation||null,planningChangeSummary:[],plannerDiagnostics:t?.planner_diagnostics||t?.plannerDiagnostics||null,publishedTasks:[]}),n(`ok`,`Plan reset.`)}catch(e){let t=e instanceof Error?e.message:String(e);if(Kg(t)){A(``),I(``),P(``),V(null),te(null),ne([]),ie(``),W(null),K({status:`none`}),xe(``),Te(null),Ce(null),ye(`The expired planner session was cleared locally.`),n(`info`,`The previous planner session had expired, so the local draft was reset.`);return}ie(t),n(`err`,t)}finally{le(!1)}},gt=async()=>{let r=Me.length?Me:k.trim()?[{id:`task-1`,title:k.trim(),objective:k.trim(),kind:`task`,dependsOn:[],inputRefs:[],outputContract:``}]:[];if(!r.length){n(`warn`,`Generate a plan before publishing tasks.`);return}se(!0),xe(``);try{if(Ne&&J){let a=s?.taskSource||{},o=Gg(a.owner),c=Gg(a.repo),d=Number(a.project),f=l,p=Number(f?.status_field_id||f?.statusFieldId||0),m=Gg(f?.status_option_map?.ready||f?.statusOptionMap?.ready||f?.status_option_map?.Ready||f?.statusOptionMap?.Ready||``);if((!p||!m)&&Gg(i))try{f=await t(`/api/aca/projects/${encodeURIComponent(i)}/board?refresh=true`)}catch{}let h=[];for(let t=0;t<r.length;t+=1){let n=r[t],a=n_(B,n,t,{goal:k,workspaceRoot:j,projectSlug:i,taskSourceType:u,selectedProject:s,notes:N,plannerProvider:L,plannerModel:z}),l=e_(await e.executeTool(`mcp.github.issue_write`,{method:`create`,owner:o,repo:c,title:n.title,body:a,labels:[`tandem`,`planned-task`,`ready`]}));if(!l)throw Error(`Created GitHub issue for "${n.title}" but could not determine the issue number from the engine response.`);let f=t_(await e.executeTool(`mcp.github.projects_write`,{method:`add_project_item`,owner:o,project_number:d,item_type:`issue`,item_owner:o,item_repo:c,issue_number:l}));f&&p&&m&&await e.executeTool(`mcp.github.projects_write`,{method:`update_project_item`,owner:o,project_number:d,item_id:f,updated_field:{id:p,value:m}}),h.push({title:n.title,issueNumber:l,issueUrl:`https://github.com/${o}/${c}/issues/${l}`,publishedAtMs:Date.now()})}let g=Date.now();De(h),xe(`Published ${h.length} GitHub tasks into Ready.`),Te(g),Ce(g),nt({session:{published_at_ms:g,published_tasks:h},publishedTasks:h}),await Promise.all([b.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-board`,i]}),b.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-tasks`,i]}),b.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]})]),n(`ok`,`Published ${h.length} task(s) to the GitHub Project.`)}else{let e=r_(B,r,{goal:k,workspaceRoot:j,projectSlug:i,notes:N,plannerProvider:L,plannerModel:z}),t=Date.now();De(r.map(e=>({title:e.title,publishedAtMs:t}))),xe(`Saved a local task bundle. Use the exported markdown to update your kanban file.`),Te(t),Ce(t),nt({session:{published_at_ms:t,published_tasks:r},publishedTasks:r.map(e=>({title:e.title,publishedAtMs:t}))}),navigator.clipboard?.writeText&&await navigator.clipboard.writeText(e),n(`ok`,`Saved a local task bundle. The plan markdown has been copied to your clipboard.`)}}catch(e){let t=e instanceof Error?e.message:String(e);xe(t),n(`err`,t)}finally{se(!1)}},_t=o(()=>r_(B,Me,{goal:k,workspaceRoot:j,projectSlug:i,notes:N,plannerProvider:L,plannerModel:z}),[k,N,B,Me,z,L,i,j]),vt=Ne?`GitHub Project task planning`:`Local kanban task planning`,yt=!!B||!!ae||U.length>0||Array.isArray(H?.messages)&&H.messages.length>0;return m(()=>{v.current&&Yr(v.current)},[G.status,Qe.length,yt,He,re,B,U.length,H,et.length,T,D,be,ve]),a(Ug,{rootRef:v,session:{plannerSessions:x,selectedSessionId:T,sessionsOpen:D,plannerSessionSummaries:et,activePlannerSessionSummary:$e,plannerTitle:vt},planner:{goal:k,workspaceRoot:j,notes:N,plannerInput:F,plannerProvider:L,plannerModel:z,planPreview:B,planningConversation:H,planningChangeSummary:U,plannerError:re,plannerDiagnostics:ae,publishing:oe,resetting:ce,clarification:G,saveStatus:ve,publishStatus:be,lastSavedAtMs:Se,publishedAtMs:we,publishedTasks:Ee,plannerChatMessages:qe,plannerInputPlaceholder:Xe,plannerStatusTitle:Je,plannerStatusDetail:Ye,exportMarkdown:_t,plannerFallbackReason:Ue,hasPlannerResponse:yt,displayTasks:Qe},status:{isGitHubProject:Ne,taskSourceType:u,engineHealthy:p,plannerCanUseLlm:ze,hasExplicitPlannerOverride:Le,hasBasePlannerModel:Ie,plannerSelectionMatchesWorkspaceDefault:Re,resolvedWorkspaceRoot:q,canPublishToGitHub:J,plannerTimedOut:Ke,clarificationNeeded:We,planIsFallbackOnly:Ze,isPlanning:He},provider:{providerOptions:Pe,providerStatus:g,selectedProjectSlug:i,selectedProject:s,githubProjectBoardSnapshot:l,connectedMcpServers:f},actions:{activatePlannerSession:tt,createNewPlannerSession:ct,renamePlannerSession:lt,duplicatePlannerSession:dt,deletePlannerSession:ft,setSessionsOpen:O,previewMutation:mt,reviseMutation:Y,resetMutation:ht,patchActivePlannerSession:st,setPlannerInput:I,setGoal:A,setWorkspaceRoot:M,setNotes:P,setPlannerProvider:R,setPlannerModel:ee,setPlannerError:ie,setPlannerDiagnostics:W,setClarification:K,setSaveStatus:ye,publishTasks:gt,plannerOperatorPreferences:i_,plannerSessionTitle:Jg},dialogs:{renameSessionDialog:me,deleteSessionDialog:ge,confirmRenamePlannerSession:ut,confirmDeletePlannerSession:pt,setRenameSessionDialog:he,setDeleteSessionDialog:_e}})}function o_(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function s_(e){return(Array.isArray(e)?e:Array.isArray(e?.servers)?e.servers:e&&typeof e==`object`?Object.entries(e).map(([e,t])=>({name:e,...t})):[]).map(e=>({name:String(e?.name||``).trim(),connected:!!e?.connected,enabled:e?.enabled!==!1,transport:String(e?.transport||``).trim(),lastError:String(e?.last_error||e?.lastError||``).trim()})).filter(e=>e.name).sort((e,t)=>e.name.localeCompare(t.name))}function c_(e){return(Array.isArray(e)?e:Array.isArray(e?.tools)?e.tools:[]).map(e=>typeof e==`string`?e:String(e?.namespaced_name||e?.namespacedName||e?.id||``).trim()).filter(Boolean)}function l_(e){let t=Array.isArray(e)?e:e&&typeof e==`object`?Object.entries(e).map(([e,t])=>({slug:e,...t})):[],n=new Map;for(let e of t){let t=e?.task_source||e?.taskSource||{},r=String(t?.type||``).trim(),i=e?.repo||{},a=String(e?.repo_url||e?.repoUrl||i?.clone_url||i?.cloneUrl||``).trim(),o=r===`github_project`&&String(t?.owner||``).trim()&&String(t?.repo||``).trim()&&String(t?.project||``).trim()?`github:${String(t.owner).trim().toLowerCase()}/${String(t.repo).trim().toLowerCase()}#${String(t.project).trim()}`:a?`repo:${a.toLowerCase()}`:`slug:${e.slug}`,s=n.get(o);if(!s){n.set(o,e);continue}let c=s?.repo||{},l=String(s?.repo_url||s?.repoUrl||c?.clone_url||c?.cloneUrl||``).trim(),u=(s.implicit?0:10)+ +!!l;(e.implicit?0:10)+ +!!a>u&&n.set(o,e)}return Array.from(n.values()).map(e=>{let t=e?.repo||{},n=e?.task_source||e?.taskSource||{};return{slug:String(e?.slug||``).trim(),name:String(e?.name||e?.display_name||e?.displayName||e?.slug||``).trim(),repoUrl:String(e?.repo_url||e?.repoUrl||t?.clone_url||t?.cloneUrl||``).trim(),repoPath:String(t?.path||e?.repo_path||e?.repoPath||``).trim(),worktreeRoot:String(t?.worktree_root||e?.worktree_root||e?.worktreeRoot||``).trim(),defaultBranch:String(t?.default_branch||e?.default_branch||e?.defaultBranch||`main`).trim(),remoteName:String(t?.remote_name||e?.remote_name||e?.remoteName||`origin`).trim(),credentialFile:String(t?.credential_file||e?.credential_file||e?.credentialFile||``).trim(),taskSource:n,implicit:e?.implicit===!0}}).filter(e=>e.slug).sort((e,t)=>e.implicit===t.implicit?e.slug.localeCompare(t.slug):e.implicit?1:-1)}function u_(e){return{items:Array.isArray(e?.items)?e.items.map((e,t)=>({id:String(e?.id||e?.project_item_id||`item-${t}`).trim(),projectItemId:String(e?.project_item_id||e?.projectItemId||``).trim(),title:String(e?.title||`Untitled item`).trim(),statusKey:String(e?.status_key||e?.statusKey||`unknown`).trim(),statusName:String(e?.status_name||e?.statusName||`Unknown`).trim(),issueNumber:e?.issue_number||e?.issueNumber||null,issueUrl:String(e?.issue_url||e?.issueUrl||``).trim(),repoName:String(e?.repo_name||e?.repoName||``).trim(),actionable:e?.actionable===!0,selector:String(e?.project_item_id||e?.projectItemId||e?.issue_number||e?.issueNumber||e?.id||``).trim()})).filter(e=>e.id):[],source:String(e?.source||``).trim(),warning:String(e?.warning||``).trim(),isStale:e?.is_stale===!0,lastSyncedAtMs:Number(e?.last_synced_at_ms||e?.lastSyncedAtMs||0)}}function d_(e,t){return String(e?.run_id||e?.runId||e?.id||`run-${t}`).trim()}function f_(e){return String(e?.title||e?.summary||e?.run_id||e?.runId||`Untitled run`).trim()}function p_(e){let t=Number(e?.updated_at_ms||e?.created_at_ms||e?.snapshot?.updated_at_ms||e?.snapshot?.created_at_ms||0);return Number.isFinite(t)?t:0}function m_(e){return String(e?.status||e?.snapshot?.status||e?.status?.run?.status||`unknown`).trim().toLowerCase()}function h_(e){return String(e?.phase?.name||e?.snapshot?.phase?.name||e?.status?.phase?.name||``).trim().toLowerCase()}function g_(e){return String(e||`unknown`).replace(/_/g,` `).replace(/\b\w/g,e=>e.toUpperCase())}var __=1800*1e3,v_=15*1e3;function y_(e){return e?.is_running===!0||e?.snapshot?.is_running===!0}function b_(e){let t=m_(e);if([`completed`,`done`,`failed`,`cancelled`,`blocked`,`archived`].includes(t))return!1;if(y_(e))return!0;let n=p_(e);return n?Date.now()-n<__:!1}function x_(e,t){let n=e?.blackboard?.task||e?.snapshot?.blackboard?.task||{},r=n?.source||{},i=n?.repo||{};return String(r?.issue_url||r?.url||r?.item_url||r?.project_item_id||r?.card_id||n?.task_id||`${i?.slug||e?.project_slug||`project`}:${f_(e)}:${t}`).trim()}function S_(e){return String(e?.issueUrl||e?.projectItemId||e?.id||``).trim()}function C_(e){let t=String(e?.statusKey||``).trim().toLowerCase();return!e?.selector||t===`in_review`||t===`done`?!1:e?.actionable===!0||[`ready`,`backlog`,`todo`].includes(t)}function w_(e){let t=new Map;return e.forEach((e,n)=>{let r=x_(e,n),i=t.get(r);(!i||p_(e)>=p_(i))&&t.set(r,e)}),Array.from(t.values()).sort((e,t)=>p_(t)-p_(e))}function T_(e){let t=String(e||``).trim();if(!t)return null;let n=e=>{let t=e.replace(/^\/+/,``).replace(/\.git$/i,``).split(`/`).map(e=>e.trim()).filter(Boolean);if(t.length<2)return null;let[n,r]=t;return!n||!r?null:{owner:n,repo:r,slug:`${n}/${r}`}},r=t.match(/^git@github\.com:([^/]+)\/(.+?)(?:\.git)?$/i);if(r?.[1]&&r?.[2])return n(`${r[1]}/${r[2]}`);try{let e=new URL(t);return e.hostname.toLowerCase()===`github.com`?n(e.pathname):null}catch{return n(t)}}function E_(e,{prompt:t,path:n,repoRef:r,projectNumber:i}){return e===`manual`?{type:`manual`,prompt:t.trim()}:e===`kanban_board`?{type:`kanban_board`,path:n.trim()}:e===`local_backlog`?{type:`local_backlog`,path:n.trim()}:{type:`github_project`,owner:r?.owner||``,repo:r?.repo||``,project:i.trim()}}function D_(e){let t=String(e||``).trim().replace(/\\/g,`/`);if(!t)return!0;if(t.startsWith(`/`)||/^[A-Za-z]:/.test(t))return!1;let n=t.split(`/`).filter(Boolean);return n.length>0&&!n.some(e=>e===`.`||e===`..`)}function O_(e){try{let t=JSON.parse(String(e||`{}`));return t&&typeof t==`object`?t:null}catch{return null}}function k_({api:e,client:t,toast:n,providerStatus:i,navigate:s}){let c=_(),[l,u]=r(`overview`),[d,f]=r(``),[h,g]=r(``),[v,b]=r(``),[x,S]=r(``),[C,w]=r(``),[T,E]=r(``),[D,O]=r(``),[k,A]=r(``),[j,M]=r(`main`),[N,P]=r(`origin`),[F,I]=r(``),[L,R]=r(`github_project`),[z,ee]=r(``),[B,V]=r(``),[H,te]=r(``),[U,ne]=r(``),[re,ie]=r(``),[ae,W]=r(``),[oe,se]=r(!1),[ce,le]=r(!1),[ue,de]=r(``),[fe,pe]=r(``),[G,K]=r(null),[me,he]=r(null),[ge,_e]=r(!1),[ve,ye]=r(null),[be,xe]=r(!1),[Se,Ce]=r(!1),[we,Te]=r([]),[Ee,De]=r({}),[Oe,ke]=r(!1),Ae=Oc(),je=Ae.data?.aca_integration===!0,Me=Ae.data?.engine_healthy===!0,Ne=Ae.data?.hosted_managed===!0,Pe=je||Me,Fe=y({queryKey:[`coding-workflows`,`health`],queryFn:()=>e(`/api/system/health`),refetchInterval:15e3}),q=y({queryKey:[`coding-workflows`,`aca-health`],queryFn:()=>e(`/api/aca/health`),enabled:je}),J=y({queryKey:[`coding-workflows`,`aca-overview`],queryFn:()=>e(`/api/aca/overview`),enabled:je,refetchInterval:je?3e4:!1}),Ie=y({queryKey:[`coding-workflows`,`aca-projects`],queryFn:()=>e(`/api/aca/projects`),enabled:je}),Le=y({queryKey:[`coding-workflows`,`aca-workspace-guide`],queryFn:()=>e(`/api/aca/workspace/guide`),enabled:je}),Re=y({queryKey:[`coding-workflows`,`aca-runs`],queryFn:()=>e(`/api/aca/runs`),enabled:je}),ze=y({queryKey:[`coding-workflows`,`coder-runs`],queryFn:()=>e(`/api/aca/operator/coder-runs`),enabled:je,refetchInterval:je?15e3:!1}),Be=y({queryKey:[`coding-workflows`,`aca-project-tasks`,d],queryFn:()=>e(`/api/aca/projects/${encodeURIComponent(d)}/tasks`),enabled:je&&!!d}),Ve=y({queryKey:[`coding-workflows`,`aca-project-board`,d],queryFn:()=>e(`/api/aca/projects/${encodeURIComponent(d)}/board`),enabled:je&&!!d&&l_(Ie.data).some(e=>e.slug===d&&String(e?.taskSource?.type||``).trim()===`github_project`),refetchInterval:je&&d&&l_(Ie.data).some(e=>e.slug===d&&String(e?.taskSource?.type||``).trim()===`github_project`)?12e4:!1}),He=y({queryKey:[`coding-workflows`,`aca-run-detail`,h],queryFn:()=>e(`/api/aca/runs/${encodeURIComponent(h)}`),enabled:je&&!!h}),Ue=y({queryKey:[`coding-workflows`,`aca-run-logs`,h],queryFn:()=>e(`/api/aca/runs/${encodeURIComponent(h)}/logs`),enabled:je&&!!h}),We=y({queryKey:[`coding-workflows`,`aca-run-log-tail`,h,v],queryFn:()=>e(`/api/aca/runs/${encodeURIComponent(h)}/logs/${encodeURIComponent(v)}?tail=120`),enabled:je&&!!h&&!!v}),Ge=y({queryKey:[`coding-workflows`,`mcp-servers`],queryFn:()=>t.mcp.list().catch(()=>({})),refetchInterval:Pe?1e4:!1,enabled:Pe}),Ke=y({queryKey:[`coding-workflows`,`mcp-tools`],queryFn:()=>t.mcp.listTools().catch(()=>[]),refetchInterval:Pe?15e3:!1,enabled:Pe}),qe=y({queryKey:[`coding-workflows`,`providers`,`catalog`],queryFn:()=>t.providers.catalog().catch(()=>({all:[]})),refetchInterval:Pe?3e4:!1,enabled:Pe}),Je=y({queryKey:[`coding-workflows`,`providers`,`config`],queryFn:()=>t.providers.config().catch(()=>({})),refetchInterval:Pe?3e4:!1,enabled:Pe}),Ye=o(()=>s_(Ge.data),[Ge.data]),Xe=o(()=>c_(Ke.data),[Ke.data]),Ze=o(()=>l_(Ie.data),[Ie.data]),Qe=o(()=>o_(Re.data,`runs`),[Re.data]),$e=o(()=>o_(ze.data,`coder_runs`),[ze.data]),et=o(()=>u_(Ve.data),[Ve.data]),tt=o(()=>ka({providerCatalog:qe.data,providerConfig:Je.data,defaultProvider:i.defaultProvider,defaultModel:i.defaultModel}),[i.defaultModel,i.defaultProvider,qe.data,Je.data]),nt=o(()=>T_(T),[T]);m(()=>{Ze.length&&(!d||!Ze.some(e=>e.slug===d))&&f(Ze[0].slug)},[Ze,d]);let rt=o(()=>d?Qe.filter(e=>String(e?.project_slug||``).trim()===d):Qe,[Qe,d]),it=o(()=>w_(rt),[rt]),at=o(()=>it.filter(b_),[it]);m(()=>{if(!it.length){g(``);return}let e=at.map((e,t)=>d_(e,t)),t=it.some((e,t)=>d_(e,t)===h),n=e.includes(h);if(e.length&&(!h||!n)){g(e[0]);return}(!h||!t)&&g(d_(it[0],0))},[at,h,it]);let ot=o(()=>o_(Ue.data,`logs`),[Ue.data]);m(()=>{if(!ot.length){b(``);return}(!v||!ot.some(e=>String(e?.name||``)===v))&&b(String(ot[0]?.name||``))},[ot,v]);let st=!!(Fe.data?.engine?.ready||Fe.data?.engine?.healthy),ct=Ye.some(e=>e.name.toLowerCase().includes(`github`)),lt=Ze.find(e=>e.slug===d)||null,ut=lt?.repo||{},dt=String(lt?.taskSource?.type||``).trim(),ft=String(Fe.data?.workspaceRoot||Fe.data?.workspace_root||(dt===`kanban_board`||dt===`local_backlog`)&&lt?.taskSource?.path||``).trim(),pt=Ye.filter(e=>e.connected).map(e=>e.name),mt=o(()=>et.items.filter(e=>we.includes(String(e.id||``))),[et.items,we]),Y=o(()=>et.items.filter(e=>C_(e)),[et.items]),ht=o(()=>new Set(Object.keys(Ee)),[Ee]),gt=i.defaultProvider&&i.defaultModel?`ACA default (${i.defaultProvider} / ${i.defaultModel})`:`ACA default`,_t=(e=!1)=>a(`div`,{className:`grid gap-2`,children:[a(ma,{providerLabel:`ACA provider`,modelLabel:`ACA model`,draft:{provider:re,model:ae},providers:tt,onChange:({provider:e,model:t})=>{ie(e),W(t)},inheritLabel:gt,disabled:e}),a(`div`,{className:`tcp-subtle text-xs`,children:`Leave blank to inherit the base ACA provider and model for this run.`})]}),vt=o(()=>new Set(at.map((e,t)=>x_(e,t)).map(e=>String(e||``).trim()).filter(Boolean)),[at]),yt=it.find((e,t)=>d_(e,t)===h)||null,bt=String(He.data?.summary||``).trim(),xt=He.data?.blackboard||null;m(()=>{pe(``)},[h]),m(()=>{if(!je)return;let e=Yi(`/api/aca/events`,e=>{let t=O_(String(e?.data||``));if(!t||t.event_type===`ping`)return;de(String(t.event_type||`event`).trim()),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-overview`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]}),d&&(c.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-board`,d]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-tasks`,d]}));let n=String(t?.payload?.run_id||t?.payload?.event?.run_id||``).trim();h&&n&&n===h&&c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-detail`,h]})});return()=>e()},[je,c,d,h]),m(()=>{if(!je||!h||!yt?.is_running)return;let e=Yi(`/api/aca/runs/${encodeURIComponent(h)}/events`,e=>{let t=O_(String(e?.data||``));!t||t.event_type===`ping`||(pe(String(t.event_type||`event`).trim()),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-detail`,h]}),c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-logs`,h]}),v&&c.invalidateQueries({queryKey:[`coding-workflows`,`aca-run-log-tail`,h,v]}))});return()=>e()},[je,c,v,yt?.is_running,h]),m(()=>{Be.data&&K(Date.now())},[Be.data]),m(()=>{Ve.data&&he(Number(Ve.data?.last_synced_at_ms||Date.now()))},[Ve.data]),m(()=>{Te([])},[d]),m(()=>{De({})},[d]),m(()=>{let e=Object.entries(Ee);if(!e.length)return;let t=e.map(([e,t])=>{let n=Date.now()-Number(t||0),r=Math.max(0,v_-n);return window.setTimeout(()=>{De(t=>{if(!t[e])return t;let n={...t};return delete n[e],n})},r)});return()=>{t.forEach(e=>window.clearTimeout(e))}},[Ee]),m(()=>{!Object.keys(Ee).length||!et.items.length||De(e=>{let t=!1,n={...e};return et.items.forEach(e=>{let r=String(e?.id||``).trim();!r||n[r]===void 0||vt.has(S_(e))&&(delete n[r],t=!0)}),t?n:e})},[vt,et.items,Ee]),m(()=>{let e=new Set(et.items.map(e=>String(e.id||``)));Te(t=>t.filter(t=>e.has(t)))},[et.items]);let St=[{id:`overview`,label:`Overview`,icon:`layout-dashboard`},{id:`board`,label:`Intake`,icon:`list-checks`},{id:`planning`,label:`Planning`,icon:`clipboard-list`},{id:`manual`,label:`Manual tasks`,icon:`code`},{id:`integrations`,label:`Integrations`,icon:`plug-zap`}];async function Ct(t){let r=String(t||``).trim();if(r)try{await e(`/api/aca/operator/coder-runs/${encodeURIComponent(r)}/reconcile`,{method:`POST`}),await c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),n(`ok`,`Reconciled coder run ${r}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function wt(t){let r=String(t||``).trim();if(r&&window.confirm(`Cancel coder run ${r}?`))try{await e(`/api/aca/operator/coder-runs/${encodeURIComponent(r)}/cancel`,{method:`POST`,body:JSON.stringify({reason:`cancelled from Tandem Control Panel Coder view`})}),await c.invalidateQueries({queryKey:[`coding-workflows`,`coder-runs`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]}),n(`ok`,`Cancelled coder run ${r}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function Tt(){let t=T_(T),r=x.trim()||L===`github_project`&&t?.slug||``,i=C.trim(),a=T.trim(),o=D.trim(),s=k.trim(),l=j.trim(),u=N.trim(),d=F.trim();if(L===`github_project`&&!t){n(`warn`,`Paste a GitHub repository URL like https://github.com/owner/repo.`);return}if(!r){n(`warn`,`Project slug is required.`);return}if(o&&!D_(o)||s&&!D_(s)){n(`warn`,`Repo paths must stay within the managed workspace root.`);return}let p=E_(L,{prompt:z,path:B,repoRef:t,projectNumber:H});if(p.type===`manual`&&!p.prompt){n(`warn`,`Manual task source requires a prompt.`);return}if([`kanban_board`,`local_backlog`].includes(p.type)&&!p.path){n(`warn`,`This task source requires a path.`);return}if(p.type===`github_project`&&(!p.owner||!p.repo||!p.project)){n(`warn`,`GitHub Project task sources require a repo URL and project number.`);return}se(!0);try{let t=new URLSearchParams({slug:r});a&&t.set(`repo_url`,a),i&&t.set(`name`,i),o&&t.set(`repo_path`,o),s&&t.set(`worktree_root`,s),l&&t.set(`default_branch`,l),u&&t.set(`remote_name`,u),d&&t.set(`credential_file`,d),await e(`/api/aca/projects?${t.toString()}`,{method:`POST`,body:JSON.stringify(p)}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-workspace-guide`]}),f(r),S(``),w(``),E(``),O(``),A(``),M(`main`),P(`origin`),I(``),n(`ok`,`Registered ACA project ${r}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{se(!1)}}async function Et(){if(!d){n(`warn`,`Select a project before triggering a run.`);return}let t={};re.trim()&&(t.ACA_PROVIDER=re.trim()),ae.trim()&&(t.ACA_MODEL=ae.trim()),le(!0);try{let r=new URLSearchParams({project_slug:d});U.trim()&&r.set(`item`,U.trim());let i=await e(`/api/aca/runs/trigger?${r.toString()}`,{method:`POST`,body:JSON.stringify(t)});await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]});let a=String(i?.run_id||``).trim();a&&(g(a),u(`board`)),n(`ok`,`ACA run started${a?`: ${a}`:`.`}`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{le(!1)}}function Dt(e){Te(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}function Ot(){Te(et.items.filter(e=>C_(e)&&!vt.has(S_(e))&&!ht.has(String(e.id||``))).map(e=>String(e.id||``)))}function kt(){Te([])}async function At(t){if(!d){n(`warn`,`Select a project before starting ACA runs.`);return}let r=t.filter(e=>C_(e)&&!vt.has(S_(e))&&!ht.has(String(e.id||``))),i=r.map(e=>String(e?.selector||``).trim()).filter(Boolean);if(!i.length){n(`warn`,`Those GitHub items are already running or are not launchable from ACA intake.`);return}let a={};re.trim()&&(a.ACA_PROVIDER=re.trim()),ae.trim()&&(a.ACA_MODEL=ae.trim()),De(e=>{let t={...e},n=Date.now();return r.forEach(e=>{let r=String(e?.id||``).trim();r&&(t[r]=n)}),t}),ke(!0);try{let t=await e(`/api/aca/runs/trigger-batch`,{method:`POST`,body:JSON.stringify({project_slug:d,items:i,overrides:a})});await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-runs`]});let r=o_(t,`runs`),o=String(r?.[0]?.run_id||``).trim();o&&(g(o),u(`board`)),n(`ok`,`Started ${i.length} ACA run${i.length===1?``:`s`}.`),Te([])}catch(e){De(e=>{let t={...e};return r.forEach(e=>{let n=String(e?.id||``).trim();n&&delete t[n]}),t}),n(`err`,e instanceof Error?e.message:String(e))}finally{ke(!1)}}async function jt(){if(!d){n(`warn`,`Select a project before refreshing GitHub intake.`);return}try{await Be.refetch(),K(Date.now()),n(`ok`,`Refreshed task intake from GitHub MCP.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function Mt(){if(!d){n(`warn`,`Select a GitHub-backed project before refreshing the board.`);return}try{let t=await e(`/api/aca/projects/${encodeURIComponent(d)}/board?refresh=true`);c.setQueryData([`coding-workflows`,`aca-project-board`,d],t),he(Number(t?.last_synced_at_ms||Date.now())),n(`ok`,`Refreshed GitHub Project items through Tandem MCP.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}}async function Nt(){if(!d){n(`warn`,`Select a project before syncing its repository.`);return}_e(!0),ye(null);try{let t=await e(`/api/aca/projects/${encodeURIComponent(d)}/repo/sync`,{method:`POST`});ye(t),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-projects`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-workspace-guide`]}),await c.invalidateQueries({queryKey:[`coding-workflows`,`aca-project-tasks`,d]}),n(`ok`,`Repository ready at ${String(t?.repo?.path||`managed checkout`)}.`)}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{_e(!1)}}return je?a(ir,{className:`grid gap-4`,children:[a(dr,{className:`overflow-hidden`,children:a(`div`,{className:`grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Coder`}),a(`h1`,{className:`tcp-page-title`,children:`Coder project intake and run dashboard`}),a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:`This view talks to the ACA control plane for project registration, task preview, durable coder runs, live logs, and final handoff artifacts.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(X,{tone:q.data?.status===`healthy`?`ok`:`warn`,children:q.data?.status===`healthy`?`ACA healthy`:`ACA checking`}),a(X,{tone:st?`ok`:`warn`,children:st?`Engine healthy`:`Engine checking`}),a(X,{tone:ct?`ok`:`warn`,children:ct?`GitHub MCP connected`:`GitHub MCP pending`}),a(cr,{tone:at.length?`live`:`info`,text:`${at.length} active runs`}),ue?a(X,{tone:`ghost`,children:[`Live `,g_(ue)]}):null]})]}),a(`div`,{className:`grid gap-3 rounded-2xl border border-white/10 bg-black/20 p-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-sm font-semibold text-slate-100`,children:`Repository`}),a(`div`,{className:`tcp-subtle mt-1 truncate text-xs`,children:d?String(ut?.path||ut?.clone_url||lt?.repo_url||d):`Select a project to sync its checkout.`})]}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:Nt,disabled:!d||ge,children:[a(`i`,{"data-lucide":ge?`loader-circle`:`refresh-cw`}),ge?`Syncing`:`Sync repo`]})]}),a(`div`,{className:`grid gap-2 text-xs`,children:[a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:ut?.clone_url?`ok`:`ghost`,children:ut?.clone_url?`remote git`:`local git`}),a(X,{tone:`ghost`,children:String(ut?.default_branch||`main`)}),ve?.repo?.dirty?a(X,{tone:`warn`,children:`dirty`}):null]}),ve?.repo?.commit?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle truncate`,children:[`Ready at `,String(ve.repo.path),` ·`,` `,String(ve.repo.commit).slice(0,7)]}),a(`div`,{className:`rounded-xl border border-sky-500/20 bg-sky-500/10 p-2 text-sky-100`,children:`Bug Monitor should use this checkout as its local directory when reporting issues for this repo.`})]}):null]})]})]})}),a(`div`,{className:`tcp-settings-tabs`,children:St.map(e=>a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${l===e.id?`active`:``}`,onClick:()=>u(e.id),children:[a(`i`,{"data-lucide":e.icon}),e.label]},e.id))}),l===`overview`?a(Tg,{projects:Ze,selectedProjectSlug:d,setSelectedProjectSlug:f,selectedProject:lt,acaOverview:J,projectTasksQuery:Be,refreshTaskPreview:jt,taskPreviewRefreshAt:G,coderRuns:$e,coderRunsQuery:ze,reconcileCoderRun:Ct,cancelCoderRun:wt,visibleRunsCount:rt.length,activeRunsCount:at.length,connectedMcpServersCount:Ye.length,registeredToolsCount:Xe.length}):null,l===`board`?a(`div`,{className:`grid gap-4`,children:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`GitHub Project intake`,subtitle:`GitHub items ACA can launch`,children:[a(`div`,{className:`mb-4`,children:a(`select`,{className:`tcp-input`,value:d,onChange:e=>f(e.target.value),children:[Ze.length?null:a(`option`,{value:``,children:`No ACA projects found`}),Ze.map(e=>a(`option`,{value:e.slug,children:e.name?`${e.name} · ${e.slug}`:e.slug},e.slug))]})}),String(lt?.taskSource?.type||``).trim()===`github_project`?Ve.isLoading?a(`div`,{className:`tcp-subtle text-sm`,children:`Loading GitHub Project items...`}):Ve.isError?a(`div`,{className:`rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-200`,children:Ve.error instanceof Error?Ve.error.message:`Could not load the GitHub Project items.`}):a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-white/10 bg-black/20 p-3`,children:[a(`div`,{className:`tcp-subtle text-xs`,children:[`Items are listed by ACA launchability with direct run controls.`,me?` Last synced ${new Date(me).toLocaleTimeString()}.`:``]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(X,{tone:et.isStale?`warn`:`ok`,children:et.isStale?`Cached snapshot`:g_(et.source||`live`)}),a(`button`,{type:`button`,className:`tcp-btn tcp-btn-secondary`,onClick:Mt,disabled:Ve.isFetching,children:Ve.isFetching?`Refreshing...`:`Refresh from GitHub`})]})]}),a(`div`,{className:`flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-cyan-500/20 bg-cyan-500/10 p-3`,children:[a(`div`,{className:`tcp-subtle text-xs`,children:`Select GitHub items here to start ACA runs directly from the board. This creates one ACA run per selected item and starts them immediately.`}),a(`div`,{className:`min-w-[320px] flex-1`,children:_t(Oe)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn tcp-btn-secondary`,onClick:Ot,disabled:!Y.length||Oe,children:`Select actionable`}),a(`button`,{type:`button`,className:`tcp-btn tcp-btn-secondary`,onClick:kt,disabled:!we.length||Oe,children:`Clear selection`}),a(`button`,{type:`button`,className:`tcp-btn-primary`,onClick:()=>At(mt),disabled:!mt.length||Oe,children:Oe?`Starting...`:`Run selected${mt.length?` (${mt.length})`:``}`})]})]}),et.warning?a(`div`,{className:`rounded-2xl border border-yellow-500/20 bg-yellow-500/10 p-4 text-sm text-yellow-100`,children:et.warning}):null,et.items.length?a(`div`,{className:`grid gap-3`,children:et.items.map(e=>{let t=C_(e),n=String(e.id||``),r=t&&vt.has(S_(e)),i=ht.has(n),o=r||i||Oe;return a(`div`,{className:`rounded-2xl border px-4 py-3 transition ${we.includes(n)?`border-cyan-400/60 bg-cyan-500/10`:`border-white/10 bg-black/20`}`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{className:`flex min-w-0 flex-1 items-start gap-3`,children:[a(`input`,{type:`checkbox`,className:`mt-1 h-4 w-4 shrink-0`,checked:we.includes(n),disabled:!t||o,onChange:()=>Dt(n)}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`break-words text-sm font-semibold leading-5`,children:String(e.title||`Untitled item`)}),a(`div`,{className:`tcp-subtle mt-1 break-words text-xs leading-5`,children:[e.repoName?String(e.repoName):d,e.issueNumber?` #${String(e.issueNumber)}`:``]})]})]}),a(`div`,{className:`flex shrink-0 flex-wrap items-center gap-2`,children:[e.actionable?a(X,{tone:`ok`,children:`Actionable`}):null,a(X,{tone:`ghost`,children:g_(String(e.statusName||e.statusKey||`Unknown`))}),r?a(X,{tone:`info`,children:`Run active`}):null,i&&!r?a(X,{tone:`warn`,children:`Starting`}):null]})]}),a(`div`,{className:`mt-3 flex flex-wrap gap-2 pl-7`,children:[e.issueUrl?a(`a`,{className:`tcp-btn h-8 px-3 text-xs`,href:e.issueUrl,target:`_blank`,rel:`noreferrer`,children:`Open in GitHub`}):null,a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>At([e]),disabled:!t||o,children:t?r?`Already running`:i?`Starting...`:`Run task`:`Not launchable`})]})]},n)})}):a(Pr,{text:`No GitHub Project items returned for this project.`})]}):a(Pr,{text:`The selected project is not backed by a GitHub Project task source.`})]}),a(dr,{title:`ACA execution history`,subtitle:`Recent runs for the selected project`,children:it.length?a(`div`,{className:`grid gap-2`,children:it.map((e,t)=>{let n=d_(e,t);return a(`button`,{type:`button`,className:`rounded-2xl border px-3 py-3 text-left transition ${n===h?`border-cyan-400/60 bg-cyan-500/10`:`border-white/10 bg-black/20 hover:border-white/20`}`,onClick:()=>g(n),children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:f_(e)}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[String(e?.project_slug||`unknown`),e?.branch?` · ${String(e.branch)}`:``]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:b_(e)?`info`:`ok`,children:g_(m_(e))}),h_(e)?a(X,{tone:`ghost`,children:g_(h_(e))}):null]})]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:n})]},n)})}):a(Pr,{text:`No ACA runs for this project yet.`})}),a(dr,{title:`Run detail`,subtitle:h?`ACA detail for ${h}`:`Select a run`,actions:a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>xe(e=>!e),children:[a(`i`,{"data-lucide":be?`chevron-down`:`chevron-right`}),be?`Collapse`:`Expand`]}),children:be?h?He.isLoading?a(`div`,{className:`tcp-subtle text-sm`,children:`Loading run detail...`}):He.isError?a(`div`,{className:`rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-200`,children:He.error instanceof Error?He.error.message:`Could not load run detail.`}):a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-sm font-semibold`,children:String(He.data?.status?.task?.title||yt?.title||h)}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(He.data?.project_slug||yt?.project_slug||`unknown`)})]}),a(X,{tone:He.data?.is_running?`info`:`ok`,children:g_(String(He.data?.status?.run?.status||yt?.status||`unknown`))})]}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[He.data?.status?.phase?.name?a(X,{tone:`info`,children:[`Phase `,g_(String(He.data.status.phase.name))]}):null,fe?a(X,{tone:`ghost`,children:[`Latest `,g_(fe)]}):null,He.data?.snapshot?.summary_available?a(X,{tone:`ok`,children:`Summary ready`}):null,He.data?.error?a(X,{tone:`warn`,children:`Has error`}):null]})]}),bt?a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`mb-2 text-sm font-semibold`,children:`Summary`}),a(`pre`,{className:`max-h-56 overflow-auto whitespace-pre-wrap text-xs leading-6 text-slate-200`,children:bt})]}):null,a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`mb-2 text-sm font-semibold`,children:`Blackboard`}),a(Lr,{value:xt||{},label:`Show blackboard`,preClassName:`max-h-72 overflow-auto whitespace-pre-wrap text-xs leading-6 text-slate-200`})]})]}):a(Pr,{text:`Select a run from the board to inspect its status, summary, and blackboard.`}):null}),a(dr,{title:`Live logs`,subtitle:`Tail ACA worker and manager logs`,actions:a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>Ce(e=>!e),children:[a(`i`,{"data-lucide":Se?`chevron-down`:`chevron-right`}),Se?`Collapse`:`Expand`]}),children:Se?h?a(`div`,{className:`grid gap-3`,children:[ot.length?a(`select`,{className:`tcp-input`,value:v,onChange:e=>b(e.target.value),children:ot.map(e=>a(`option`,{value:String(e?.name||``),children:String(e?.name||``)},String(e?.name||``)))}):a(`div`,{className:`tcp-subtle text-sm`,children:`No logs available yet.`}),v&&We.data?.lines?a(`pre`,{className:`max-h-80 overflow-auto rounded-2xl border border-white/10 bg-black/30 p-4 text-xs leading-6 text-slate-200`,children:o_(We.data,`lines`).join(`
2897
2897
  `)}):null]}):a(Pr,{text:`Choose a run to inspect log output.`}):null})]})}):null,l===`manual`?a(`div`,{className:`grid gap-4`,children:a(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[a(dr,{title:`Register project`,subtitle:`Bind a repository, managed checkout, and task source into ACA`,children:a(`div`,{className:`grid gap-3`,children:[L===`github_project`?a(p,{children:[a(`input`,{className:`tcp-input`,placeholder:`GitHub repo URL, e.g. https://github.com/frumu-ai/tandem`,value:T,onInput:e=>E(e.target.value)}),a(`div`,{className:`rounded-2xl border border-cyan-500/20 bg-cyan-500/10 px-3 py-2 text-xs text-cyan-100`,children:nt?`Detected ${nt.owner}/${nt.repo}. ACA will use this for the GitHub Project owner/repo binding.`:`Paste a GitHub repository URL and ACA will derive the owner, repo, and default project slug.`})]}):a(`input`,{className:`tcp-input`,placeholder:`Repo URL (optional)`,value:T,onInput:e=>E(e.target.value)}),Ne?a(p,{children:[a(`input`,{className:`tcp-input`,placeholder:`Managed checkout path, e.g. repos/team-alpha`,value:D,onInput:e=>O(e.target.value)}),a(`input`,{className:`tcp-input`,placeholder:`Worktree root (optional)`,value:k,onInput:e=>A(e.target.value)}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`input`,{className:`tcp-input`,placeholder:`Default branch (optional)`,value:j,onInput:e=>M(e.target.value)}),a(`input`,{className:`tcp-input`,placeholder:`Remote name (optional)`,value:N,onInput:e=>P(e.target.value)})]}),a(`input`,{className:`tcp-input`,placeholder:`Token file for private repos (optional)`,value:F,onInput:e=>I(e.target.value)})]}):null,Ne?a(`div`,{className:`rounded-2xl border border-lime-500/20 bg-lime-500/10 px-3 py-2 text-xs text-lime-100`,children:`Hosted installs can use these fields to register named repos and managed checkout directories without exposing an interactive shell.`}):null,a(`input`,{className:`tcp-input`,placeholder:L===`github_project`?`Project slug (optional, defaults to owner/repo)`:`Project slug`,value:x,onInput:e=>S(e.target.value)}),a(`input`,{className:`tcp-input`,placeholder:`Project display name (optional)`,value:C,onInput:e=>w(e.target.value)}),a(`select`,{className:`tcp-input`,value:L,onChange:e=>R(e.target.value),children:[a(`option`,{value:`manual`,children:`Manual prompt`}),a(`option`,{value:`kanban_board`,children:`Kanban board`}),a(`option`,{value:`local_backlog`,children:`Local backlog`}),a(`option`,{value:`github_project`,children:`GitHub Project`})]}),L===`manual`?a(`textarea`,{className:`tcp-input min-h-[120px]`,placeholder:`Manual task prompt`,value:z,onInput:e=>ee(e.target.value)}):null,L===`kanban_board`||L===`local_backlog`?a(`input`,{className:`tcp-input`,placeholder:`Absolute file path`,value:B,onInput:e=>V(e.target.value)}):null,L===`github_project`?a(p,{children:[a(`input`,{className:`tcp-input`,placeholder:`GitHub Project number`,value:H,onInput:e=>te(e.target.value)}),a(`div`,{className:`tcp-subtle text-xs`,children:`Only GitHub Project board tasks are imported. Public issues that are not on this project board remain outside ACA intake.`})]}):null,a(`button`,{type:`button`,className:`tcp-btn`,disabled:oe,onClick:Tt,children:oe?`Registering...`:`Register Project`})]})}),a(dr,{title:`Trigger run`,subtitle:`Launch an ACA coding session for the selected project`,children:a(`div`,{className:`grid gap-3`,children:[a(`select`,{className:`tcp-input`,value:d,onChange:e=>f(e.target.value),children:[Ze.length?null:a(`option`,{value:``,children:`No ACA projects found`}),Ze.map(e=>a(`option`,{value:e.slug,children:e.slug},e.slug))]}),a(`input`,{className:`tcp-input`,placeholder:`Specific item or card id (optional)`,value:U,onInput:e=>ne(e.target.value)}),_t(ce),a(`button`,{type:`button`,className:`tcp-btn-primary`,disabled:ce,onClick:Et,children:ce?`Starting...`:`Trigger ACA Run`})]})})]})}):null,l===`planning`?a(a_,{client:t,api:e,toast:n,selectedProjectSlug:d,selectedProject:lt,githubProjectBoardSnapshot:Ve.data||null,taskSourceType:dt,workspaceRootSeed:ft,connectedMcpServers:pt,engineHealthy:st,providerStatus:i}):null,l===`integrations`?a(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[a(dr,{title:`ACA connection`,subtitle:`Control-plane endpoint the coding page uses`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`text-sm font-semibold`,children:`Health`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[q.data?.status||`Unavailable`,q.data?.version?` · ${String(q.data.version)}`:``]})]}),a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`text-sm font-semibold`,children:`Projects`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[Ze.length,` registered`]})]}),a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`text-sm font-semibold`,children:`Runs`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[Qe.length,` visible through ACA`]})]})]})}),a(dr,{title:`Workspace guide`,subtitle:`What the agent should inspect first`,children:Le.data?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`text-sm font-semibold`,children:`Active project`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[String(Le.data?.active_project?.name||`None`).trim(),Le.data?.active_project?.repo?.path?` · ${String(Le.data.active_project.repo.path)}`:``]})]}),a(`div`,{className:`rounded-2xl border border-white/10 bg-black/20 p-4`,children:[a(`div`,{className:`text-sm font-semibold`,children:`Layout`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:String(Le.data?.layout?.worktree_root||`managed root`)})]}),a(`ul`,{className:`grid gap-2 text-xs text-slate-200`,children:(Array.isArray(Le.data?.instructions)?Le.data.instructions:[]).map((e,t)=>a(`li`,{className:`rounded-xl border border-white/10 bg-black/10 px-3 py-2`,children:e},`${t}-${e}`))})]}):a(Pr,{text:`Workspace guide unavailable yet.`})}),a(dr,{title:`Connected MCP servers`,subtitle:`Engine integrations still available alongside ACA`,children:Ye.length?a(`div`,{className:`grid gap-2`,children:Ye.map(e=>a(`div`,{className:`flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-black/20 px-3 py-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:e.name}),a(`div`,{className:`tcp-subtle text-xs`,children:[e.transport||`transport pending`,e.lastError?` · ${e.lastError}`:``]})]}),a(X,{tone:e.connected?`ok`:e.enabled?`warn`:`ghost`,children:e.connected?`Connected`:e.enabled?`Configured`:`Disabled`})]},e.name))}):a(Pr,{text:`No MCP servers detected yet.`})})]}):null]}):a(ir,{className:`grid gap-4`,children:a(dr,{className:`overflow-hidden`,children:a(`div`,{className:`grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start`,children:a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Coder`}),a(`h1`,{className:`tcp-page-title`,children:`Coder dashboard`}),a(`p`,{className:`tcp-subtle mt-2 max-w-3xl`,children:`ACA integration is required for Coder. Connect the ACA control plane so this workspace can load registered projects, task intake, and live run details.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(X,{tone:Me?`ok`:`warn`,children:Me?`Engine healthy`:`Engine unavailable`}),a(X,{tone:`warn`,children:`ACA disconnected`})]}),a(`div`,{className:`mt-4 rounded-2xl border border-yellow-500/20 bg-yellow-500/10 p-4`,children:[a(`p`,{className:`text-sm text-yellow-200`,children:[a(`strong`,{children:`ACA integration required.`})," Set `ACA_BASE_URL` and make sure the control panel can authenticate to ACA with `ACA_API_TOKEN` or `ACA_API_TOKEN_FILE`."]}),a(`button`,{type:`button`,className:`tcp-btn mt-3`,onClick:()=>s(`settings`),children:`Open ACA setup`})]})]})})})})}function A_({client:e,toast:t}){let n=_(),r=y({queryKey:[`channels`,`status`],queryFn:()=>e.channels.status().catch(()=>({})),refetchInterval:6e3}),i=y({queryKey:[`channels`,`config`],queryFn:()=>e.channels.config().catch(()=>({})),refetchInterval:15e3}),o=x({mutationFn:async t=>{let n=(i.data||{})[t];if(!n)throw Error(`No config found for ${t}`);await e.channels.put(t,n)},onSuccess:async()=>{t(`ok`,`Channel reconfigured.`),await n.invalidateQueries({queryKey:[`channels`]})},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),s=r.data&&typeof r.data==`object`?r.data:{},c=Object.entries(s);return a(`div`,{className:`grid gap-4`,children:[a(Nr,{title:`Chat automation drafts`,subtitle:`How Tandem turns channel messages into bounded automations`,children:a(`div`,{className:`grid gap-3 text-sm`,children:[a(`p`,{className:`tcp-subtle`,children:`When someone asks Tandem to create an automation from Discord, Telegram, Slack, or a direct chat, Tandem keeps the draft in that same conversation instead of opening the workflow editor.`}),a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`strong`,{children:`Questions`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Tandem captures the next non-command reply from the same person in the same chat scope.`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`strong`,{children:`Confirmation`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`The draft is only created after a plain text confirm. Reply cancel to stop.`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`strong`,{children:`Bounds`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`The created automation records the source channel, sender, scope, and allowed tool policy.`})]})]})]})}),a(Nr,{title:`Channels`,subtitle:`Connector health and quick reconnect`,children:a(`div`,{className:`grid gap-2`,children:c.length?c.map(([e,t])=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:e}),a(`span`,{className:t?.connected?`tcp-badge-ok`:`tcp-badge-warn`,children:t?.connected?`connected`:`disconnected`})]}),a(`div`,{className:`tcp-subtle text-xs`,children:String(t?.last_error||t?.error||``)||`No recent errors.`}),a(`div`,{className:`mt-2`,children:a(`button`,{className:`tcp-btn h-7 px-2 text-xs`,onClick:()=>o.mutate(e),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Reconnect`]})})]},e)):a(Pr,{text:`No channels configured.`})})})]})}function j_(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function M_(e){return String(e||``).trim()}function N_(e){return e?`ok`:`ghost`}function P_(e){return M_(e?.event_type||e?.type||e?.event||`workflow.event`)}function F_(e,t){return`/api/engine/packs/${encodeURIComponent(M_(e))}/files/${encodeURI(M_(t))}`}function I_({api:e,toast:t}){let n=_(),[i,s]=r(``),[c,l]=r(``),[u,d]=r(``),[f,m]=r(`context.task.created`),[h,g]=r(`{
2898
2898
  "event_id": "demo-task-1"
2899
2899
  }`),[v,b]=r([]),S=y({queryKey:[`packs`,`list`],queryFn:()=>e(`/api/engine/packs`,{method:`GET`}).catch(()=>({packs:[]})),refetchInterval:15e3}),C=y({queryKey:[`workflows`,`list`],queryFn:()=>e(`/api/engine/workflows`,{method:`GET`}).catch(()=>({workflows:[]})),refetchInterval:15e3}),w=y({queryKey:[`workflows`,`hooks`],queryFn:()=>e(`/api/engine/workflow-hooks`,{method:`GET`}).catch(()=>({hooks:[]})),refetchInterval:15e3}),T=j_(S.data,`packs`),E=j_(C.data,`workflows`),D=j_(w.data,`hooks`),O=o(()=>c||M_(T[0]?.pack_id||T[0]?.name),[T,c]),k=o(()=>u||M_(E[0]?.workflow_id),[u,E]),A=j_(y({queryKey:[`workflows`,`runs`,k],queryFn:()=>e(`/api/engine/workflows/runs${k?`?workflow_id=${encodeURIComponent(k)}&limit=20`:`?limit=20`}`,{method:`GET`}).catch(()=>({runs:[]})),refetchInterval:6e3}).data,`runs`),j=y({queryKey:[`packs`,`detail`,O],enabled:!!O,queryFn:()=>e(`/api/engine/packs/${encodeURIComponent(O)}`,{method:`GET`})}),M=y({queryKey:[`workflows`,`detail`,k],enabled:!!k,queryFn:()=>e(`/api/engine/workflows/${encodeURIComponent(k)}`,{method:`GET`})}),N=x({mutationFn:()=>e(`/api/engine/packs/install`,{method:`POST`,body:JSON.stringify({path:i,source:{kind:`control-panel`}})}),onSuccess:async()=>{t(`ok`,`Pack installed.`),s(``),await Promise.all([n.invalidateQueries({queryKey:[`packs`]}),n.invalidateQueries({queryKey:[`workflows`]})])},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),P=x({mutationFn:t=>e(`/api/engine/workflows/${encodeURIComponent(t)}/run`,{method:`POST`}),onSuccess:async e=>{t(`ok`,`Workflow ${M_(e?.run?.workflow_id||k)} started.`),await Promise.all([n.invalidateQueries({queryKey:[`workflows`]}),n.invalidateQueries({queryKey:[`workflows`,`runs`]})])},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),F=x({mutationFn:async()=>{let t={},n=M_(h);return n&&(t=JSON.parse(n)),e(`/api/engine/workflows/simulate`,{method:`POST`,body:JSON.stringify({event_type:f,properties:t})})},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),I=x({mutationFn:({bindingId:t,enabled:n})=>e(`/api/engine/workflow-hooks/${encodeURIComponent(t)}`,{method:`PATCH`,body:JSON.stringify({enabled:n})}),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:[`workflows`,`hooks`]}),n.invalidateQueries({queryKey:[`workflows`,`detail`]})])},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),L=j.data?.pack||null,R=M.data?.workflow||null,z=j_(M.data,`hooks`),ee=F.data?.simulation||null,B=L?.manifest?.marketplace||null,V=B?.publisher||null,H=B?.listing||null,te=M_(H?.icon||``),U=M_(y({queryKey:[`packs`,`readme`,O],enabled:!!O,queryFn:async()=>{let e=await fetch(F_(O,`README.md`),{credentials:`include`});return e.ok?e.text():``}}).data||``),ne=te?F_(O,te):``,re=j_(H,`screenshots`).map(e=>M_(e));return Zu(`/api/engine/workflows/events${k?`?workflow_id=${encodeURIComponent(k)}`:``}`,e=>{try{let t=JSON.parse(e.data);if(t?.status===`ready`)return;b(e=>[...e.slice(-59),{at:Date.now(),data:t}])}catch{}},{enabled:!0}),a(ir,{className:`grid gap-4`,children:[a(pr,{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:a(p,{children:[a(X,{tone:`info`,children:[T.length,` installed packs`]}),a(X,{tone:`warn`,children:[E.length,` workflows`]}),a(X,{tone:`ghost`,children:[D.length,` hooks`]})]})}),a(mr,{main:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`Installed packs`,subtitle:`Select a pack to inspect its manifest, declared workflow contents, and hook contributions.`,children:a(`div`,{className:`grid gap-2`,children:T.length?T.map((e,t)=>{let n=M_(e?.pack_id||e?.name||t);return a(`button`,{type:`button`,className:`tcp-list-item text-left ${n===O?`border-amber-400/70`:``}`,onClick:()=>l(n),children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:M_(e?.name||n)}),a(`span`,{className:`tcp-badge-info`,children:M_(e?.version||`-`)})]}),a(`div`,{className:`flex flex-wrap gap-2 text-xs`,children:[a(`span`,{className:`tcp-subtle`,children:M_(e?.pack_type||`pack`)}),a(`span`,{className:`tcp-subtle`,children:M_(e?.install_path||``)})]})]},n)}):a(Pr,{text:`No packs are installed yet.`})})}),a(dr,{title:`Workflow registry`,subtitle:`This is the live workflow registry resolved from built-ins, installed packs, and workspace-local overrides.`,children:a(`div`,{className:`grid gap-2`,children:E.length?E.map(e=>{let t=M_(e?.workflow_id),n=t===k,r=M_(e?.source?.kind||`unknown`);return a(`button`,{type:`button`,className:`tcp-list-item text-left ${n?`border-amber-400/70`:``}`,onClick:()=>d(t),children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:M_(e?.name||t)}),a(`span`,{className:`tcp-badge-${r===`pack`?`warn`:`info`}`,children:r})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[t,` · `,j_(e?.steps,`steps`).length,` steps`]})]},t)}):a(Pr,{text:`No workflows are currently registered.`})})})]}),aside:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`Install pack`,subtitle:`Install a local pack path and reload workflow contributions automatically.`,children:a(`div`,{className:`grid gap-3`,children:[a(`input`,{className:`tcp-input`,value:i,onInput:e=>s(e.target.value),placeholder:`/path/to/pack.zip`}),a(`button`,{className:`tcp-btn-primary`,disabled:!i.trim()||N.isPending,onClick:()=>N.mutate(),children:[a(`i`,{"data-lucide":`download`}),`Install from path`]})]})}),a(dr,{title:`Pack inspector`,subtitle:`Shows which workflows and hooks a pack contributes, alongside its current capability surface.`,children:L?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:M_(L?.installed?.name||O)}),a(X,{tone:`info`,children:M_(L?.installed?.version||`-`)})]}),a(`div`,{className:`flex flex-wrap gap-2 text-xs`,children:[a(X,{tone:`ghost`,children:[Number(L?.workflow_extensions?.workflow_count||0),` `,`workflows`]}),a(X,{tone:`ghost`,children:[Number(L?.workflow_extensions?.workflow_hook_count||0),` `,`hooks`]}),a(X,{tone:`ghost`,children:[Number(L?.risk?.required_capabilities_count||0),` `,`required caps`]})]})]}),H?a(`div`,{className:`tcp-list-item grid gap-3`,children:[a(`div`,{className:`flex items-start gap-3`,children:[ne?a(`img`,{src:ne,alt:`${M_(H?.display_name||L?.installed?.name||O)} cover art`,className:`h-24 w-24 rounded-2xl border border-white/10 object-cover`}):null,a(`div`,{className:`min-w-0 flex-1`,children:[a(`div`,{className:`mb-1 flex flex-wrap items-center gap-2`,children:[a(`strong`,{children:M_(H?.display_name||O)}),a(X,{tone:`info`,children:M_(V?.verification_tier||`unverified`)})]}),a(`div`,{className:`tcp-subtle text-sm`,children:M_(H?.description||``)}),a(`div`,{className:`mt-2 flex flex-wrap gap-2 text-xs`,children:[a(X,{tone:`ghost`,children:M_(V?.display_name||`Unknown publisher`)}),j_(H,`categories`).map(e=>a(X,{tone:`ghost`,children:M_(e)},M_(e))),j_(H,`tags`).map(e=>a(X,{tone:`ghost`,children:M_(e)},M_(e)))]})]})]}),re.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-xs uppercase tracking-[0.24em]`,children:`Screenshots`}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:re.map(e=>a(`img`,{src:F_(O,e),alt:`${M_(H?.display_name||O)} screenshot`,className:`rounded-2xl border border-white/10`},e))})]}):null,a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-xs uppercase tracking-[0.24em]`,children:`README Preview`}),U?a(`div`,{className:`prose prose-invert max-w-none rounded-2xl border border-white/10 bg-black/20 p-4`,dangerouslySetInnerHTML:{__html:Xr(U)}}):a(Pr,{text:`No README preview is available for this pack.`})]})]}):null,a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-xs uppercase tracking-[0.24em]`,children:`Workflow Entry Points`}),j_(L?.workflow_extensions,`workflow_entrypoints`).length?j_(L?.workflow_extensions,`workflow_entrypoints`).map((e,t)=>a(`div`,{className:`tcp-list-item text-sm`,children:M_(e)},`${M_(e)}-${t}`)):a(Pr,{text:`This pack does not declare workflow entrypoints.`})]}),a(Lr,{value:L?.manifest||{},label:`Manifest`,className:`tcp-list-item`,preClassName:`tcp-subtle mt-3 overflow-x-auto text-xs`})]}):a(Pr,{text:`Select an installed pack to inspect workflow extensions.`})})]})}),a(mr,{main:a(dr,{title:`Workflow viewer`,subtitle:`Structured view of workflow steps and source provenance for the selected workflow.`,actions:a(`button`,{className:`tcp-btn`,disabled:!k||P.isPending,onClick:()=>k&&P.mutate(k),children:[a(`i`,{"data-lucide":`play`}),`Run workflow`]}),children:R?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:M_(R?.name||k)}),a(X,{tone:`info`,children:M_(R?.source?.kind||`unknown`)})]}),a(`div`,{className:`tcp-subtle text-sm`,children:M_(R?.description||`No description provided.`)})]}),a(`div`,{className:`grid gap-2`,children:j_(R,`steps`).length?j_(R,`steps`).map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 text-xs uppercase tracking-[0.24em] text-slate-400`,children:[`Step `,t+1]}),a(`div`,{className:`font-medium`,children:M_(e?.action||`unknown`)}),e?.with?a(Lr,{value:e.with,label:`Show step config`,preClassName:`tcp-subtle mt-2 overflow-x-auto text-xs`}):null]},M_(e?.step_id||t))):a(Pr,{text:`This workflow does not define any linear steps.`})})]}):a(Pr,{text:`Select a workflow to inspect its current resolved definition.`})}),aside:a(`div`,{className:`grid gap-4`,children:[a(dr,{title:`Hook manager`,subtitle:`Enable or disable hook bindings on the live registry and inspect the attached actions.`,children:a(`div`,{className:`grid gap-2`,children:z.length?z.map(e=>{let t=M_(e?.binding_id),n=!!e?.enabled;return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-2 flex items-start justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:M_(e?.event||t)}),a(`div`,{className:`tcp-subtle text-xs`,children:t})]}),a(`button`,{className:`tcp-btn`,disabled:I.isPending,onClick:()=>I.mutate({bindingId:t,enabled:!n}),children:n?`Disable`:`Enable`})]}),a(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[a(X,{tone:N_(n),children:n?`Enabled`:`Disabled`}),a(X,{tone:`ghost`,children:[j_(e,`actions`).length,` actions`]})]}),a(`div`,{className:`grid gap-1`,children:j_(e,`actions`).map((e,n)=>a(`div`,{className:`tcp-subtle text-xs`,children:M_(e?.action||e)},`${t}-${n}`))})]},t)}):a(Pr,{text:`The selected workflow has no registered hooks.`})})}),a(dr,{title:`Recent workflow runs`,subtitle:`Latest workflow executions for the selected workflow, including hook-triggered runs.`,children:a(`div`,{className:`grid gap-2`,children:A.length?A.map((e,t)=>{let n=M_(e?.status||`unknown`),r=n===`completed`?`ok`:n===`failed`?`err`:n===`running`?`warn`:`ghost`;return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:M_(e?.run_id||`run-${t+1}`)}),a(X,{tone:r,children:n})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`trigger: `,M_(e?.trigger_event||`manual`)]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`actions: `,j_(e,`actions`).length]})]},M_(e?.run_id||t))}):a(Pr,{text:`No workflow runs have been recorded yet.`})})})]})}),a(mr,{main:a(dr,{title:`Workflow testing mode`,subtitle:`Simulate a source event to see which hooks will match before triggering real actions.`,actions:a(`button`,{className:`tcp-btn-primary`,disabled:!f.trim()||F.isPending,onClick:()=>F.mutate(),children:[a(`i`,{"data-lucide":`flask-conical`}),`Simulate`]}),children:a(`div`,{className:`grid gap-3`,children:[a(`input`,{className:`tcp-input`,value:f,onInput:e=>m(e.target.value),placeholder:`context.task.created`}),a(`textarea`,{className:`tcp-input min-h-[180px] font-mono text-xs`,value:h,onInput:e=>g(e.target.value),spellCheck:!1}),ee?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`flex flex-wrap gap-2`,children:j_(ee,`canonical_events`).map((e,t)=>a(X,{tone:`info`,children:M_(e)},`${M_(e)}-${t}`))}),a(`div`,{className:`grid gap-2`,children:j_(ee,`matched_bindings`).length?j_(ee,`matched_bindings`).map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:M_(e?.binding_id)}),a(`div`,{className:`tcp-subtle text-xs`,children:[M_(e?.event),` · `,j_(e,`actions`).length,` `,`actions`]})]},M_(e?.binding_id))):a(Pr,{text:`No workflow hooks matched this event.`})})]}):a(Pr,{text:`Run a simulation to inspect canonical events, matched bindings, and planned actions.`})]})}),aside:a(dr,{title:`Triggered actions`,subtitle:`Preview of actions the engine plans to execute for the simulated event.`,children:a(`div`,{className:`grid gap-2`,children:j_(ee,`planned_actions`).length?j_(ee,`planned_actions`).map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:M_(e?.action||e)}),e?.with?a(Lr,{value:e.with,label:`Show action config`,preClassName:`tcp-subtle mt-2 overflow-x-auto text-xs`}):null]},`${M_(e?.action||e)}-${t}`)):a(Pr,{text:`No planned actions yet.`})})})}),a(dr,{title:`Live workflow events`,subtitle:"Real-time `workflow.*` events for the selected workflow, including run start, action completion, and failures.",actions:a(`button`,{className:`tcp-btn`,onClick:()=>b([]),children:[a(`i`,{"data-lucide":`trash-2`}),`Clear stream`]}),children:a(`div`,{className:`grid max-h-[28rem] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2`,children:v.length?[...v].reverse().map((e,t)=>{let n=P_(e.data),r=n.endsWith(`.failed`)?`err`:n.endsWith(`.completed`)?`ok`:n.endsWith(`.started`)?`warn`:`info`;return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:n}),a(X,{tone:r,children:new Date(e.at).toLocaleTimeString()})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`run: `,M_(e.data?.properties?.runID||`n/a`)]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`action:`,` `,M_(e.data?.properties?.action||e.data?.properties?.actionID||`-`)]})]},`${e.at}-${t}`)}):a(Pr,{text:`Run a workflow or trigger a hook to watch live workflow events here.`})})})]})}function L_(e){return e>=1?`bg-rose-500`:e>=.8?`bg-amber-500`:`bg-emerald-500`}function R_(e,t){return!t||t<=0?0:Math.min(e/t,1)}function z_({label:e,used:t,max:n,unit:r,advisory:i=!1}){let o=R_(t,n),s=i?o>=.8?`bg-sky-400`:`bg-cyan-500`:L_(o);return a(`div`,{className:`grid gap-1`,children:[a(`div`,{className:`flex items-center justify-between text-xs`,children:[a(`span`,{className:`tcp-subtle`,children:e}),a(`span`,{className:`font-mono text-[11px] text-slate-200`,children:[t.toLocaleString(),r||``,` / `,n.toLocaleString(),r||``]})]}),a(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-slate-800/80`,children:a(`div`,{className:`h-full ${s}`,style:{width:`${o*100}%`}})})]})}function B_({budget:e}){let[t,n]=r(!1),i=e.limits_enforced===!1,o=Math.max(R_(e.iterations_used,e.max_iterations),R_(e.tokens_used,e.max_tokens),R_(e.wall_time_secs,e.max_wall_time_secs),R_(e.subagent_runs_used,e.max_subagent_runs));return a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/25 p-3`,children:[a(`button`,{className:`flex w-full items-center justify-between`,onClick:()=>n(e=>!e),children:[a(`div`,{className:`text-sm font-medium`,children:`Budget + Tokens`}),a(`div`,{className:`flex items-center gap-2`,children:[a(`div`,{className:`h-2 w-24 overflow-hidden rounded-full bg-slate-800/80`,children:a(`div`,{className:`h-full ${i?o>=.8?`bg-sky-400`:`bg-cyan-500`:L_(o)}`,style:{width:`${o*100}%`}})}),a(`span`,{className:`tcp-subtle text-xs`,children:[Math.round(o*100),`%`]})]})]}),t?a(`div`,{className:`mt-3 grid gap-3 border-t border-slate-700/60 pt-3`,children:[a(z_,{label:`Iterations`,used:e.iterations_used,max:e.max_iterations,advisory:i}),a(z_,{label:`Tokens`,used:e.tokens_used,max:e.max_tokens,advisory:i}),a(z_,{label:`Wall time`,used:e.wall_time_secs,max:e.max_wall_time_secs,unit:`s`,advisory:i}),a(z_,{label:`Agent calls`,used:e.subagent_runs_used,max:e.max_subagent_runs,advisory:i}),i?a(`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,e.exceeded&&e.exceeded_reason?a(`div`,{className:`rounded border border-rose-500/40 bg-rose-950/30 p-2 text-xs text-rose-200`,children:e.exceeded_reason}):null]}):null]})}function V_(e,t=0){return String(e?.run_id||e?.runId||`run-${t}`).trim()}function H_(e){let t=Number(e?.updated_at_ms||e?.updatedAtMs||0),n=Number(e?.created_at_ms||e?.createdAtMs||0),r=Number.isFinite(t)&&t>0?t:n;return Number.isFinite(r)&&r>0?r:0}function U_(e,t=``){let n=String(t||``).trim(),r=[...Array.isArray(e)?e:[]].sort((e,t)=>H_(t)-H_(e));if(n){let e=r.find((e,t)=>V_(e,t)===n);if(e){let t=String(e?.status||``).trim().toLowerCase();if(![`completed`,`failed`,`cancelled`].includes(t))return n}}let i=r.find(e=>{let t=String(e?.status||``).trim().toLowerCase();return![`completed`,`failed`,`cancelled`].includes(t)})||r[0];return i?V_(i):``}function W_(e,t){if(t.type===`sync_runs`){let n={},r=[];for(let e=0;e<t.runs.length;e+=1){let i=t.runs[e],a=V_(i,e);a&&(n[a]=i,r.push(a))}let i=e.selectedRunId;return i||=U_(t.runs,t.preferredRunId),{runsById:n,orderedRunIds:r,selectedRunId:i,cursorsByRunId:e.cursorsByRunId}}if(t.type===`select_run`)return{...e,selectedRunId:String(t.runId||``).trim()};if(t.type===`clear_selection`)return{...e,selectedRunId:``};if(t.type===`advance_cursor`){let n=String(t.runId||``).trim();if(!n)return e;let r=Number(t.seq||0);if(!Number.isFinite(r)||r<=0)return e;let i=String(t.kind||``).trim().toLowerCase(),a=e.cursorsByRunId[n]||{eventSeq:0,patchSeq:0},o={eventSeq:i===`context_run_event`?Math.max(a.eventSeq,r):a.eventSeq,patchSeq:i===`blackboard_patch`?Math.max(a.patchSeq,r):a.patchSeq};return o.eventSeq===a.eventSeq&&o.patchSeq===a.patchSeq?e:{...e,cursorsByRunId:{...e.cursorsByRunId,[n]:o}}}return e}function G_(e,t=``){let[n,r]=f(W_,{runsById:{},orderedRunIds:[],selectedRunId:``,cursorsByRunId:{}});m(()=>{r({type:`sync_runs`,runs:Array.isArray(e)?e:[],preferredRunId:t})},[e,t]);let i=o(()=>n.orderedRunIds.map(e=>n.runsById[e]).filter(Boolean),[n.orderedRunIds,n.runsById]);return{runsById:n.runsById,orderedRunIds:n.orderedRunIds,orderedRuns:i,selectedRunId:n.selectedRunId,cursorsByRunId:n.cursorsByRunId,setSelectedRunId:e=>r({type:`select_run`,runId:e}),clearSelectedRunId:()=>r({type:`clear_selection`}),advanceCursor:(e,t,n)=>r({type:`advance_cursor`,runId:e,kind:t,seq:n})}}function K_(e){let t={},n={};for(let[r,i]of Object.entries(e||{})){let e=Number(i?.eventSeq||0),a=Number(i?.patchSeq||0);e>0&&(t[r]=e),a>0&&(n[r]=a)}let r=JSON.stringify({events:t,patches:n});return!r||r===`{"events":{},"patches":{}}`?``:btoa(r).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function q_({workspace:e,runIds:t,cursorToken:n,onEnvelope:r,onError:i}){let a=o(()=>[...new Set((t||[]).map(e=>String(e||``).trim()).filter(Boolean))],[t]),s=o(()=>{let t=String(e||``).trim();if(!t||!a.length)return``;let r=new URLSearchParams;return r.set(`workspace`,t),r.set(`runIds`,a.join(`,`)),n&&r.set(`cursor`,n),`/api/orchestrator/events?${r.toString()}`},[n,a,e]);m(()=>{if(!s)return;let e=Yi(s,e=>{let t=null;try{t=JSON.parse(String(e?.data||`{}`))}catch{return}!t||typeof t!=`object`||r(t)},{onError:e=>{i&&i(e)}});return()=>e()},[r,i,s])}var J_={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 Y_(e){let t=String(e||``).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 X_(e){let t=String(e||``).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 Z_(e){let t=Number(e||0);return!Number.isFinite(t)||t<=0?`Run`:`Run ${new Date(t).toLocaleTimeString()}`}function Q_(e){return Number(e?.updated_at_ms||e?.created_at_ms||0)}function $_(e){let t=Number(e||0);return!Number.isFinite(t)||t<=0?`--:--:--`:new Date(t).toLocaleTimeString()}function ev(e){let t=Number(e||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 tv(e){let t=String(e||``).trim(),n=t.lastIndexOf(`.`);return n<0?``:t.slice(n+1).toLowerCase()}function nv(e){let t=String(e||``).trim().replace(/\\/g,`/`);return t?t.startsWith(`/`)?t.replace(/\/{2,}/g,`/`):t:``}function rv(e,t){let n=nv(e).replace(/\/+$/,``),r=nv(t).replace(/^\/+/,``);return n?r?`${n}/${r}`:n:r}function iv(e,t){let n=nv(e).replace(/\/+$/,``),r=nv(t);return!n||!r?!1:r===n?!0:r.startsWith(`${n}/`)}function av(e){let t=[e?.workspace?.canonical_path,e?.workspace?.path,e?.workspace?.root,e?.workspace_root,e?.workspacePath,e?.cwd,e?.path];for(let e of t){let t=nv(String(e||``));if(t.startsWith(`/`))return t}return``}function ov(e){let t={};for(let n of e){let e=String(n?.type||``).trim().toLowerCase();if(![`task_started`,`step_started`,`task_completed`,`step_completed`].includes(e))continue;let r=String(n?.step_id||``).trim();if(!r)continue;let i=Number(n?.seq||0);!Number.isFinite(i)||i<=0||(t[r]=Math.max(Number(t[r]||0),i))}return t}function sv(e){return String(e?.event_type||e?.type||e?.event||`workflow.event`).trim().toLowerCase()}function cv(e){let t=[`type: ${String(e.type||``).trim()||`unknown`}`,`task: ${String(e.taskId||``).trim()||`n/a`}`,`title: ${String(e.title||``).trim()||`n/a`}`,`mode: ${String(e.mode||``).trim()||`strict`}`,`at: ${$_(e.at)}`,``,`reason:`,String(e.reason||``).trim()||`No verification detail.`],n=e.verification?.execution_trace;return n&&typeof n==`object`&&t.push(``,`execution_trace:`,`session: ${String(n.session_id||`n/a`)}`,`model: ${[String(n?.model?.provider||``).trim(),String(n?.model?.model_id||``).trim()].filter(Boolean).join(` / `)||`unknown`}`,`source: ${String(n?.model?.source||`n/a`)}`),t.push(``,`verification_json:`,JSON.stringify(e.verification||{},null,2)),t.join(`
@@ -7372,8 +7372,8 @@ Return:
7372
7372
 
7373
7373
  Do not guarantee ranking outcomes or propose manipulative tactics unless explicitly requested by the parent agent.`,tags:[`seo`,`specialist`,`specialized`,`domains`,`read-only`],requires:[],role:`worker`}]},Jy=`tandem.studio.agentCatalogHandoff`,Yy=[`worker`,`reviewer`,`tester`,`watcher`,`delegator`,`committer`,`orchestrator`],Xy={worker:`Executes hands-on work and reports concrete progress.`,reviewer:`Critiques output, spots risks, and improves quality.`,tester:`Validates behavior and looks for regressions or gaps.`,watcher:`Monitors activity, incidents, and changes over time.`,delegator:`Breaks work down and routes tasks across participants.`,committer:`Finalizes work and drives it toward completion.`,orchestrator:`Coordinates multi-agent flow and synthesizes updates.`},Zy=[`You are the frontend lead. Focus on shipped UI changes, active branches, visual regressions, and blockers from design or review.`,`You are the backend lead. Focus on APIs, database work, deploys, incidents, and blockers from reliability or dependencies.`,`You are the product and ops agent. Focus on launches, customer feedback, analytics, triage, and operational blockers.`],Qy={templateId:``,displayName:``,avatarUrl:``,role:`worker`,systemPrompt:``,modelProvider:``,modelId:``};function $y(e,t){return Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[]}function eb(e){let t=e?.default_model||e?.defaultModel||{};return{templateId:String(e?.template_id||e?.templateID||e?.id||``).trim(),displayName:String(e?.display_name||e?.displayName||e?.name||``).trim(),avatarUrl:String(e?.avatar_url||e?.avatarUrl||``).trim(),role:String(e?.role||`worker`).trim()||`worker`,systemPrompt:String(e?.system_prompt||e?.systemPrompt||``).trim(),modelProvider:String(t?.provider_id||t?.providerId||``).trim(),modelId:String(t?.model_id||t?.modelId||``).trim()}}function tb(e){let t={templateID:e.templateId.trim(),display_name:e.displayName.trim()||void 0,avatar_url:e.avatarUrl.trim()||void 0,role:e.role,system_prompt:e.systemPrompt.trim()||void 0,skills:[],default_budget:{},capabilities:{}};return e.modelProvider.trim()&&e.modelId.trim()&&(t.default_model={provider_id:e.modelProvider.trim(),model_id:e.modelId.trim()}),t}function nb(e){return String(e||``).trim().toLowerCase()}function rb(e){return String(e.instructions||``).trim().split(/\n\s*\n/).find(Boolean)?.trim()||e.summary}function ib({client:e,toast:t,navigate:n}){let i=_(),s=e?.agentTeams,l=c(null),[u,d]=r(Qy),[f,p]=r(null),[h,g]=r(``),[v,b]=r(`all`),[S,C]=r(``),[w,T]=r(``),[E,D]=r(()=>$u()),O=c(null),k=c(null),A=Oc().data?.agent_teams===!0,j=y({queryKey:[`teams`,`health`],queryFn:()=>e?.health?.().catch(()=>({}))??Promise.resolve({}),refetchInterval:3e4}),M=String(j.data?.workspaceRoot||j.data?.workspace_root||``).trim(),N=String(w||M||``).trim();m(()=>{M&&T(e=>e||M)},[M]);let P=y({queryKey:[`teams`,`templates`],queryFn:()=>s?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:8e3}),F=y({queryKey:[`teams`,`instances`],queryFn:()=>s?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),I=y({queryKey:[`teams`,`approvals`],queryFn:()=>s?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),L=x({mutationFn:async()=>{if(!u.templateId.trim())throw Error(`Template ID is required.`);return f?s?.updateTemplate?.(f,{display_name:u.displayName.trim()||void 0,avatar_url:u.avatarUrl.trim()||void 0,role:u.role,system_prompt:u.systemPrompt.trim()||void 0,default_model:u.modelProvider.trim()&&u.modelId.trim()?{provider_id:u.modelProvider.trim(),model_id:u.modelId.trim()}:void 0}):s?.createTemplate?.({template:tb(u)})},onSuccess:async()=>{t(`ok`,f?`Template updated.`:`Template created.`),d(Qy),p(null),await i.invalidateQueries({queryKey:[`teams`]})},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),R=x({mutationFn:e=>s?.deleteTemplate?.(e),onSuccess:async()=>{t(`ok`,`Template deleted.`),f&&(p(null),d(Qy)),await i.invalidateQueries({queryKey:[`teams`]})},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),z=x({mutationFn:({requestId:e,decision:t})=>t===`approve`?s?.approveSpawn?.(e):s?.denySpawn?.(e),onSuccess:async()=>{t(`ok`,`Approval updated.`),await i.invalidateQueries({queryKey:[`teams`]})},onError:e=>t(`err`,e instanceof Error?e.message:String(e))}),ee=o(()=>$y(P.data,`templates`).map(eb).filter(e=>e.templateId),[P.data]),B=$y(F.data,`instances`),V=$y(I.data,`spawnApprovals`),H=!!(f||u.templateId||u.displayName||u.systemPrompt),te=u.displayName.trim()||u.templateId.trim()||`New Agent`,U=te.slice(0,1).toUpperCase()||`A`,ne=Xy[u.role],re=u.avatarUrl.trim(),ie=o(()=>{let e=nb(h);return qy.agents.filter(t=>v!==`all`&&t.category_id!==v?!1:e?[t.name,t.summary,t.category_title,t.category_id,t.source_path,t.source_file,t.sandbox_mode,t.role,...t.tags||[],...t.requires||[]].join(` `).toLowerCase().includes(e):!0)},[v,h]),ae=o(()=>{let e=new Map;for(let t of ie){let n=e.get(t.category_id)||[];n.push(t),e.set(t.category_id,n)}return qy.categories.map(t=>({...t,agents:e.get(t.id)||[]})).filter(e=>e.agents.length>0)},[ie]);m(()=>{let e=l.current;e&&Yr(e)},[ee.length,B.length,V.length,u.role,u.templateId,u.displayName,u.avatarUrl,u.modelProvider,u.modelId,u.systemPrompt,f,L.isPending,R.isPending,z.isPending]);let[W,oe]=r(``),se=async e=>{try{await navigator.clipboard.writeText(e),oe(e),C(`Copied: ${e}`),setTimeout(()=>oe(t=>t===e?``:t),2e3)}catch(e){C(e instanceof Error?e.message:String(e))}},ce=e=>{try{sessionStorage.setItem(Jy,JSON.stringify({agentId:e.id,displayName:e.name,categoryId:e.category_id,categoryTitle:e.category_title,summary:e.summary,sourcePath:e.source_path,sandboxMode:e.sandbox_mode,role:e.role,tags:e.tags,requires:e.requires,instructions:e.instructions}));let t=window.location.href.replace(/#.*$/,``);window.open(`${t}#studio`,`_blank`,`noopener`)}catch(e){t(`err`,e instanceof Error?e.message:String(e))}},le=e=>{let t=e.name.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``),n={worker:`worker`,reviewer:`reviewer`,delegator:`delegator`,orchestrator:`orchestrator`,watcher:`watcher`,committer:`committer`,tester:`tester`}[e.role]??`worker`;p(null),d({templateId:t,displayName:e.name,avatarUrl:``,role:n,systemPrompt:[e.summary,rb(e)===e.summary?``:rb(e)].filter(Boolean).join(`
7374
7374
 
7375
- `).trim(),modelProvider:``,modelId:``}),C(`Imported "${e.name}" into the agent form — review and save below.`),setTimeout(()=>{k.current?.scrollIntoView({behavior:`smooth`,block:`start`})},80)},ue=e=>{if(!e)return;if(e.size>10*1024*1024){t(`err`,`Avatar image is too large (max 10 MB).`);return}let n=new FileReader;n.onload=()=>{let e=typeof n.result==`string`?n.result:``;if(!e){t(`err`,`Failed to read avatar image.`);return}d(t=>({...t,avatarUrl:e}))},n.onerror=()=>t(`err`,`Failed to read avatar image.`),n.readAsDataURL(e)};return a(`div`,{ref:l,className:`grid gap-4`,children:[A&&a(Nr,{title:`Agent Standup`,subtitle:`Compose scheduled standups from the same saved agents you manage here`,children:a(Ky,{client:e,toast:t,workspaceRoot:N,onWorkspaceRootChange:T,defaultWorkspaceRoot:M,timezone:E,onTimezoneChange:D,templates:ee.map(e=>({templateId:e.templateId,displayName:e.displayName||e.templateId,role:e.role,modelLabel:e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:``}))})}),a(Nr,{title:`Agent Catalog`,subtitle:`Browse and import from the canonical Codex subagent set. Use any entry to pre-fill the agent form below.`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`grid gap-2 md:grid-cols-[1fr_auto]`,children:[a(`input`,{className:`tcp-input`,placeholder:`Search agent name, category, tag, or path`,value:h,onInput:e=>g(e.target.value)}),a(`button`,{className:`tcp-btn`,onClick:()=>{g(``),b(`all`)},disabled:!h&&v===`all`,children:`Clear`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs ${v===`all`?`border-amber-400/60 bg-amber-400/10`:``}`,onClick:()=>b(`all`),children:`All`}),qy.categories.map(e=>a(`button`,{className:`tcp-btn h-8 px-3 text-xs ${v===e.id?`border-amber-400/60 bg-amber-400/10`:``}`,onClick:()=>b(e.id),children:[e.title,` (`,e.count,`)`]},e.id))]}),S?a(`div`,{className:`text-xs text-slate-400`,children:S}):null,ae.length?ae.map(e=>a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex items-start justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-medium text-slate-100`,children:e.title}),a(`div`,{className:`text-xs text-slate-400`,children:e.summary})]}),a(`div`,{className:`tcp-badge-info`,children:[e.agents.length,` agents`]})]}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:e.agents.map(e=>a(`div`,{className:`tcp-list-item grid gap-2`,children:[a(`div`,{className:`flex items-start justify-between gap-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate font-semibold text-slate-100`,children:e.name}),a(`div`,{className:`text-xs text-slate-400`,children:e.summary})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`span`,{className:`tcp-badge-info`,children:e.role}),a(`span`,{className:e.sandbox_mode===`read-only`?`tcp-badge-warn`:`tcp-badge-ok`,children:e.sandbox_mode})]})]}),a(`div`,{className:`font-mono text-xs text-slate-400`,children:e.source_path}),a(`div`,{className:`line-clamp-3 text-xs text-slate-200`,children:rb(e)}),a(`div`,{className:`flex flex-wrap gap-1`,children:[e.tags.slice(0,4).map(t=>a(`span`,{className:`tcp-badge-muted`,children:t},`${e.id}-${t}`)),e.requires.slice(0,3).map(t=>a(`span`,{className:`tcp-badge-info`,children:t},`${e.id}-${t}`))]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,title:`Pre-fill the agent creation form from this catalog entry`,onClick:()=>le(e),children:[a(`i`,{"data-lucide":`download`}),`Import as Agent`]}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,title:`Open this agent in Studio (new tab)`,onClick:()=>ce(e),children:[a(`i`,{"data-lucide":`external-link`}),`Studio ↗`]}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs ${W===e.source_path?`border-emerald-400/60 bg-emerald-400/10 text-emerald-300`:``}`,title:`Copy source path to clipboard`,onClick:()=>void se(e.source_path),children:[a(`i`,{"data-lucide":W===e.source_path?`check`:`copy`}),W===e.source_path?`Copied`:`Copy path`]})]})]},e.source_path))})]},e.id)):a(Pr,{text:`No agents match your search.`})]})}),a(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[a(`div`,{ref:k,children:a(Nr,{title:`Agents`,subtitle:`Create reusable agent personalities, prompts, and default models for automation workflows`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-cyan-300`,children:`Reusable Personalities`}),a(`div`,{className:`mt-2 text-sm text-slate-300`,children:`Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses.`})]}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:[a(`input`,{className:`tcp-input`,placeholder:`template-id`,value:u.templateId,disabled:!!f,onInput:e=>d(t=>({...t,templateId:e.target.value}))}),a(`input`,{className:`tcp-input`,placeholder:`Display name`,value:u.displayName,onInput:e=>d(t=>({...t,displayName:e.target.value}))}),a(`select`,{className:`tcp-input`,value:u.role,onInput:e=>d(t=>({...t,role:e.target.value})),children:Yy.map(e=>a(`option`,{value:e,children:e},e))}),a(`input`,{className:`tcp-input`,placeholder:`Avatar URL or upload (optional)`,value:u.avatarUrl,onInput:e=>d(t=>({...t,avatarUrl:e.target.value}))}),a(`input`,{className:`tcp-input`,placeholder:`Model provider (optional)`,value:u.modelProvider,onInput:e=>d(t=>({...t,modelProvider:e.target.value}))}),a(`input`,{className:`tcp-input`,placeholder:`Model ID (optional)`,value:u.modelId,onInput:e=>d(t=>({...t,modelId:e.target.value}))})]}),a(`div`,{className:`grid gap-3 lg:grid-cols-[1.15fr_0.85fr]`,children:[a(`div`,{className:`rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-slate-500`,children:`Prompt Guidance`}),a(`div`,{className:`mt-2 text-sm text-slate-300`,children:`Write the lasting perspective for this agent, not a one-off task. Good prompts describe ownership and judgment: frontend lead, backend lead, product ops, incident watcher.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:Zy.map(e=>a(`button`,{type:`button`,className:`tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs`,onClick:()=>d(t=>({...t,systemPrompt:e})),children:`Use Example`},e))})]}),a(`div`,{className:`rounded-[28px] border border-slate-800/80 bg-[radial-gradient(circle_at_top,_rgba(34,211,238,0.18),_transparent_45%),linear-gradient(180deg,rgba(15,23,42,0.9),rgba(2,6,23,0.96))] p-5`,children:[a(`div`,{className:`flex items-start justify-between gap-4`,children:[a(`div`,{className:`flex items-start gap-4`,children:[a(`div`,{className:`flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-lg font-semibold text-cyan-100`,children:re?a(`img`,{src:re,alt:te,className:`h-full w-full object-cover`}):U}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(`strong`,{className:`text-white`,children:te}),a(`span`,{className:`tcp-badge-info`,children:u.role})]}),a(`div`,{className:`mt-1 text-xs text-slate-400`,children:u.templateId.trim()||`template-id`}),a(`div`,{className:`mt-2 text-sm text-slate-300`,children:ne})]})]}),a(`div`,{className:`flex items-center gap-2`,children:[a(`button`,{type:`button`,className:`tcp-icon-btn`,title:`Upload avatar`,"aria-label":`Upload avatar`,onClick:()=>O.current?.click(),children:a(`i`,{"data-lucide":`pencil`})}),a(`button`,{type:`button`,className:`tcp-icon-btn`,title:`Clear avatar`,"aria-label":`Clear avatar`,onClick:()=>d(e=>({...e,avatarUrl:``})),children:a(`i`,{"data-lucide":`trash-2`})})]})]}),a(`div`,{className:`mt-3 text-xs text-slate-400`,children:`Upload an image like Settings Identity preview, or paste a direct avatar URL.`}),a(`input`,{ref:O,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>{ue(e.target.files?.[0]||null),e.target.value=``}}),a(`div`,{className:`mt-4 rounded-2xl border border-slate-800/70 bg-black/20 p-4`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-slate-500`,children:`Personality Preview`}),a(`div`,{className:`mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-200`,children:u.systemPrompt.trim()||`This agent will respond from the persistent personality you define here across workflows and standups.`})]}),(u.modelProvider.trim()||u.modelId.trim())&&a(`div`,{className:`mt-3 text-xs text-cyan-200`,children:[`Default model: `,u.modelProvider.trim()||`provider`,`/`,u.modelId.trim()||`model`]})]})]}),a(`textarea`,{className:`tcp-input min-h-[140px]`,placeholder:`Persistent system prompt`,value:u.systemPrompt,onInput:e=>d(t=>({...t,systemPrompt:e.target.value}))}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:L.isPending,onClick:()=>L.mutate(),children:[a(`i`,{"data-lucide":`save`}),f?`Update Agent`:`Create Agent`]}),H&&a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>{p(null),d(Qy)},children:[a(`i`,{"data-lucide":`rotate-ccw`}),`Reset`]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-slate-500`,children:`Saved Agents`}),a(`div`,{className:`tcp-subtle text-xs`,children:[ee.length,` saved`]})]}),ee.length?ee.map(e=>a(`div`,{className:`tcp-list-item`,children:a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`flex items-center gap-2`,children:[a(`strong`,{children:e.displayName||e.templateId}),a(`span`,{className:`tcp-badge-info`,children:e.role}),e.modelProvider&&e.modelId?a(`span`,{className:`tcp-badge-ok`,children:[e.modelProvider,`/`,e.modelId]}):null]}),a(`div`,{className:`tcp-subtle text-xs`,children:e.templateId}),e.systemPrompt?a(`div`,{className:`mt-2 line-clamp-4 text-xs text-slate-300`,children:e.systemPrompt}):a(`div`,{className:`mt-2 text-xs text-slate-500`,children:`No persistent prompt set yet.`})]}),a(`div`,{className:`flex gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-xs`,onClick:()=>{p(e.templateId),d({templateId:e.templateId,displayName:e.displayName,avatarUrl:e.avatarUrl,role:Yy.includes(e.role)?e.role:`worker`,systemPrompt:e.systemPrompt,modelProvider:e.modelProvider,modelId:e.modelId})},children:[a(`i`,{"data-lucide":`pencil`}),`Edit`]}),a(`button`,{type:`button`,className:`tcp-btn-danger h-7 px-2 text-xs`,onClick:()=>R.mutate(e.templateId),children:[a(`i`,{"data-lucide":`trash-2`}),`Delete`]})]})]})},e.templateId)):a(Pr,{title:`No agents yet`,text:`Create your first saved personality here, then reuse it across automation workflows and standups.`})]})]})})}),a(Nr,{title:`Team Instances`,subtitle:`Running collaborative agent instances`,children:a(`div`,{className:`grid gap-2`,children:B.length?B.map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:String(e?.template_id||e?.templateID||e?.instance_id||`Instance`)}),a(`span`,{className:`tcp-badge-info`,children:String(e?.status||`active`)})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`mission: `,String(e?.mission_id||e?.missionID||`n/a`)]})]},String(e?.instance_id||e?.id||t))):a(Pr,{text:`No team instances found.`})})}),a(Nr,{title:`Spawn Approvals`,subtitle:`Pending team approval requests`,children:a(`div`,{className:`grid gap-2`,children:V.length?V.map((e,t)=>{let n=String(e?.approval_id||e?.request_id||e?.id||`request-${t}`);return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 font-medium`,children:String(e?.reason||e?.title||n)}),a(`div`,{className:`tcp-subtle text-xs`,children:n}),a(`div`,{className:`mt-2 flex gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-xs`,onClick:()=>z.mutate({requestId:n,decision:`approve`}),children:[a(`i`,{"data-lucide":`badge-check`}),`Approve`]}),a(`button`,{type:`button`,className:`tcp-btn-danger h-7 px-2 text-xs`,onClick:()=>z.mutate({requestId:n,decision:`deny`}),children:[a(`i`,{"data-lucide":`x`}),`Deny`]})]})]},n)}):a(Pr,{text:`No pending approvals.`})})})]})]})}function ab({theme:e}){let t=e?.cssVars?.[`--color-background`]||`#000000`,n=e?.cssVars?.[`--color-surface`]||`#111111`,r=e?.cssVars?.[`--color-primary`]||`#ffffff`,i=e?.cssVars?.[`--color-secondary`]||`#ffffff`;return a(`div`,{className:`flex items-center gap-2`,children:[a(`span`,{className:`tcp-theme-swatch`,style:{background:t},"aria-hidden":`true`}),a(`span`,{className:`tcp-theme-swatch`,style:{background:n},"aria-hidden":`true`}),a(`span`,{className:`tcp-theme-swatch`,style:{background:r},"aria-hidden":`true`}),a(`span`,{className:`tcp-theme-swatch`,style:{background:i},"aria-hidden":`true`})]})}function ob({themes:e,themeId:t,onChange:n}){return a(`div`,{className:`grid grid-cols-1 gap-3 md:grid-cols-2`,children:e.map(e=>{let r=e.id===t;return a(s.button,{type:`button`,layout:!0,onClick:()=>n(e.id),className:`tcp-theme-tile ${r?`active`:``}`,whileHover:{y:-2},whileTap:{scale:.985},transition:Kn.spring.gentle,children:[a(`div`,{className:`tcp-theme-tile-top`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-theme-tile-title`,children:e.name}),a(`p`,{className:`tcp-subtle mt-1 text-xs`,children:e.description})]}),a(ab,{theme:e})]}),a(`div`,{className:`tcp-theme-preview`,children:a(`div`,{className:`tcp-theme-preview-bg`,style:{background:e.cssVars[`--color-background`]||`#000`},children:a(`div`,{className:`tcp-theme-preview-card`,style:{background:e.cssVars[`--color-surface`]||`#111`,borderColor:e.cssVars[`--color-border`]||`rgba(255,255,255,0.1)`},children:[a(`div`,{className:`tcp-theme-preview-line short`,style:{background:e.cssVars[`--color-text`]||`#fff`}}),a(`div`,{className:`tcp-theme-preview-line`,style:{background:e.cssVars[`--color-text-muted`]||`#aaa`}}),a(`div`,{className:`tcp-theme-preview-pill`,style:{background:e.cssVars[`--color-primary`]||`#fff`}})]})})}),a(l,{initial:!1,children:r?a(s.span,{className:`tcp-theme-active`,initial:{opacity:0,scale:.86},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.86},transition:Kn.spring.snappy,children:[a(`i`,{"data-lucide":`badge-check`}),`Active`]}):null})]},e.id)})})}var sb=`tcp.nav.visibility.v1`,cb=new Set([`dashboard`,`chat`,`workflows`,`automations`,`coding`,`files`,`bug-monitor`,`settings`]);function lb(e){let t=new Set([`planner`,`studio`,`coding`,`memory`,`files`,`marketplace`,`orchestrator`,`experiments`,`teams`]);return Object.fromEntries(Cr.map(([n])=>[n,e?cb.has(n):!t.has(n)]))}function ub(e,t){let n=lb(t);if(!e||typeof e!=`object`)return n;let r=e,i={...n};for(let[e]of Cr)typeof r[e]==`boolean`&&(i[e]=r[e]);if(t)for(let e of cb)i[e]=!0;return i}function db(e){try{let t=localStorage.getItem(sb);return t?ub(JSON.parse(t),e):lb(e)}catch{return lb(e)}}function fb(e){try{localStorage.setItem(sb,JSON.stringify(e))}catch{}}function pb(e){return Cr.filter(([t])=>e[t]!==!1)}var mb=`tandem_control_panel_pending_provider_oauth`;function hb(){if(typeof window>`u`)return{};try{let e=window.sessionStorage.getItem(mb)||``;if(!e)return{};let t=JSON.parse(e);return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([e,t])=>[String(e||``).trim().toLowerCase(),String(t||``).trim()]).filter(([e,t])=>!!e&&!!t))}catch{return{}}}function gb(e){if(!(typeof window>`u`))try{let t=Object.fromEntries(Object.entries(e||{}).map(([e,t])=>[String(e||``).trim().toLowerCase(),String(t||``).trim()]).filter(([e,t])=>!!e&&!!t));if(!Object.keys(t).length){window.sessionStorage.removeItem(mb);return}window.sessionStorage.setItem(mb,JSON.stringify(t))}catch{}}var _b=new Set([`openai`,`openai-codex`,`openrouter`,`anthropic`,`ollama`,`groq`,`mistral`,`together`,`azure`,`bedrock`,`vertex`,`copilot`,`cohere`]),vb=`openai-codex`,yb=[`telegram`,`discord`,`slack`];function bb(e){let t=String(e||``).trim().toLowerCase();return t.startsWith(`mcp_header::`)||t.startsWith(`channel::`)}var xb=[{label:`File`,tools:[`read`,`glob`,`ls`,`list`,`grep`,`codesearch`,`search`]},{label:`Web`,tools:[`websearch`,`webfetch`,`webfetch_html`]},{label:`Terminal`,tools:[`bash`,`write`,`edit`,`apply_patch`]},{label:`Memory`,tools:[`memory_search`,`memory_store`,`memory_list`]},{label:`Other`,tools:[`skill`,`task`,`question`,`pack_builder`]}],Sb=`tandem.workflow_planner`,Cb=[`websearch`,`webfetch`,`webfetch_html`,`memory_search`,`memory_store`,`memory_list`];function wb(e){try{return new URL(e)}catch{return null}}function Tb(e){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)||`mcp-server`}function Eb(e){let t=wb(e);if(!t)return``;let n=String(t.hostname||``).toLowerCase();if(!n)return``;if(n.endsWith(`composio.dev`))return`composio`;let r=n.split(`.`).filter(Boolean);return r.length?Tb([`backend`,`api`,`mcp`,`www`].includes(r[0])&&r[1]||r[0]):``}function Db(e){let t=wb(e);return t?String(t.hostname||``).toLowerCase().endsWith(`composio.dev`):!1}function Ob(e){let t=wb(e);if(!t)return!1;let n=String(t.hostname||``).toLowerCase();return n===`api.githubcopilot.com`||n.endsWith(`.githubcopilot.com`)}function kb(e){let t=wb(e);if(!t)return!1;let n=String(t.hostname||``).toLowerCase();return n===`mcp.notion.com`||n.endsWith(`.notion.com`)}function Ab(e,t){return String(e||``).trim().toLowerCase()===`notion`||kb(t)?`Notion uses browser OAuth. Save the server, finish the Notion sign-in in your browser, then come back and click Mark sign-in complete. Token paste is not the right flow for this MCP.`:`This MCP server uses browser OAuth. Save it, complete the authorization page that opens in your browser, then come back and finish the connection in Tandem.`}function jb(e){return e.map(e=>({key:String(e?.key||``).trim(),value:String(e?.value||``).trim()}))}function Mb(e,t){let n={...e};for(let e of jb(t))!e.key||!e.value||(n[e.key]=e.value);return n}function Nb({authMode:e,token:t,customHeader:n,transport:r}){let i=String(t||``).trim();if(e===`oauth`||!i||e===`none`)return{};if(e===`custom`){let e=String(n||``).trim();if(!e)throw Error(`Custom header name is required.`);return{[e]:i}}return e===`x-api-key`?{"x-api-key":i}:e===`bearer`?{Authorization:`Bearer ${i.replace(/^bearer\s+/i,``).trim()}`}:Db(r)?{"x-api-key":i}:{Authorization:`Bearer ${i.replace(/^bearer\s+/i,``).trim()}`}}function Pb(e,t,n,r){return e===`oauth`?`OAuth handoff: Tandem will open the server authorization flow on connect.`:!String(t||``).trim()||e===`none`?`No auth header will be sent.`:e===`custom`?n?`Header preview: ${n}: <token>`:`Set a custom header name.`:e===`x-api-key`?`Header preview: x-api-key: <token>`:e===`bearer`?`Header preview: Authorization: Bearer <token>`:Db(r)?`Auto mode: selected x-api-key for this endpoint`:`Auto mode: using Authorization Bearer token`}function Fb(e,t=``){if(!e||typeof e!=`object`)return null;let n=e,r=String(n.name||t||``).trim();if(!r)return null;let i=n.last_auth_challenge||n.lastAuthChallenge||null;return{name:r,transport:String(n.transport||``).trim(),authKind:String(n.auth_kind||n.authKind||``).trim().toLowerCase(),connected:!!n.connected,enabled:n.enabled!==!1,lastError:String(n.last_error||n.lastError||``).trim(),lastAuthChallenge:i&&typeof i==`object`?i:null,authorizationUrl:String(n.authorization_url||n.authorizationUrl||``).trim(),headers:n.headers&&typeof n.headers==`object`?n.headers:{},toolCache:Array.isArray(n.tool_cache||n.toolCache)?n.tool_cache||n.toolCache:[],allowedTools:Array.isArray(n.allowed_tools||n.allowedTools)?(n.allowed_tools||n.allowedTools).map(e=>String(e||``).trim()).filter(Boolean):null}}function Ib(e,t,n){let r=String(t||``).trim().toLowerCase(),i=String(n||``).trim().replace(/\/+$/,``).toLowerCase(),a=e.servers.find(e=>{let t=String(e.transportUrl||``).trim().replace(/\/+$/,``).toLowerCase(),n=String(e.slug||``).trim().toLowerCase(),a=String(e.serverConfigName||``).trim().toLowerCase();return i&&t&&t===i||i&&t&&t.includes(i)||i&&t&&i.includes(t)||!!r&&(n===r||a===r)});return String(a?.authKind||``).trim().toLowerCase()}function Lb(e){return Array.isArray(e)?e.map(e=>Fb(e)).filter(e=>!!e).sort((e,t)=>e.name.localeCompare(t.name)):!e||typeof e!=`object`?[]:Array.isArray(e.servers)?e.servers.map(e=>Fb(e)).filter(e=>!!e).sort((e,t)=>e.name.localeCompare(t.name)):Object.entries(e).map(([e,t])=>Fb(t&&typeof t==`object`?t:{transport:String(t||``)},e)).filter(e=>!!e).sort((e,t)=>e.name.localeCompare(t.name))}function Rb(e){return(Array.isArray(e)?e:Array.isArray(e?.tools)?e.tools:[]).map(e=>typeof e==`string`?e:!e||typeof e!=`object`?``:String(e.namespaced_name||e.namespacedName||e.id||e.tool_name||e.toolName||``).trim()).filter(Boolean)}function zb(e){let t=e&&typeof e==`object`?e:{},n=Array.isArray(t.servers)?t.servers:[];return{generatedAt:String(t.generated_at||``).trim(),count:Number.isFinite(Number(t.count))?Number(t.count):n.length,servers:n.map(e=>!e||typeof e!=`object`?null:{slug:String(e.slug||``).trim(),name:String(e.name||e.slug||``).trim(),description:String(e.description||``).trim(),transportUrl:String(e.transport_url||``).trim(),serverConfigName:String(e.server_config_name||e.slug||``).trim(),documentationUrl:String(e.documentation_url||``).trim(),directoryUrl:String(e.directory_url||``).trim(),toolCount:Number.isFinite(Number(e.tool_count))?Number(e.tool_count):0,requiresAuth:e.requires_auth!==!1,requiresSetup:!!e.requires_setup,authKind:String(e.auth_kind||e.authKind||``).trim().toLowerCase()}).filter(e=>!!e&&!!e.slug&&!!e.transportUrl).sort((e,t)=>e.name.localeCompare(t.name))}}function Bb(e,t){let n=t&&typeof t==`object`?t:{};return{botToken:``,allowedUsers:Array.isArray(n.allowed_users)?n.allowed_users.join(`, `):``,mentionOnly:n.mention_only!==!1&&e===`discord`?!0:!!n.mention_only,guildId:String(n.guild_id||``).trim(),channelId:String(n.channel_id||``).trim(),modelProviderId:String(n.model_provider_id||``).trim(),modelId:String(n.model_id||``).trim(),styleProfile:String(n.style_profile||`default`).trim()||`default`,securityProfile:String(n.security_profile||`operator`).trim()||`operator`}}function Vb(){return{enabled_tools:[],disabled_tools:[],enabled_mcp_servers:[],enabled_mcp_tools:[]}}function Hb(e){return Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)))}function Ub(e){let t=e&&typeof e==`object`?e:{};return{enabled_tools:Array.isArray(t.enabled_tools)?Hb(t.enabled_tools.map(e=>String(e))):[],disabled_tools:Array.isArray(t.disabled_tools)?Hb(t.disabled_tools.map(e=>String(e))):[],enabled_mcp_servers:Array.isArray(t.enabled_mcp_servers)?Hb(t.enabled_mcp_servers.map(e=>String(e))):[],enabled_mcp_tools:Array.isArray(t.enabled_mcp_tools)?Hb(t.enabled_mcp_tools.map(e=>String(e))):[]}}function Wb(e){let t=e&&typeof e==`object`?e:{};return(Array.isArray(t.scopes)?t.scopes:[]).map(e=>{if(!e||typeof e!=`object`)return null;let t=String(e.scope_id||e.scopeId||``).trim();return t?{scope_id:t,scope_kind:String(e.scope_kind||e.scopeKind||``).trim(),session_count:Number.isFinite(Number(e.session_count))?Number(e.session_count):Number.isFinite(Number(e.sessionCount))?Number(e.sessionCount):0,sender_count:Number.isFinite(Number(e.sender_count))?Number(e.sender_count):Number.isFinite(Number(e.senderCount))?Number(e.senderCount):0,last_seen_at_ms:Number.isFinite(Number(e.last_seen_at_ms))?Number(e.last_seen_at_ms):Number.isFinite(Number(e.lastSeenAtMs))?Number(e.lastSeenAtMs):0}:null}).filter(e=>!!e).sort((e,t)=>e.last_seen_at_ms===t.last_seen_at_ms?e.scope_id.localeCompare(t.scope_id):t.last_seen_at_ms-e.last_seen_at_ms)}function Gb(e){let t=[];return e.scope_kind&&t.push(e.scope_kind),t.push(e.scope_id),e.session_count>1?t.push(`${e.session_count} sessions`):e.session_count===1&&t.push(`1 session`),t.join(` · `)}function Kb(e,t){let n=e.enabled_tools.filter(e=>e!==Sb);return t===Sb?e.disabled_tools.includes(t)?!1:e.enabled_tools.includes(t):e.disabled_tools.includes(t)?!1:n.length===0||n.includes(t)}function qb(e,t,n){let r=e.disabled_tools.filter(e=>e!==t),i=e.enabled_tools.filter(e=>e!==Sb);return t===Sb?n?{...e,disabled_tools:r,enabled_tools:Hb([...e.enabled_tools,t])}:{...e,disabled_tools:Hb([...r,t]),enabled_tools:e.enabled_tools.filter(e=>e!==t)}:n?{...e,disabled_tools:r,enabled_tools:i.length>0?Hb([...e.enabled_tools,t]):e.enabled_tools}:{...e,disabled_tools:Hb([...r,t]),enabled_tools:i.length>0?e.enabled_tools.filter(e=>e!==t):e.enabled_tools}}function Jb(e,t,n){let r=e.enabled_mcp_servers.filter(e=>e!==t);return{...e,enabled_mcp_servers:n?Hb([...r,t]):r}}function Yb(e,t,n){let r=`mcp.${Ic(t)}.`,i=e.enabled_mcp_tools.filter(e=>e.startsWith(r));return i.length?n.some(e=>e.startsWith(r))?i:i.map(e=>e.slice(r.length)).filter(Boolean):null}function Xb(e,t,n,r){let i=`mcp.${Ic(t)}.`,a=e=>{let t=String(e||``).trim();return t?t.startsWith(`mcp.`)?t:`${i}${t}`:``},o=Hb(n.map(a).filter(Boolean)),s=e.enabled_mcp_tools.filter(e=>!e.startsWith(i)),c=r===null?o:Hb(r.map(a).filter(Boolean));return{...e,enabled_mcp_tools:Hb([...s,...c])}}function Zb(e,t){return e===`public_demo`?Cb.includes(t):!0}function Qb(e,t,n){return Zb(n,t)&&Kb(e,t)}function $b(e){let t=String(e||``).split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:[`*`]}function ex(e){let t=(Array.isArray(e)?e:String(e||``).split(`,`)).map(e=>String(e||``).trim()).filter(Boolean);return t.length?Array.from(new Set(t)):[`*`]}function tx(e,t){let n=ex(e).slice().sort(),r=ex(t).slice().sort();return n.length===r.length?n.every((e,t)=>e===r[t]):!1}function nx(e,t){let n=t&&typeof t==`object`?t:{},r=ex(n.allowed_users);return!!n.has_token||r.some(e=>e!==`*`)||!!n.mention_only||!!String(n.guild_id||``).trim()||!!String(n.channel_id||``).trim()||!!String(n.model_provider_id||``).trim()||!!String(n.model_id||``).trim()||String(n.style_profile||`default`).trim()!==`default`||String(n.security_profile||`operator`).trim()!==`operator`}function rx(e,t,n){let r=Bb(e,n);return!String(t.botToken||``).trim()&&tx(t.allowedUsers,r.allowedUsers)&&!!t.mentionOnly==!!r.mentionOnly&&String(t.guildId||``).trim()===String(r.guildId||``).trim()&&String(t.channelId||``).trim()===String(r.channelId||``).trim()&&String(t.modelProviderId||``).trim()===String(r.modelProviderId||``).trim()&&String(t.modelId||``).trim()===String(r.modelId||``).trim()&&String(t.styleProfile||`default`).trim()===String(r.styleProfile||`default`).trim()&&String(t.securityProfile||`operator`).trim()===String(r.securityProfile||`operator`).trim()}function ix(e,t){let n=String(e?.catalog_source||``).trim().toLowerCase();return n===`remote`&&t>0?{tone:`ok`,text:`${t} models`}:n===`config`&&t>0?{tone:`info`,text:`configured models`}:{tone:`warn`,text:`manual entry`}}function ax(e,t){return String(e?.catalog_message||``).trim()||`Default model: ${t||`none`}`}var ox={dashboard:`Command status, activity, and fast paths.`,chat:`Session-driven conversation, uploads, and live responses.`,planner:`Advanced long-horizon planning and governed handoff.`,studio:`Advanced template-first workflow builder.`,automations:`Reusable routines, approvals, and execution history.`,experiments:`Opt-in automation experiments, optimization campaigns, and team approvals.`,coding:`ACA intake, task launchers, and coding runs.`,agents:`Reusable agent roles and workflow drafts.`,orchestrator:`Task board planning, approvals, and execution.`,memory:`Searchable memory records and operational context.`,files:`Managed files plus the hosted knowledgebase upload surface.`,runs:`Live operations overview with queue state and per-run inspection.`,settings:`Provider defaults, themes, and runtime diagnostics.`};function sx({client:e,api:t,toast:n,navigate:i,currentRoute:u,providerStatus:d,identity:f,themes:g,setTheme:v,themeId:b,refreshProviderStatus:S,refreshIdentityStatus:C,navigation:w}){let T=_(),E=c(null),[D,O]=r({}),[k,A]=r(String(f?.botName||`Tandem`)),[j,M]=r(String(f?.botAvatarUrl||``)),[N,P]=r(`Control Center`),[F,I]=r(d?.needsOnboarding?`providers`:w?.acaMode?`navigation`:`install`),[L,R]=r(``),[z,ee]=r(``),[B,V]=r(`auto`),[H,te]=r(``),[U,ne]=r(``),[re,ie]=r(`10000`),[ae,W]=r(``),[oe,se]=r(``),[ce,le]=r(`autonomous AI agentic workflows`),[ue,de]=r(null),[fe,pe]=r(`multi`),[G,K]=r(``),[me,he]=r(!1),[ge,_e]=r(!1),[ve,ye]=r(!0),[be,xe]=r(!1),[Se,Ce]=r(()=>hb()),[we,Te]=r(`custom`),[Ee,De]=r(``),[Oe,ke]=r(``),[Ae,je]=r(``),[Me,Ne]=r(!0),[Pe,Fe]=r(``),[q,J]=r({}),Ie=c({telegram:!1,discord:!1,slack:!1}),[Le,Re]=r({telegram:``,discord:``,slack:``}),[ze,Be]=r({telegram:!1,discord:!1,slack:!1}),[Ve,He]=r({}),[Ue,We]=r(!1),[Ge,Ke]=r(``),[qe,Je]=r(``),[Ye,Xe]=r(`none`),[Ze,Qe]=r(``),[$e,et]=r(``),[tt,nt]=r(``),[rt,it]=r([]),[at,ot]=r(!0),[st,ct]=r(``),[lt,ut]=r(`manual`),[dt,ft]=r(``),[pt,mt]=r(!1),[Y,ht]=r(!1),[gt,_t]=r(``),[vt,yt]=r(``),[bt,xt]=r(``),[St,Ct]=r(`auto`),[wt,Tt]=r(``),[Et,Dt]=r(``),[Ot,kt]=r(!0),[At,jt]=r(!1),[Mt,Nt]=r(!0),[Pt,Ft]=r(``),[It,Lt]=r(!1),[Rt,zt]=r(0),[Bt,Vt]=r(null),[Ht,Ut]=r(!1),[Wt,Gt]=r(``),[Kt,qt]=r(``),Jt=c(null),Yt=c(null),[Xt,Zt]=r(``);m(()=>{gb(Se)},[Se]);let Qt=async()=>{let n=e?.identity;return n?.get?n.get():t(`/api/engine/config/identity`,{method:`GET`})},$t=async n=>{let r=e?.identity;return r?.patch?r.patch(n):t(`/api/engine/config/identity`,{method:`PATCH`,body:JSON.stringify(n)})},en=y({queryKey:[`settings`,`identity`,`config`],queryFn:()=>Qt().catch(()=>({identity:{}}))});m(()=>{let e=en.data?.identity?.bot||{},t=e?.aliases||{},n=String(e?.canonicalName||e?.canonical_name||f?.botName||`Tandem`).trim(),r=String(e?.avatarUrl||e?.avatar_url||f?.botAvatarUrl||``).trim(),i=String(t?.controlPanel||t?.control_panel||``).trim();A(n||`Tandem`),M(r),P(i||`Control Center`)},[f?.botAvatarUrl,f?.botName,en.data]),m(()=>{u===`mcp`&&I(`mcp`),u===`channels`&&I(`channels`),u===`bug-monitor`&&I(`bug_monitor`)},[u]);let tn=y({queryKey:[`settings`,`install`,`profile`],queryFn:()=>t(`/api/install/profile`,{method:`GET`}).catch(()=>null),refetchInterval:3e4}),nn=y({queryKey:[`settings`,`install`,`config`],queryFn:()=>t(`/api/control-panel/config`,{method:`GET`}).catch(()=>null)});m(()=>{let e=nn.data?.config||null;if(e)try{R(JSON.stringify(e,null,2)),ee(``)}catch{ee(`Loaded config could not be rendered as JSON.`)}},[nn.data]),m(()=>{if(u===`settings`){if(d?.needsOnboarding){I(`providers`),ye(!0);return}if(!w?.acaMode){I(`install`);return}I(tn.data?.aca_integration!==!0||tn.data?.control_panel_config_ready!==!0?`install`:`navigation`)}},[u,w?.acaMode,d?.needsOnboarding,tn.data?.aca_integration,tn.data?.control_panel_config_ready]),m(()=>{F===`providers`&&ye(!0)},[F]);let rn=y({queryKey:[`settings`,`providers`,`catalog`],enabled:F===`providers`||F===`channels`||F===`bug_monitor`,staleTime:300*1e3,queryFn:()=>e.providers.catalog().catch(()=>({all:[],connected:[]}))}),an=y({queryKey:[`settings`,`providers`,`config`],queryFn:()=>e.providers.config().catch(()=>({default:``,providers:{}}))}),on=y({queryKey:[`settings`,`providers`,`auth`],queryFn:()=>e.providers.authStatus().catch(()=>({providers:{}})),refetchInterval:15e3}),sn=y({queryKey:[`settings`,`system`,`health`],queryFn:()=>t(`/api/system/health`,{method:`GET`}).catch(()=>null),refetchInterval:3e4}),cn=o(()=>ka({providerCatalog:rn.data,providerConfig:an.data,defaultProvider:String(an.data?.default||``).trim(),defaultModel:String(an.data?.providers?.[String(an.data?.default||``).trim()]?.default_model||an.data?.providers?.[String(an.data?.default||``).trim()]?.defaultModel||``).trim(),includeUnconfiguredProviders:!0}),[rn.data,an.data]),ln=o(()=>{let e=on.data?.providers;return e&&typeof e==`object`?e:on.data&&typeof on.data==`object`?on.data:{}},[on.data]),un=sn.data?.localEngine===!0,dn=tn.data?.hosted_managed===!0;m(()=>{let e=String(sn.data?.workspace_root||``).trim();e&&Ft(t=>t.trim()?t:e)},[sn.data?.workspace_root]);let fn=o(()=>{let e=String(an.data?.default||``).trim();return{provider:e,model:String(an.data?.providers?.[e]?.default_model||an.data?.providers?.[e]?.defaultModel||``).trim()}},[an.data]),pn=o(()=>an.data?.providers||{},[an.data?.providers]),mn=o(()=>Object.entries(pn).filter(([e])=>{let t=e.trim().toLowerCase();return t&&!_b.has(t)&&!bb(t)}).map(([e,t])=>({id:e,url:String(t?.url||``).trim(),model:String(t?.default_model||t?.defaultModel||``).trim(),isDefault:String(an.data?.default||``).trim().toLowerCase()===e.trim().toLowerCase()})),[pn,an.data?.default]),hn=y({queryKey:[`settings`,`search`,`config`],queryFn:()=>t(`/api/system/search-settings`,{method:`GET`}).catch(()=>null)}),gn=y({queryKey:[`settings`,`scheduler`,`config`],queryFn:()=>t(`/api/system/scheduler-settings`,{method:`GET`}).catch(()=>null)});m(()=>{let e=hn.data?.settings||null;e&&(V(String(e.backend||`auto`).trim()||`auto`),te(String(e.tandem_url||``).trim()),ne(String(e.searxng_url||``).trim()),ie(String(e.timeout_ms||1e4)))},[hn.data]),m(()=>{let e=gn.data?.settings||null;e&&(pe(String(e.mode||`multi`).trim()||`multi`),K(e.max_concurrent_runs==null?``:String(e.max_concurrent_runs)))},[gn.data]);let _n=y({queryKey:[`settings`,`browser`,`status`],queryFn:()=>t(`/api/engine/browser/status`,{method:`GET`}).catch(()=>null),refetchInterval:3e4}),[vn,yn]=r(null),bn=x({mutationFn:()=>t(`/api/engine/browser/install`,{method:`POST`}),onSuccess:async()=>{n(`ok`,`Browser sidecar installed on the engine host.`),await _n.refetch()},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),xn=x({mutationFn:()=>t(`/api/engine/browser/smoke-test`,{method:`POST`,body:JSON.stringify({url:`https://example.com`})}),onSuccess:async e=>{yn(e),n(`ok`,`Browser smoke test passed.`),await _n.refetch()},onError:e=>{yn(null),n(`err`,e instanceof Error?e.message:String(e))}}),Sn=x({mutationFn:e=>t(`/api/engine/worktree/cleanup`,{method:`POST`,body:JSON.stringify({repo_root:e.repoRoot,dry_run:e.dryRun,remove_orphan_dirs:!0})}),onMutate:()=>{Vt(null)},onSuccess:e=>{Vt(e);let t=(e.cleaned_worktrees?.length||0)+(e.orphan_dirs_removed?.length||0),r=e.failures?.length||0;n(r?`warn`:e.dry_run?`info`:`ok`,e.dry_run?`Found ${e.stale_paths?.length||0} stale worktrees and ${e.orphan_dirs?.length||0} orphan directories.`:r?`Cleanup removed ${t} entries with ${r} failures.`:`Cleanup removed ${t} stale worktree entries.`)},onError:e=>{Vt(null),n(`err`,e instanceof Error?e.message:String(e))}});m(()=>{if(!Sn.isPending){zt(0);return}let e=window.setInterval(()=>{zt(e=>e+1)},800);return()=>window.clearInterval(e)},[Sn.isPending]);let Cn=y({queryKey:[`settings`,`mcp`,`servers`],queryFn:()=>e.mcp.list().catch(()=>({})),refetchInterval:1e4}),wn=y({queryKey:[`settings`,`mcp`,`tools`],queryFn:()=>e.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),Tn=y({queryKey:[`settings`,`mcp`,`catalog`],queryFn:()=>t(`/api/engine/mcp/catalog`,{method:`GET`}).catch(()=>null),refetchInterval:6e4}),En=y({queryKey:[`settings`,`bug-monitor`,`config`],queryFn:()=>t(`/api/engine/config/bug-monitor`,{method:`GET`}).catch(()=>({bug_monitor:{}}))}),Dn=y({queryKey:[`settings`,`bug-monitor`,`status`],queryFn:()=>t(`/api/engine/bug-monitor/status`,{method:`GET`}).catch(()=>({status:{}})),refetchInterval:1e4}),On=y({queryKey:[`settings`,`bug-monitor`,`drafts`],queryFn:()=>t(`/api/engine/bug-monitor/drafts?limit=10`,{method:`GET`}).catch(()=>({drafts:[]})),refetchInterval:15e3}),kn=y({queryKey:[`settings`,`bug-monitor`,`incidents`],queryFn:()=>t(`/api/engine/bug-monitor/incidents?limit=10`,{method:`GET`}).catch(()=>({incidents:[]})),refetchInterval:1e4}),An=y({queryKey:[`settings`,`bug-monitor`,`posts`],queryFn:()=>t(`/api/engine/bug-monitor/posts?limit=10`,{method:`GET`}).catch(()=>({posts:[]})),refetchInterval:15e3}),jn=y({queryKey:[`settings`,`bug-monitor`,`workspace-browser`,Wt],enabled:Ht&&!!Wt,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(Wt)}`,{method:`GET`})}),Mn=y({queryKey:[`settings`,`channels`,`config`],queryFn:()=>e.channels.config().catch(()=>({})),refetchInterval:15e3}),Nn=y({queryKey:[`settings`,`channels`,`status`],queryFn:()=>e.channels.status().catch(()=>({})),refetchInterval:6e3}),Pn=y({queryKey:[`settings`,`channels`,`scopes`],queryFn:async()=>{let e=await Promise.all(yb.map(async e=>[e,Wb(await t(`/api/engine/channels/${e}/scopes`,{method:`GET`}).catch(()=>({scopes:[]})))]));return Object.fromEntries(e)},refetchInterval:15e3}),Fn=y({queryKey:[`settings`,`channels`,`tool-preferences`,Le],queryFn:async()=>{let e=await Promise.all(yb.map(async e=>{let n=String(Le[e]||``).trim();return[e,Ub(await t(`/api/engine/channels/${e}/tool-preferences${n?`?scope_id=${encodeURIComponent(n)}`:``}`,{method:`GET`}).catch(()=>Vb()))]}));return Object.fromEntries(e)},refetchInterval:15e3}),In=x({mutationFn:async({providerId:t,modelId:n})=>e.providers.setDefaults(t,n),onSuccess:async()=>{n(`ok`,`Updated provider defaults.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Ln=()=>String(an.data?.providers?.[vb]?.default_model||an.data?.providers?.[vb]?.defaultModel||`gpt-5.4`).trim()||`gpt-5.4`,Rn=async()=>{await e.providers.setDefaults(vb,Ln())},zn=x({mutationFn:async({providerId:n,url:r,modelId:i,apiKey:a,makeDefault:o})=>{let s=n.trim().toLowerCase(),c=r.trim(),l=i.trim();if(!s)throw Error(`Custom provider ID is required.`);if(!c)throw Error(`Custom provider URL is required.`);await t(`/api/engine/config`,{method:`PATCH`,body:JSON.stringify({...o?{default_provider:s}:{},providers:{[s]:{url:c,...l?{default_model:l}:{}}}})}),a.trim()&&await e.providers.setApiKey(s,a.trim())},onSuccess:async()=>{n(`ok`,`Custom provider saved.`),je(``),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Bn=x({mutationFn:async()=>t(`/api/engine/config/bug-monitor`,{method:`PATCH`,body:JSON.stringify({bug_monitor:{enabled:pt,paused:Y,workspace_root:String(gt||``).trim()||null,repo:String(vt||``).trim()||null,mcp_server:String(bt||``).trim()||null,provider_preference:String(St||`auto`).trim(),model_policy:wt&&Et?{default_model:{provider_id:wt,model_id:Et}}:null,auto_create_new_issues:Ot,require_approval_for_new_issues:At,auto_comment_on_matched_open_issues:Mt,label_mode:`reporter_only`}})}),onSuccess:async()=>{n(`ok`,`Bug Monitor settings saved.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})])},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Vn=x({mutationFn:async()=>t(`/api/engine/capabilities/bindings/refresh-builtins`,{method:`POST`}),onSuccess:async()=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]}),T.invalidateQueries({queryKey:[`settings`,`mcp`]})]),n(`ok`,`Capability bindings refreshed from built-ins.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Hn=x({mutationFn:async({draftId:e,decision:n})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/${n}`,{method:`POST`,body:JSON.stringify({reason:`${n}d from control panel settings`})}),onSuccess:async(e,t)=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,`Bug Monitor draft ${t.decision===`approve`?`approved`:`denied`}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Un=x({mutationFn:async({draftId:e})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/triage-run`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,e?.deduped?`Bug Monitor triage run already exists: ${e?.run?.run_id||`unknown`}`:`Bug Monitor triage run created: ${e?.run?.run_id||`unknown`}`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Wn=x({mutationFn:async({action:e})=>t(`/api/engine/bug-monitor/${e}`,{method:`POST`}),onSuccess:async(e,t)=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,`Bug Monitor ${t.action===`pause`?`paused`:`resumed`}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Gn=x({mutationFn:async({incidentId:e})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(e)}/replay`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,e?.deduped?`Bug Monitor triage run already exists: ${e?.run?.run_id||`unknown`}`:`Bug Monitor replay queued triage: ${e?.run?.run_id||`unknown`}`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Kn=x({mutationFn:async({draftId:e})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/publish`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,e?.action===`comment_issue`?`Bug Monitor commented on issue #${e?.draft?.issue_number||`unknown`}.`:`Bug Monitor published issue #${e?.draft?.issue_number||`unknown`}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),qn=x({mutationFn:async({draftId:e})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/recheck-match`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,`GitHub match result: ${String(e?.action||`rechecked`).replaceAll(`_`,` `)}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),Jn=x({mutationFn:({providerId:t,apiKey:n})=>e.providers.setApiKey(t,n),onSuccess:async()=>{n(`ok`,`API key updated.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Yn=x({mutationFn:({providerId:t})=>e.providers.oauthAuthorize(t),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase(),i=e?.ok!==!1,a=String(e?.error||e?.message||``).trim(),o=String(e?.session_id||e?.sessionId||``).trim(),s=String(e?.authorization_url||e?.authorizationUrl||e?.url||``).trim();if(!i||!r||!o||!s){n(`err`,a||`OAuth authorize response was incomplete.`);return}Ce(e=>({...e,[r]:o})),window.open(s,`_blank`,`noopener,noreferrer`),n(`info`,r===vb?`Browser sign-in opened for Codex. Finish the flow there, then return to Tandem.`:`Browser sign-in opened for ${r}.`),await T.invalidateQueries({queryKey:[`settings`,`providers`,`auth`]})},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Xn=x({mutationFn:({providerId:t})=>e.providers.oauthDisconnect(t),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase();Ce(e=>{if(!e[r])return e;let t={...e};return delete t[r],t}),n(`ok`,r===vb?`Codex account disconnected.`:`${r} disconnected.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Zn=x({mutationFn:({providerId:t})=>e.providers.oauthUseLocalSession(t),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase(),i=e?.ok!==!1,a=String(e?.error||e?.message||``).trim();if(!i){n(`err`,a||`Unable to import the local Codex session. Make sure Codex CLI is signed in on this machine.`);return}Ce(e=>{if(!e[r])return e;let t={...e};return delete t[r],t});let o=String(e?.email||``).trim();if(n(`ok`,r===vb?o?`Local Codex session imported: ${o}`:`Local Codex session imported.`:`${r} local session imported.`),r===vb)try{await Rn(),n(`ok`,`Codex is now the default provider for Tandem runs.`)}catch(e){n(`warn`,e instanceof Error?e.message:`Codex session imported, but Tandem could not switch the default provider.`)}await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Qn=x({mutationFn:({providerId:e,authJson:n})=>t(`/api/engine/provider/${encodeURIComponent(e)}/oauth/session/import`,{method:`POST`,body:JSON.stringify({auth_json:n})}),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase(),i=e?.ok!==!1,a=String(e?.error||e?.message||``).trim();if(!i){n(`err`,a||`Unable to import the Codex auth.json file. Make sure it was copied from a signed-in Codex CLI session.`);return}Fe(``),Ce(e=>{if(!e[r])return e;let t={...e};return delete t[r],t});let o=String(e?.email||``).trim();if(n(`ok`,r===vb?o?`Codex auth.json imported: ${o}`:`Codex auth.json imported.`:`${r} auth.json imported.`),r===vb)try{await Rn(),n(`ok`,`Codex is now the default provider for Tandem runs.`)}catch(e){n(`warn`,e instanceof Error?e.message:`Codex auth.json imported, but Tandem could not switch the default provider.`)}await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),$n=h(async(e,t)=>{if(t)try{let r=await t.text();if(Zt(t.name||`auth.json`),Fe(r),!r.trim()){n(`warn`,`Selected auth.json file was empty.`);return}Qn.mutate({providerId:e,authJson:r})}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{Yt.current&&(Yt.current.value=``)}},[Qn,n]);m(()=>{let t=Object.entries(Se).filter(([e,t])=>!!e&&!!t);if(!t.length)return;let r=!1,i=new Set,a=async()=>{let a=await Promise.all(t.map(async([t,n])=>{try{return{providerId:t,sessionId:n,payload:await e.providers.oauthStatus(t,n),error:null}}catch(e){return{providerId:t,sessionId:n,payload:null,error:e instanceof Error?e:Error(String(e))}}}));for(let e of a){if(r||i.has(e.providerId))continue;if(e.error){i.add(e.providerId),Ce(t=>{if(t[e.providerId]!==e.sessionId)return t;let n={...t};return delete n[e.providerId],n}),n(`err`,e.error.message);continue}let t=e.payload,a=String(t?.status||``).trim().toLowerCase();if(!(!a||a===`pending`)){if(i.add(e.providerId),Ce(t=>{if(t[e.providerId]!==e.sessionId)return t;let n={...t};return delete n[e.providerId],n}),a===`connected`){let r=String(t?.email||``).trim();if(n(`ok`,r?`Codex account connected: ${r}`:`Codex account connected.`),e.providerId===vb)try{await Rn(),n(`ok`,`Codex is now the default provider for Tandem runs.`)}catch(e){n(`warn`,e instanceof Error?e.message:`Codex connected, but Tandem could not switch the default provider.`)}}else a===`expired`?n(`warn`,`Codex sign-in expired. Start the connection again.`):n(`err`,String(t?.error||t?.message||``).trim()||`Codex sign-in did not complete. Please try again.`);await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])}}};a();let o=window.setInterval(()=>{a()},2e3);return()=>{r=!0,window.clearInterval(o)}},[e,Se,T,S,n]);let er=x({mutationFn:async e=>t(`/api/system/search-settings`,{method:`PATCH`,body:JSON.stringify(e)}),onSuccess:async e=>{W(``),se(``),await T.invalidateQueries({queryKey:[`settings`,`search`]}),n(`ok`,e?.restart_required?`Search settings saved. Restart tandem-engine to apply them.`:`Search settings saved.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),tr=x({mutationFn:async e=>t(`/api/system/scheduler-settings`,{method:`PATCH`,body:JSON.stringify(e)}),onSuccess:async e=>{await T.invalidateQueries({queryKey:[`settings`,`scheduler`]}),n(`ok`,e?.restart_required?`Scheduler settings saved. Restart tandem-engine to apply them.`:`Scheduler settings saved.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),nr=x({mutationFn:async({query:e})=>t(`/api/system/search-settings/test`,{method:`POST`,body:JSON.stringify({query:e,limit:5})}),onSuccess:e=>{de(e),n(`ok`,`Websearch test completed.`)},onError:e=>{de(null),n(`err`,e instanceof Error?e.message:String(e))}}),rr=x({mutationFn:async()=>{let e;try{e=JSON.parse(L)}catch(e){throw Error(e instanceof Error?`Config JSON is invalid: ${e.message}`:`Config JSON is invalid.`)}return t(`/api/control-panel/config`,{method:`PATCH`,body:JSON.stringify({config:e})})},onSuccess:async()=>{ee(``),n(`ok`,`Control panel config saved.`),await T.invalidateQueries({queryKey:[`settings`,`install`]}),await T.invalidateQueries({queryKey:[`system`,`capabilities`]})},onError:e=>{let t=e instanceof Error?e.message:String(e);ee(t),n(`err`,t)}}),or=x({mutationFn:async()=>{let e=(en.data?.identity?.bot||{})?.aliases||{},t=String(k||``).trim();if(!t)throw Error(`Bot name is required.`);let n=String(j||``).trim(),r=String(N||``).trim();return $t({identity:{bot:{canonical_name:t,avatar_url:n||null,aliases:{...e,control_panel:r||void 0}}}})},onSuccess:async()=>{n(`ok`,`Identity updated.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`identity`]}),C()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),sr=h(async()=>Promise.all([T.invalidateQueries({queryKey:[`settings`,`channels`]}),T.invalidateQueries({queryKey:[`settings`,`channels`,`scopes`]}),T.invalidateQueries({queryKey:[`settings`,`channels`,`tool-preferences`]})]),[T]),cr=x({mutationFn:async({channel:e,scopeId:n,payload:r})=>{let i=String(n||``).trim()?`?scope_id=${encodeURIComponent(String(n||``).trim())}`:``;return`reset`in r?t(`/api/engine/channels/${e}/tool-preferences${i}`,{method:`PUT`,body:JSON.stringify({reset:!0})}):t(`/api/engine/channels/${e}/tool-preferences${i}`,{method:`PUT`,body:JSON.stringify(r)})},onSuccess:async(e,t)=>{await T.invalidateQueries({queryKey:[`settings`,`channels`,`tool-preferences`]}),await T.invalidateQueries({queryKey:[`settings`,`channels`,`scopes`]});let r=String(t.scopeId||``).trim();n(`ok`,r?`Saved ${t.channel} scope ${r}.`:`Saved ${t.channel} channel tool scope.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),ur=x({mutationFn:async t=>{let n=q[t];if(!n)throw Error(`No draft found for ${t}.`);let r=String(n.modelProviderId||``).trim(),i=String(n.modelId||``).trim(),a={allowed_users:$b(n.allowedUsers),mention_only:!!n.mentionOnly,security_profile:String(n.securityProfile||`operator`).trim()||`operator`,model_provider_id:r||null,model_id:i||null},o=String(n.botToken||``).trim();if(o&&(a.bot_token=o),t===`telegram`&&(a.style_profile=String(n.styleProfile||`default`).trim()||`default`),t===`discord`&&(a.guild_id=String(n.guildId||``).trim()),t===`slack`){let e=String(n.channelId||``).trim();if(!e&&!Mn.data?.slack?.channel_id)throw Error(`Slack channel ID is required.`);e&&(a.channel_id=e)}return e.channels.put(t,a)},onSuccess:async(e,t)=>{n(`ok`,`Saved ${t} channel settings.`),He(e=>({...e,[t]:null})),J(e=>({...e,[t]:{...e[t],botToken:``}})),await sr()},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),fr=x({mutationFn:async t=>e.channels.delete(t),onSuccess:async(e,t)=>{n(`ok`,`Removed ${t} channel settings.`),He(e=>({...e,[t]:null})),Re(e=>({...e,[t]:``})),Ie.current[t]=!1,J(e=>({...e,[t]:Bb(t,null)})),await sr()},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),pr=x({mutationFn:async t=>{let n=q[t],r=String(n?.botToken||``).trim(),i={};return r&&(i.bot_token=r),e.channels.verify(t,i)},onSuccess:(e,t)=>{He(n=>({...n,[t]:e})),n(`ok`,`${t} verification complete.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),gr=h(async()=>T.invalidateQueries({queryKey:[`settings`,`mcp`]}),[T]),_r=x({mutationFn:async({serverName:t,allowedTools:n})=>e.mcp.patch(t,{allowed_tools:n??void 0,clear_allowed_tools:n===null}),onSuccess:async()=>{await gr(),n(`ok`,`MCP tool access updated.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),vr=x({mutationFn:async({action:n,server:r})=>{if(!r)throw Error(`No MCP server selected.`);if(n===`connect`)return e.mcp.connect(r.name);if(n===`disconnect`)return e.mcp.disconnect(r.name);if(n===`refresh`)return e.mcp.refresh(r.name);if(n===`authenticate`)return t(`/api/engine/mcp/${encodeURIComponent(r.name)}/auth/authenticate`,{method:`POST`});if(n===`toggle-enabled`)return e.mcp.setEnabled(r.name,!r.enabled);if(n===`delete`)return t(`/api/engine/mcp/${encodeURIComponent(r.name)}`,{method:`DELETE`});throw Error(`Unknown action: ${n}`)},onSuccess:async(e,t)=>{await gr();let r=!!e?.pendingAuth||!!e?.lastAuthChallenge||!!e?.authorizationUrl,i=e?.ok!==!1,a=String(t.server?.authKind||``).trim().toLowerCase();if(t.action===`connect`)if(r||!i&&a===`oauth`){let r=e?.lastAuthChallenge||{},i=String(r?.message||``).trim();n(`warn`,i?`OAuth authorization required for ${t.server?.name}: ${i}`:`OAuth authorization required for ${t.server?.name}.`)}else if(i)n(`ok`,`Connected ${t.server?.name}.`);else{let r=String(e?.error?.message||e?.error||``).trim();n(`err`,r?`Failed to connect ${t.server?.name}: ${r}`:`Failed to connect ${t.server?.name}.`)}if(t.action===`disconnect`&&n(`ok`,`Disconnected ${t.server?.name}.`),t.action===`refresh`)if(r||!i&&a===`oauth`){let r=e?.lastAuthChallenge||{},i=String(r?.message||``).trim();n(`warn`,i?`OAuth authorization required for ${t.server?.name}: ${i}`:`OAuth authorization required for ${t.server?.name}.`)}else if(i)n(`ok`,`Refreshed ${t.server?.name}.`);else{let r=String(e?.error?.message||e?.error||``).trim();n(`err`,r?`Failed to refresh ${t.server?.name}: ${r}`:`Failed to refresh ${t.server?.name}.`)}if(t.action===`authenticate`){let i=e?.ok!==!1,a=String(e?.error?.message||e?.error||``).trim();if(!i&&!r)n(`err`,a?`OAuth authorization check failed for ${t.server?.name}: ${a}`:`OAuth authorization check failed for ${t.server?.name}.`);else if(r){let r=e?.lastAuthChallenge||{},i=String(r?.message||``).trim();n(`warn`,i?`OAuth authorization still pending for ${t.server?.name}: ${i}`:`OAuth authorization still pending for ${t.server?.name}.`)}else n(`ok`,`Marked ${t.server?.name} as signed in.`)}t.action===`toggle-enabled`&&n(`ok`,`${t.server?.enabled?`Disabled`:`Enabled`} ${t.server?.name}.`),t.action===`delete`&&n(`ok`,`Deleted ${t.server?.name}.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),yr=x({mutationFn:async()=>{let n=String(qe||``).trim(),r=Eb(n),i=Tb(Ge||r);if(!n)throw Error(`Transport URL is required.`);if(!wb(n)&&!n.startsWith(`stdio:`))throw Error(`Transport must be a valid URL or stdio:* transport.`);let a=Mb(Nb({authMode:Ye,token:Ze,customHeader:$e,transport:n}),rt),o=String(tt||``).trim();Ob(n)&&o&&(a[`X-MCP-Toolsets`]=o);let s={name:i,transport:n,enabled:!0,auth_kind:Ye===`oauth`?`oauth`:``};Object.keys(a).length&&(s.headers=a);let c=String(st||``).trim();if(c&&c!==i&&await t(`/api/engine/mcp/${encodeURIComponent(c)}`,{method:`DELETE`}).catch(()=>null),await e.mcp.add(s),at){let t=await e.mcp.connect(s.name),n=t?.pendingAuth===!0||!!t?.lastAuthChallenge||!!t?.authorizationUrl;if(!t?.ok&&!n&&Ye!==`oauth`)throw Error(`Added "${s.name}" but connect failed.`);return{name:s.name,connectResult:t,connectAfterAdd:!0,authKind:Ye===`oauth`?`oauth`:``}}return{name:s.name,connectAfterAdd:!1,authKind:Ye===`oauth`?`oauth`:``}},onSuccess:async e=>{await gr(),We(!1),Ke(``),Je(``),Xe(`none`),Qe(``),et(``),nt(``),it([]),ot(!0),ct(``);let t=String(e?.name||``).trim(),r=e?.connectResult,i=String(e?.authKind||``).trim().toLowerCase(),a=!!r?.pendingAuth||!!r?.lastAuthChallenge||!!r?.authorizationUrl;if(e?.connectAfterAdd&&a){let e=r?.lastAuthChallenge||{},i=String(e?.message||``).trim();n(`warn`,i?`Saved MCP "${t}" and OAuth authorization is still required: ${i}`:`Saved MCP "${t}" and OAuth authorization is still required.`)}else e?.connectAfterAdd?i===`oauth`&&r&&r.ok!==!0?n(`warn`,`Saved MCP "${t}" as OAuth-backed. If it still needs authorization, open the auth link from the server row and refresh after signing in.`):n(`ok`,`Saved MCP "${t}" and connected it.`):n(`ok`,`Saved MCP "${t}".`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),br=e=>{if(!e)return;if(e.size>10*1024*1024){n(`err`,`Avatar image is too large (max 10 MB).`);return}let t=new FileReader;t.onload=()=>{let e=typeof t.result==`string`?t.result:``;if(!e){n(`err`,`Failed to read avatar image.`);return}M(e)},t.onerror=()=>n(`err`,`Failed to read avatar image.`),t.readAsDataURL(e)},Sr=Array.isArray(rn.data?.all)?rn.data.all:[],wr=Array.isArray(d?.connected)?d.connected.length:0;m(()=>{let e=mn.find(e=>e.isDefault)||mn[0];e&&(Te(t=>t.trim()&&t.trim().toLowerCase()!==`custom`?t:e.id),De(t=>t.trim()?t:e.url),ke(t=>t.trim()?t:e.model),Ne(String(an.data?.default||``).trim().toLowerCase()===e.id.trim().toLowerCase()))},[mn,an.data?.default]);let Tr=o(()=>Lb(Cn.data),[Cn.data]),Er=o(()=>Rb(wn.data),[wn.data]),Dr=o(()=>zb(Tn.data?.catalog||Tn.data||null),[Tn.data]),Or=o(()=>new Set(Tr.map(e=>e.name.toLowerCase())),[Tr]);m(()=>{let e=Tr.filter(e=>{let t=String(e.authKind||``).trim().toLowerCase(),n=String(e.lastAuthChallenge?.authorization_url||e.lastAuthChallenge?.authorizationUrl||e.authorizationUrl||``).trim();return t===`oauth`&&(!!e.lastAuthChallenge||!!n)});if(!e.length)return;let n=!1,r=!1,i=async()=>{if(!(n||r)){r=!0;try{let r=await Promise.all(e.map(async e=>{try{return{payload:await t(`/api/engine/mcp/${encodeURIComponent(e.name)}/auth/authenticate`,{method:`POST`}),error:null}}catch(e){return{payload:null,error:e instanceof Error?e:Error(String(e))}}}));if(n)return;r.some(({payload:e,error:t})=>t?!1:!(e?.pendingAuth===!0||e?.lastAuthChallenge||e?.authorizationUrl))&&await T.invalidateQueries({queryKey:[`settings`,`mcp`]})}finally{r=!1}}};i();let a=window.setInterval(()=>{i()},3e3);return()=>{n=!0,window.clearInterval(a)}},[t,Tr,T]);let kr=o(()=>{let e=String(dt||``).trim().toLowerCase();return Dr.servers.filter(t=>e?t.name.toLowerCase().includes(e)||t.slug.toLowerCase().includes(e)||t.transportUrl.toLowerCase().includes(e):!0).slice(0,36)},[Dr.servers,dt]),Ar=Tr.filter(e=>e.connected).length,jr=o(()=>Dn.data?.status||{},[Dn.data]),Mr=o(()=>Array.isArray(On.data?.drafts)&&On.data.drafts||[],[On.data]),Nr=o(()=>Array.isArray(kn.data?.incidents)&&kn.data.incidents||[],[kn.data]),Fr=o(()=>Array.isArray(An.data?.posts)&&An.data.posts||[],[An.data]),Ir=o(()=>Tr.find(e=>e.name.toLowerCase()===String(bt||``).trim().toLowerCase())||null,[bt,Tr]),Lr=o(()=>Sr.find(e=>String(e?.id||``).toLowerCase()===String(wt||``).trim().toLowerCase())||null,[wt,Sr]),Rr=o(()=>{let e=Lr&&typeof Lr==`object`&&Lr.models||{};return Object.keys(e).sort((e,t)=>e.localeCompare(t))},[Lr]),zr=Array.isArray(_n.data?.blocking_issues)&&_n.data?.blocking_issues||[],Br=Array.isArray(_n.data?.recommendations)&&_n.data?.recommendations||[],Vr=Array.isArray(_n.data?.install_hints)&&_n.data?.install_hints||[],Hr=yb.filter(e=>!!Nn.data?.[e]?.connected).length,Ur=Array.isArray(jn.data?.directories)?jn.data.directories:[],Wr=String(Kt||``).trim().toLowerCase(),Gr=o(()=>Wr?Ur.filter(e=>String(e?.name||e?.path||``).trim().toLowerCase().includes(Wr)):Ur,[Ur,Wr]),Kr=String(jn.data?.parent||``).trim(),qr=String(jn.data?.dir||Wt||``).trim();m(()=>{let e=En.data?.bug_monitor&&typeof En.data?.bug_monitor==`object`?En.data.bug_monitor:{};mt(!!e.enabled),ht(!!e.paused),_t(String(e.workspace_root||``).trim()),yt(String(e.repo||``).trim()),xt(String(e.mcp_server||``).trim()),Ct(String(e.provider_preference||`auto`).trim()||`auto`),Tt(String(e.model_policy?.default_model?.provider_id||``).trim()),Dt(String(e.model_policy?.default_model?.model_id||``).trim()),kt(e.auto_create_new_issues!==!1),jt(!!e.require_approval_for_new_issues),Nt(e.auto_comment_on_matched_open_issues!==!1)},[En.data]),m(()=>{let e=Mn.data&&typeof Mn.data==`object`?Mn.data:{};!Mn.data||typeof Mn.data!=`object`||J(t=>{let n={...t};for(let t of yb)n[t]||(n[t]=Bb(t,e[t]),Ie.current[t]=!0);return n})},[Mn.data]);let Jr=(e,t)=>{let n=String(t||``).trim();n&&In.mutate({providerId:e,modelId:n})},Zr=e=>{if(e){ut(`manual`);let t=e.headers&&typeof e.headers==`object`?e.headers:{},n=Object.keys(t),r=n.find(e=>String(e).toLowerCase()===`authorization`),i=n.find(e=>String(e).toLowerCase()===`x-api-key`),a=n.find(e=>String(e).toLowerCase()===`x-mcp-toolsets`),o=String(e.lastAuthChallenge?.authorization_url||e.lastAuthChallenge?.authorizationUrl||e.authorizationUrl||``).trim(),s=n.filter(e=>![r,i,a].filter(Boolean).map(e=>String(e).toLowerCase()).includes(String(e).toLowerCase())),c=String(e.authKind||``).trim().toLowerCase()||Ib(Dr,e.name,e.transport),l=o||c===`oauth`?`oauth`:`none`,u=``,d=``;o?d=``:i?(l=`x-api-key`,d=String(t[i]||``).trim()):r?(l=`bearer`,d=String(t[r]||``).replace(/^bearer\s+/i,``).trim()):s.length===1&&(l=`custom`,u=s[0],d=String(t[s[0]]||``).trim()),ct(e.name),Ke(e.name),Je(e.transport||``),ot(e.connected||!1),nt(a?String(t[a]||``).trim():Ob(e.transport||``)?`default`:``),Xe(l),et(u),Qe(d);let f=new Set([r,i,a,l===`custom`?u:``].filter(Boolean).map(e=>String(e).toLowerCase()));it(n.filter(e=>!f.has(String(e).toLowerCase())).map(e=>({key:e,value:String(t[e]||``).trim()})))}else ut(`catalog`),ct(``),Ke(``),Je(``),Xe(`none`),et(``),Qe(``),nt(``),it([]),ot(!0);We(!0)},Qr=async()=>{let e=await t(`/api/engine/bug-monitor/debug`,{method:`GET`});await navigator.clipboard.writeText(JSON.stringify(e,null,2)),n(`ok`,`Bug Monitor debug payload copied.`)},$r=[`Scanning registered Git worktrees...`,`Comparing managed worktrees against live runtime records...`,`Removing stale worktrees and orphan directories...`],ei=$r[Rt%$r.length],ti=o(()=>{let e=[];for(let t of Bt?.cleaned_worktrees||[])e.push({kind:`removed`,title:t.path||`Removed worktree`,detail:t.branch&&t.branch_deleted===!1&&t.branch_delete_error?`Removed worktree, but branch cleanup failed: ${t.branch_delete_error}`:t.branch?`Removed registered worktree and branch ${t.branch}.`:`Removed registered worktree.`,tone:`ok`});for(let t of Bt?.active_paths||[])e.push({kind:`active`,title:t,detail:`Skipped because the current Tandem runtime still tracks it as active.`,tone:`info`});for(let t of Bt?.stale_paths||[])(Bt?.cleaned_worktrees||[]).some(e=>e.path===t.path)||e.push({kind:`stale`,title:t.path||`Stale worktree`,detail:Bt?.dry_run?t.branch?`Would remove managed worktree and branch ${t.branch}.`:`Would remove managed worktree.`:`Marked stale but not removed.`,tone:`warn`});for(let t of Bt?.orphan_dirs_removed||[])e.push({kind:`orphan_removed`,title:t.path||`Removed orphan directory`,detail:`Removed an unregistered directory left behind under .tandem/worktrees.`,tone:`ok`});if(Bt?.dry_run)for(let t of Bt?.orphan_dirs||[])e.push({kind:`stale`,title:t,detail:`Would remove orphaned directory left on disk.`,tone:`warn`});for(let t of Bt?.failures||[])e.push({kind:`failure`,title:t.path||t.code||`Cleanup failure`,detail:t.error||t.stderr||t.branch_delete_error||`Cleanup failed.`,tone:`err`});return e},[Bt]),ni=[{id:`install`,label:`Install`,icon:`clipboard-list`},{id:`navigation`,label:`Navigation`,icon:`panel-left`},{id:`providers`,label:`Providers`,icon:`cpu`},{id:`search`,label:`Web Search`,icon:`globe`},{id:`scheduler`,label:`Scheduler`,icon:`layers`},{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`},{id:`maintenance`,label:`Maintenance`,icon:`wrench`}],ri=o(()=>Pb(Ye,Ze,$e,qe),[Ye,$e,Ze,qe]),ii=o(()=>Ab(Ge,qe),[Ge,qe]),ai=Ye===`oauth`&&at,oi=o(()=>Ob(qe),[qe]),si=w?.routeVisibility||{},ci=lb(!!w?.acaMode),li=Cr.map(([e,t,n])=>{let r=e;return{routeId:e,label:t,icon:n,enabled:si[r]!==!1,pinned:!!w?.acaMode&&cb.has(r),defaultVisible:ci[r]!==!1,description:ox[e]||`Open the ${String(t||e).toLowerCase()} section.`}}),ui=li.filter(e=>e.enabled).length,di=li.filter(e=>e.defaultVisible),fi=li.filter(e=>!e.defaultVisible),pi=fi.filter(e=>!e.enabled).length;return m(()=>{let e=E.current;e?Yr(e):Yr()},[F,pt,Y,gt,bt,jr.readiness?.runtime_ready,jr.runtime?.monitoring_active,jr.runtime?.paused,jr.runtime?.pending_incidents,jr.pending_drafts,Mr.length,Nr.length,Vn.isPending,Wn.isPending,Hn.isPending,Gn.isPending,Un.isPending,Bn.isPending,vr.isPending,er.isPending]),a(ir,{className:`grid gap-4`,children:a(`div`,{ref:E,className:`grid gap-4`,children:[a(`div`,{className:`tcp-settings-tabs`,children:ni.map(e=>a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${F===e.id?`active`:``}`,onClick:()=>I(e.id),children:[a(`i`,{"data-lucide":e.icon}),e.label]},e.id))}),a(mr,{main:a(ar,{className:`grid gap-4`,children:[F===`navigation`?a(dr,{title:`Sidebar navigation`,subtitle:w?.acaMode?`ACA mode keeps Dashboard, Chat, Coder, and Settings visible by default.`:`Choose which sections appear in the sidebar. Advanced and experimental surfaces stay hidden until you turn them on.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:w?.acaMode?`ok`:`info`,children:w?.acaMode?`ACA compact default`:`Core-first default`}),a(X,{tone:`ghost`,children:[ui,`/`,li.length,` visible`]}),a(`button`,{className:`tcp-btn`,type:`button`,onClick:()=>w?.showAllSections(),children:`Show all sections`}),a(`button`,{className:`tcp-btn-primary`,type:`button`,onClick:()=>w?.resetNavigation(),children:[`Reset `,w?.acaMode?`ACA compact`:`default`]})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Default sections`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`These sections are part of the standard control panel and start on by default.`})]}),a(X,{tone:`ok`,children:[di.filter(e=>e.enabled).length,`/`,di.length,` shown`]})]}),a(`div`,{className:`mt-3 grid gap-2`,children:di.map(e=>a(`button`,{type:`button`,className:`flex items-center justify-between rounded-xl border px-3 py-3 text-left transition ${e.enabled?`border-lime-500/40 bg-lime-500/10 hover:border-lime-400/70`:`border-slate-700/60 bg-slate-900/20 hover:border-slate-500/70`}`,onClick:()=>w?.setRouteVisibility(e.routeId,!e.enabled),children:[a(`div`,{className:`flex min-w-0 items-center gap-3`,children:[a(`span`,{className:`flex h-9 w-9 items-center justify-center rounded-lg border ${e.enabled?`border-lime-500/30 bg-lime-500/10 text-lime-200`:`border-slate-700/70 bg-slate-950/30 text-slate-300`}`,children:a(`i`,{"data-lucide":e.icon})}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:e.label}),a(`div`,{className:`tcp-subtle truncate text-xs`,children:e.description})]})]}),a(`div`,{className:`flex items-center gap-2`,children:[e.pinned?a(X,{tone:`ok`,children:`Pinned`}):null,a(X,{tone:e.enabled?`ok`:`ghost`,children:e.enabled?`Shown`:`Hidden`})]})]},e.routeId))})]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Advanced / experimental sections`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Only routes that ship hidden by default live here.`})]}),a(X,{tone:pi>0?`warn`:`ok`,children:[pi,` hidden`]})]}),a(`div`,{className:`mt-3 grid gap-2`,children:fi.map(e=>a(`button`,{type:`button`,className:`flex items-center justify-between rounded-xl border px-3 py-3 text-left transition ${e.enabled?`border-lime-500/40 bg-lime-500/10 hover:border-lime-400/70`:`border-slate-700/60 bg-slate-900/20 hover:border-slate-500/70`}`,onClick:()=>w?.setRouteVisibility(e.routeId,!e.enabled),children:[a(`div`,{className:`flex min-w-0 items-center gap-3`,children:[a(`span`,{className:`flex h-9 w-9 items-center justify-center rounded-lg border ${e.enabled?`border-lime-500/30 bg-lime-500/10 text-lime-200`:`border-slate-700/70 bg-slate-950/30 text-slate-300`}`,children:a(`i`,{"data-lucide":e.icon})}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:e.label}),a(`div`,{className:`tcp-subtle truncate text-xs`,children:e.description})]})]}),a(X,{tone:e.enabled?`ok`:`ghost`,children:e.enabled?`Shown`:`Hidden`})]},e.routeId))})]}),a(`div`,{className:`tcp-subtle text-xs`,children:`These preferences are stored in this browser only.`})]})}):null,F===`install`?a(dr,{title:`Install config`,subtitle:`Durable non-secret install preferences stored in tandem-data for Tandem startup and navigation defaults.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:String(tn.data?.control_panel_mode||``).trim().toLowerCase()===`aca`?`ok`:`info`,children:tn.data?.control_panel_mode||`auto`}),a(X,{tone:tn.data?.control_panel_config_ready?`ok`:`warn`,children:tn.data?.control_panel_config_ready?`Ready`:`Needs setup`}),a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>nn.refetch().then(()=>n(`ok`,`Install config refreshed.`)),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh`]}),a(`button`,{type:`button`,className:`tcp-btn-primary`,onClick:()=>rr.mutate(),disabled:rr.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save config`]})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`font-medium`,children:`Startup profile`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:tn.data?.control_panel_mode_reason||`The control panel auto-detects its startup mode and can be overridden with TANDEM_CONTROL_PANEL_MODE.`}),a(`div`,{className:`mt-3 grid gap-2 text-xs`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Mode source`}),a(`span`,{children:tn.data?.control_panel_mode_source||`detected`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Integration detected`}),a(`span`,{children:tn.data?.aca_integration?`yes`:`no`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Compact nav`}),a(`span`,{children:tn.data?.control_panel_compact_nav?`on`:`off`})]})]})]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`font-medium`,children:`Hosted management`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Detect whether this panel is running on a Tandem-managed hosted deployment so hosted-only update and notification UX can stay gated.`}),a(`div`,{className:`mt-3 grid gap-2 text-xs`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Managed hosted server`}),a(`span`,{children:tn.data?.hosted_managed?`yes`:`no`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Provider`}),a(`span`,{children:tn.data?.hosted_provider||`—`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Deployment slug`}),a(`span`,{children:tn.data?.hosted_deployment_slug||`—`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Release`}),a(`span`,{children:[tn.data?.hosted_release_version||`—`,tn.data?.hosted_release_channel?` · ${tn.data.hosted_release_channel}`:``]})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Update policy`}),a(`span`,{children:tn.data?.hosted_update_policy||`—`})]})]}),tn.data?.hosted_managed?a(`div`,{className:`mt-3 rounded-xl border border-lime-500/20 bg-lime-500/10 px-3 py-2 text-xs text-lime-200`,children:`Hosted-managed features can safely key off this signal instead of guessing from hostname or environment.`}):null]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`font-medium`,children:`Config file`}),a(`div`,{className:`tcp-subtle mt-1 break-all text-xs`,children:tn.data?.control_panel_config_path||nn.data?.path||`control-panel-config.json`}),a(`div`,{className:`mt-3 grid gap-2 text-xs`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Ready`}),a(`span`,{children:tn.data?.control_panel_config_ready?`yes`:`no`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Missing`}),a(`span`,{children:Array.isArray(tn.data?.control_panel_config_missing)?tn.data?.control_panel_config_missing.join(`, `)||`none`:`unknown`})]})]})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-sm font-medium`,children:`Control panel config JSON`}),a(`textarea`,{className:`tcp-input min-h-[28rem] font-mono text-xs leading-5`,value:L,onInput:e=>R(e.target.value),spellCheck:!1})]}),z?a(`div`,{className:`rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200`,children:z}):null,a(`div`,{className:`tcp-subtle text-xs`,children:"This file holds non-secret install state: repo binding, provider defaults, task source, swarm policy, GitHub MCP preferences, and navigation defaults. Secrets should stay in `.env` or token files."})]})}):null,F===`providers`?a(dr,{title:`Provider defaults`,subtitle:`Provider catalog, model selection, and API key entry.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:String(an.data?.default||``).trim()?`ok`:`warn`,children:[`Default: `,String(an.data?.default||`none`)]}),a(X,{tone:`info`,children:[wr,` connected`]}),a(`button`,{className:`tcp-btn`,onClick:()=>S().then(()=>n(`ok`,`Provider status refreshed.`)),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh provider`]})]}),children:a(`div`,{className:`grid gap-3`,children:[a(`button`,{type:`button`,className:`tcp-list-item text-left`,onClick:()=>ye(e=>!e),"aria-expanded":ve,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":ve?`chevron-down`:`chevron-right`}),a(`span`,{children:ve?`Hide provider catalog`:`Show provider catalog`})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[Sr.length,` providers available for configuration. Expand to change models and API keys.`]})]}),a(X,{tone:`info`,children:[wr,` connected`]})]})}),a(l,{initial:!1,children:ve?a(s.div,{className:`grid gap-3`,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:[a(`div`,{className:`tcp-list-item grid gap-3`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Custom OpenAI-compatible provider`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Add providers like MiniMax by ID, base URL, default model, and API key.`})]}),a(X,{tone:mn.length?`ok`:`info`,children:[mn.length,` configured`]})]}),a(`button`,{type:`button`,className:`tcp-list-item text-left`,onClick:()=>xe(e=>!e),"aria-expanded":be,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":be?`chevron-down`:`chevron-right`}),a(`span`,{children:be?`Hide custom provider form`:`Show custom provider form`})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Use this for OpenAI-compatible endpoints. Anthropic is handled by the built-in provider row below.`})]}),a(X,{tone:`info`,children:`OpenAI-compatible only`})]})}),a(l,{initial:!1,children:be?a(s.div,{className:`grid gap-3`,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:a(`form`,{className:`grid gap-3`,onSubmit:e=>{e.preventDefault(),zn.mutate({providerId:we,url:Ee,modelId:Oe,apiKey:Ae,makeDefault:Me})},children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Provider ID`}),a(`input`,{className:`tcp-input`,value:we,onInput:e=>Te(e.target.value),placeholder:`custom`})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Default model`}),a(`input`,{className:`tcp-input`,value:Oe,onInput:e=>ke(e.target.value),placeholder:`MiniMax-M2`})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Base URL`}),a(`input`,{className:`tcp-input`,value:Ee,onInput:e=>De(e.target.value),placeholder:`https://api.minimax.io/v1`})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`API key`}),a(`input`,{className:`tcp-input`,type:`password`,value:Ae,onInput:e=>je(e.target.value),placeholder:`Optional. Leave blank to keep the existing key.`})]}),a(`label`,{className:`inline-flex items-center gap-2 text-sm text-slate-200`,children:[a(`input`,{type:`checkbox`,className:`accent-slate-400`,checked:Me,onChange:e=>Ne(e.target.checked)}),`Make this the default provider`]}),a(`div`,{className:`flex flex-wrap justify-end gap-2`,children:a(`button`,{className:`tcp-btn-primary`,type:`submit`,disabled:zn.isPending,children:[a(`i`,{"data-lucide":`plus`}),`Save custom provider`]})})]})}):null}),mn.length?a(`div`,{className:`grid gap-2`,children:mn.map(e=>a(`div`,{className:`flex flex-wrap items-start justify-between gap-2 rounded-xl border border-slate-700/60 bg-slate-900/20 px-3 py-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:e.id}),a(`div`,{className:`tcp-subtle break-all text-xs`,children:e.url||`No URL configured`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Model: `,e.model||`not set`]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[e.isDefault?a(X,{tone:`ok`,children:`default`}):null,a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>{Te(e.id),De(e.url),ke(e.model),Ne(e.isDefault),xe(!0),ye(!0)},children:[a(`i`,{"data-lucide":`square-pen`}),`Edit`]})]})]},e.id))}):null]}),rn.isPending?a(`div`,{className:`tcp-list-item grid gap-2`,children:[a(`div`,{className:`font-medium`,children:`Loading provider catalog`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Tandem is checking live provider models and auth state now.`})]}):Sr.length?Sr.map(e=>{let t=String(e?.id||``),n=Object.keys(e?.models||{}),r=String(an.data?.providers?.[t]?.default_model||n[0]||``),i=String(D[t]??r).trim(),o=i.toLowerCase(),c=n.filter(e=>o?e.toLowerCase().includes(o):!0).slice(0,80),l=ix(e,n.length),u=ax(e,r),d=xr[t]||null,f=String(d?.keyUrl||``).trim(),p=ln[t]||{},m=String(an.data?.default||``).trim().toLowerCase(),h=t===vb&&m===vb,g=String(p?.auth_kind||p?.authKind||``).trim().toLowerCase(),_=String(p?.status||``).trim().toLowerCase(),v=String(p?.email||``).trim(),y=String(p?.display_name||p?.displayName||``).trim(),b=String(p?.managed_by||p?.managedBy||``).trim(),x=Number(p?.expires_at_ms||p?.expiresAtMs||0),S=p?.local_session_available===!0||p?.localSessionAvailable===!0,C=!!String(Se[t]||``).trim()||Yn.isPending&&String(Yn.variables?.providerId||``).trim().toLowerCase()===t,w=g===`oauth`&&p?.connected===!0&&_!==`reauth_required`,T=t===vb,E=!T||un||dn,k=C?{tone:`info`,text:`sign-in pending`}:w?{tone:`ok`,text:`account connected`}:_===`reauth_required`?{tone:`warn`,text:`reauth required`}:{tone:`warn`,text:`not connected`},A=dn&&t===vb;return a(s.details,{layout:!0,className:`tcp-list-item`,children:[a(`summary`,{className:`cursor-pointer list-none`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:t}),a(`div`,{className:`tcp-subtle text-xs`,children:u})]}),a(X,{tone:l.tone,children:l.text})]})}),a(`div`,{className:`mt-3 grid gap-3`,children:[f&&!T?a(`div`,{className:`flex justify-end`,children:a(`a`,{className:`tcp-btn h-8 px-3 text-xs`,href:f,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Get API key`]})}):null,a(`form`,{className:`grid gap-2`,onSubmit:e=>{e.preventDefault(),Jr(t,i)},children:[a(`div`,{className:`flex gap-2`,children:[a(`input`,{className:`tcp-input`,value:i,placeholder:`Type model id for ${t}`,onInput:e=>O(n=>({...n,[t]:e.target.value}))}),a(`button`,{className:`tcp-btn`,type:`submit`,children:[a(`i`,{"data-lucide":`badge-check`}),`Apply`]})]}),a(`div`,{className:`max-h-48 overflow-auto rounded-xl border border-slate-700/60 bg-slate-900/20 p-1`,children:c.length?c.map(e=>a(`button`,{type:`button`,className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${e===r?`bg-slate-700/40`:``}`,onClick:()=>{O(n=>({...n,[t]:e})),Jr(t,e)},children:e},e)):a(`div`,{className:`tcp-subtle px-2 py-1 text-xs`,children:n.length?`No matching models.`:`No live catalog available. Type a model ID manually.`})})]}),T?a(`div`,{className:`grid gap-3 rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:String(d?.label||`Codex Account`)}),a(`div`,{className:`tcp-subtle text-xs`,children:String(d?.description||`Use your ChatGPT/Codex subscription instead of a separate API key.`)})]}),a(X,{tone:k.tone,children:k.text})]}),a(`div`,{className:`grid gap-1 text-xs tcp-subtle`,children:[A?a(`div`,{className:`rounded-xl border border-sky-700/50 bg-sky-950/20 px-3 py-2 text-sky-100`,children:[a(`div`,{className:`font-medium`,children:`Recommended for hosted servers`}),a(`div`,{className:`mt-1`,children:[`Import a Codex `,a(`code`,{children:`auth.json`}),` from a signed-in machine. Browser OAuth on provisioned servers can stall after the consent screen, so the import path is the reliable v1 flow.`]})]}):null,C?a(`div`,{children:`Pending browser sign-in is saved in this browser session, so you can refresh this page and Tandem will keep checking when you come back.`}):null,w?a(`div`,{children:y||v?`Connected as ${y||v}.`:`Connected to a Codex account.`}):null,b?a(`div`,{children:[`Managed by`,` `,b===`codex-cli`?`the local Codex CLI session`:b===`codex-upload`?`an uploaded Codex auth.json`:`Tandem`,`.`]}):null,A&&w&&b===`codex-upload`?a(`div`,{children:[`This hosted server is currently using an imported Codex session stored on the VM. Import another`,` `,a(`code`,{children:`auth.json`}),` any time to replace it.`]}):null,x>0?a(`div`,{children:[`Session status refreshes through`,` `,new Date(x).toLocaleString(),`.`]}):null,t===vb&&w&&!h?a(`div`,{children:`Tandem is connected to Codex, but new runs are still using a different default provider.`}):null,E?a(`div`,{children:A?`This Tandem-hosted server can import a Codex auth.json from a signed-in machine and keep the session on the VM.`:S?`Local Codex CLI session detected on this machine.`:`If the Codex CLI is already signed in on this machine, you can mirror that session here instead of starting a fresh browser login.`}):null,E?null:a(`div`,{children:`Codex account sign-in is only enabled when this control panel is connected to a local engine or a Tandem-hosted managed server.`})]}),A?a(`div`,{className:`grid gap-3`,children:[a(`input`,{ref:Yt,type:`file`,accept:`.json,application/json`,className:`hidden`,onChange:e=>{$n(t,e.target.files?.[0]||null)}}),a(`textarea`,{className:`tcp-input min-h-40 resize-y rounded-xl p-3 font-mono text-xs leading-5`,value:Pe,onChange:e=>Fe(e.target.value),placeholder:`Paste the contents of ~/.codex/auth.json here.
7375
+ `).trim(),modelProvider:``,modelId:``}),C(`Imported "${e.name}" into the agent form — review and save below.`),setTimeout(()=>{k.current?.scrollIntoView({behavior:`smooth`,block:`start`})},80)},ue=e=>{if(!e)return;if(e.size>10*1024*1024){t(`err`,`Avatar image is too large (max 10 MB).`);return}let n=new FileReader;n.onload=()=>{let e=typeof n.result==`string`?n.result:``;if(!e){t(`err`,`Failed to read avatar image.`);return}d(t=>({...t,avatarUrl:e}))},n.onerror=()=>t(`err`,`Failed to read avatar image.`),n.readAsDataURL(e)};return a(`div`,{ref:l,className:`grid gap-4`,children:[A&&a(Nr,{title:`Agent Standup`,subtitle:`Compose scheduled standups from the same saved agents you manage here`,children:a(Ky,{client:e,toast:t,workspaceRoot:N,onWorkspaceRootChange:T,defaultWorkspaceRoot:M,timezone:E,onTimezoneChange:D,templates:ee.map(e=>({templateId:e.templateId,displayName:e.displayName||e.templateId,role:e.role,modelLabel:e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:``}))})}),a(Nr,{title:`Agent Catalog`,subtitle:`Browse and import from the canonical Codex subagent set. Use any entry to pre-fill the agent form below.`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`grid gap-2 md:grid-cols-[1fr_auto]`,children:[a(`input`,{className:`tcp-input`,placeholder:`Search agent name, category, tag, or path`,value:h,onInput:e=>g(e.target.value)}),a(`button`,{className:`tcp-btn`,onClick:()=>{g(``),b(`all`)},disabled:!h&&v===`all`,children:`Clear`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs ${v===`all`?`border-amber-400/60 bg-amber-400/10`:``}`,onClick:()=>b(`all`),children:`All`}),qy.categories.map(e=>a(`button`,{className:`tcp-btn h-8 px-3 text-xs ${v===e.id?`border-amber-400/60 bg-amber-400/10`:``}`,onClick:()=>b(e.id),children:[e.title,` (`,e.count,`)`]},e.id))]}),S?a(`div`,{className:`text-xs text-slate-400`,children:S}):null,ae.length?ae.map(e=>a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex items-start justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-medium text-slate-100`,children:e.title}),a(`div`,{className:`text-xs text-slate-400`,children:e.summary})]}),a(`div`,{className:`tcp-badge-info`,children:[e.agents.length,` agents`]})]}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:e.agents.map(e=>a(`div`,{className:`tcp-list-item grid gap-2`,children:[a(`div`,{className:`flex items-start justify-between gap-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate font-semibold text-slate-100`,children:e.name}),a(`div`,{className:`text-xs text-slate-400`,children:e.summary})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`span`,{className:`tcp-badge-info`,children:e.role}),a(`span`,{className:e.sandbox_mode===`read-only`?`tcp-badge-warn`:`tcp-badge-ok`,children:e.sandbox_mode})]})]}),a(`div`,{className:`font-mono text-xs text-slate-400`,children:e.source_path}),a(`div`,{className:`line-clamp-3 text-xs text-slate-200`,children:rb(e)}),a(`div`,{className:`flex flex-wrap gap-1`,children:[e.tags.slice(0,4).map(t=>a(`span`,{className:`tcp-badge-muted`,children:t},`${e.id}-${t}`)),e.requires.slice(0,3).map(t=>a(`span`,{className:`tcp-badge-info`,children:t},`${e.id}-${t}`))]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,title:`Pre-fill the agent creation form from this catalog entry`,onClick:()=>le(e),children:[a(`i`,{"data-lucide":`download`}),`Import as Agent`]}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,title:`Open this agent in Studio (new tab)`,onClick:()=>ce(e),children:[a(`i`,{"data-lucide":`external-link`}),`Studio ↗`]}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs ${W===e.source_path?`border-emerald-400/60 bg-emerald-400/10 text-emerald-300`:``}`,title:`Copy source path to clipboard`,onClick:()=>void se(e.source_path),children:[a(`i`,{"data-lucide":W===e.source_path?`check`:`copy`}),W===e.source_path?`Copied`:`Copy path`]})]})]},e.source_path))})]},e.id)):a(Pr,{text:`No agents match your search.`})]})}),a(`div`,{className:`grid gap-4 xl:grid-cols-2`,children:[a(`div`,{ref:k,children:a(Nr,{title:`Agents`,subtitle:`Create reusable agent personalities, prompts, and default models for automation workflows`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-cyan-300`,children:`Reusable Personalities`}),a(`div`,{className:`mt-2 text-sm text-slate-300`,children:`Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses.`})]}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:[a(`input`,{className:`tcp-input`,placeholder:`template-id`,value:u.templateId,disabled:!!f,onInput:e=>d(t=>({...t,templateId:e.target.value}))}),a(`input`,{className:`tcp-input`,placeholder:`Display name`,value:u.displayName,onInput:e=>d(t=>({...t,displayName:e.target.value}))}),a(`select`,{className:`tcp-input`,value:u.role,onInput:e=>d(t=>({...t,role:e.target.value})),children:Yy.map(e=>a(`option`,{value:e,children:e},e))}),a(`input`,{className:`tcp-input`,placeholder:`Avatar URL or upload (optional)`,value:u.avatarUrl,onInput:e=>d(t=>({...t,avatarUrl:e.target.value}))}),a(`input`,{className:`tcp-input`,placeholder:`Model provider (optional)`,value:u.modelProvider,onInput:e=>d(t=>({...t,modelProvider:e.target.value}))}),a(`input`,{className:`tcp-input`,placeholder:`Model ID (optional)`,value:u.modelId,onInput:e=>d(t=>({...t,modelId:e.target.value}))})]}),a(`div`,{className:`grid gap-3 lg:grid-cols-[1.15fr_0.85fr]`,children:[a(`div`,{className:`rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-slate-500`,children:`Prompt Guidance`}),a(`div`,{className:`mt-2 text-sm text-slate-300`,children:`Write the lasting perspective for this agent, not a one-off task. Good prompts describe ownership and judgment: frontend lead, backend lead, product ops, incident watcher.`}),a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:Zy.map(e=>a(`button`,{type:`button`,className:`tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs`,onClick:()=>d(t=>({...t,systemPrompt:e})),children:`Use Example`},e))})]}),a(`div`,{className:`rounded-[28px] border border-slate-800/80 bg-[radial-gradient(circle_at_top,_rgba(34,211,238,0.18),_transparent_45%),linear-gradient(180deg,rgba(15,23,42,0.9),rgba(2,6,23,0.96))] p-5`,children:[a(`div`,{className:`flex items-start justify-between gap-4`,children:[a(`div`,{className:`flex items-start gap-4`,children:[a(`div`,{className:`flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-lg font-semibold text-cyan-100`,children:re?a(`img`,{src:re,alt:te,className:`h-full w-full object-cover`}):U}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(`strong`,{className:`text-white`,children:te}),a(`span`,{className:`tcp-badge-info`,children:u.role})]}),a(`div`,{className:`mt-1 text-xs text-slate-400`,children:u.templateId.trim()||`template-id`}),a(`div`,{className:`mt-2 text-sm text-slate-300`,children:ne})]})]}),a(`div`,{className:`flex items-center gap-2`,children:[a(`button`,{type:`button`,className:`tcp-icon-btn`,title:`Upload avatar`,"aria-label":`Upload avatar`,onClick:()=>O.current?.click(),children:a(`i`,{"data-lucide":`pencil`})}),a(`button`,{type:`button`,className:`tcp-icon-btn`,title:`Clear avatar`,"aria-label":`Clear avatar`,onClick:()=>d(e=>({...e,avatarUrl:``})),children:a(`i`,{"data-lucide":`trash-2`})})]})]}),a(`div`,{className:`mt-3 text-xs text-slate-400`,children:`Upload an image like Settings Identity preview, or paste a direct avatar URL.`}),a(`input`,{ref:O,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>{ue(e.target.files?.[0]||null),e.target.value=``}}),a(`div`,{className:`mt-4 rounded-2xl border border-slate-800/70 bg-black/20 p-4`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-slate-500`,children:`Personality Preview`}),a(`div`,{className:`mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-200`,children:u.systemPrompt.trim()||`This agent will respond from the persistent personality you define here across workflows and standups.`})]}),(u.modelProvider.trim()||u.modelId.trim())&&a(`div`,{className:`mt-3 text-xs text-cyan-200`,children:[`Default model: `,u.modelProvider.trim()||`provider`,`/`,u.modelId.trim()||`model`]})]})]}),a(`textarea`,{className:`tcp-input min-h-[140px]`,placeholder:`Persistent system prompt`,value:u.systemPrompt,onInput:e=>d(t=>({...t,systemPrompt:e.target.value}))}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:L.isPending,onClick:()=>L.mutate(),children:[a(`i`,{"data-lucide":`save`}),f?`Update Agent`:`Create Agent`]}),H&&a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>{p(null),d(Qy)},children:[a(`i`,{"data-lucide":`rotate-ccw`}),`Reset`]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`text-xs font-medium uppercase tracking-[0.24em] text-slate-500`,children:`Saved Agents`}),a(`div`,{className:`tcp-subtle text-xs`,children:[ee.length,` saved`]})]}),ee.length?ee.map(e=>a(`div`,{className:`tcp-list-item`,children:a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`flex items-center gap-2`,children:[a(`strong`,{children:e.displayName||e.templateId}),a(`span`,{className:`tcp-badge-info`,children:e.role}),e.modelProvider&&e.modelId?a(`span`,{className:`tcp-badge-ok`,children:[e.modelProvider,`/`,e.modelId]}):null]}),a(`div`,{className:`tcp-subtle text-xs`,children:e.templateId}),e.systemPrompt?a(`div`,{className:`mt-2 line-clamp-4 text-xs text-slate-300`,children:e.systemPrompt}):a(`div`,{className:`mt-2 text-xs text-slate-500`,children:`No persistent prompt set yet.`})]}),a(`div`,{className:`flex gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-xs`,onClick:()=>{p(e.templateId),d({templateId:e.templateId,displayName:e.displayName,avatarUrl:e.avatarUrl,role:Yy.includes(e.role)?e.role:`worker`,systemPrompt:e.systemPrompt,modelProvider:e.modelProvider,modelId:e.modelId})},children:[a(`i`,{"data-lucide":`pencil`}),`Edit`]}),a(`button`,{type:`button`,className:`tcp-btn-danger h-7 px-2 text-xs`,onClick:()=>R.mutate(e.templateId),children:[a(`i`,{"data-lucide":`trash-2`}),`Delete`]})]})]})},e.templateId)):a(Pr,{title:`No agents yet`,text:`Create your first saved personality here, then reuse it across automation workflows and standups.`})]})]})})}),a(Nr,{title:`Team Instances`,subtitle:`Running collaborative agent instances`,children:a(`div`,{className:`grid gap-2`,children:B.length?B.map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 flex items-center justify-between gap-2`,children:[a(`strong`,{children:String(e?.template_id||e?.templateID||e?.instance_id||`Instance`)}),a(`span`,{className:`tcp-badge-info`,children:String(e?.status||`active`)})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`mission: `,String(e?.mission_id||e?.missionID||`n/a`)]})]},String(e?.instance_id||e?.id||t))):a(Pr,{text:`No team instances found.`})})}),a(Nr,{title:`Spawn Approvals`,subtitle:`Pending team approval requests`,children:a(`div`,{className:`grid gap-2`,children:V.length?V.map((e,t)=>{let n=String(e?.approval_id||e?.request_id||e?.id||`request-${t}`);return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`mb-1 font-medium`,children:String(e?.reason||e?.title||n)}),a(`div`,{className:`tcp-subtle text-xs`,children:n}),a(`div`,{className:`mt-2 flex gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-7 px-2 text-xs`,onClick:()=>z.mutate({requestId:n,decision:`approve`}),children:[a(`i`,{"data-lucide":`badge-check`}),`Approve`]}),a(`button`,{type:`button`,className:`tcp-btn-danger h-7 px-2 text-xs`,onClick:()=>z.mutate({requestId:n,decision:`deny`}),children:[a(`i`,{"data-lucide":`x`}),`Deny`]})]})]},n)}):a(Pr,{text:`No pending approvals.`})})})]})]})}function ab(e){let t=Number(e||0);return!Number.isFinite(t)||t<=0?`never`:new Date(t).toLocaleString()}function ob(e){let t=Number(e||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 sb(e,t){return`${e||`project`}::${t||`source`}`}function cb({projects:e,watcher:t,projectsJson:n,projectsJsonError:i,intakeKeys:s,createdRawKey:c,isCreatingKey:l,disablingKeyId:u,resettingSourceKey:d,replayingSourceKey:f,actionResult:p,onProjectsJsonChange:m,onCreateKey:h,onDisableKey:g,onClearCreatedRawKey:_,onResetSourceOffset:v,onReplayLatestSourceCandidate:y}){let[b,x]=r(``),[S,C]=r(`external reporter`),[w,T]=r(`external-demo`),[E,D]=r(`owner/repo`),[O,k]=r(`/path/to/repo`),[A,j]=r(`app-log`),[M,N]=r(`logs/app.log`),[P,F]=r(`all`),I=Array.isArray(t.sources)?t.sources:[],L=o(()=>new Map(I.map(e=>[sb(String(e.project_id||``),String(e.source_id||``)),e])),[I]),R=Number(t.enabled_projects||0),z=Number(t.enabled_sources||0),ee=o(()=>e.map((e,t)=>({id:String(e.project_id||`project-${t+1}`).trim(),label:String(e.name||e.project_id||`project-${t+1}`).trim()})).filter(e=>e.id),[e]),B=b||ee[0]?.id||``,V=o(()=>e.map((e,t)=>{let n=String(e.project_id||`project-${t+1}`),r=Array.isArray(e.log_sources)?e.log_sources:[],i=r.map((e,t)=>{let r=String(e.source_id||`source-${t+1}`);return L.get(sb(n,r))}).filter(Boolean),a=i.filter(e=>e.healthy===!1).length,o=i.reduce((e,t)=>e+Number(t.total_candidates||0),0),s=i.reduce((e,t)=>e+Number(t.total_submitted||0),0);return{project:e,projectId:n,logSourceCount:r.length,observedSourceCount:i.length,unhealthyCount:a,candidateCount:o,submittedCount:s,lastPollAtMs:Math.max(...i.map(e=>Number(e.last_poll_at_ms||0)),0)}}),[e,L]),H=o(()=>P===`all`?V:V.filter(e=>e.projectId===P),[P,V]);return a(`div`,{className:`grid gap-3 rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`External project log intake`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Configure monitored projects as JSON, then watch source health here after saving.`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:t.running?`ok`:z?`warn`:`info`,children:t.running?`Watcher running`:`Watcher idle`}),a(X,{tone:R?`info`:`warn`,children:[R,` projects`]}),a(X,{tone:z?`info`:`warn`,children:[z,` sources`]})]})]}),V.length?a(`div`,{className:`grid gap-2 md:grid-cols-[minmax(0,1fr)_auto]`,children:[a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:V.slice(0,6).map(e=>a(`button`,{type:`button`,className:`tcp-list-item text-left ${P===e.projectId?`ring-1 ring-sky-400/50`:``}`,onClick:()=>{F(t=>t===e.projectId?`all`:e.projectId)},children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`truncate font-medium`,children:e.project.name||e.projectId}),a(X,{tone:e.unhealthyCount?`warn`:e.observedSourceCount?`ok`:`info`,children:e.unhealthyCount?`${e.unhealthyCount} unhealthy`:`ok`})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.observedSourceCount,`/`,e.logSourceCount,` observed · `,e.candidateCount,` `,`candidates · `,e.submittedCount,` submitted`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[`Last poll: `,ab(e.lastPollAtMs)]})]},e.projectId))}),a(`label`,{className:`grid min-w-48 gap-1`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Project filter`}),a(`select`,{className:`tcp-input`,value:P,onChange:e=>F(e.currentTarget.value),children:[a(`option`,{value:`all`,children:`All projects`}),V.map(e=>a(`option`,{value:e.projectId,children:e.project.name||e.projectId},e.projectId))]})]})]}):null,t.last_error?a(`div`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-xs text-amber-100`,children:t.last_error}):null,p?a(`div`,{className:`rounded-lg border border-sky-500/30 bg-sky-500/10 p-3`,children:[a(`div`,{className:`text-sm font-medium text-sky-100`,children:[String(p.action||`Log source action`),` completed`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[String(p.project_id||`unknown project`),` /`,` `,String(p.source_id||`unknown source`)]}),a(`pre`,{className:`tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs`,children:JSON.stringify(p,null,2)})]}):null,a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Monitored projects`}),a(`div`,{className:`grid gap-2 rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 md:grid-cols-5`,children:[a(`input`,{className:`tcp-input text-xs`,value:w,onChange:e=>T(e.currentTarget.value),placeholder:`project_id`}),a(`input`,{className:`tcp-input text-xs`,value:E,onChange:e=>D(e.currentTarget.value),placeholder:`owner/repo`}),a(`input`,{className:`tcp-input text-xs`,value:O,onChange:e=>k(e.currentTarget.value),placeholder:`/path/to/repo`}),a(`input`,{className:`tcp-input text-xs`,value:M,onChange:e=>N(e.currentTarget.value),placeholder:`logs/app.log`}),a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>{let e=w.trim()||`external-demo`,t=A.trim()||`app-log`;m(JSON.stringify([{project_id:e,name:e,enabled:!0,repo:E.trim()||`owner/repo`,workspace_root:O.trim()||`/path/to/repo`,log_sources:[{source_id:t,path:M.trim()||`logs/app.log`,format:`auto`,minimum_level:`error`,start_position:`end`,watch_interval_seconds:5}]}],null,2))},children:`Generate starter`})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Starter source id:`,` `,a(`input`,{className:`tcp-input ml-2 inline-block h-7 w-40 text-xs`,value:A,onChange:e=>j(e.currentTarget.value),placeholder:`source_id`})]}),a(`textarea`,{className:`tcp-input min-h-48 font-mono text-xs`,value:n,onChange:e=>m(e.currentTarget.value),spellCheck:!1,placeholder:`[{"project_id":"aca","repo":"owner/repo","workspace_root":"/path/to/repo","log_sources":[{"source_id":"ci","path":"logs/ci.jsonl"}]}]`}),a(`div`,{className:i?`text-xs text-amber-200`:`tcp-subtle text-xs`,children:i||`This PATCH payload is validated by the engine. Paths must stay under each workspace root.`})]}),H.length?a(`div`,{className:`grid gap-2`,children:H.map(({project:e,projectId:t})=>{let n=Array.isArray(e.log_sources)?e.log_sources:[];return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:e.name||t}),a(`div`,{className:`tcp-subtle text-xs`,children:[e.repo||`repo not set`,` ·`,` `,e.workspace_root||`workspace not set`]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:e.enabled===!1||e.paused?`warn`:`ok`,children:e.enabled===!1?`Disabled`:e.paused?`Paused`:`Enabled`}),a(X,{tone:`info`,children:[n.length,` log sources`]})]})]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`MCP: `,e.mcp_server||`global default`,` · Posting:`,` `,e.require_approval_for_new_issues?`manual approval`:e.auto_create_new_issues===!1?`draft only`:`auto-create enabled`]}),n.length?a(`div`,{className:`mt-3 grid gap-2`,children:n.map((e,n)=>{let r=String(e.source_id||`source-${n+1}`),i=sb(t,r),o=L.get(sb(t,r));return a(`div`,{className:`rounded-lg border border-slate-700/60 bg-slate-950/30 p-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`text-sm font-medium`,children:r}),a(`div`,{className:`tcp-subtle text-xs`,children:e.path||`path not set`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:e.enabled===!1||e.paused||o?.healthy===!1?`warn`:o?`ok`:`info`,children:e.enabled===!1?`Disabled`:e.paused?`Paused`:o?.healthy===!1?`Unhealthy`:o?`Healthy`:`Waiting`}),a(X,{tone:`info`,children:e.format||`auto`}),a(X,{tone:`info`,children:[e.minimum_level||`error`,`+`]})]})]}),a(`div`,{className:`tcp-subtle mt-2 grid gap-1 text-xs md:grid-cols-2`,children:[a(`div`,{children:[`Offset: `,Number(o?.offset||0).toLocaleString(),` bytes`]}),a(`div`,{children:[`File size: `,ob(o?.file_size)]}),a(`div`,{children:[`Last poll: `,ab(o?.last_poll_at_ms)]}),a(`div`,{children:[`Last candidate: `,ab(o?.last_candidate_at_ms)]}),a(`div`,{children:[`Total candidates: `,Number(o?.total_candidates||0)]}),a(`div`,{children:[`Total submitted: `,Number(o?.total_submitted||0)]})]}),o?.last_error?a(`div`,{className:`mt-2 rounded border border-amber-500/30 bg-amber-500/10 p-2 text-xs text-amber-100`,children:o.last_error}):null,a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:d===i,onClick:()=>v({project_id:t,source_id:r}),children:`Reset offset`}),a(`button`,{type:`button`,className:`tcp-btn`,disabled:f===i,onClick:()=>y({project_id:t,source_id:r}),children:`Replay latest`})]})]},`${t}-${r}`)})}):a(`div`,{className:`tcp-subtle mt-3 text-xs`,children:`No log sources configured.`})]},t)})}):e.length?a(Pr,{text:`No projects match the current filter.`}):a(Pr,{text:`No external projects configured yet. Paste a monitored_projects JSON array above and save.`}),a(`div`,{className:`grid gap-3 rounded-xl border border-slate-700/60 bg-slate-950/30 p-3`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Scoped intake keys`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Create project-limited keys for CI or external reporters. Raw keys are shown once.`})]}),a(X,{tone:s.length?`info`:`warn`,children:[s.length,` keys`]})]}),c?a(`div`,{className:`rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-3`,children:[a(`div`,{className:`text-sm font-medium text-emerald-100`,children:`New raw key`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Store this now. Tandem only keeps the hash after creation.`}),a(`pre`,{className:`tcp-code mt-2 overflow-auto whitespace-pre-wrap break-all text-xs`,children:c}),a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>navigator.clipboard?.writeText(c),children:`Copy`}),a(`button`,{type:`button`,className:`tcp-btn`,onClick:_,children:`Hide`})]})]}):null,a(`div`,{className:`grid gap-2 md:grid-cols-[1fr_1fr_auto]`,children:[a(`label`,{className:`grid gap-1`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Project`}),a(`select`,{className:`tcp-input`,value:B,onChange:e=>x(e.currentTarget.value),disabled:!ee.length,children:ee.length?ee.map(e=>a(`option`,{value:e.id,children:e.label},e.id)):a(`option`,{value:``,children:`Configure a project first`})})]}),a(`label`,{className:`grid gap-1`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Key name`}),a(`input`,{className:`tcp-input`,value:S,onChange:e=>C(e.currentTarget.value),placeholder:`ci reporter`})]}),a(`div`,{className:`flex items-end`,children:a(`button`,{type:`button`,className:`tcp-btn-primary w-full`,disabled:!B||!S.trim()||l,onClick:()=>h({project_id:B,name:S.trim()}),children:`Create key`})})]}),s.length?a(`div`,{className:`grid gap-2`,children:s.map(e=>{let t=String(e.key_id||``);return a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:e.name||t||`intake key`}),a(`div`,{className:`tcp-subtle text-xs`,children:[e.project_id||`unknown project`,` ·`,` `,(e.scopes||[`bug_monitor:report`]).join(`, `)]})]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(X,{tone:e.enabled===!1?`warn`:`ok`,children:e.enabled===!1?`Disabled`:`Enabled`}),e.enabled!==!1&&t?a(`button`,{type:`button`,className:`tcp-btn-danger`,disabled:u===t,onClick:()=>g(t),children:`Disable`}):null]})]}),a(`div`,{className:`tcp-subtle mt-2 grid gap-1 text-xs md:grid-cols-2`,children:[a(`div`,{children:[`Created: `,ab(e.created_at_ms)]}),a(`div`,{children:[`Last used: `,ab(e.last_used_at_ms)]}),a(`div`,{className:`md:col-span-2`,children:[`Hash: `,e.key_hash||`[redacted]`]})]})]},t||`${e.project_id}-${e.name}`)})}):a(Pr,{text:`No scoped intake keys yet.`})]})]})}function lb({theme:e}){let t=e?.cssVars?.[`--color-background`]||`#000000`,n=e?.cssVars?.[`--color-surface`]||`#111111`,r=e?.cssVars?.[`--color-primary`]||`#ffffff`,i=e?.cssVars?.[`--color-secondary`]||`#ffffff`;return a(`div`,{className:`flex items-center gap-2`,children:[a(`span`,{className:`tcp-theme-swatch`,style:{background:t},"aria-hidden":`true`}),a(`span`,{className:`tcp-theme-swatch`,style:{background:n},"aria-hidden":`true`}),a(`span`,{className:`tcp-theme-swatch`,style:{background:r},"aria-hidden":`true`}),a(`span`,{className:`tcp-theme-swatch`,style:{background:i},"aria-hidden":`true`})]})}function ub({themes:e,themeId:t,onChange:n}){return a(`div`,{className:`grid grid-cols-1 gap-3 md:grid-cols-2`,children:e.map(e=>{let r=e.id===t;return a(s.button,{type:`button`,layout:!0,onClick:()=>n(e.id),className:`tcp-theme-tile ${r?`active`:``}`,whileHover:{y:-2},whileTap:{scale:.985},transition:Kn.spring.gentle,children:[a(`div`,{className:`tcp-theme-tile-top`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-theme-tile-title`,children:e.name}),a(`p`,{className:`tcp-subtle mt-1 text-xs`,children:e.description})]}),a(lb,{theme:e})]}),a(`div`,{className:`tcp-theme-preview`,children:a(`div`,{className:`tcp-theme-preview-bg`,style:{background:e.cssVars[`--color-background`]||`#000`},children:a(`div`,{className:`tcp-theme-preview-card`,style:{background:e.cssVars[`--color-surface`]||`#111`,borderColor:e.cssVars[`--color-border`]||`rgba(255,255,255,0.1)`},children:[a(`div`,{className:`tcp-theme-preview-line short`,style:{background:e.cssVars[`--color-text`]||`#fff`}}),a(`div`,{className:`tcp-theme-preview-line`,style:{background:e.cssVars[`--color-text-muted`]||`#aaa`}}),a(`div`,{className:`tcp-theme-preview-pill`,style:{background:e.cssVars[`--color-primary`]||`#fff`}})]})})}),a(l,{initial:!1,children:r?a(s.span,{className:`tcp-theme-active`,initial:{opacity:0,scale:.86},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.86},transition:Kn.spring.snappy,children:[a(`i`,{"data-lucide":`badge-check`}),`Active`]}):null})]},e.id)})})}var db=`tcp.nav.visibility.v1`,fb=new Set([`dashboard`,`chat`,`workflows`,`automations`,`coding`,`files`,`bug-monitor`,`settings`]);function pb(e){let t=new Set([`planner`,`studio`,`coding`,`memory`,`files`,`marketplace`,`orchestrator`,`experiments`,`teams`]);return Object.fromEntries(Cr.map(([n])=>[n,e?fb.has(n):!t.has(n)]))}function mb(e,t){let n=pb(t);if(!e||typeof e!=`object`)return n;let r=e,i={...n};for(let[e]of Cr)typeof r[e]==`boolean`&&(i[e]=r[e]);if(t)for(let e of fb)i[e]=!0;return i}function hb(e){try{let t=localStorage.getItem(db);return t?mb(JSON.parse(t),e):pb(e)}catch{return pb(e)}}function gb(e){try{localStorage.setItem(db,JSON.stringify(e))}catch{}}function _b(e){return Cr.filter(([t])=>e[t]!==!1)}var vb=`/workspace/repos`,yb=`/workspace/aca/repos`,bb=`/workspace/tandem-data`;function xb(e){let t=String(e||``).trim().replace(/\.git$/i,``).split(/[/:]/).map(e=>e.trim()).filter(Boolean);return t[t.length-1]||``}function Sb(e){let t=xb(e);return t?`${vb}/${t}`:vb}function Cb(e){let t=String(e||``).trim();return t===vb?`Shared Coder checkouts`:t.startsWith(`${vb}/`)?`Synced repo checkout`:t===yb?`Coder compatibility mount`:t.startsWith(`${yb}/`)?`Same repo via ACA path`:t===bb?`Runtime data, not source code`:``}function wb(e,t){let n=String(e||``).trim();if(!n)return`Select the synced repo folder before enabling hosted Bug Monitor triage.`;if(n===vb)return`Select the repo folder under ${vb}, not the parent folder.`;if(n===yb)return`Select the repo folder under ${yb}, not the parent folder.`;if(n===bb||n.startsWith(`${bb}/`))return`${bb} stores runtime state. Bug Monitor needs the source checkout under ${vb}.`;let r=xb(t);return r&&(n.startsWith(`${vb}/`)||n.startsWith(`${yb}/`))&&n.split(`/`).filter(Boolean).pop()!==r?`Target repo looks like \`${r}\`, but the selected folder is \`${n}\`. Confirm this is the intended checkout.`:``}var Tb=`tandem_control_panel_pending_provider_oauth`;function Eb(){if(typeof window>`u`)return{};try{let e=window.sessionStorage.getItem(Tb)||``;if(!e)return{};let t=JSON.parse(e);return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([e,t])=>[String(e||``).trim().toLowerCase(),String(t||``).trim()]).filter(([e,t])=>!!e&&!!t))}catch{return{}}}function Db(e){if(!(typeof window>`u`))try{let t=Object.fromEntries(Object.entries(e||{}).map(([e,t])=>[String(e||``).trim().toLowerCase(),String(t||``).trim()]).filter(([e,t])=>!!e&&!!t));if(!Object.keys(t).length){window.sessionStorage.removeItem(Tb);return}window.sessionStorage.setItem(Tb,JSON.stringify(t))}catch{}}var Ob=new Set([`openai`,`openai-codex`,`openrouter`,`anthropic`,`ollama`,`groq`,`mistral`,`together`,`azure`,`bedrock`,`vertex`,`copilot`,`cohere`]),kb=`openai-codex`,Ab=[`telegram`,`discord`,`slack`];function jb(e){let t=String(e||``).trim().toLowerCase();return t.startsWith(`mcp_header::`)||t.startsWith(`channel::`)}var Mb=[{label:`File`,tools:[`read`,`glob`,`ls`,`list`,`grep`,`codesearch`,`search`]},{label:`Web`,tools:[`websearch`,`webfetch`,`webfetch_html`]},{label:`Terminal`,tools:[`bash`,`write`,`edit`,`apply_patch`]},{label:`Memory`,tools:[`memory_search`,`memory_store`,`memory_list`]},{label:`Other`,tools:[`skill`,`task`,`question`,`pack_builder`]}],Nb=`tandem.workflow_planner`,Pb=[`websearch`,`webfetch`,`webfetch_html`,`memory_search`,`memory_store`,`memory_list`];function Fb(e){try{return new URL(e)}catch{return null}}function Ib(e){return String(e||``).trim().toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``)||`mcp-server`}function Lb(e){let t=Fb(e);if(!t)return``;let n=String(t.hostname||``).toLowerCase();if(!n)return``;if(n.endsWith(`composio.dev`))return`composio`;let r=n.split(`.`).filter(Boolean);return r.length?Ib([`backend`,`api`,`mcp`,`www`].includes(r[0])&&r[1]||r[0]):``}function Rb(e){let t=Fb(e);return t?String(t.hostname||``).toLowerCase().endsWith(`composio.dev`):!1}function zb(e){let t=Fb(e);if(!t)return!1;let n=String(t.hostname||``).toLowerCase();return n===`api.githubcopilot.com`||n.endsWith(`.githubcopilot.com`)}function Bb(e){let t=Fb(e);if(!t)return!1;let n=String(t.hostname||``).toLowerCase();return n===`mcp.notion.com`||n.endsWith(`.notion.com`)}function Vb(e,t){return String(e||``).trim().toLowerCase()===`notion`||Bb(t)?`Notion uses browser OAuth. Save the server, finish the Notion sign-in in your browser, then come back and click Mark sign-in complete. Token paste is not the right flow for this MCP.`:`This MCP server uses browser OAuth. Save it, complete the authorization page that opens in your browser, then come back and finish the connection in Tandem.`}function Hb(e){return e.map(e=>({key:String(e?.key||``).trim(),value:String(e?.value||``).trim()}))}function Ub(e,t){let n={...e};for(let e of Hb(t))!e.key||!e.value||(n[e.key]=e.value);return n}function Wb({authMode:e,token:t,customHeader:n,transport:r}){let i=String(t||``).trim();if(e===`oauth`||!i||e===`none`)return{};if(e===`custom`){let e=String(n||``).trim();if(!e)throw Error(`Custom header name is required.`);return{[e]:i}}return e===`x-api-key`?{"x-api-key":i}:e===`bearer`?{Authorization:`Bearer ${i.replace(/^bearer\s+/i,``).trim()}`}:Rb(r)?{"x-api-key":i}:{Authorization:`Bearer ${i.replace(/^bearer\s+/i,``).trim()}`}}function Gb(e,t,n,r){return e===`oauth`?`OAuth handoff: Tandem will open the server authorization flow on connect.`:!String(t||``).trim()||e===`none`?`No auth header will be sent.`:e===`custom`?n?`Header preview: ${n}: <token>`:`Set a custom header name.`:e===`x-api-key`?`Header preview: x-api-key: <token>`:e===`bearer`?`Header preview: Authorization: Bearer <token>`:Rb(r)?`Auto mode: selected x-api-key for this endpoint`:`Auto mode: using Authorization Bearer token`}function Kb(e,t=``){if(!e||typeof e!=`object`)return null;let n=e,r=String(n.name||t||``).trim();if(!r)return null;let i=n.last_auth_challenge||n.lastAuthChallenge||null;return{name:r,transport:String(n.transport||``).trim(),authKind:String(n.auth_kind||n.authKind||``).trim().toLowerCase(),connected:!!n.connected,enabled:n.enabled!==!1,lastError:String(n.last_error||n.lastError||``).trim(),lastAuthChallenge:i&&typeof i==`object`?i:null,authorizationUrl:String(n.authorization_url||n.authorizationUrl||``).trim(),headers:n.headers&&typeof n.headers==`object`?n.headers:{},toolCache:Array.isArray(n.tool_cache||n.toolCache)?n.tool_cache||n.toolCache:[],allowedTools:Array.isArray(n.allowed_tools||n.allowedTools)?(n.allowed_tools||n.allowedTools).map(e=>String(e||``).trim()).filter(Boolean):null}}function qb(e,t,n){let r=String(t||``).trim().toLowerCase(),i=String(n||``).trim().replace(/\/+$/,``).toLowerCase(),a=e.servers.find(e=>{let t=String(e.transportUrl||``).trim().replace(/\/+$/,``).toLowerCase(),n=String(e.slug||``).trim().toLowerCase(),a=String(e.serverConfigName||``).trim().toLowerCase();return i&&t&&t===i||i&&t&&t.includes(i)||i&&t&&i.includes(t)||!!r&&(n===r||a===r)});return String(a?.authKind||``).trim().toLowerCase()}function Jb(e){return Array.isArray(e)?e.map(e=>Kb(e)).filter(e=>!!e).sort((e,t)=>e.name.localeCompare(t.name)):!e||typeof e!=`object`?[]:Array.isArray(e.servers)?e.servers.map(e=>Kb(e)).filter(e=>!!e).sort((e,t)=>e.name.localeCompare(t.name)):Object.entries(e).map(([e,t])=>Kb(t&&typeof t==`object`?t:{transport:String(t||``)},e)).filter(e=>!!e).sort((e,t)=>e.name.localeCompare(t.name))}function Yb(e){return(Array.isArray(e)?e:Array.isArray(e?.tools)?e.tools:[]).map(e=>typeof e==`string`?e:!e||typeof e!=`object`?``:String(e.namespaced_name||e.namespacedName||e.id||e.tool_name||e.toolName||``).trim()).filter(Boolean)}function Xb(e){let t=e&&typeof e==`object`?e:{},n=Array.isArray(t.servers)?t.servers:[];return{generatedAt:String(t.generated_at||``).trim(),count:Number.isFinite(Number(t.count))?Number(t.count):n.length,servers:n.map(e=>!e||typeof e!=`object`?null:{slug:String(e.slug||``).trim(),name:String(e.name||e.slug||``).trim(),description:String(e.description||``).trim(),transportUrl:String(e.transport_url||``).trim(),serverConfigName:String(e.server_config_name||e.slug||``).trim(),documentationUrl:String(e.documentation_url||``).trim(),directoryUrl:String(e.directory_url||``).trim(),toolCount:Number.isFinite(Number(e.tool_count))?Number(e.tool_count):0,requiresAuth:e.requires_auth!==!1,requiresSetup:!!e.requires_setup,authKind:String(e.auth_kind||e.authKind||``).trim().toLowerCase()}).filter(e=>!!e&&!!e.slug&&!!e.transportUrl).sort((e,t)=>e.name.localeCompare(t.name))}}function Zb(e,t){let n=t&&typeof t==`object`?t:{};return{botToken:``,allowedUsers:Array.isArray(n.allowed_users)?n.allowed_users.join(`, `):``,mentionOnly:n.mention_only!==!1&&e===`discord`?!0:!!n.mention_only,guildId:String(n.guild_id||``).trim(),channelId:String(n.channel_id||``).trim(),modelProviderId:String(n.model_provider_id||``).trim(),modelId:String(n.model_id||``).trim(),styleProfile:String(n.style_profile||`default`).trim()||`default`,securityProfile:String(n.security_profile||`operator`).trim()||`operator`}}function Qb(){return{enabled_tools:[],disabled_tools:[],enabled_mcp_servers:[],enabled_mcp_tools:[]}}function $b(e){return Array.from(new Set(e.map(e=>e.trim()).filter(Boolean)))}function ex(e){let t=e&&typeof e==`object`?e:{};return{enabled_tools:Array.isArray(t.enabled_tools)?$b(t.enabled_tools.map(e=>String(e))):[],disabled_tools:Array.isArray(t.disabled_tools)?$b(t.disabled_tools.map(e=>String(e))):[],enabled_mcp_servers:Array.isArray(t.enabled_mcp_servers)?$b(t.enabled_mcp_servers.map(e=>String(e))):[],enabled_mcp_tools:Array.isArray(t.enabled_mcp_tools)?$b(t.enabled_mcp_tools.map(e=>String(e))):[]}}function tx(e){let t=e&&typeof e==`object`?e:{};return(Array.isArray(t.scopes)?t.scopes:[]).map(e=>{if(!e||typeof e!=`object`)return null;let t=String(e.scope_id||e.scopeId||``).trim();return t?{scope_id:t,scope_kind:String(e.scope_kind||e.scopeKind||``).trim(),session_count:Number.isFinite(Number(e.session_count))?Number(e.session_count):Number.isFinite(Number(e.sessionCount))?Number(e.sessionCount):0,sender_count:Number.isFinite(Number(e.sender_count))?Number(e.sender_count):Number.isFinite(Number(e.senderCount))?Number(e.senderCount):0,last_seen_at_ms:Number.isFinite(Number(e.last_seen_at_ms))?Number(e.last_seen_at_ms):Number.isFinite(Number(e.lastSeenAtMs))?Number(e.lastSeenAtMs):0}:null}).filter(e=>!!e).sort((e,t)=>e.last_seen_at_ms===t.last_seen_at_ms?e.scope_id.localeCompare(t.scope_id):t.last_seen_at_ms-e.last_seen_at_ms)}function nx(e){let t=[];return e.scope_kind&&t.push(e.scope_kind),t.push(e.scope_id),e.session_count>1?t.push(`${e.session_count} sessions`):e.session_count===1&&t.push(`1 session`),t.join(` · `)}function rx(e,t){let n=e.enabled_tools.filter(e=>e!==Nb);return t===Nb?e.disabled_tools.includes(t)?!1:e.enabled_tools.includes(t):e.disabled_tools.includes(t)?!1:n.length===0||n.includes(t)}function ix(e,t,n){let r=e.disabled_tools.filter(e=>e!==t),i=e.enabled_tools.filter(e=>e!==Nb);return t===Nb?n?{...e,disabled_tools:r,enabled_tools:$b([...e.enabled_tools,t])}:{...e,disabled_tools:$b([...r,t]),enabled_tools:e.enabled_tools.filter(e=>e!==t)}:n?{...e,disabled_tools:r,enabled_tools:i.length>0?$b([...e.enabled_tools,t]):e.enabled_tools}:{...e,disabled_tools:$b([...r,t]),enabled_tools:i.length>0?e.enabled_tools.filter(e=>e!==t):e.enabled_tools}}function ax(e,t,n){let r=e.enabled_mcp_servers.filter(e=>e!==t);return{...e,enabled_mcp_servers:n?$b([...r,t]):r}}function ox(e,t,n){let r=`mcp.${Ic(t)}.`,i=e.enabled_mcp_tools.filter(e=>e.startsWith(r));return i.length?n.some(e=>e.startsWith(r))?i:i.map(e=>e.slice(r.length)).filter(Boolean):null}function sx(e,t,n,r){let i=`mcp.${Ic(t)}.`,a=e=>{let t=String(e||``).trim();return t?t.startsWith(`mcp.`)?t:`${i}${t}`:``},o=$b(n.map(a).filter(Boolean)),s=e.enabled_mcp_tools.filter(e=>!e.startsWith(i)),c=r===null?o:$b(r.map(a).filter(Boolean));return{...e,enabled_mcp_tools:$b([...s,...c])}}function cx(e,t){return e===`public_demo`?Pb.includes(t):!0}function lx(e,t,n){return cx(n,t)&&rx(e,t)}function ux(e){let t=String(e||``).split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:[`*`]}function dx(e){let t=(Array.isArray(e)?e:String(e||``).split(`,`)).map(e=>String(e||``).trim()).filter(Boolean);return t.length?Array.from(new Set(t)):[`*`]}function fx(e,t){let n=dx(e).slice().sort(),r=dx(t).slice().sort();return n.length===r.length?n.every((e,t)=>e===r[t]):!1}function px(e,t){let n=t&&typeof t==`object`?t:{},r=dx(n.allowed_users);return!!n.has_token||r.some(e=>e!==`*`)||!!n.mention_only||!!String(n.guild_id||``).trim()||!!String(n.channel_id||``).trim()||!!String(n.model_provider_id||``).trim()||!!String(n.model_id||``).trim()||String(n.style_profile||`default`).trim()!==`default`||String(n.security_profile||`operator`).trim()!==`operator`}function mx(e,t,n){let r=Zb(e,n);return!String(t.botToken||``).trim()&&fx(t.allowedUsers,r.allowedUsers)&&!!t.mentionOnly==!!r.mentionOnly&&String(t.guildId||``).trim()===String(r.guildId||``).trim()&&String(t.channelId||``).trim()===String(r.channelId||``).trim()&&String(t.modelProviderId||``).trim()===String(r.modelProviderId||``).trim()&&String(t.modelId||``).trim()===String(r.modelId||``).trim()&&String(t.styleProfile||`default`).trim()===String(r.styleProfile||`default`).trim()&&String(t.securityProfile||`operator`).trim()===String(r.securityProfile||`operator`).trim()}function hx(e,t){let n=String(e?.catalog_source||``).trim().toLowerCase();return n===`remote`&&t>0?{tone:`ok`,text:`${t} models`}:n===`config`&&t>0?{tone:`info`,text:`configured models`}:{tone:`warn`,text:`manual entry`}}function gx(e,t){return String(e?.catalog_message||``).trim()||`Default model: ${t||`none`}`}var _x={dashboard:`Command status, activity, and fast paths.`,chat:`Session-driven conversation, uploads, and live responses.`,planner:`Advanced long-horizon planning and governed handoff.`,studio:`Advanced template-first workflow builder.`,automations:`Reusable routines, approvals, and execution history.`,experiments:`Opt-in automation experiments, optimization campaigns, and team approvals.`,coding:`ACA intake, task launchers, and coding runs.`,agents:`Reusable agent roles and workflow drafts.`,orchestrator:`Task board planning, approvals, and execution.`,memory:`Searchable memory records and operational context.`,files:`Managed files plus the hosted knowledgebase upload surface.`,runs:`Live operations overview with queue state and per-run inspection.`,settings:`Provider defaults, themes, and runtime diagnostics.`};function vx({client:e,api:t,toast:n,navigate:i,currentRoute:u,providerStatus:d,identity:f,themes:g,setTheme:v,themeId:b,refreshProviderStatus:S,refreshIdentityStatus:C,navigation:w}){let T=_(),E=c(null),[D,O]=r({}),[k,A]=r(String(f?.botName||`Tandem`)),[j,M]=r(String(f?.botAvatarUrl||``)),[N,P]=r(`Control Center`),[F,I]=r(d?.needsOnboarding?`providers`:w?.acaMode?`navigation`:`install`),[L,R]=r(``),[z,ee]=r(``),[B,V]=r(`auto`),[H,te]=r(``),[U,ne]=r(``),[re,ie]=r(`10000`),[ae,W]=r(``),[oe,se]=r(``),[ce,le]=r(`autonomous AI agentic workflows`),[ue,de]=r(null),[fe,pe]=r(`multi`),[G,K]=r(``),[me,he]=r(!1),[ge,_e]=r(!1),[ve,ye]=r(!0),[be,xe]=r(!1),[Se,Ce]=r(()=>Eb()),[we,Te]=r(`custom`),[Ee,De]=r(``),[Oe,ke]=r(``),[Ae,je]=r(``),[Me,Ne]=r(!0),[Pe,Fe]=r(``),[q,J]=r({}),Ie=c({telegram:!1,discord:!1,slack:!1}),[Le,Re]=r({telegram:``,discord:``,slack:``}),[ze,Be]=r({telegram:!1,discord:!1,slack:!1}),[Ve,He]=r({}),[Ue,We]=r(!1),[Ge,Ke]=r(``),[qe,Je]=r(``),[Ye,Xe]=r(`none`),[Ze,Qe]=r(``),[$e,et]=r(``),[tt,nt]=r(``),[rt,it]=r([]),[at,ot]=r(!0),[st,ct]=r(``),[lt,ut]=r(`manual`),[dt,ft]=r(``),[pt,mt]=r(!1),[Y,ht]=r(!1),[gt,_t]=r(``),[vt,yt]=r(``),[bt,xt]=r(``),[St,Ct]=r(`auto`),[wt,Tt]=r(``),[Et,Dt]=r(``),[Ot,kt]=r(!0),[At,jt]=r(!1),[Mt,Nt]=r(!0),[Pt,Ft]=r(`[]`),[It,Lt]=r(``),[Rt,zt]=r(``),[Bt,Vt]=r(``),[Ht,Ut]=r(``),[Wt,Gt]=r(``),[Kt,qt]=r(null),[Jt,Yt]=r(``),[Xt,Zt]=r(!1),[Qt,$t]=r(0),[en,tn]=r(null),[nn,rn]=r(!1),[an,on]=r(``),[sn,cn]=r(``),ln=c(null),un=c(null),[dn,fn]=r(``);m(()=>{Db(Se)},[Se]);let pn=async()=>{let n=e?.identity;return n?.get?n.get():t(`/api/engine/config/identity`,{method:`GET`})},mn=async n=>{let r=e?.identity;return r?.patch?r.patch(n):t(`/api/engine/config/identity`,{method:`PATCH`,body:JSON.stringify(n)})},hn=y({queryKey:[`settings`,`identity`,`config`],queryFn:()=>pn().catch(()=>({identity:{}}))});m(()=>{let e=hn.data?.identity?.bot||{},t=e?.aliases||{},n=String(e?.canonicalName||e?.canonical_name||f?.botName||`Tandem`).trim(),r=String(e?.avatarUrl||e?.avatar_url||f?.botAvatarUrl||``).trim(),i=String(t?.controlPanel||t?.control_panel||``).trim();A(n||`Tandem`),M(r),P(i||`Control Center`)},[f?.botAvatarUrl,f?.botName,hn.data]),m(()=>{u===`mcp`&&I(`mcp`),u===`channels`&&I(`channels`),u===`bug-monitor`&&I(`bug_monitor`)},[u]);let gn=y({queryKey:[`settings`,`install`,`profile`],queryFn:()=>t(`/api/install/profile`,{method:`GET`}).catch(()=>null),refetchInterval:3e4}),_n=y({queryKey:[`settings`,`install`,`config`],queryFn:()=>t(`/api/control-panel/config`,{method:`GET`}).catch(()=>null)});m(()=>{let e=_n.data?.config||null;if(e)try{R(JSON.stringify(e,null,2)),ee(``)}catch{ee(`Loaded config could not be rendered as JSON.`)}},[_n.data]),m(()=>{if(u===`settings`){if(d?.needsOnboarding){I(`providers`),ye(!0);return}if(!w?.acaMode){I(`install`);return}I(gn.data?.aca_integration!==!0||gn.data?.control_panel_config_ready!==!0?`install`:`navigation`)}},[u,w?.acaMode,d?.needsOnboarding,gn.data?.aca_integration,gn.data?.control_panel_config_ready]),m(()=>{F===`providers`&&ye(!0)},[F]);let vn=y({queryKey:[`settings`,`providers`,`catalog`],enabled:F===`providers`||F===`channels`||F===`bug_monitor`,staleTime:300*1e3,queryFn:()=>e.providers.catalog().catch(()=>({all:[],connected:[]}))}),yn=y({queryKey:[`settings`,`providers`,`config`],queryFn:()=>e.providers.config().catch(()=>({default:``,providers:{}}))}),bn=y({queryKey:[`settings`,`providers`,`auth`],queryFn:()=>e.providers.authStatus().catch(()=>({providers:{}})),refetchInterval:15e3}),xn=y({queryKey:[`settings`,`system`,`health`],queryFn:()=>t(`/api/system/health`,{method:`GET`}).catch(()=>null),refetchInterval:3e4}),Sn=o(()=>ka({providerCatalog:vn.data,providerConfig:yn.data,defaultProvider:String(yn.data?.default||``).trim(),defaultModel:String(yn.data?.providers?.[String(yn.data?.default||``).trim()]?.default_model||yn.data?.providers?.[String(yn.data?.default||``).trim()]?.defaultModel||``).trim(),includeUnconfiguredProviders:!0}),[vn.data,yn.data]),Cn=o(()=>{let e=bn.data?.providers;return e&&typeof e==`object`?e:bn.data&&typeof bn.data==`object`?bn.data:{}},[bn.data]),wn=xn.data?.localEngine===!0,Tn=gn.data?.hosted_managed===!0;m(()=>{let e=String(xn.data?.workspace_root||``).trim();e&&Yt(t=>t.trim()?t:e)},[xn.data?.workspace_root]);let En=o(()=>{let e=String(yn.data?.default||``).trim();return{provider:e,model:String(yn.data?.providers?.[e]?.default_model||yn.data?.providers?.[e]?.defaultModel||``).trim()}},[yn.data]),Dn=o(()=>yn.data?.providers||{},[yn.data?.providers]),On=o(()=>Object.entries(Dn).filter(([e])=>{let t=e.trim().toLowerCase();return t&&!Ob.has(t)&&!jb(t)}).map(([e,t])=>({id:e,url:String(t?.url||``).trim(),model:String(t?.default_model||t?.defaultModel||``).trim(),isDefault:String(yn.data?.default||``).trim().toLowerCase()===e.trim().toLowerCase()})),[Dn,yn.data?.default]),kn=y({queryKey:[`settings`,`search`,`config`],queryFn:()=>t(`/api/system/search-settings`,{method:`GET`}).catch(()=>null)}),An=y({queryKey:[`settings`,`scheduler`,`config`],queryFn:()=>t(`/api/system/scheduler-settings`,{method:`GET`}).catch(()=>null)});m(()=>{let e=kn.data?.settings||null;e&&(V(String(e.backend||`auto`).trim()||`auto`),te(String(e.tandem_url||``).trim()),ne(String(e.searxng_url||``).trim()),ie(String(e.timeout_ms||1e4)))},[kn.data]),m(()=>{let e=An.data?.settings||null;e&&(pe(String(e.mode||`multi`).trim()||`multi`),K(e.max_concurrent_runs==null?``:String(e.max_concurrent_runs)))},[An.data]);let jn=y({queryKey:[`settings`,`browser`,`status`],queryFn:()=>t(`/api/engine/browser/status`,{method:`GET`}).catch(()=>null),refetchInterval:3e4}),[Mn,Nn]=r(null),Pn=x({mutationFn:()=>t(`/api/engine/browser/install`,{method:`POST`}),onSuccess:async()=>{n(`ok`,`Browser sidecar installed on the engine host.`),await jn.refetch()},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Fn=x({mutationFn:()=>t(`/api/engine/browser/smoke-test`,{method:`POST`,body:JSON.stringify({url:`https://example.com`})}),onSuccess:async e=>{Nn(e),n(`ok`,`Browser smoke test passed.`),await jn.refetch()},onError:e=>{Nn(null),n(`err`,e instanceof Error?e.message:String(e))}}),In=x({mutationFn:e=>t(`/api/engine/worktree/cleanup`,{method:`POST`,body:JSON.stringify({repo_root:e.repoRoot,dry_run:e.dryRun,remove_orphan_dirs:!0})}),onMutate:()=>{tn(null)},onSuccess:e=>{tn(e);let t=(e.cleaned_worktrees?.length||0)+(e.orphan_dirs_removed?.length||0),r=e.failures?.length||0;n(r?`warn`:e.dry_run?`info`:`ok`,e.dry_run?`Found ${e.stale_paths?.length||0} stale worktrees and ${e.orphan_dirs?.length||0} orphan directories.`:r?`Cleanup removed ${t} entries with ${r} failures.`:`Cleanup removed ${t} stale worktree entries.`)},onError:e=>{tn(null),n(`err`,e instanceof Error?e.message:String(e))}});m(()=>{if(!In.isPending){$t(0);return}let e=window.setInterval(()=>{$t(e=>e+1)},800);return()=>window.clearInterval(e)},[In.isPending]);let Ln=y({queryKey:[`settings`,`mcp`,`servers`],queryFn:()=>e.mcp.list().catch(()=>({})),refetchInterval:1e4}),Rn=y({queryKey:[`settings`,`mcp`,`tools`],queryFn:()=>e.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),zn=y({queryKey:[`settings`,`mcp`,`catalog`],queryFn:()=>t(`/api/engine/mcp/catalog`,{method:`GET`}).catch(()=>null),refetchInterval:6e4}),Bn=y({queryKey:[`settings`,`bug-monitor`,`config`],queryFn:()=>t(`/api/engine/config/bug-monitor`,{method:`GET`}).catch(()=>({bug_monitor:{}}))}),Vn=y({queryKey:[`settings`,`bug-monitor`,`status`],queryFn:()=>t(`/api/engine/bug-monitor/status`,{method:`GET`}).catch(()=>({status:{}})),refetchInterval:1e4}),Hn=y({queryKey:[`settings`,`bug-monitor`,`drafts`],queryFn:()=>t(`/api/engine/bug-monitor/drafts?limit=10`,{method:`GET`}).catch(()=>({drafts:[]})),refetchInterval:15e3}),Un=y({queryKey:[`settings`,`bug-monitor`,`incidents`],queryFn:()=>t(`/api/engine/bug-monitor/incidents?limit=10`,{method:`GET`}).catch(()=>({incidents:[]})),refetchInterval:1e4}),Wn=y({queryKey:[`settings`,`bug-monitor`,`posts`],queryFn:()=>t(`/api/engine/bug-monitor/posts?limit=10`,{method:`GET`}).catch(()=>({posts:[]})),refetchInterval:15e3}),Gn=y({queryKey:[`settings`,`bug-monitor`,`intake-keys`],queryFn:()=>t(`/api/engine/bug-monitor/intake/keys`,{method:`GET`}).catch(()=>({keys:[]})),refetchInterval:3e4}),Kn=y({queryKey:[`settings`,`bug-monitor`,`workspace-browser`,an],enabled:nn&&!!an,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(an)}`,{method:`GET`})}),qn=y({queryKey:[`settings`,`channels`,`config`],queryFn:()=>e.channels.config().catch(()=>({})),refetchInterval:15e3}),Jn=y({queryKey:[`settings`,`channels`,`status`],queryFn:()=>e.channels.status().catch(()=>({})),refetchInterval:6e3}),Yn=y({queryKey:[`settings`,`channels`,`scopes`],queryFn:async()=>{let e=await Promise.all(Ab.map(async e=>[e,tx(await t(`/api/engine/channels/${e}/scopes`,{method:`GET`}).catch(()=>({scopes:[]})))]));return Object.fromEntries(e)},refetchInterval:15e3}),Xn=y({queryKey:[`settings`,`channels`,`tool-preferences`,Le],queryFn:async()=>{let e=await Promise.all(Ab.map(async e=>{let n=String(Le[e]||``).trim();return[e,ex(await t(`/api/engine/channels/${e}/tool-preferences${n?`?scope_id=${encodeURIComponent(n)}`:``}`,{method:`GET`}).catch(()=>Qb()))]}));return Object.fromEntries(e)},refetchInterval:15e3}),Zn=x({mutationFn:async({providerId:t,modelId:n})=>e.providers.setDefaults(t,n),onSuccess:async()=>{n(`ok`,`Updated provider defaults.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Qn=()=>String(yn.data?.providers?.[kb]?.default_model||yn.data?.providers?.[kb]?.defaultModel||`gpt-5.4`).trim()||`gpt-5.4`,$n=async()=>{await e.providers.setDefaults(kb,Qn())},er=x({mutationFn:async({providerId:n,url:r,modelId:i,apiKey:a,makeDefault:o})=>{let s=n.trim().toLowerCase(),c=r.trim(),l=i.trim();if(!s)throw Error(`Custom provider ID is required.`);if(!c)throw Error(`Custom provider URL is required.`);await t(`/api/engine/config`,{method:`PATCH`,body:JSON.stringify({...o?{default_provider:s}:{},providers:{[s]:{url:c,...l?{default_model:l}:{}}}})}),a.trim()&&await e.providers.setApiKey(s,a.trim())},onSuccess:async()=>{n(`ok`,`Custom provider saved.`),je(``),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),tr=x({mutationFn:async()=>{let e=[];try{let t=JSON.parse(Pt||`[]`);if(!Array.isArray(t))throw Error(`monitored_projects must be a JSON array`);e=t,Lt(``)}catch(e){let t=e instanceof Error?e.message:`monitored_projects JSON is invalid`;throw Lt(t),Error(t)}return t(`/api/engine/config/bug-monitor`,{method:`PATCH`,body:JSON.stringify({bug_monitor:{enabled:pt,paused:Y,workspace_root:String(gt||``).trim()||null,repo:String(vt||``).trim()||null,mcp_server:String(bt||``).trim()||null,provider_preference:String(St||`auto`).trim(),model_policy:wt&&Et?{default_model:{provider_id:wt,model_id:Et}}:null,auto_create_new_issues:Ot,require_approval_for_new_issues:At,auto_comment_on_matched_open_issues:Mt,label_mode:`reporter_only`,monitored_projects:e}})})},onSuccess:async()=>{n(`ok`,`Bug Monitor settings saved.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})])},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),nr=x({mutationFn:async()=>t(`/api/engine/capabilities/bindings/refresh-builtins`,{method:`POST`}),onSuccess:async()=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]}),T.invalidateQueries({queryKey:[`settings`,`mcp`]})]),n(`ok`,`Capability bindings refreshed from built-ins.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),rr=x({mutationFn:async e=>t(`/api/engine/bug-monitor/intake/keys`,{method:`POST`,body:JSON.stringify({project_id:e.project_id,name:e.name,scopes:[`bug_monitor:report`]})}),onSuccess:async e=>{zt(String(e?.raw_key||``)),n(`ok`,`Bug Monitor intake key created.`),await T.invalidateQueries({queryKey:[`settings`,`bug-monitor`,`intake-keys`]})},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),or=x({mutationFn:async e=>(Vt(e),t(`/api/engine/bug-monitor/intake/keys/${encodeURIComponent(e)}/disable`,{method:`POST`})),onSuccess:async()=>{n(`ok`,`Bug Monitor intake key disabled.`),await T.invalidateQueries({queryKey:[`settings`,`bug-monitor`,`intake-keys`]})},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))},onSettled:()=>Vt(``)}),sr=x({mutationFn:async e=>(Ut(`${e.project_id||`project`}::${e.source_id||`source`}`),t(`/api/engine/bug-monitor/log-sources/${encodeURIComponent(e.project_id)}/${encodeURIComponent(e.source_id)}/reset-offset`,{method:`POST`})),onSuccess:async e=>{qt({action:`reset-offset`,project_id:e?.project_id,source_id:e?.source_id,offset:e?.state?.offset,path:e?.state?.path,updated_at_ms:e?.state?.updated_at_ms}),n(`ok`,`Bug Monitor log source offset reset.`),await T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))},onSettled:()=>Ut(``)}),cr=x({mutationFn:async e=>(Gt(`${e.project_id||`project`}::${e.source_id||`source`}`),t(`/api/engine/bug-monitor/log-sources/${encodeURIComponent(e.project_id)}/${encodeURIComponent(e.source_id)}/replay-latest`,{method:`POST`})),onSuccess:async e=>{qt({action:`replay-latest`,project_id:e?.project_id,source_id:e?.source_id,incident_id:e?.incident?.incident_id,occurrence_count:e?.incident?.occurrence_count,draft_id:e?.draft?.draft_id,draft_status:e?.draft?.status}),n(`ok`,`Bug Monitor latest log candidate replayed.`),await T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))},onSettled:()=>Gt(``)}),ur=x({mutationFn:async({draftId:e,decision:n})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/${n}`,{method:`POST`,body:JSON.stringify({reason:`${n}d from control panel settings`})}),onSuccess:async(e,t)=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,`Bug Monitor draft ${t.decision===`approve`?`approved`:`denied`}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),fr=x({mutationFn:async({draftId:e})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/triage-run`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,e?.deduped?`Bug Monitor triage run already exists: ${e?.run?.run_id||`unknown`}`:`Bug Monitor triage run created: ${e?.run?.run_id||`unknown`}`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),pr=x({mutationFn:async({action:e})=>t(`/api/engine/bug-monitor/${e}`,{method:`POST`}),onSuccess:async(e,t)=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,`Bug Monitor ${t.action===`pause`?`paused`:`resumed`}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),gr=x({mutationFn:async({incidentId:e})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(e)}/replay`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,e?.deduped?`Bug Monitor triage run already exists: ${e?.run?.run_id||`unknown`}`:`Bug Monitor replay queued triage: ${e?.run?.run_id||`unknown`}`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),_r=x({mutationFn:async({draftId:e})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/publish`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,e?.action===`comment_issue`?`Bug Monitor commented on issue #${e?.draft?.issue_number||`unknown`}.`:`Bug Monitor published issue #${e?.draft?.issue_number||`unknown`}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),vr=x({mutationFn:async({draftId:e})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(e)}/recheck-match`,{method:`POST`}),onSuccess:async e=>{await Promise.all([T.invalidateQueries({queryKey:[`settings`,`bug-monitor`]})]),n(`ok`,`GitHub match result: ${String(e?.action||`rechecked`).replaceAll(`_`,` `)}.`)},onError:e=>{n(`err`,e instanceof Error?e.message:String(e?.detail||e?.error||e))}}),yr=x({mutationFn:({providerId:t,apiKey:n})=>e.providers.setApiKey(t,n),onSuccess:async()=>{n(`ok`,`API key updated.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),br=x({mutationFn:({providerId:t})=>e.providers.oauthAuthorize(t),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase(),i=e?.ok!==!1,a=String(e?.error||e?.message||``).trim(),o=String(e?.session_id||e?.sessionId||``).trim(),s=String(e?.authorization_url||e?.authorizationUrl||e?.url||``).trim();if(!i||!r||!o||!s){n(`err`,a||`OAuth authorize response was incomplete.`);return}Ce(e=>({...e,[r]:o})),window.open(s,`_blank`,`noopener,noreferrer`),n(`info`,r===kb?`Browser sign-in opened for Codex. Finish the flow there, then return to Tandem.`:`Browser sign-in opened for ${r}.`),await T.invalidateQueries({queryKey:[`settings`,`providers`,`auth`]})},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Sr=x({mutationFn:({providerId:t})=>e.providers.oauthDisconnect(t),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase();Ce(e=>{if(!e[r])return e;let t={...e};return delete t[r],t}),n(`ok`,r===kb?`Codex account disconnected.`:`${r} disconnected.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),wr=x({mutationFn:({providerId:t})=>e.providers.oauthUseLocalSession(t),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase(),i=e?.ok!==!1,a=String(e?.error||e?.message||``).trim();if(!i){n(`err`,a||`Unable to import the local Codex session. Make sure Codex CLI is signed in on this machine.`);return}Ce(e=>{if(!e[r])return e;let t={...e};return delete t[r],t});let o=String(e?.email||``).trim();if(n(`ok`,r===kb?o?`Local Codex session imported: ${o}`:`Local Codex session imported.`:`${r} local session imported.`),r===kb)try{await $n(),n(`ok`,`Codex is now the default provider for Tandem runs.`)}catch(e){n(`warn`,e instanceof Error?e.message:`Codex session imported, but Tandem could not switch the default provider.`)}await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Tr=x({mutationFn:({providerId:e,authJson:n})=>t(`/api/engine/provider/${encodeURIComponent(e)}/oauth/session/import`,{method:`POST`,body:JSON.stringify({auth_json:n})}),onSuccess:async(e,t)=>{let r=String(t.providerId||``).trim().toLowerCase(),i=e?.ok!==!1,a=String(e?.error||e?.message||``).trim();if(!i){n(`err`,a||`Unable to import the Codex auth.json file. Make sure it was copied from a signed-in Codex CLI session.`);return}Fe(``),Ce(e=>{if(!e[r])return e;let t={...e};return delete t[r],t});let o=String(e?.email||``).trim();if(n(`ok`,r===kb?o?`Codex auth.json imported: ${o}`:`Codex auth.json imported.`:`${r} auth.json imported.`),r===kb)try{await $n(),n(`ok`,`Codex is now the default provider for Tandem runs.`)}catch(e){n(`warn`,e instanceof Error?e.message:`Codex auth.json imported, but Tandem could not switch the default provider.`)}await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Er=h(async(e,t)=>{if(t)try{let r=await t.text();if(fn(t.name||`auth.json`),Fe(r),!r.trim()){n(`warn`,`Selected auth.json file was empty.`);return}Tr.mutate({providerId:e,authJson:r})}catch(e){n(`err`,e instanceof Error?e.message:String(e))}finally{un.current&&(un.current.value=``)}},[Tr,n]);m(()=>{let t=Object.entries(Se).filter(([e,t])=>!!e&&!!t);if(!t.length)return;let r=!1,i=new Set,a=async()=>{let a=await Promise.all(t.map(async([t,n])=>{try{return{providerId:t,sessionId:n,payload:await e.providers.oauthStatus(t,n),error:null}}catch(e){return{providerId:t,sessionId:n,payload:null,error:e instanceof Error?e:Error(String(e))}}}));for(let e of a){if(r||i.has(e.providerId))continue;if(e.error){i.add(e.providerId),Ce(t=>{if(t[e.providerId]!==e.sessionId)return t;let n={...t};return delete n[e.providerId],n}),n(`err`,e.error.message);continue}let t=e.payload,a=String(t?.status||``).trim().toLowerCase();if(!(!a||a===`pending`)){if(i.add(e.providerId),Ce(t=>{if(t[e.providerId]!==e.sessionId)return t;let n={...t};return delete n[e.providerId],n}),a===`connected`){let r=String(t?.email||``).trim();if(n(`ok`,r?`Codex account connected: ${r}`:`Codex account connected.`),e.providerId===kb)try{await $n(),n(`ok`,`Codex is now the default provider for Tandem runs.`)}catch(e){n(`warn`,e instanceof Error?e.message:`Codex connected, but Tandem could not switch the default provider.`)}}else a===`expired`?n(`warn`,`Codex sign-in expired. Start the connection again.`):n(`err`,String(t?.error||t?.message||``).trim()||`Codex sign-in did not complete. Please try again.`);await Promise.all([T.invalidateQueries({queryKey:[`settings`,`providers`]}),S()])}}};a();let o=window.setInterval(()=>{a()},2e3);return()=>{r=!0,window.clearInterval(o)}},[e,Se,T,S,n]);let Dr=x({mutationFn:async e=>t(`/api/system/search-settings`,{method:`PATCH`,body:JSON.stringify(e)}),onSuccess:async e=>{W(``),se(``),await T.invalidateQueries({queryKey:[`settings`,`search`]}),n(`ok`,e?.restart_required?`Search settings saved. Restart tandem-engine to apply them.`:`Search settings saved.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Or=x({mutationFn:async e=>t(`/api/system/scheduler-settings`,{method:`PATCH`,body:JSON.stringify(e)}),onSuccess:async e=>{await T.invalidateQueries({queryKey:[`settings`,`scheduler`]}),n(`ok`,e?.restart_required?`Scheduler settings saved. Restart tandem-engine to apply them.`:`Scheduler settings saved.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),kr=x({mutationFn:async({query:e})=>t(`/api/system/search-settings/test`,{method:`POST`,body:JSON.stringify({query:e,limit:5})}),onSuccess:e=>{de(e),n(`ok`,`Websearch test completed.`)},onError:e=>{de(null),n(`err`,e instanceof Error?e.message:String(e))}}),Ar=x({mutationFn:async()=>{let e;try{e=JSON.parse(L)}catch(e){throw Error(e instanceof Error?`Config JSON is invalid: ${e.message}`:`Config JSON is invalid.`)}return t(`/api/control-panel/config`,{method:`PATCH`,body:JSON.stringify({config:e})})},onSuccess:async()=>{ee(``),n(`ok`,`Control panel config saved.`),await T.invalidateQueries({queryKey:[`settings`,`install`]}),await T.invalidateQueries({queryKey:[`system`,`capabilities`]})},onError:e=>{let t=e instanceof Error?e.message:String(e);ee(t),n(`err`,t)}}),jr=x({mutationFn:async()=>{let e=(hn.data?.identity?.bot||{})?.aliases||{},t=String(k||``).trim();if(!t)throw Error(`Bot name is required.`);let n=String(j||``).trim(),r=String(N||``).trim();return mn({identity:{bot:{canonical_name:t,avatar_url:n||null,aliases:{...e,control_panel:r||void 0}}}})},onSuccess:async()=>{n(`ok`,`Identity updated.`),await Promise.all([T.invalidateQueries({queryKey:[`settings`,`identity`]}),C()])},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Mr=h(async()=>Promise.all([T.invalidateQueries({queryKey:[`settings`,`channels`]}),T.invalidateQueries({queryKey:[`settings`,`channels`,`scopes`]}),T.invalidateQueries({queryKey:[`settings`,`channels`,`tool-preferences`]})]),[T]),Nr=x({mutationFn:async({channel:e,scopeId:n,payload:r})=>{let i=String(n||``).trim()?`?scope_id=${encodeURIComponent(String(n||``).trim())}`:``;return`reset`in r?t(`/api/engine/channels/${e}/tool-preferences${i}`,{method:`PUT`,body:JSON.stringify({reset:!0})}):t(`/api/engine/channels/${e}/tool-preferences${i}`,{method:`PUT`,body:JSON.stringify(r)})},onSuccess:async(e,t)=>{await T.invalidateQueries({queryKey:[`settings`,`channels`,`tool-preferences`]}),await T.invalidateQueries({queryKey:[`settings`,`channels`,`scopes`]});let r=String(t.scopeId||``).trim();n(`ok`,r?`Saved ${t.channel} scope ${r}.`:`Saved ${t.channel} channel tool scope.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Fr=x({mutationFn:async t=>{let n=q[t];if(!n)throw Error(`No draft found for ${t}.`);let r=String(n.modelProviderId||``).trim(),i=String(n.modelId||``).trim(),a={allowed_users:ux(n.allowedUsers),mention_only:!!n.mentionOnly,security_profile:String(n.securityProfile||`operator`).trim()||`operator`,model_provider_id:r||null,model_id:i||null},o=String(n.botToken||``).trim();if(o&&(a.bot_token=o),t===`telegram`&&(a.style_profile=String(n.styleProfile||`default`).trim()||`default`),t===`discord`&&(a.guild_id=String(n.guildId||``).trim()),t===`slack`){let e=String(n.channelId||``).trim();if(!e&&!qn.data?.slack?.channel_id)throw Error(`Slack channel ID is required.`);e&&(a.channel_id=e)}return e.channels.put(t,a)},onSuccess:async(e,t)=>{n(`ok`,`Saved ${t} channel settings.`),He(e=>({...e,[t]:null})),J(e=>({...e,[t]:{...e[t],botToken:``}})),await Mr()},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Ir=x({mutationFn:async t=>e.channels.delete(t),onSuccess:async(e,t)=>{n(`ok`,`Removed ${t} channel settings.`),He(e=>({...e,[t]:null})),Re(e=>({...e,[t]:``})),Ie.current[t]=!1,J(e=>({...e,[t]:Zb(t,null)})),await Mr()},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Lr=x({mutationFn:async t=>{let n=q[t],r=String(n?.botToken||``).trim(),i={};return r&&(i.bot_token=r),e.channels.verify(t,i)},onSuccess:(e,t)=>{He(n=>({...n,[t]:e})),n(`ok`,`${t} verification complete.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Rr=h(async()=>T.invalidateQueries({queryKey:[`settings`,`mcp`]}),[T]),zr=x({mutationFn:async({serverName:t,allowedTools:n})=>e.mcp.patch(t,{allowed_tools:n??void 0,clear_allowed_tools:n===null}),onSuccess:async()=>{await Rr(),n(`ok`,`MCP tool access updated.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Br=x({mutationFn:async({action:n,server:r})=>{if(!r)throw Error(`No MCP server selected.`);if(n===`connect`)return e.mcp.connect(r.name);if(n===`disconnect`)return e.mcp.disconnect(r.name);if(n===`refresh`)return e.mcp.refresh(r.name);if(n===`authenticate`)return t(`/api/engine/mcp/${encodeURIComponent(r.name)}/auth/authenticate`,{method:`POST`});if(n===`toggle-enabled`)return e.mcp.setEnabled(r.name,!r.enabled);if(n===`delete`)return t(`/api/engine/mcp/${encodeURIComponent(r.name)}`,{method:`DELETE`});throw Error(`Unknown action: ${n}`)},onSuccess:async(e,t)=>{await Rr();let r=!!e?.pendingAuth||!!e?.lastAuthChallenge||!!e?.authorizationUrl,i=e?.ok!==!1,a=String(t.server?.authKind||``).trim().toLowerCase();if(t.action===`connect`)if(r||!i&&a===`oauth`){let r=e?.lastAuthChallenge||{},i=String(r?.message||``).trim();n(`warn`,i?`OAuth authorization required for ${t.server?.name}: ${i}`:`OAuth authorization required for ${t.server?.name}.`)}else if(i)n(`ok`,`Connected ${t.server?.name}.`);else{let r=String(e?.error?.message||e?.error||``).trim();n(`err`,r?`Failed to connect ${t.server?.name}: ${r}`:`Failed to connect ${t.server?.name}.`)}if(t.action===`disconnect`&&n(`ok`,`Disconnected ${t.server?.name}.`),t.action===`refresh`)if(r||!i&&a===`oauth`){let r=e?.lastAuthChallenge||{},i=String(r?.message||``).trim();n(`warn`,i?`OAuth authorization required for ${t.server?.name}: ${i}`:`OAuth authorization required for ${t.server?.name}.`)}else if(i)n(`ok`,`Refreshed ${t.server?.name}.`);else{let r=String(e?.error?.message||e?.error||``).trim();n(`err`,r?`Failed to refresh ${t.server?.name}: ${r}`:`Failed to refresh ${t.server?.name}.`)}if(t.action===`authenticate`){let i=e?.ok!==!1,a=String(e?.error?.message||e?.error||``).trim();if(!i&&!r)n(`err`,a?`OAuth authorization check failed for ${t.server?.name}: ${a}`:`OAuth authorization check failed for ${t.server?.name}.`);else if(r){let r=e?.lastAuthChallenge||{},i=String(r?.message||``).trim();n(`warn`,i?`OAuth authorization still pending for ${t.server?.name}: ${i}`:`OAuth authorization still pending for ${t.server?.name}.`)}else n(`ok`,`Marked ${t.server?.name} as signed in.`)}t.action===`toggle-enabled`&&n(`ok`,`${t.server?.enabled?`Disabled`:`Enabled`} ${t.server?.name}.`),t.action===`delete`&&n(`ok`,`Deleted ${t.server?.name}.`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Vr=x({mutationFn:async()=>{let n=String(qe||``).trim(),r=Lb(n),i=Ib(Ge||r);if(!n)throw Error(`Transport URL is required.`);if(!Fb(n)&&!n.startsWith(`stdio:`))throw Error(`Transport must be a valid URL or stdio:* transport.`);let a=Ub(Wb({authMode:Ye,token:Ze,customHeader:$e,transport:n}),rt),o=String(tt||``).trim();zb(n)&&o&&(a[`X-MCP-Toolsets`]=o);let s={name:i,transport:n,enabled:!0,auth_kind:Ye===`oauth`?`oauth`:``};Object.keys(a).length&&(s.headers=a);let c=String(st||``).trim();if(c&&c!==i&&await t(`/api/engine/mcp/${encodeURIComponent(c)}`,{method:`DELETE`}).catch(()=>null),await e.mcp.add(s),at){let t=await e.mcp.connect(s.name),n=t?.pendingAuth===!0||!!t?.lastAuthChallenge||!!t?.authorizationUrl;if(!t?.ok&&!n&&Ye!==`oauth`)throw Error(`Added "${s.name}" but connect failed.`);return{name:s.name,connectResult:t,connectAfterAdd:!0,authKind:Ye===`oauth`?`oauth`:``}}return{name:s.name,connectAfterAdd:!1,authKind:Ye===`oauth`?`oauth`:``}},onSuccess:async e=>{await Rr(),We(!1),Ke(``),Je(``),Xe(`none`),Qe(``),et(``),nt(``),it([]),ot(!0),ct(``);let t=String(e?.name||``).trim(),r=e?.connectResult,i=String(e?.authKind||``).trim().toLowerCase(),a=!!r?.pendingAuth||!!r?.lastAuthChallenge||!!r?.authorizationUrl;if(e?.connectAfterAdd&&a){let e=r?.lastAuthChallenge||{},i=String(e?.message||``).trim();n(`warn`,i?`Saved MCP "${t}" and OAuth authorization is still required: ${i}`:`Saved MCP "${t}" and OAuth authorization is still required.`)}else e?.connectAfterAdd?i===`oauth`&&r&&r.ok!==!0?n(`warn`,`Saved MCP "${t}" as OAuth-backed. If it still needs authorization, open the auth link from the server row and refresh after signing in.`):n(`ok`,`Saved MCP "${t}" and connected it.`):n(`ok`,`Saved MCP "${t}".`)},onError:e=>n(`err`,e instanceof Error?e.message:String(e))}),Hr=e=>{if(!e)return;if(e.size>10*1024*1024){n(`err`,`Avatar image is too large (max 10 MB).`);return}let t=new FileReader;t.onload=()=>{let e=typeof t.result==`string`?t.result:``;if(!e){n(`err`,`Failed to read avatar image.`);return}M(e)},t.onerror=()=>n(`err`,`Failed to read avatar image.`),t.readAsDataURL(e)},Ur=Array.isArray(vn.data?.all)?vn.data.all:[],Wr=Array.isArray(d?.connected)?d.connected.length:0;m(()=>{let e=On.find(e=>e.isDefault)||On[0];e&&(Te(t=>t.trim()&&t.trim().toLowerCase()!==`custom`?t:e.id),De(t=>t.trim()?t:e.url),ke(t=>t.trim()?t:e.model),Ne(String(yn.data?.default||``).trim().toLowerCase()===e.id.trim().toLowerCase()))},[On,yn.data?.default]);let Gr=o(()=>Jb(Ln.data),[Ln.data]),Kr=o(()=>Yb(Rn.data),[Rn.data]),qr=o(()=>Xb(zn.data?.catalog||zn.data||null),[zn.data]),Jr=o(()=>new Set(Gr.map(e=>e.name.toLowerCase())),[Gr]);m(()=>{let e=Gr.filter(e=>{let t=String(e.authKind||``).trim().toLowerCase(),n=String(e.lastAuthChallenge?.authorization_url||e.lastAuthChallenge?.authorizationUrl||e.authorizationUrl||``).trim();return t===`oauth`&&(!!e.lastAuthChallenge||!!n)});if(!e.length)return;let n=!1,r=!1,i=async()=>{if(!(n||r)){r=!0;try{let r=await Promise.all(e.map(async e=>{try{return{payload:await t(`/api/engine/mcp/${encodeURIComponent(e.name)}/auth/authenticate`,{method:`POST`}),error:null}}catch(e){return{payload:null,error:e instanceof Error?e:Error(String(e))}}}));if(n)return;r.some(({payload:e,error:t})=>t?!1:!(e?.pendingAuth===!0||e?.lastAuthChallenge||e?.authorizationUrl))&&await T.invalidateQueries({queryKey:[`settings`,`mcp`]})}finally{r=!1}}};i();let a=window.setInterval(()=>{i()},3e3);return()=>{n=!0,window.clearInterval(a)}},[t,Gr,T]);let Zr=o(()=>{let e=String(dt||``).trim().toLowerCase();return qr.servers.filter(t=>e?t.name.toLowerCase().includes(e)||t.slug.toLowerCase().includes(e)||t.transportUrl.toLowerCase().includes(e):!0).slice(0,36)},[qr.servers,dt]),Qr=Gr.filter(e=>e.connected).length,$r=o(()=>Vn.data?.status||{},[Vn.data]),ei=o(()=>{try{let e=JSON.parse(Pt||`[]`);if(Array.isArray(e))return e}catch{}return Array.isArray($r.config?.monitored_projects)?$r.config.monitored_projects:[]},[Pt,$r.config?.monitored_projects]),ti=o(()=>$r.log_watcher||{},[$r.log_watcher]),ni=o(()=>Array.isArray(Hn.data?.drafts)&&Hn.data.drafts||[],[Hn.data]),ri=o(()=>Array.isArray(Un.data?.incidents)&&Un.data.incidents||[],[Un.data]),ii=o(()=>Array.isArray(Wn.data?.posts)&&Wn.data.posts||[],[Wn.data]),ai=o(()=>Array.isArray(Gn.data?.keys)&&Gn.data.keys||[],[Gn.data]),oi=o(()=>Gr.find(e=>e.name.toLowerCase()===String(bt||``).trim().toLowerCase())||null,[bt,Gr]),si=o(()=>Ur.find(e=>String(e?.id||``).toLowerCase()===String(wt||``).trim().toLowerCase())||null,[wt,Ur]),ci=o(()=>{let e=si&&typeof si==`object`&&si.models||{};return Object.keys(e).sort((e,t)=>e.localeCompare(t))},[si]),li=Array.isArray(jn.data?.blocking_issues)&&jn.data?.blocking_issues||[],ui=Array.isArray(jn.data?.recommendations)&&jn.data?.recommendations||[],di=Array.isArray(jn.data?.install_hints)&&jn.data?.install_hints||[],fi=Ab.filter(e=>!!Jn.data?.[e]?.connected).length,pi=Array.isArray(Kn.data?.directories)?Kn.data.directories:[],mi=String(sn||``).trim().toLowerCase(),hi=o(()=>mi?pi.filter(e=>String(e?.name||e?.path||``).trim().toLowerCase().includes(mi)):pi,[pi,mi]),gi=String(Kn.data?.parent||``).trim(),_i=String(Kn.data?.dir||an||``).trim(),vi=o(()=>Sb(vt),[vt]),yi=Cb(gt),bi=wb(gt,vt);m(()=>{let e=Bn.data?.bug_monitor&&typeof Bn.data?.bug_monitor==`object`?Bn.data.bug_monitor:{};mt(!!e.enabled),ht(!!e.paused),_t(String(e.workspace_root||``).trim()),yt(String(e.repo||``).trim()),xt(String(e.mcp_server||``).trim()),Ct(String(e.provider_preference||`auto`).trim()||`auto`),Tt(String(e.model_policy?.default_model?.provider_id||``).trim()),Dt(String(e.model_policy?.default_model?.model_id||``).trim()),kt(e.auto_create_new_issues!==!1),jt(!!e.require_approval_for_new_issues),Nt(e.auto_comment_on_matched_open_issues!==!1);let t=Array.isArray(e.monitored_projects)?e.monitored_projects:[];Ft(JSON.stringify(t,null,2)),Lt(``)},[Bn.data]),m(()=>{let e=qn.data&&typeof qn.data==`object`?qn.data:{};!qn.data||typeof qn.data!=`object`||J(t=>{let n={...t};for(let t of Ab)n[t]||(n[t]=Zb(t,e[t]),Ie.current[t]=!0);return n})},[qn.data]);let xi=(e,t)=>{let n=String(t||``).trim();n&&Zn.mutate({providerId:e,modelId:n})},Si=e=>{if(e){ut(`manual`);let t=e.headers&&typeof e.headers==`object`?e.headers:{},n=Object.keys(t),r=n.find(e=>String(e).toLowerCase()===`authorization`),i=n.find(e=>String(e).toLowerCase()===`x-api-key`),a=n.find(e=>String(e).toLowerCase()===`x-mcp-toolsets`),o=String(e.lastAuthChallenge?.authorization_url||e.lastAuthChallenge?.authorizationUrl||e.authorizationUrl||``).trim(),s=n.filter(e=>![r,i,a].filter(Boolean).map(e=>String(e).toLowerCase()).includes(String(e).toLowerCase())),c=String(e.authKind||``).trim().toLowerCase()||qb(qr,e.name,e.transport),l=o||c===`oauth`?`oauth`:`none`,u=``,d=``;o?d=``:i?(l=`x-api-key`,d=String(t[i]||``).trim()):r?(l=`bearer`,d=String(t[r]||``).replace(/^bearer\s+/i,``).trim()):s.length===1&&(l=`custom`,u=s[0],d=String(t[s[0]]||``).trim()),ct(e.name),Ke(e.name),Je(e.transport||``),ot(e.connected||!1),nt(a?String(t[a]||``).trim():zb(e.transport||``)?`default`:``),Xe(l),et(u),Qe(d);let f=new Set([r,i,a,l===`custom`?u:``].filter(Boolean).map(e=>String(e).toLowerCase()));it(n.filter(e=>!f.has(String(e).toLowerCase())).map(e=>({key:e,value:String(t[e]||``).trim()})))}else ut(`catalog`),ct(``),Ke(``),Je(``),Xe(`none`),et(``),Qe(``),nt(``),it([]),ot(!0);We(!0)},Ci=async()=>{let e=await t(`/api/engine/bug-monitor/debug`,{method:`GET`});await navigator.clipboard.writeText(JSON.stringify(e,null,2)),n(`ok`,`Bug Monitor debug payload copied.`)},wi=[`Scanning registered Git worktrees...`,`Comparing managed worktrees against live runtime records...`,`Removing stale worktrees and orphan directories...`],Ti=wi[Qt%wi.length],Ei=o(()=>{let e=[];for(let t of en?.cleaned_worktrees||[])e.push({kind:`removed`,title:t.path||`Removed worktree`,detail:t.branch&&t.branch_deleted===!1&&t.branch_delete_error?`Removed worktree, but branch cleanup failed: ${t.branch_delete_error}`:t.branch?`Removed registered worktree and branch ${t.branch}.`:`Removed registered worktree.`,tone:`ok`});for(let t of en?.active_paths||[])e.push({kind:`active`,title:t,detail:`Skipped because the current Tandem runtime still tracks it as active.`,tone:`info`});for(let t of en?.stale_paths||[])(en?.cleaned_worktrees||[]).some(e=>e.path===t.path)||e.push({kind:`stale`,title:t.path||`Stale worktree`,detail:en?.dry_run?t.branch?`Would remove managed worktree and branch ${t.branch}.`:`Would remove managed worktree.`:`Marked stale but not removed.`,tone:`warn`});for(let t of en?.orphan_dirs_removed||[])e.push({kind:`orphan_removed`,title:t.path||`Removed orphan directory`,detail:`Removed an unregistered directory left behind under .tandem/worktrees.`,tone:`ok`});if(en?.dry_run)for(let t of en?.orphan_dirs||[])e.push({kind:`stale`,title:t,detail:`Would remove orphaned directory left on disk.`,tone:`warn`});for(let t of en?.failures||[])e.push({kind:`failure`,title:t.path||t.code||`Cleanup failure`,detail:t.error||t.stderr||t.branch_delete_error||`Cleanup failed.`,tone:`err`});return e},[en]),Di=[{id:`install`,label:`Install`,icon:`clipboard-list`},{id:`navigation`,label:`Navigation`,icon:`panel-left`},{id:`providers`,label:`Providers`,icon:`cpu`},{id:`search`,label:`Web Search`,icon:`globe`},{id:`scheduler`,label:`Scheduler`,icon:`layers`},{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`},{id:`maintenance`,label:`Maintenance`,icon:`wrench`}],Oi=o(()=>Gb(Ye,Ze,$e,qe),[Ye,$e,Ze,qe]),ki=o(()=>Vb(Ge,qe),[Ge,qe]),Ai=Ye===`oauth`&&at,ji=o(()=>zb(qe),[qe]),Mi=w?.routeVisibility||{},Ni=pb(!!w?.acaMode),Pi=Cr.map(([e,t,n])=>{let r=e;return{routeId:e,label:t,icon:n,enabled:Mi[r]!==!1,pinned:!!w?.acaMode&&fb.has(r),defaultVisible:Ni[r]!==!1,description:_x[e]||`Open the ${String(t||e).toLowerCase()} section.`}}),Fi=Pi.filter(e=>e.enabled).length,Ii=Pi.filter(e=>e.defaultVisible),Li=Pi.filter(e=>!e.defaultVisible),Ri=Li.filter(e=>!e.enabled).length;return m(()=>{let e=E.current;e?Yr(e):Yr()},[F,pt,Y,gt,bt,$r.readiness?.runtime_ready,$r.runtime?.monitoring_active,$r.runtime?.paused,$r.runtime?.pending_incidents,$r.pending_drafts,ni.length,ri.length,nr.isPending,pr.isPending,ur.isPending,gr.isPending,fr.isPending,tr.isPending,Br.isPending,Dr.isPending]),a(ir,{className:`grid gap-4`,children:a(`div`,{ref:E,className:`grid gap-4`,children:[a(`div`,{className:`tcp-settings-tabs`,children:Di.map(e=>a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${F===e.id?`active`:``}`,onClick:()=>I(e.id),children:[a(`i`,{"data-lucide":e.icon}),e.label]},e.id))}),a(mr,{main:a(ar,{className:`grid gap-4`,children:[F===`navigation`?a(dr,{title:`Sidebar navigation`,subtitle:w?.acaMode?`ACA mode keeps Dashboard, Chat, Coder, and Settings visible by default.`:`Choose which sections appear in the sidebar. Advanced and experimental surfaces stay hidden until you turn them on.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:w?.acaMode?`ok`:`info`,children:w?.acaMode?`ACA compact default`:`Core-first default`}),a(X,{tone:`ghost`,children:[Fi,`/`,Pi.length,` visible`]}),a(`button`,{className:`tcp-btn`,type:`button`,onClick:()=>w?.showAllSections(),children:`Show all sections`}),a(`button`,{className:`tcp-btn-primary`,type:`button`,onClick:()=>w?.resetNavigation(),children:[`Reset `,w?.acaMode?`ACA compact`:`default`]})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Default sections`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`These sections are part of the standard control panel and start on by default.`})]}),a(X,{tone:`ok`,children:[Ii.filter(e=>e.enabled).length,`/`,Ii.length,` shown`]})]}),a(`div`,{className:`mt-3 grid gap-2`,children:Ii.map(e=>a(`button`,{type:`button`,className:`flex items-center justify-between rounded-xl border px-3 py-3 text-left transition ${e.enabled?`border-lime-500/40 bg-lime-500/10 hover:border-lime-400/70`:`border-slate-700/60 bg-slate-900/20 hover:border-slate-500/70`}`,onClick:()=>w?.setRouteVisibility(e.routeId,!e.enabled),children:[a(`div`,{className:`flex min-w-0 items-center gap-3`,children:[a(`span`,{className:`flex h-9 w-9 items-center justify-center rounded-lg border ${e.enabled?`border-lime-500/30 bg-lime-500/10 text-lime-200`:`border-slate-700/70 bg-slate-950/30 text-slate-300`}`,children:a(`i`,{"data-lucide":e.icon})}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:e.label}),a(`div`,{className:`tcp-subtle truncate text-xs`,children:e.description})]})]}),a(`div`,{className:`flex items-center gap-2`,children:[e.pinned?a(X,{tone:`ok`,children:`Pinned`}):null,a(X,{tone:e.enabled?`ok`:`ghost`,children:e.enabled?`Shown`:`Hidden`})]})]},e.routeId))})]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Advanced / experimental sections`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Only routes that ship hidden by default live here.`})]}),a(X,{tone:Ri>0?`warn`:`ok`,children:[Ri,` hidden`]})]}),a(`div`,{className:`mt-3 grid gap-2`,children:Li.map(e=>a(`button`,{type:`button`,className:`flex items-center justify-between rounded-xl border px-3 py-3 text-left transition ${e.enabled?`border-lime-500/40 bg-lime-500/10 hover:border-lime-400/70`:`border-slate-700/60 bg-slate-900/20 hover:border-slate-500/70`}`,onClick:()=>w?.setRouteVisibility(e.routeId,!e.enabled),children:[a(`div`,{className:`flex min-w-0 items-center gap-3`,children:[a(`span`,{className:`flex h-9 w-9 items-center justify-center rounded-lg border ${e.enabled?`border-lime-500/30 bg-lime-500/10 text-lime-200`:`border-slate-700/70 bg-slate-950/30 text-slate-300`}`,children:a(`i`,{"data-lucide":e.icon})}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:e.label}),a(`div`,{className:`tcp-subtle truncate text-xs`,children:e.description})]})]}),a(X,{tone:e.enabled?`ok`:`ghost`,children:e.enabled?`Shown`:`Hidden`})]},e.routeId))})]}),a(`div`,{className:`tcp-subtle text-xs`,children:`These preferences are stored in this browser only.`})]})}):null,F===`install`?a(dr,{title:`Install config`,subtitle:`Durable non-secret install preferences stored in tandem-data for Tandem startup and navigation defaults.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:String(gn.data?.control_panel_mode||``).trim().toLowerCase()===`aca`?`ok`:`info`,children:gn.data?.control_panel_mode||`auto`}),a(X,{tone:gn.data?.control_panel_config_ready?`ok`:`warn`,children:gn.data?.control_panel_config_ready?`Ready`:`Needs setup`}),a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>_n.refetch().then(()=>n(`ok`,`Install config refreshed.`)),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh`]}),a(`button`,{type:`button`,className:`tcp-btn-primary`,onClick:()=>Ar.mutate(),disabled:Ar.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save config`]})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`font-medium`,children:`Startup profile`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:gn.data?.control_panel_mode_reason||`The control panel auto-detects its startup mode and can be overridden with TANDEM_CONTROL_PANEL_MODE.`}),a(`div`,{className:`mt-3 grid gap-2 text-xs`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Mode source`}),a(`span`,{children:gn.data?.control_panel_mode_source||`detected`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Integration detected`}),a(`span`,{children:gn.data?.aca_integration?`yes`:`no`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Compact nav`}),a(`span`,{children:gn.data?.control_panel_compact_nav?`on`:`off`})]})]})]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`font-medium`,children:`Hosted management`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Detect whether this panel is running on a Tandem-managed hosted deployment so hosted-only update and notification UX can stay gated.`}),a(`div`,{className:`mt-3 grid gap-2 text-xs`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Managed hosted server`}),a(`span`,{children:gn.data?.hosted_managed?`yes`:`no`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Provider`}),a(`span`,{children:gn.data?.hosted_provider||`—`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Deployment slug`}),a(`span`,{children:gn.data?.hosted_deployment_slug||`—`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Release`}),a(`span`,{children:[gn.data?.hosted_release_version||`—`,gn.data?.hosted_release_channel?` · ${gn.data.hosted_release_channel}`:``]})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Update policy`}),a(`span`,{children:gn.data?.hosted_update_policy||`—`})]})]}),gn.data?.hosted_managed?a(`div`,{className:`mt-3 rounded-xl border border-lime-500/20 bg-lime-500/10 px-3 py-2 text-xs text-lime-200`,children:`Hosted-managed features can safely key off this signal instead of guessing from hostname or environment.`}):null]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`font-medium`,children:`Config file`}),a(`div`,{className:`tcp-subtle mt-1 break-all text-xs`,children:gn.data?.control_panel_config_path||_n.data?.path||`control-panel-config.json`}),a(`div`,{className:`mt-3 grid gap-2 text-xs`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Ready`}),a(`span`,{children:gn.data?.control_panel_config_ready?`yes`:`no`})]}),a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`span`,{className:`tcp-subtle`,children:`Missing`}),a(`span`,{children:Array.isArray(gn.data?.control_panel_config_missing)?gn.data?.control_panel_config_missing.join(`, `)||`none`:`unknown`})]})]})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-sm font-medium`,children:`Control panel config JSON`}),a(`textarea`,{className:`tcp-input min-h-[28rem] font-mono text-xs leading-5`,value:L,onInput:e=>R(e.target.value),spellCheck:!1})]}),z?a(`div`,{className:`rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-200`,children:z}):null,a(`div`,{className:`tcp-subtle text-xs`,children:"This file holds non-secret install state: repo binding, provider defaults, task source, swarm policy, GitHub MCP preferences, and navigation defaults. Secrets should stay in `.env` or token files."})]})}):null,F===`providers`?a(dr,{title:`Provider defaults`,subtitle:`Provider catalog, model selection, and API key entry.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:String(yn.data?.default||``).trim()?`ok`:`warn`,children:[`Default: `,String(yn.data?.default||`none`)]}),a(X,{tone:`info`,children:[Wr,` connected`]}),a(`button`,{className:`tcp-btn`,onClick:()=>S().then(()=>n(`ok`,`Provider status refreshed.`)),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh provider`]})]}),children:a(`div`,{className:`grid gap-3`,children:[a(`button`,{type:`button`,className:`tcp-list-item text-left`,onClick:()=>ye(e=>!e),"aria-expanded":ve,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":ve?`chevron-down`:`chevron-right`}),a(`span`,{children:ve?`Hide provider catalog`:`Show provider catalog`})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[Ur.length,` providers available for configuration. Expand to change models and API keys.`]})]}),a(X,{tone:`info`,children:[Wr,` connected`]})]})}),a(l,{initial:!1,children:ve?a(s.div,{className:`grid gap-3`,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:[a(`div`,{className:`tcp-list-item grid gap-3`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Custom OpenAI-compatible provider`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Add providers like MiniMax by ID, base URL, default model, and API key.`})]}),a(X,{tone:On.length?`ok`:`info`,children:[On.length,` configured`]})]}),a(`button`,{type:`button`,className:`tcp-list-item text-left`,onClick:()=>xe(e=>!e),"aria-expanded":be,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":be?`chevron-down`:`chevron-right`}),a(`span`,{children:be?`Hide custom provider form`:`Show custom provider form`})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:`Use this for OpenAI-compatible endpoints. Anthropic is handled by the built-in provider row below.`})]}),a(X,{tone:`info`,children:`OpenAI-compatible only`})]})}),a(l,{initial:!1,children:be?a(s.div,{className:`grid gap-3`,initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:a(`form`,{className:`grid gap-3`,onSubmit:e=>{e.preventDefault(),er.mutate({providerId:we,url:Ee,modelId:Oe,apiKey:Ae,makeDefault:Me})},children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Provider ID`}),a(`input`,{className:`tcp-input`,value:we,onInput:e=>Te(e.target.value),placeholder:`custom`})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Default model`}),a(`input`,{className:`tcp-input`,value:Oe,onInput:e=>ke(e.target.value),placeholder:`MiniMax-M2`})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Base URL`}),a(`input`,{className:`tcp-input`,value:Ee,onInput:e=>De(e.target.value),placeholder:`https://api.minimax.io/v1`})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`API key`}),a(`input`,{className:`tcp-input`,type:`password`,value:Ae,onInput:e=>je(e.target.value),placeholder:`Optional. Leave blank to keep the existing key.`})]}),a(`label`,{className:`inline-flex items-center gap-2 text-sm text-slate-200`,children:[a(`input`,{type:`checkbox`,className:`accent-slate-400`,checked:Me,onChange:e=>Ne(e.target.checked)}),`Make this the default provider`]}),a(`div`,{className:`flex flex-wrap justify-end gap-2`,children:a(`button`,{className:`tcp-btn-primary`,type:`submit`,disabled:er.isPending,children:[a(`i`,{"data-lucide":`plus`}),`Save custom provider`]})})]})}):null}),On.length?a(`div`,{className:`grid gap-2`,children:On.map(e=>a(`div`,{className:`flex flex-wrap items-start justify-between gap-2 rounded-xl border border-slate-700/60 bg-slate-900/20 px-3 py-2`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:e.id}),a(`div`,{className:`tcp-subtle break-all text-xs`,children:e.url||`No URL configured`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Model: `,e.model||`not set`]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[e.isDefault?a(X,{tone:`ok`,children:`default`}):null,a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>{Te(e.id),De(e.url),ke(e.model),Ne(e.isDefault),xe(!0),ye(!0)},children:[a(`i`,{"data-lucide":`square-pen`}),`Edit`]})]})]},e.id))}):null]}),vn.isPending?a(`div`,{className:`tcp-list-item grid gap-2`,children:[a(`div`,{className:`font-medium`,children:`Loading provider catalog`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Tandem is checking live provider models and auth state now.`})]}):Ur.length?Ur.map(e=>{let t=String(e?.id||``),n=Object.keys(e?.models||{}),r=String(yn.data?.providers?.[t]?.default_model||n[0]||``),i=String(D[t]??r).trim(),o=i.toLowerCase(),c=n.filter(e=>o?e.toLowerCase().includes(o):!0).slice(0,80),l=hx(e,n.length),u=gx(e,r),d=xr[t]||null,f=String(d?.keyUrl||``).trim(),p=Cn[t]||{},m=String(yn.data?.default||``).trim().toLowerCase(),h=t===kb&&m===kb,g=String(p?.auth_kind||p?.authKind||``).trim().toLowerCase(),_=String(p?.status||``).trim().toLowerCase(),v=String(p?.email||``).trim(),y=String(p?.display_name||p?.displayName||``).trim(),b=String(p?.managed_by||p?.managedBy||``).trim(),x=Number(p?.expires_at_ms||p?.expiresAtMs||0),S=p?.local_session_available===!0||p?.localSessionAvailable===!0,C=!!String(Se[t]||``).trim()||br.isPending&&String(br.variables?.providerId||``).trim().toLowerCase()===t,w=g===`oauth`&&p?.connected===!0&&_!==`reauth_required`,T=t===kb,E=!T||wn||Tn,k=C?{tone:`info`,text:`sign-in pending`}:w?{tone:`ok`,text:`account connected`}:_===`reauth_required`?{tone:`warn`,text:`reauth required`}:{tone:`warn`,text:`not connected`},A=Tn&&t===kb;return a(s.details,{layout:!0,className:`tcp-list-item`,children:[a(`summary`,{className:`cursor-pointer list-none`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:t}),a(`div`,{className:`tcp-subtle text-xs`,children:u})]}),a(X,{tone:l.tone,children:l.text})]})}),a(`div`,{className:`mt-3 grid gap-3`,children:[f&&!T?a(`div`,{className:`flex justify-end`,children:a(`a`,{className:`tcp-btn h-8 px-3 text-xs`,href:f,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Get API key`]})}):null,a(`form`,{className:`grid gap-2`,onSubmit:e=>{e.preventDefault(),xi(t,i)},children:[a(`div`,{className:`flex gap-2`,children:[a(`input`,{className:`tcp-input`,value:i,placeholder:`Type model id for ${t}`,onInput:e=>O(n=>({...n,[t]:e.target.value}))}),a(`button`,{className:`tcp-btn`,type:`submit`,children:[a(`i`,{"data-lucide":`badge-check`}),`Apply`]})]}),a(`div`,{className:`max-h-48 overflow-auto rounded-xl border border-slate-700/60 bg-slate-900/20 p-1`,children:c.length?c.map(e=>a(`button`,{type:`button`,className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${e===r?`bg-slate-700/40`:``}`,onClick:()=>{O(n=>({...n,[t]:e})),xi(t,e)},children:e},e)):a(`div`,{className:`tcp-subtle px-2 py-1 text-xs`,children:n.length?`No matching models.`:`No live catalog available. Type a model ID manually.`})})]}),T?a(`div`,{className:`grid gap-3 rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`font-medium`,children:String(d?.label||`Codex Account`)}),a(`div`,{className:`tcp-subtle text-xs`,children:String(d?.description||`Use your ChatGPT/Codex subscription instead of a separate API key.`)})]}),a(X,{tone:k.tone,children:k.text})]}),a(`div`,{className:`grid gap-1 text-xs tcp-subtle`,children:[A?a(`div`,{className:`rounded-xl border border-sky-700/50 bg-sky-950/20 px-3 py-2 text-sky-100`,children:[a(`div`,{className:`font-medium`,children:`Recommended for hosted servers`}),a(`div`,{className:`mt-1`,children:[`Import a Codex `,a(`code`,{children:`auth.json`}),` from a signed-in machine. Browser OAuth on provisioned servers can stall after the consent screen, so the import path is the reliable v1 flow.`]})]}):null,C?a(`div`,{children:`Pending browser sign-in is saved in this browser session, so you can refresh this page and Tandem will keep checking when you come back.`}):null,w?a(`div`,{children:y||v?`Connected as ${y||v}.`:`Connected to a Codex account.`}):null,b?a(`div`,{children:[`Managed by`,` `,b===`codex-cli`?`the local Codex CLI session`:b===`codex-upload`?`an uploaded Codex auth.json`:`Tandem`,`.`]}):null,A&&w&&b===`codex-upload`?a(`div`,{children:[`This hosted server is currently using an imported Codex session stored on the VM. Import another`,` `,a(`code`,{children:`auth.json`}),` any time to replace it.`]}):null,x>0?a(`div`,{children:[`Session status refreshes through`,` `,new Date(x).toLocaleString(),`.`]}):null,t===kb&&w&&!h?a(`div`,{children:`Tandem is connected to Codex, but new runs are still using a different default provider.`}):null,E?a(`div`,{children:A?`This Tandem-hosted server can import a Codex auth.json from a signed-in machine and keep the session on the VM.`:S?`Local Codex CLI session detected on this machine.`:`If the Codex CLI is already signed in on this machine, you can mirror that session here instead of starting a fresh browser login.`}):null,E?null:a(`div`,{children:`Codex account sign-in is only enabled when this control panel is connected to a local engine or a Tandem-hosted managed server.`})]}),A?a(`div`,{className:`grid gap-3`,children:[a(`input`,{ref:un,type:`file`,accept:`.json,application/json`,className:`hidden`,onChange:e=>{Er(t,e.target.files?.[0]||null)}}),a(`textarea`,{className:`tcp-input min-h-40 resize-y rounded-xl p-3 font-mono text-xs leading-5`,value:Pe,onChange:e=>Fe(e.target.value),placeholder:`Paste the contents of ~/.codex/auth.json here.
7376
7376
 
7377
- Tandem will store it on this server and reuse it for Codex sessions.`}),a(`div`,{className:`grid gap-1 text-xs tcp-subtle`,children:[a(`div`,{children:`You can paste the JSON directly, or choose the file from a signed-in machine.`}),Xt?a(`div`,{children:[`Loaded file: `,Xt]}):null]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:!E||!Pe.trim()||Qn.isPending||Xn.isPending,onClick:()=>Qn.mutate({providerId:t,authJson:Pe}),children:[a(`i`,{"data-lucide":`upload`}),w?`Replace hosted Codex session`:`Import pasted auth.json`]}),a(`button`,{type:`button`,className:`tcp-btn`,disabled:Qn.isPending||Xn.isPending,onClick:()=>Yt.current?.click(),children:[a(`i`,{"data-lucide":`file-up`}),`Choose auth.json file`]}),S?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!E||Yn.isPending||Zn.isPending,onClick:()=>{Ce(e=>{if(!e[t])return e;let n={...e};return delete n[t],n}),Zn.mutate({providerId:t})},children:[a(`i`,{"data-lucide":`link-2`}),`Use Local Codex Session`]}):null,t===vb&&w&&!h?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:In.isPending,onClick:()=>In.mutate({providerId:t,modelId:r||`gpt-5.4`}),children:[a(`i`,{"data-lucide":`sparkles`}),`Use for Tandem Runs`]}):null,a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!w||Xn.isPending||Qn.isPending||C,onClick:()=>Xn.mutate({providerId:t}),children:[a(`i`,{"data-lucide":`unlink`}),`Disconnect`]})]})]}):a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:!E||C||Xn.isPending,onClick:()=>Yn.mutate({providerId:t}),children:[a(`i`,{"data-lucide":`log-in`}),w?`Reconnect Codex Account`:`Connect Codex Account`]}),un&&t===vb&&S?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!E||Yn.isPending||Zn.isPending,onClick:()=>{Ce(e=>{if(!e[t])return e;let n={...e};return delete n[t],n}),Zn.mutate({providerId:t})},children:[a(`i`,{"data-lucide":`link-2`}),`Use Local Codex Session`]}):null,t===vb&&w&&!h?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:In.isPending,onClick:()=>In.mutate({providerId:t,modelId:r||`gpt-5.4`}),children:[a(`i`,{"data-lucide":`sparkles`}),`Use for Tandem Runs`]}):null,a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!w||Xn.isPending||C,onClick:()=>Xn.mutate({providerId:t}),children:[a(`i`,{"data-lucide":`unlink`}),`Disconnect`]}),C?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,onClick:()=>window.open(`https://chatgpt.com/codex`,`_blank`,`noopener,noreferrer`),children:[a(`i`,{"data-lucide":`external-link`}),`Open Codex`]}):null]})]}):a(`form`,{onSubmit:e=>{e.preventDefault();let n=e.currentTarget.elements.namedItem(`apiKey`),r=String(n?.value||``).trim();r&&(Jn.mutate({providerId:t,apiKey:r}),n.value=``)},className:`flex gap-2`,children:[a(`input`,{name:`apiKey`,className:`tcp-input`,placeholder:String(d?.placeholder||`Set ${t} API key`)}),a(`button`,{className:`tcp-btn`,type:`submit`,children:[a(`i`,{"data-lucide":`save`}),`Save`]})]})]})]},t)}):a(Pr,{text:`No provider catalog is available yet. You can still enter a model ID manually for custom providers.`})]}):null})]})}):null,F===`search`?a(dr,{title:`Web Search`,subtitle:"Configure the engine's `websearch` backend and provider keys.",actions:a(lr,{children:[a(X,{tone:hn.data?.settings?.has_brave_key?`ok`:`warn`,children:[`Brave`,` `,hn.data?.settings?.has_brave_key?`configured`:`missing`]}),a(X,{tone:hn.data?.settings?.has_exa_key?`ok`:`warn`,children:[`Exa`,` `,hn.data?.settings?.has_exa_key?`configured`:`missing`]}),a(`button`,{className:`tcp-btn`,onClick:()=>nr.mutate({query:ce.trim()}),disabled:!hn.data?.available||!ce.trim()||nr.isPending,children:[a(`i`,{"data-lucide":nr.isPending?`loader-circle`:`search`}),nr.isPending?`Testing...`:`Test search`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>er.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),brave_api_key:ae.trim()||void 0,exa_api_key:oe.trim()||void 0}),disabled:!hn.data?.available||er.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save`]})]}),children:hn.data?.available?a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4 text-sm`,children:[a(`div`,{className:`font-medium`,children:`Engine env file`}),a(`div`,{className:`tcp-subtle mt-1 break-all`,children:hn.data?.managed_env_path||`/etc/tandem/engine.env`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:hn.data?.restart_hint||`Changes apply immediately.`})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Backend`}),a(`select`,{className:`tcp-select`,value:B,onChange:e=>V(e.target.value),children:[a(`option`,{value:`auto`,children:`Auto failover`}),a(`option`,{value:`brave`,children:`Brave Search`}),a(`option`,{value:`exa`,children:`Exa`}),a(`option`,{value:`searxng`,children:`SearxNG`}),a(`option`,{value:`tandem`,children:`Tandem hosted search`}),a(`option`,{value:`none`,children:`Disable websearch`})]})]}),a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Timeout (ms)`}),a(`input`,{className:`tcp-input`,type:`number`,min:1e3,max:12e4,value:re,onInput:e=>ie(e.target.value)})]})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Tandem search URL`}),a(`input`,{className:`tcp-input`,placeholder:`https://search.tandem.ac`,value:H,onInput:e=>te(e.target.value)}),a(`span`,{className:`tcp-subtle text-xs`,children:"Only used when backend is set to `tandem` or `auto`. This is the hosted Tandem search router, not the SearXNG endpoint."})]}),a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`SearxNG URL`}),a(`input`,{className:`tcp-input`,placeholder:`http://127.0.0.1:8080`,value:U,onInput:e=>ne(e.target.value)}),a(`span`,{className:`tcp-subtle text-xs`,children:"Only used when backend is `searxng` or `auto`."})]})]}),a(`div`,{className:`grid gap-3 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Search test`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:"Runs `websearch` against the currently running engine config and renders the result as markdown below."})]}),a(X,{tone:`warn`,children:`Tests live engine config`})]}),a(`div`,{className:`grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]`,children:[a(`input`,{className:`tcp-input`,placeholder:`Try a test query like autonomous AI agentic workflows`,value:ce,onInput:e=>le(e.target.value)}),a(`button`,{className:`tcp-btn`,onClick:()=>nr.mutate({query:ce.trim()}),disabled:!hn.data?.available||!ce.trim()||nr.isPending,children:[a(`i`,{"data-lucide":nr.isPending?`loader-circle`:`play`}),nr.isPending?`Running...`:`Run test`]})]}),ue?.markdown?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[a(X,{tone:`ok`,children:[`Backend`,` `,String(ue.parsed_output?.backend||ue.metadata?.backend||`unknown`)]}),ue.parsed_output?.configured_backend?a(X,{tone:`info`,children:[`Configured`,` `,String(ue.parsed_output.configured_backend)]}):null,ue.metadata?.error?a(X,{tone:`warn`,children:String(ue.metadata.error).replaceAll(`_`,` `)}):null]}),a(`div`,{className:`tcp-markdown tcp-markdown-ai max-h-[320px] overflow-auto rounded-xl border border-slate-700/60 bg-black/20 p-3 text-sm`,dangerouslySetInnerHTML:{__html:Xr(ue.markdown||``)}})]}):null]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:`Brave Search key`}),a(X,{tone:hn.data?.settings?.has_brave_key?`ok`:`warn`,children:hn.data?.settings?.has_brave_key?`Saved`:`Missing`})]}),a(`input`,{className:`tcp-input`,type:`password`,placeholder:`Paste Brave Search key`,value:ae,onInput:e=>W(e.target.value)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>er.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),brave_api_key:ae.trim()||void 0}),disabled:!ae.trim()||er.isPending,children:`Save Brave Key`}),hn.data?.settings?.has_brave_key?a(`button`,{className:`tcp-btn`,onClick:()=>er.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),clear_brave_key:!0}),disabled:er.isPending,children:`Remove`}):null]})]}),a(`div`,{className:`grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:`Exa key`}),a(X,{tone:hn.data?.settings?.has_exa_key?`ok`:`warn`,children:hn.data?.settings?.has_exa_key?`Saved`:`Missing`})]}),a(`input`,{className:`tcp-input`,type:`password`,placeholder:`Paste Exa API key`,value:oe,onInput:e=>se(e.target.value)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>er.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),exa_api_key:oe.trim()||void 0}),disabled:!oe.trim()||er.isPending,children:`Save Exa Key`}),hn.data?.settings?.has_exa_key?a(`button`,{className:`tcp-btn`,onClick:()=>er.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),clear_exa_key:!0}),disabled:er.isPending,children:`Remove`}):null]})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:"`auto` tries the configured backends with failover. If Brave is rate-limited and Exa is configured, the engine can continue with Exa instead of returning a generic unavailable message."})]}):a(Pr,{text:hn.data?.reason||`Search settings are only editable here when the panel points at a local engine host or a Tandem-hosted managed server.`})}):null,F===`scheduler`?a(dr,{title:`Automation Scheduler`,subtitle:`Controls parallel execution of automation runs. Restart tandem-engine after changing.`,actions:a(lr,{children:a(`button`,{className:`tcp-btn-primary`,onClick:()=>tr.mutate({mode:fe,max_concurrent_runs:G?Number.parseInt(G,10):null}),disabled:!gn.data?.available||tr.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save`]})}),children:gn.data?.available?a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4 text-sm`,children:[a(`div`,{className:`font-medium`,children:`Engine env file`}),a(`div`,{className:`tcp-subtle mt-1 break-all`,children:gn.data?.managed_env_path||`/etc/tandem/engine.env`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:gn.data?.restart_hint||`Restart tandem-engine after changing scheduler mode.`})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Mode`}),a(`select`,{className:`tcp-select`,value:fe,onChange:e=>pe(e.target.value),children:[a(`option`,{value:`multi`,children:`Multi — parallel runs (recommended)`}),a(`option`,{value:`single`,children:`Single — one run at a time`})]})]}),a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Max concurrent runs`}),a(`input`,{className:`tcp-input`,type:`number`,min:1,max:32,placeholder:`8 (default)`,value:G,onInput:e=>K(e.target.value)})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:`Multi mode allows several automation runs to execute concurrently. Max concurrent runs caps parallelism. Changes require a tandem-engine restart to take effect.`})]}):a(Pr,{text:gn.data?.reason||`Scheduler settings are only editable here when the panel points at a local engine host or a Tandem-hosted managed server.`})}):null,F===`identity`?a(dr,{title:`Identity preview`,subtitle:`Live preview of how the assistant appears across the panel.`,actions:a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>C().then(()=>n(`ok`,`Identity refreshed.`)),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh identity`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>or.mutate(),disabled:or.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save`]})]}),children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{className:`inline-flex items-center gap-3`,children:[a(`span`,{className:`tcp-brand-avatar inline-grid h-12 w-12 rounded-xl`,children:a(`img`,{src:j||`/icon.png`,alt:k||`Tandem`,className:`block h-full w-full object-contain p-1`})}),a(`div`,{children:[a(`div`,{className:`font-semibold`,children:k||`Tandem`}),a(`div`,{className:`tcp-subtle text-xs`,children:N||`Control Center`})]})]}),a(lr,{children:[a(`button`,{className:`tcp-icon-btn`,title:`Upload avatar`,"aria-label":`Upload avatar`,onClick:()=>Jt.current?.click(),children:a(`i`,{"data-lucide":`pencil`})}),a(`button`,{className:`tcp-icon-btn`,title:`Clear avatar`,"aria-label":`Clear avatar`,onClick:()=>M(``),children:a(`i`,{"data-lucide":`trash-2`})})]})]})}),a(`input`,{className:`tcp-input`,value:k,onInput:e=>A(e.target.value),placeholder:`Bot name`}),a(`input`,{className:`tcp-input`,value:N,onInput:e=>P(e.target.value),placeholder:`Control panel alias`}),a(`input`,{className:`tcp-input`,value:j,onInput:e=>M(e.target.value),placeholder:`Avatar URL or data URL`}),a(`input`,{ref:Jt,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>br(e.target.files?.[0]||null)})]})}):null,F===`theme`?a(dr,{title:`Theme studio`,subtitle:`Preview tiles with richer feedback and immediate switching.`,children:a(ob,{themes:g,themeId:b,onChange:v})}):null,F===`channels`?a(dr,{title:`Channel connections`,subtitle:`Telegram, Discord, and Slack delivery setup and live listener status.`,actions:a(lr,{children:[a(X,{tone:Hr?`ok`:`warn`,children:[Hr,`/`,yb.length,` connected`]}),a(`button`,{className:`tcp-btn`,onClick:()=>void sr(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh channels`]})]}),children:a(`div`,{className:`grid gap-3`,children:yb.map(e=>{let t=Mn.data?.[e]||{},n=Nn.data?.[e]||{},r=q[e]||Bb(e,t),i=Ve[e],o=(Pn.data||{})[e]?.slice()||[],c=String(Le[e]||``).trim(),u=o.find(e=>e.scope_id===c)||null,d=u?Gb(u):c||`Channel default`,f=c?`scope`:`channel`,p=Ub(Fn.data?.[e]||Vb()),m=Tr.map(e=>`mcp.${Ic(e.name)}.`),h=new Set(p.enabled_mcp_tools.filter(e=>m.some(t=>e.startsWith(t)))),g=r.securityProfile===`public_demo`,_=nx(e,t),v=!rx(e,r,t);return a(`div`,{className:`tcp-list-item grid gap-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-semibold capitalize`,children:e}),a(`div`,{className:`tcp-subtle text-xs`,children:e===`telegram`?`Bot token, allowed users, style profile, and optional model override.`:e===`discord`?`Bot token, allowed users, mention policy, guild targeting, and optional model override.`:`Bot token, allowed users, mention policy, default channel, and optional model override.`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:n.connected?`ok`:`warn`,children:n.connected?`Connected`:n.enabled?`Configured`:`Disconnected`}),a(X,{tone:t.has_token?`info`:`warn`,children:t.has_token?`Token saved`:`No token`})]})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`input`,{className:`tcp-input`,type:`password`,placeholder:t.has_token?String(t.token_masked||`****`):`Paste ${e} bot token`,value:r.botToken,onInput:t=>J(n=>({...n,[e]:{...r,botToken:t.target.value}}))}),t.has_token&&!r.botToken?a(`div`,{className:`tcp-subtle text-xs`,children:`Token is already stored. Enter a new token only if you want to replace it.`}):null,a(`input`,{className:`tcp-input`,placeholder:`Allowed users (comma separated)`,value:r.allowedUsers,onInput:t=>J(n=>({...n,[e]:{...r,allowedUsers:t.target.value}}))})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`select`,{className:`tcp-input`,value:r.securityProfile,onInput:t=>J(n=>({...n,[e]:{...r,securityProfile:t.target.value}})),children:[a(`option`,{value:`operator`,children:`Operator`}),a(`option`,{value:`trusted_team`,children:`Trusted team`}),a(`option`,{value:`public_demo`,children:`Public demo`})]}),e===`telegram`?a(`input`,{className:`tcp-input`,placeholder:`Style profile`,value:r.styleProfile,onInput:t=>J(n=>({...n,[e]:{...r,styleProfile:t.target.value}}))}):null,e===`discord`?a(`input`,{className:`tcp-input`,placeholder:`Guild ID (optional)`,value:r.guildId,onInput:t=>J(n=>({...n,[e]:{...r,guildId:t.target.value}}))}):null,e===`slack`?a(`input`,{className:`tcp-input`,placeholder:`Default channel ID`,value:r.channelId,onInput:t=>J(n=>({...n,[e]:{...r,channelId:t.target.value}}))}):null,a(`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:[a(`input`,{type:`checkbox`,checked:r.mentionOnly,onChange:t=>J(n=>({...n,[e]:{...r,mentionOnly:t.target.checked}}))}),`Mention only`]})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-3 flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Channel model override`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Pick the provider and model this channel should use. Leave both blank to inherit Tandem's global default.`})]}),a(X,{tone:r.modelProviderId&&r.modelId?`ok`:`info`,children:r.modelProviderId&&r.modelId?`Custom model`:`Global default`})]}),a(ma,{providerLabel:`Provider`,modelLabel:`Model`,draft:{provider:r.modelProviderId,model:r.modelId},providers:cn,onChange:({provider:t,model:n})=>J(i=>({...i,[e]:{...r,modelProviderId:t,modelId:n}})),inheritLabel:`Use global default`}),a(`div`,{className:`mt-2 tcp-subtle text-xs`,children:r.modelProviderId&&r.modelId?a(`span`,{children:[`Selected model: `,a(`strong`,{children:r.modelProviderId}),` /`,` `,a(`strong`,{children:r.modelId})]}):fn.provider&&fn.model?a(`span`,{children:[`Inheriting Tandem default:`,` `,a(`strong`,{children:fn.provider}),` /`,` `,a(`strong`,{children:fn.model})]}):a(`span`,{children:`No global default model is configured yet.`})})]}),r.securityProfile===`public_demo`?a(`div`,{className:`tcp-subtle text-xs`,children:"Public demo mode blocks operator commands, file/workspace access, MCP access, shell access, and tool-scope widening. Memory stays confined to this channel's quarantined public namespace, and `/help` still advertises restricted capabilities for security."}):null,a(`div`,{className:`tcp-subtle text-xs`,children:[`Active sessions: `,Number(n.active_sessions||0),n.last_error?` · Last error: ${n.last_error}`:``]}),i?.hints?.length?a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3 text-xs`,children:[a(`div`,{className:`mb-1 font-medium`,children:`Verification hints`}),a(`div`,{className:`grid gap-1`,children:i.hints.map((t,n)=>a(`div`,{className:`tcp-subtle`,children:t},`${e}-hint-${n}`))})]}):null,a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn-primary`,disabled:ur.isPending||!v,onClick:()=>ur.mutate(e),children:[a(`i`,{"data-lucide":`save`}),`Save`]}),e===`discord`?a(`button`,{className:`tcp-btn`,disabled:pr.isPending,onClick:()=>pr.mutate(`discord`),children:[a(`i`,{"data-lucide":`shield-check`}),`Verify`]}):null,a(`button`,{className:`tcp-btn-danger`,disabled:fr.isPending||!_,onClick:()=>fr.mutate(e),children:[a(`i`,{"data-lucide":`trash-2`}),`Remove`]})]}),a(s.div,{layout:!0,className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-3 flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Channel tool scope`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Built-in tools and MCP servers available to `,e,` sessions.`]}),p.enabled_tools.some(e=>e!==Sb)?a(`div`,{className:`mt-1 text-xs text-amber-300`,children:[`Explicit built-in allowlist is active for this`,` `,f,`.`]}):null,g?a(`div`,{className:`mt-1 text-xs text-slate-400`,children:`Public demo profile can only expose web and quarantined public-memory tools here. File, shell, MCP, and operator-facing tools stay disabled even if saved in channel preferences.`}):null]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(`button`,{className:`tcp-btn`,disabled:cr.isPending,onClick:()=>cr.mutate({channel:e,scopeId:c||null,payload:{reset:!0}}),children:`Reset scope`}),a(`button`,{className:`tcp-btn`,"aria-expanded":!!ze[e],onClick:()=>Be(t=>({...t,[e]:!t[e]})),children:[a(`span`,{children:ze[e]?`Hide`:`Show`}),a(`i`,{"data-lucide":`chevron-down`,className:`h-4 w-4 transition-transform duration-200 ${ze[e]?`rotate-180`:``}`})]})]})]}),a(`div`,{className:`mb-3 grid gap-3 md:grid-cols-[minmax(0,1fr)_320px] md:items-end`,children:[a(`div`,{className:`grid gap-1`,children:[a(`div`,{className:`tcp-subtle text-xs`,children:c?`Editing ${d}. Saving here stores a scope-specific override on top of the ${e} default.`:`Editing the ${e} default. Pick a conversation scope to override one specific ${e} thread, room, or chat.`}),a(`div`,{className:`tcp-subtle text-[11px]`,children:o.length?`${o.length} known scope${o.length===1?``:`s`} discovered from channel sessions.`:`No scoped conversations discovered yet.`})]}),a(`label`,{className:`grid gap-1`,children:[a(`span`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`Conversation scope`}),a(`select`,{className:`tcp-input`,value:c,onChange:t=>Re(n=>({...n,[e]:t.target.value})),children:[a(`option`,{value:``,children:`Channel default`}),c&&!o.some(e=>e.scope_id===c)?a(`option`,{value:c,children:d}):null,o.map(e=>a(`option`,{value:e.scope_id,children:Gb(e)},e.scope_id))]})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[p.enabled_mcp_servers.length?`${p.enabled_mcp_servers.length} MCP server${p.enabled_mcp_servers.length===1?``:`s`} enabled for this ${f}.`:g?`MCP servers stay disabled in public demo mode.`:`No MCP servers enabled for this ${f}.`,p.enabled_mcp_tools.length?` ${p.enabled_mcp_tools.length} exact MCP tool${p.enabled_mcp_tools.length===1?``:`s`} also selected.`:``,` ${Zb(r.securityProfile,Sb)?Kb(p,Sb)?`Workflow drafts from chat are enabled.`:`Workflow drafts from chat are disabled.`:`Workflow drafts stay disabled in public demo mode.`}`]}),a(l,{initial:!1,children:ze[e]?a(s.div,{initial:{opacity:0,height:0,y:-6},animate:{opacity:1,height:`auto`,y:0},exit:{opacity:0,height:0,y:-6},transition:{duration:.22,ease:[.22,1,.36,1]},className:`overflow-hidden`,children:a(`div`,{className:`grid gap-3 pt-3`,children:[a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`Workflow planning`}),a(`label`,{className:`flex items-center justify-between rounded-xl border border-slate-700/60 bg-slate-950/30 px-3 py-2 text-sm`,children:[a(`div`,{className:`flex flex-col`,children:[a(`span`,{className:`font-mono text-xs`,children:`Allow workflow drafts from chat`}),a(`span`,{className:`tcp-subtle text-[11px]`,children:"Stores the `tandem.workflow_planner` pseudo-tool in this channel scope without changing the normal tool allowlist."})]}),a(`input`,{type:`checkbox`,checked:Kb(p,Sb),disabled:cr.isPending||!Zb(r.securityProfile,Sb),onChange:t=>cr.mutate({channel:e,scopeId:c||null,payload:qb(p,Sb,t.currentTarget.checked)})})]})]}),xb.map(t=>a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:t.label}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:t.tools.map(t=>{let n=Zb(r.securityProfile,t),i=Qb(p,t,r.securityProfile);return a(`label`,{className:`flex items-center justify-between rounded-xl border border-slate-700/60 bg-slate-950/30 px-3 py-2 text-sm`,children:[a(`div`,{className:`flex flex-col`,children:[a(`span`,{className:`font-mono text-xs`,children:t}),n?null:a(`span`,{className:`tcp-subtle text-[11px]`,children:`Disabled by security profile`})]}),a(`input`,{type:`checkbox`,checked:i,disabled:cr.isPending||!n,onChange:n=>cr.mutate({channel:e,scopeId:c||null,payload:qb(p,t,n.currentTarget.checked)})})]},`${e}-tool-${t}`)})})]},`${e}-${t.label}`)),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`MCP servers`}),Tr.length?a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:Tr.map(t=>{let n=!g&&p.enabled_mcp_servers.includes(t.name);return a(`label`,{className:`flex items-center justify-between rounded-xl border border-slate-700/60 bg-slate-950/30 px-3 py-2 text-sm`,children:[a(`div`,{className:`flex flex-col`,children:[a(`span`,{className:`font-mono text-xs`,children:t.name}),g?a(`span`,{className:`tcp-subtle text-[11px]`,children:`Disabled by security profile`}):null]}),a(`input`,{type:`checkbox`,checked:n,disabled:cr.isPending||g,onChange:n=>cr.mutate({channel:e,scopeId:c||null,payload:Jb(p,t.name,n.currentTarget.checked)})})]},`${e}-mcp-${t.name}`)})}):a(`div`,{className:`tcp-subtle text-xs`,children:g?`MCP servers stay disabled in public demo mode.`:`No MCP servers configured yet.`})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`Exact MCP tools`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Choose exact tool names for this `,f,`. This narrows access without changing the whole-server toggles above.`]}),Tr.length?a(`div`,{className:`grid gap-3`,children:[Tr.map(t=>{let n=Rb(Array.isArray(t.toolCache)?t.toolCache:[]),r=Yb(p,t.name,n);return a(Hc,{title:t.name,subtitle:t.connected?t.enabled?`Connected and enabled globally. Pick the exact tools this scope can use.`:`Connected, but disabled globally. Exact selections are saved here and will apply if the server is enabled.`:`This server is disconnected. Exact selections are saved here and will apply when it reconnects.`,discoveredTools:n,value:r,disabled:cr.isPending||g,collapsible:!0,defaultCollapsed:!0,emptyText:`No MCP tools have been discovered for this server yet.`,onChange:r=>cr.mutate({channel:e,scopeId:c||null,payload:Xb(p,t.name,n,r)})},`${e}-exact-mcp-${t.name}`)}),p.enabled_mcp_tools.filter(e=>!h.has(e)).length?a(Hc,{title:`Saved exact tools not currently matched`,subtitle:`These exact MCP tools are still stored for this scope, but no discovered server is currently exposing them.`,discoveredTools:[],value:p.enabled_mcp_tools.filter(e=>!h.has(e)),disabled:cr.isPending||g,emptyText:`All saved exact MCP tools currently match a discovered server.`,onChange:t=>cr.mutate({channel:e,scopeId:c||null,payload:{...p,enabled_mcp_tools:Hb([...p.enabled_mcp_tools.filter(e=>h.has(e)),...t===null?[]:t])}})}):null]}):a(`div`,{className:`tcp-subtle text-xs`,children:g?`Exact MCP tools stay disabled in public demo mode.`:`No MCP servers configured yet.`})]})]})},`${e}-tool-scope-body`):null})]})]},e)})})}):null,F===`mcp`?a(dr,{title:`MCP connections`,subtitle:`Configured MCP servers, connection state, and discovered tool coverage. Per-channel exact tool scopes live under Channels.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:Ar?`ok`:`warn`,children:[Ar,`/`,Tr.length,` connected`]}),a(X,{tone:`info`,children:[Er.length,` tools`]}),a(`button`,{className:`tcp-btn`,onClick:()=>I(`channels`),children:`Channel scopes`}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>Zr(),children:[a(`i`,{"data-lucide":`plus`}),`Add MCP server`]}),a(`button`,{className:`tcp-btn`,onClick:()=>void gr(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Reload`]})]}),children:a(`div`,{className:`grid gap-3`,children:[Tr.length?Tr.map(e=>{let t=Object.keys(e.headers||{}).filter(Boolean),n=Array.isArray(e.toolCache)?e.toolCache.length:0;return a(`div`,{className:`tcp-list-item grid gap-2`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-semibold`,children:e.name}),a(`div`,{className:`tcp-subtle text-sm`,children:e.transport||`No transport set`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:e.connected?`ok`:`warn`,children:e.connected?`Connected`:`Disconnected`}),a(X,{tone:e.enabled?`info`:`warn`,children:e.enabled?`Enabled`:`Disabled`}),String(e.authKind||``).trim().toLowerCase()===`oauth`?a(X,{tone:`info`,children:`OAuth`}):null,a(X,{tone:`info`,children:[n,` tools`]})]})]}),e.lastError?a(`div`,{className:`rounded-xl border border-rose-700/60 bg-rose-950/20 px-2 py-1 text-xs text-rose-300`,children:e.lastError}):null,e.lastAuthChallenge?a(`div`,{className:`rounded-xl border border-amber-700/60 bg-amber-950/20 px-3 py-2 text-xs text-amber-100`,children:[a(`div`,{className:`font-medium`,children:`OAuth authorization pending`}),a(`div`,{className:`tcp-subtle mt-1`,children:String(e.lastAuthChallenge.message||``).trim()||`Open the authorization URL to finish connecting this MCP server.`}),a(`div`,{className:`tcp-subtle mt-1`,children:`Tandem will keep checking for completion automatically while this page is open.`}),String(e.lastAuthChallenge.authorization_url||e.lastAuthChallenge.authorizationUrl||e.authorizationUrl||``).trim()?a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(`a`,{className:`tcp-btn inline-flex h-8 px-3 text-xs`,href:String(e.lastAuthChallenge.authorization_url||e.lastAuthChallenge.authorizationUrl||e.authorizationUrl||``).trim(),target:`_blank`,rel:`noreferrer`,children:`Open auth URL`}),a(`button`,{type:`button`,className:`tcp-btn inline-flex h-8 px-3 text-xs`,disabled:vr.isPending,onClick:()=>vr.mutate({action:`authenticate`,server:e}),children:`Mark sign-in complete`})]}):null]}):null,a(`div`,{className:`tcp-subtle text-xs`,children:t.length?`Auth headers: ${t.join(`, `)}`:`No stored auth headers.`}),a(Hc,{title:`Tool access`,subtitle:`Leave all discovered tools selected to expose the full MCP server, or uncheck tools to hide them from agents and workflows.`,discoveredTools:Array.isArray(e.toolCache)?e.toolCache:[],value:e.allowedTools,disabled:_r.isPending,onChange:t=>_r.mutate({serverName:e.name,allowedTools:t})}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>Zr(e),children:`Edit`}),a(`button`,{className:`tcp-btn`,disabled:vr.isPending,onClick:()=>vr.mutate({action:e.connected?`disconnect`:`connect`,server:e}),children:e.connected?`Disconnect`:`Connect`}),a(`button`,{className:`tcp-btn`,disabled:vr.isPending,onClick:()=>vr.mutate({action:`refresh`,server:e}),children:`Refresh`}),a(`button`,{className:`tcp-btn`,disabled:vr.isPending,onClick:()=>vr.mutate({action:`toggle-enabled`,server:e}),children:e.enabled?`Disable`:`Enable`}),a(`button`,{className:`tcp-btn-danger`,disabled:vr.isPending,onClick:()=>vr.mutate({action:`delete`,server:e}),children:`Delete`})]})]},e.name)}):a(`div`,{className:`grid gap-3`,children:[a(Pr,{text:`No MCP servers configured.`}),a(`div`,{className:`flex justify-start`,children:a(`button`,{className:`tcp-btn-primary`,onClick:()=>Zr(),children:[a(`i`,{"data-lucide":`plus`}),`Add MCP server`]})})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Discovered tools`}),a(`pre`,{className:`tcp-code max-h-56 overflow-auto whitespace-pre-wrap break-words`,children:Er.length?Er.slice(0,250).join(`
7378
- `):`No MCP tools discovered yet. Connect a server first.`})]})]})}):null,F===`bug_monitor`?a(dr,{title:`Bug monitor`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:jr.runtime?.monitoring_active?jr.readiness?.publish_ready?`ok`:`info`:jr.readiness?.ingest_ready?`info`:`warn`,children:jr.runtime?.monitoring_active?jr.readiness?.publish_ready?`Monitoring`:`Watching locally`:jr.readiness?.ingest_ready?`Ready`:`Not ready`}),Y||jr.runtime?.paused?a(X,{tone:`warn`,children:`Paused`}):null,a(X,{tone:`info`,children:[Number(jr.runtime?.pending_incidents||0),` incidents`]}),a(X,{tone:`info`,children:[Number(jr.pending_drafts||0),` pending drafts`]}),a(X,{tone:`info`,children:[Number(jr.pending_posts||0),` post attempts`]}),a(`button`,{className:`tcp-icon-btn`,title:`Reload status`,"aria-label":`Reload status`,onClick:()=>Promise.all([Dn.refetch(),On.refetch(),kn.refetch(),An.refetch()]).then(()=>n(`ok`,`Bug Monitor status refreshed.`)),children:a(`i`,{"data-lucide":`refresh-cw`})}),a(`button`,{className:`tcp-icon-btn`,title:Y||jr.runtime?.paused?`Resume monitoring`:`Pause monitoring`,"aria-label":Y||jr.runtime?.paused?`Resume monitoring`:`Pause monitoring`,disabled:Wn.isPending,onClick:()=>Wn.mutate({action:Y||jr.runtime?.paused?`resume`:`pause`}),children:a(`i`,{"data-lucide":Y||jr.runtime?.paused?`play`:`pause`})}),a(`button`,{className:`tcp-icon-btn`,title:`Refresh capability bindings`,"aria-label":`Refresh capability bindings`,disabled:Vn.isPending,onClick:()=>Vn.mutate(),children:a(`i`,{"data-lucide":`rotate-cw`})}),a(`button`,{className:`tcp-icon-btn`,title:`Copy debug payload`,"aria-label":`Copy debug payload`,onClick:()=>void Qr(),children:a(`i`,{"data-lucide":`copy`})}),a(`button`,{className:`tcp-icon-btn`,title:`Open GitHub MCP guide`,"aria-label":`Open GitHub MCP guide`,onClick:()=>_e(!0),children:a(`i`,{"data-lucide":`book-open`})})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Reporter state`}),a(`button`,{type:`button`,className:`tcp-list-item text-left ${pt?`ring-1 ring-emerald-400/40`:``}`,onClick:()=>mt(e=>!e),children:[a(`div`,{className:`font-medium`,children:pt?Y?`Paused`:`Enabled`:`Disabled`}),a(`div`,{className:`tcp-subtle text-xs`,children:pt?Y?`Monitoring is paused. Resume to process new failures.`:`Failure events can be analyzed once readiness is green.`:`No reporter work will execute.`})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Local directory`}),a(`div`,{className:`grid gap-2 md:grid-cols-[auto_1fr_auto]`,children:[a(`button`,{className:`tcp-btn`,type:`button`,onClick:()=>{Gt(String(gt||`/`).trim()||`/`),qt(``),Ut(!0)},children:[a(`i`,{"data-lucide":`folder-open`}),`Browse`]}),a(`input`,{className:`tcp-input`,readOnly:!0,value:gt,placeholder:`No local directory selected. Use Browse.`}),a(`button`,{className:`tcp-btn`,type:`button`,onClick:()=>_t(``),disabled:!gt,children:[a(`i`,{"data-lucide":`x`}),`Clear`]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:gt?`Reporter analysis root: ${gt}`:`Defaults to the engine workspace root if not set.`})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Target repo`}),a(`input`,{className:`tcp-input`,value:vt,onChange:e=>yt(e.target.value),placeholder:`owner/repo`})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`MCP server`}),a(`select`,{className:`tcp-input`,value:bt,onChange:e=>xt(e.target.value),children:[a(`option`,{value:``,children:`Select an MCP server`}),Tr.map(e=>a(`option`,{value:e.name,children:e.name},e.name))]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Provider preference`}),a(`select`,{className:`tcp-input`,value:St,onChange:e=>Ct(e.target.value),children:[a(`option`,{value:`auto`,children:`Auto`}),a(`option`,{value:`official_github`,children:`Official GitHub`}),a(`option`,{value:`composio`,children:`Composio`}),a(`option`,{value:`arcade`,children:`Arcade`})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Provider`}),a(`select`,{className:`tcp-input`,value:wt,onChange:e=>{let t=e.target.value;Tt(t),Dt(``)},children:[a(`option`,{value:``,children:`Select a provider`}),Sr.map(e=>a(`option`,{value:String(e?.id||``),children:String(e?.id||``)},String(e?.id||``)))]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Model`}),a(`input`,{className:`tcp-input`,value:Et,onChange:e=>Dt(e.target.value),list:`bug-monitor-models`,disabled:!wt,placeholder:wt?`Type or paste a model id`:`Choose a provider first`,spellCheck:!1}),a(`datalist`,{id:`bug-monitor-models`,children:Rr.map(e=>a(`option`,{value:e},e))}),a(`div`,{className:`tcp-subtle text-xs`,children:wt?Rr.length?`${Rr.length} suggested models from provider catalog`:`No provider catalog models available. Manual model ids are allowed.`:`Select a provider to load model suggestions.`})]}),a(`div`,{className:`grid gap-2 md:col-span-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`GitHub posting`}),a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`button`,{type:`button`,className:`tcp-list-item text-left ${Ot&&!At?`ring-1 ring-emerald-400/40`:``}`,onClick:()=>{kt(e=>!e),At&&Ot&&jt(!1)},children:[a(`div`,{className:`font-medium`,children:`Auto-create new issues`}),a(`div`,{className:`tcp-subtle text-xs`,children:Ot?`New drafts post to GitHub automatically.`:`New drafts stay internal until published manually.`})]}),a(`button`,{type:`button`,className:`tcp-list-item text-left ${At?`ring-1 ring-amber-400/40`:``}`,onClick:()=>{jt(e=>{let t=!e;return t&&kt(!1),t})},children:[a(`div`,{className:`font-medium`,children:`Require approval`}),a(`div`,{className:`tcp-subtle text-xs`,children:At?`New drafts wait for a manual publish click.`:`Approval gate disabled.`})]}),a(`button`,{type:`button`,className:`tcp-list-item text-left ${Mt?`ring-1 ring-sky-400/40`:``}`,onClick:()=>Nt(e=>!e),children:[a(`div`,{className:`font-medium`,children:`Auto-comment matches`}),a(`div`,{className:`tcp-subtle text-xs`,children:Mt?`Open matching GitHub issues receive new evidence comments.`:`Matching issues are detected but not updated automatically.`})]})]})]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn-primary`,disabled:Bn.isPending,title:`Save Bug Monitor settings`,"aria-label":`Save Bug Monitor settings`,onClick:()=>Bn.mutate(),children:[a(`i`,{"data-lucide":`save`}),Bn.isPending?`Saving...`:null]}),a(`button`,{className:`tcp-icon-btn`,title:`Add MCP server`,"aria-label":`Add MCP server`,onClick:()=>Zr(),children:a(`i`,{"data-lucide":`plus`})}),a(`button`,{className:`tcp-icon-btn`,title:`Open setup guide`,"aria-label":`Open setup guide`,onClick:()=>_e(!0),children:a(`i`,{"data-lucide":`external-link`})}),a(`button`,{className:`tcp-icon-btn`,title:`Refresh capability bindings`,"aria-label":`Refresh capability bindings`,disabled:Vn.isPending,onClick:()=>Vn.mutate(),children:a(`i`,{"data-lucide":`rotate-cw`})}),a(`button`,{className:`tcp-icon-btn`,title:`Copy debug payload`,"aria-label":`Copy debug payload`,onClick:()=>void Qr(),children:a(`i`,{"data-lucide":`copy`})}),Ir?a(`button`,{className:`tcp-icon-btn`,title:Ir.connected?`Refresh selected MCP`:`Connect selected MCP`,"aria-label":Ir.connected?`Refresh selected MCP`:`Connect selected MCP`,disabled:vr.isPending,onClick:()=>vr.mutate({action:Ir.connected?`refresh`:`connect`,server:Ir}),children:a(`i`,{"data-lucide":Ir.connected?`refresh-cw`:`plug-zap`})}):null]}),a(`div`,{className:`grid gap-3 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Readiness`}),a(`div`,{className:`mt-1 text-sm`,children:jr.runtime?.monitoring_active?jr.readiness?.publish_ready?`Monitoring`:`Watching locally`:jr.runtime?.paused||Y?`Paused`:jr.readiness?.ingest_ready?`Ready`:`Blocked`}),a(`div`,{className:`tcp-subtle text-xs`,children:jr.runtime?.last_runtime_error||jr.last_error||`No blocking issue reported.`}),!jr.readiness?.publish_ready&&Array.isArray(jr.missing_required_capabilities)&&jr.missing_required_capabilities.length?a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Missing: `,jr.missing_required_capabilities.join(`, `)]}):null]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Selected MCP`}),a(`div`,{className:`mt-1 text-sm`,children:Ir?.name||`None selected`}),a(`div`,{className:`tcp-subtle text-xs`,children:Ir?Ir.connected?`Connected`:`Disconnected`:`No server selected`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Bindings: `,jr.binding_source_version||`unknown version`,jr.bindings_last_merged_at_ms?` · merged ${new Date(jr.bindings_last_merged_at_ms).toLocaleString()}`:``]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Local directory:`,` `,gt||String(jr.config?.workspace_root||``).trim()||`engine workspace root`]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Last event:`,` `,String(jr.runtime?.last_incident_event_type||``).trim()||`No incidents processed yet`]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Model route`}),a(`div`,{className:`mt-1 break-all text-sm`,children:jr.selected_model?.provider_id&&jr.selected_model?.model_id?`${jr.selected_model.provider_id} / ${jr.selected_model.model_id}`:`No dedicated model selected`}),a(`div`,{className:`tcp-subtle text-xs`,children:jr.readiness?.selected_model_ready?`Available`:`Fail-closed when unavailable`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Last processed:`,` `,jr.runtime?.last_processed_at_ms?new Date(Number(jr.runtime.last_processed_at_ms)).toLocaleString():`Not processed yet`]})]})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:`Capability readiness`}),a(`div`,{className:`tcp-subtle mt-2 grid gap-1 text-xs`,children:[a(`div`,{children:[`github.list_issues:`,` `,jr.required_capabilities?.github_list_issues?`ready`:`missing`]}),a(`div`,{children:[`github.get_issue:`,` `,jr.required_capabilities?.github_get_issue?`ready`:`missing`]}),a(`div`,{children:[`github.create_issue:`,` `,jr.required_capabilities?.github_create_issue?`ready`:`missing`]}),a(`div`,{children:[`github.comment_on_issue:`,` `,jr.required_capabilities?.github_comment_on_issue?`ready`:`missing`]})]}),Array.isArray(jr.resolved_capabilities)&&jr.resolved_capabilities.length?a(`div`,{className:`tcp-subtle mt-3 grid gap-1 text-xs`,children:jr.resolved_capabilities.map((e,t)=>a(`div`,{children:[String(e.capability_id||`unknown`),`:`,` `,String(e.tool_name||`unresolved`)]},`${e.capability_id||`cap`}-${t}`))}):null,Array.isArray(jr.selected_server_binding_candidates)&&jr.selected_server_binding_candidates.length?a(`div`,{className:`tcp-subtle mt-3 grid gap-1 text-xs`,children:jr.selected_server_binding_candidates.map((e,t)=>a(`div`,{children:[String(e.capability_id||`unknown`),`:`,` `,String(e.binding_tool_name||`unknown`),e.matched?` · matched`:` · candidate`]},`${e.capability_id||`candidate`}-${t}`))}):null,Array.isArray(jr.discovered_mcp_tools)&&jr.discovered_mcp_tools.length?a(`div`,{className:`mt-3`,children:[a(`div`,{className:`tcp-subtle text-xs font-medium`,children:`Discovered MCP tools`}),a(`pre`,{className:`tcp-code mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs`,children:jr.discovered_mcp_tools.join(`
7379
- `)})]}):a(`div`,{className:`tcp-subtle mt-3 text-xs`,children:`No MCP tools were discovered for the selected server.`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:`Posting policy`}),a(`div`,{className:`tcp-subtle mt-2 grid gap-1 text-xs`,children:[a(`div`,{children:[`New issues:`,` `,At?`Manual publish`:Ot?`Auto-create`:`Internal draft only`]}),a(`div`,{children:[`Matched open issues:`,` `,Mt?`Auto-comment`:`Detect only`]}),a(`div`,{children:`Dedupe: Fingerprint marker + label`}),a(`div`,{children:`Labels: bug-monitor`}),a(`div`,{children:`Workspace write tools: Disabled`}),a(`div`,{children:`Model fallback: Fail closed`})]})]})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Recent incidents`}),Nr.length?a(`div`,{className:`grid gap-2`,children:Nr.map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:e.title||e.event_type}),a(X,{tone:e.last_error?`warn`:`info`,children:e.status})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.event_type,` · seen`,` `,Number(e.occurrence_count||0),`x`,` · `,e.updated_at_ms?new Date(e.updated_at_ms).toLocaleString():`time unavailable`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.workspace_root||`engine workspace root`}),e.last_error?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.last_error}):null,e.detail?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.detail}):null,a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-icon-btn`,title:`Replay triage for this incident`,"aria-label":`Replay triage for this incident`,disabled:Gn.isPending,onClick:()=>Gn.mutate({incidentId:e.incident_id}),children:a(`i`,{"data-lucide":`rotate-cw`})}),e.triage_run_id?a(`span`,{className:`tcp-subtle text-xs`,children:[`triage run: `,e.triage_run_id]}):null,e.draft_id?a(`span`,{className:`tcp-subtle text-xs`,children:[`draft: `,e.draft_id]}):null]})]},e.incident_id))}):a(Pr,{text:`No Bug Monitor incidents yet.`})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Recent reporter drafts`}),Mr.length?a(`div`,{className:`grid gap-2`,children:Mr.map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:e.title||e.fingerprint}),a(X,{tone:e.status===`approval_required`?`warn`:`info`,children:e.status})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.repo,` ·`,` `,e.issue_number?`issue #${e.issue_number}`:`draft only`,` `,`·`,` `,e.created_at_ms?new Date(e.created_at_ms).toLocaleString():`time unavailable`]}),e.github_status?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[`GitHub: `,e.github_status,e.matched_issue_number?` · matched #${e.matched_issue_number}${e.matched_issue_state?` (${e.matched_issue_state})`:``}`:``]}):null,e.detail?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.detail}):null,e.last_post_error?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.last_post_error}):null,e.triage_run_id?a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`triage run: `,e.triage_run_id]}):null,e.status===`approval_required`?a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn-primary`,disabled:Hn.isPending,title:`Approve draft`,"aria-label":`Approve draft`,onClick:()=>Hn.mutate({draftId:e.draft_id,decision:`approve`}),children:[a(`i`,{"data-lucide":`check`}),Hn.isPending?`Updating...`:null]}),a(`button`,{className:`tcp-icon-btn`,title:`Deny draft`,"aria-label":`Deny draft`,disabled:Hn.isPending,onClick:()=>Hn.mutate({draftId:e.draft_id,decision:`deny`}),children:a(`i`,{"data-lucide":`x`})})]}):null,e.issue_number?null:a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-icon-btn`,title:`Publish this draft to GitHub now`,"aria-label":`Publish this draft to GitHub now`,disabled:Kn.isPending,onClick:()=>Kn.mutate({draftId:e.draft_id}),children:a(`i`,{"data-lucide":`bug-play`})}),a(`button`,{className:`tcp-icon-btn`,title:`Recheck GitHub for an existing matching issue`,"aria-label":`Recheck GitHub for an existing matching issue`,disabled:qn.isPending,onClick:()=>qn.mutate({draftId:e.draft_id}),children:a(`i`,{"data-lucide":`refresh-cw`})})]}),(e.github_issue_url||e.github_comment_url)&&a(`div`,{className:`mt-3 flex flex-wrap gap-2 text-xs`,children:[e.github_issue_url?a(`a`,{className:`tcp-btn`,href:e.github_issue_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Open issue`]}):null,e.github_comment_url?a(`a`,{className:`tcp-btn`,href:e.github_comment_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`message-square`}),`Open comment`]}):null]}),(e.status===`draft_ready`||e.status===`triage_queued`)&&!e.triage_run_id?a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:a(`button`,{className:`tcp-icon-btn`,title:`Create triage run`,"aria-label":`Create triage run`,disabled:Un.isPending,onClick:()=>Un.mutate({draftId:e.draft_id}),children:a(`i`,{"data-lucide":`sparkles`})})}):null]},e.draft_id))}):a(Pr,{text:`No Bug Monitor drafts yet.`})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Recent GitHub posts`}),Fr.length?a(`div`,{className:`grid gap-2`,children:Fr.map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:e.operation}),a(X,{tone:e.status===`posted`?`ok`:`warn`,children:e.status})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.repo,e.issue_number?` · issue #${e.issue_number}`:``,e.updated_at_ms?` · ${new Date(e.updated_at_ms).toLocaleString()}`:``]}),e.error?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.error}):null,a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[e.issue_url?a(`a`,{className:`tcp-btn`,href:e.issue_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Open issue`]}):null,e.comment_url?a(`a`,{className:`tcp-btn`,href:e.comment_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`message-square`}),`Open comment`]}):null]})]},e.post_id))}):a(Pr,{text:`No GitHub post attempts yet.`})]})]})}):null,F===`maintenance`?a(dr,{title:`Managed worktree cleanup`,subtitle:`Scan repo-local .tandem/worktrees entries, keep live runtime worktrees, and remove stale or orphaned leftovers.`,actions:a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>{Vt(null),sn.refetch()},children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh root`]}),a(`button`,{className:`tcp-btn`,onClick:()=>Sn.mutate({repoRoot:Pt.trim(),dryRun:!0}),disabled:Sn.isPending||!Pt.trim(),children:[a(`i`,{"data-lucide":`search`}),`Preview stale worktrees`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>Sn.mutate({repoRoot:Pt.trim(),dryRun:It}),disabled:Sn.isPending||!Pt.trim(),children:[a(`i`,{"data-lucide":`trash-2`}),Sn.isPending?`Cleaning up...`:It?`Run preview`:`Clean stale worktrees`]})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-sm font-medium`,children:`Repository root`}),a(`input`,{className:`tcp-input`,value:Pt,onInput:e=>Ft(e.target.value),placeholder:`/absolute/path/to/repo`})]}),a(`label`,{className:`flex items-center gap-3 text-sm`,children:[a(`input`,{type:`checkbox`,checked:It,onChange:e=>Lt(e.target.checked)}),`Use dry run when clicking the primary action`]}),a(`div`,{className:`grid gap-3 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Detected workspace root`}),a(`div`,{className:`mt-1 break-all text-xs`,children:String(sn.data?.workspace_root||`Unavailable`)})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Cleanup target`}),a(`div`,{className:`mt-1 break-all text-xs`,children:Bt?.managed_root||`${Pt||`repo`}/.tandem/worktrees`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Host mode`}),a(`div`,{className:`mt-1 text-xs`,children:[un?`Local engine`:`Remote engine`,` ·`,` `,dn?`hosted-managed`:`self-managed`]})]})]}),Sn.isPending?a(s.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},className:`rounded-2xl border border-cyan-500/30 bg-cyan-500/10 px-4 py-3`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`text-sm font-medium`,children:`Cleanup running`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:ei})]}),a(s.div,{className:`h-2 w-24 overflow-hidden rounded-full bg-slate-800`,initial:!1,children:a(s.div,{className:`h-full rounded-full bg-cyan-400`,animate:{x:[`-100%`,`120%`]},transition:{duration:1.2,repeat:1/0,ease:`easeInOut`}})})]})}):null,Bt?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`grid gap-3 md:grid-cols-4`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Tracked active`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:Bt.active_paths?.length||0})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Stale candidates`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:Bt.stale_paths?.length||0})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Removed`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:(Bt.cleaned_worktrees?.length||0)+(Bt.orphan_dirs_removed?.length||0)})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Failures`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:Bt.failures?.length||0})]})]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:Bt.dry_run?`Preview results`:`Cleanup log`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:Bt.repo_root||Pt})]}),a(X,{tone:(Bt.failures?.length||0)>0?`warn`:Bt.dry_run?`info`:`ok`,children:Bt.dry_run?`Dry run`:`Applied`})]}),a(`div`,{className:`mt-3 grid gap-2`,children:[a(l,{initial:!1,children:ti.map((e,t)=>a(s.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.18,delay:t*.03},className:`tcp-list-item`,children:a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-sm font-medium break-all`,children:e.title}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.detail})]}),a(X,{tone:e.tone,children:e.kind===`orphan_removed`?`orphan`:e.kind.replaceAll(`_`,` `)})]})},`${e.kind}-${e.title}-${t}`))}),ti.length?null:a(`div`,{className:`tcp-subtle text-xs`,children:`No stale managed worktrees were detected for this repository.`})]})]})]}):null,a(`div`,{className:`tcp-subtle text-xs`,children:[`This action only targets repo-local managed worktrees under`,` `,a(`code`,{children:`.tandem/worktrees`}),` and skips paths that the current Tandem process still tracks as active.`]})]})}):null,F===`browser`?a(dr,{title:`Browser readiness`,subtitle:`Operational browser status, diagnostics, and recovery actions.`,actions:a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>void _n.refetch(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh browser status`]}),a(`button`,{className:`tcp-btn`,onClick:()=>bn.mutate(),disabled:bn.isPending,children:[a(`i`,{"data-lucide":`download`}),bn.isPending?`Installing sidecar...`:`Install sidecar`]}),a(`button`,{className:`tcp-btn`,onClick:()=>xn.mutate(),disabled:xn.isPending,children:[a(`i`,{"data-lucide":`globe`}),xn.isPending?`Running smoke test...`:`Run smoke test`]}),a(`button`,{className:`tcp-btn`,onClick:()=>he(!0),children:[a(`i`,{"data-lucide":`activity`}),`Diagnostics`]})]}),children:[a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Status`}),a(`div`,{className:`mt-1 text-sm`,children:_n.data?_n.data.runnable?`Ready`:_n.data.enabled?`Blocked`:`Disabled`:`Unknown`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Headless default: `,_n.data?.headless_default?`yes`:`no`]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Sidecar`}),a(`div`,{className:`mt-1 break-all text-sm`,children:_n.data?.sidecar?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:_n.data?.sidecar?.version||`No version detected`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Browser`}),a(`div`,{className:`mt-1 break-all text-sm`,children:_n.data?.browser?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:_n.data?.browser?.version||_n.data?.browser?.channel||`No version detected`})]})]}),zr.length?a(`div`,{className:`mt-3 grid gap-2`,children:zr.map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:e.code||`browser_issue`}),a(`div`,{className:`tcp-subtle text-xs`,children:e.message||`Unknown browser issue.`})]},`${e.code||`issue`}-${t}`))}):null,vn?a(`div`,{className:`mt-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm`,children:[a(`div`,{className:`font-medium`,children:[`Smoke test passed`,vn.title?`: ${vn.title}`:``]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:vn.final_url||vn.url||`No URL returned`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Load state: `,vn.load_state||`unknown`,` · elements:`,` `,String(vn.element_count??0),` · closed:`,` `,vn.closed?`yes`:`no`]}),vn.excerpt?a(`pre`,{className:`tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words`,children:vn.excerpt}):null]}):null]}):null]})}),a(hr,{open:ge,onClose:()=>_e(!1),title:`Official GitHub MCP guide`,children:a(`div`,{className:`grid gap-3`,children:[a(`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.`}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Transport URL`}),a(`div`,{className:`mt-1 break-all text-sm`,children:`https://api.githubcopilot.com/mcp/`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Use this as the MCP server transport in Tandem Settings.`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Auth mode`}),a(`div`,{className:`mt-1 text-sm`,children:`Authorization Bearer`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Paste a GitHub token in the MCP server dialog and use bearer auth.`})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Recommended setup`}),a(`div`,{className:`tcp-list-item text-sm`,children:["1. Open `Add MCP server`.",a(`br`,{}),"2. Name it `github` or another stable name.",a(`br`,{}),"3. Set transport to `https://api.githubcopilot.com/mcp/`.",a(`br`,{}),"4. Set auth mode to `Authorization Bearer`.",a(`br`,{}),`5. Paste a GitHub Personal Access Token.`,a(`br`,{}),`6. Save, connect, then select that MCP server in Bug Monitor settings.`]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Token guidance`}),a(`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.`})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Direct links`}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`a`,{className:`tcp-btn`,href:`https://github.com/github/github-mcp-server?tab=readme-ov-file`,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`GitHub MCP README`]}),a(`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:[a(`i`,{"data-lucide":`external-link`}),`GitHub Docs`]})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Issue tools to expect`}),a(`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.`})]})]})}),a(l,{children:Ht?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-confirm-backdrop`,"aria-label":`Close Bug Monitor workspace dialog`,onClick:()=>{Ut(!1),qt(``)}}),a(s.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:[a(`h3`,{className:`tcp-confirm-title`,children:`Select Bug Monitor Directory`}),a(`p`,{className:`tcp-confirm-message`,children:[`Current: `,qr||`n/a`]}),a(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>{Kr&&Gt(Kr)},disabled:!Kr,children:[a(`i`,{"data-lucide":`arrow-up-circle`}),`Up`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>{qr&&(_t(qr),Ut(!1),qt(``),n(`ok`,`Bug Monitor directory selected: ${qr}`))},children:[a(`i`,{"data-lucide":`badge-check`}),`Select This Folder`]}),a(`button`,{className:`tcp-btn`,onClick:()=>{Ut(!1),qt(``)},children:[a(`i`,{"data-lucide":`x`}),`Close`]})]}),a(`div`,{className:`mb-2`,children:a(`input`,{className:`tcp-input`,placeholder:`Type to filter folders...`,value:Kt,onInput:e=>qt(e.target.value)})}),a(`div`,{className:`max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2`,children:Gr.length?Gr.map(e=>a(`button`,{className:`tcp-list-item mb-1 w-full text-left`,onClick:()=>Gt(String(e?.path||``)),children:[a(`i`,{"data-lucide":`folder-open`}),String(e?.name||e?.path||``)]},String(e?.path||e?.name))):a(Pr,{text:Wr?`No folders match your search.`:`No subdirectories in this folder.`})})]})]}):null}),a(hr,{open:me,onClose:()=>he(!1),title:`Browser diagnostics`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Status`}),a(`div`,{className:`mt-1 text-sm`,children:_n.data?_n.data.runnable?`Ready`:_n.data.enabled?`Blocked`:`Disabled`:`Unknown`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Headless default: `,_n.data?.headless_default?`yes`:`no`]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Sidecar`}),a(`div`,{className:`mt-1 break-all text-sm`,children:_n.data?.sidecar?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:_n.data?.sidecar?.version||`No version detected`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Browser`}),a(`div`,{className:`mt-1 break-all text-sm`,children:_n.data?.browser?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:_n.data?.browser?.version||_n.data?.browser?.channel||`No version detected`})]})]}),a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>void _n.refetch(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh browser status`]}),a(`button`,{className:`tcp-btn`,onClick:()=>bn.mutate(),disabled:bn.isPending,children:[a(`i`,{"data-lucide":`download`}),bn.isPending?`Installing sidecar...`:`Install sidecar`]}),a(`button`,{className:`tcp-btn`,onClick:()=>xn.mutate(),disabled:xn.isPending,children:[a(`i`,{"data-lucide":`globe`}),xn.isPending?`Running smoke test...`:`Run smoke test`]}),a(`button`,{className:`tcp-btn`,onClick:()=>t(`/api/engine/browser/status`,{method:`GET`}).then(()=>n(`ok`,`Browser diagnostics refreshed.`)).catch(e=>n(`err`,e instanceof Error?e.message:String(e))),children:[a(`i`,{"data-lucide":`activity`}),`Re-run diagnostics`]})]}),_n.isLoading?a(Pr,{text:`Loading browser diagnostics...`}):_n.data?a(p,{children:[zr.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Blocking issues`}),zr.map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:e.code||`browser_issue`}),a(`div`,{className:`tcp-subtle text-xs`,children:e.message||`Unknown browser issue.`})]},`${e.code||`issue`}-${t}`))]}):a(`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.`}),vn?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Latest smoke test`}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:vn.title||`Smoke test`}),a(`div`,{className:`tcp-subtle text-xs`,children:vn.final_url||vn.url||`No URL returned`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Load state: `,vn.load_state||`unknown`,` · elements:`,` `,String(vn.element_count??0),` · closed:`,` `,vn.closed?`yes`:`no`]}),vn.excerpt?a(`pre`,{className:`tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words`,children:vn.excerpt}):null]})]}):null,Br.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Recommendations`}),Br.map((e,t)=>a(`div`,{className:`tcp-list-item text-sm`,children:e},`browser-recommendation-${t}`))]}):null,Vr.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Install hints`}),Vr.map((e,t)=>a(`div`,{className:`tcp-list-item text-sm`,children:e},`browser-install-hint-${t}`))]}):null,_n.data?.last_error?a(`div`,{className:`tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-3 text-xs`,children:[`Last error: `,_n.data.last_error]}):null]}):a(Pr,{text:`Browser diagnostics are unavailable.`})]})}),a(l,{children:Ue?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-confirm-backdrop`,"aria-label":`Close MCP server dialog`,onClick:()=>We(!1)}),a(s.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:[a(`div`,{className:`mb-3 flex items-start justify-between gap-3`,children:[a(`div`,{children:[a(`h3`,{className:`tcp-confirm-title`,children:st?`Edit MCP Server`:`Add MCP Server`}),a(`p`,{className:`tcp-confirm-message`,children:`Configure transport and auth without leaving Settings.`})]}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-2`,onClick:()=>We(!1),children:a(`i`,{"data-lucide":`x`})})]}),a(`form`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,onSubmit:e=>{e.preventDefault(),yr.mutate()},children:[a(`div`,{className:`tcp-settings-tabs`,children:[a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${lt===`catalog`?`active`:``}`,onClick:()=>ut(`catalog`),children:[a(`i`,{"data-lucide":`blocks`}),`Built-in packs`]}),a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${lt===`manual`?`active`:``}`,onClick:()=>ut(`manual`),children:[a(`i`,{"data-lucide":`square-pen`}),`Manual`]})]}),lt===`catalog`?a(`div`,{className:`grid min-h-0 flex-1 content-start gap-3 overflow-hidden`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{className:`tcp-subtle text-sm`,children:Dr.generatedAt?`Built-in MCP packs · generated ${Dr.generatedAt}`:`Built-in MCP packs`}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>void Tn.refetch(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh`]})]}),a(`input`,{className:`tcp-input`,value:dt,onInput:e=>ft(e.target.value),placeholder:`Search built-in MCP packs`}),a(`div`,{className:`grid min-h-0 flex-1 auto-rows-max content-start gap-2 overflow-y-auto pr-1 md:grid-cols-2`,children:kr.length?kr.map(e=>{let t=Or.has(String(e.serverConfigName||e.slug||``).toLowerCase());return a(`div`,{className:`tcp-list-item grid h-full min-h-[8.5rem] content-start gap-2`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-semibold`,children:e.name}),a(`div`,{className:`tcp-subtle text-xs`,children:[e.slug,e.requiresSetup?` · setup required`:``]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:`info`,children:[e.toolCount,` tools`]}),e.authKind===`oauth`?a(X,{tone:`info`,children:`OAuth`}):a(X,{tone:e.requiresAuth?`warn`:`ok`,children:e.requiresAuth?`Auth`:`Authless`})]})]}),a(`div`,{className:`tcp-subtle line-clamp-2 text-xs`,children:e.description||e.transportUrl}),a(`div`,{className:`tcp-subtle break-all text-xs`,children:e.transportUrl}),e.authKind===`oauth`?a(`div`,{className:`rounded-xl border border-sky-700/40 bg-sky-950/20 px-3 py-2 text-xs text-sky-100`,children:`Save this pack to start browser sign-in. Tandem will keep the MCP in a pending state until the authorization completes.`}):null,a(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>{let t=e.transportUrl,r=Tb(e.serverConfigName||e.slug||e.name);Ke(r),Je(t),Xe(e.authKind===`oauth`?`oauth`:r===`github`||Ob(t)?`bearer`:`none`),e.authKind===`oauth`&&Qe(``),nt(r===`github`||Ob(t)?`default`:``),it([]),ut(`manual`),n(`ok`,e.authKind===`oauth`?`Loaded ${e.name}. Save to start browser sign-in.`:`Loaded ${e.name}. Review and save when ready.`)},children:`Use pack`}),e.documentationUrl?a(`a`,{className:`tcp-btn h-8 px-3 text-xs`,href:e.documentationUrl,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Docs`]}):null,t?a(X,{tone:`ok`,children:`added`}):null]})]},e.slug)}):a(Pr,{text:`No built-in MCP packs match this search.`})})]}):a(p,{children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Name`}),a(`input`,{className:`tcp-input`,value:Ge,onInput:e=>Ke(e.target.value),placeholder:`mcp-server`})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Auth mode`}),a(`select`,{className:`tcp-select`,value:Ye,onChange:e=>{let t=e.target.value;Xe(t),t===`oauth`&&Qe(``)},children:[a(`option`,{value:`none`,children:`No Auth Header`}),a(`option`,{value:`auto`,children:`Auto`}),a(`option`,{value:`oauth`,children:`OAuth`}),a(`option`,{value:`x-api-key`,children:`x-api-key`}),a(`option`,{value:`bearer`,children:`Authorization Bearer`}),a(`option`,{value:`custom`,children:`Custom Header`})]})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Transport URL`}),a(`input`,{className:`tcp-input`,value:qe,onInput:e=>{let t=e.target.value;if(Je(t),Ob(t)&&!String(tt||``).trim()&&nt(`default`),!String(Ge||``).trim()||Ge===`mcp-server`){let e=Eb(t);e&&Ke(e)}Ib(Dr,Ge,t)===`oauth`&&(Ye===`none`||Ye===`auto`)&&(Xe(`oauth`),Qe(``))},placeholder:`https://example.com/mcp`})]}),Ye===`custom`?a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Custom header name`}),a(`input`,{className:`tcp-input`,value:$e,onInput:e=>et(e.target.value),placeholder:`X-My-Token`})]}):null,Ye===`oauth`?a(`div`,{className:`grid gap-2 rounded-xl border border-sky-700/50 bg-sky-950/20 px-3 py-3 text-xs text-sky-100`,children:[a(`div`,{className:`font-medium`,children:`OAuth sign-in flow`}),a(`div`,{children:ii}),a(`div`,{className:`tcp-subtle text-xs text-sky-100/80`,children:ai?`Saving this server will immediately start the browser handoff.`:"Turn on `Connect after save` to launch the authorization flow as soon as the server is saved."}),a(`div`,{className:`tcp-subtle text-xs text-sky-100/80`,children:ri})]}):a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Token`}),a(`input`,{className:`tcp-input`,type:`password`,value:Ze,onInput:e=>Qe(e.target.value),placeholder:`token`}),a(`div`,{className:`tcp-subtle text-xs`,children:ri})]}),oi?a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`GitHub toolsets`}),a(`input`,{className:`tcp-input`,value:tt,onInput:e=>nt(e.target.value),placeholder:`default,projects`}),a(`div`,{className:`tcp-subtle text-xs`,children:"Sent as `X-MCP-Toolsets`. Built-in GitHub starts with `default`; add values like `projects`, `issues`, or `pull_requests`."})]}):null,a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Additional headers`}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>it(e=>[...e,{key:``,value:``}]),children:[a(`i`,{"data-lucide":`plus`}),`Add header`]})]}),rt.length?a(`div`,{className:`grid gap-2`,children:rt.map((e,t)=>a(`div`,{className:`grid gap-2 md:grid-cols-[1fr_1fr_auto]`,children:[a(`input`,{className:`tcp-input`,value:e.key,onInput:e=>it(n=>n.map((n,r)=>r===t?{...n,key:e.target.value}:n)),placeholder:`Header name`}),a(`input`,{className:`tcp-input`,value:e.value,onInput:e=>it(n=>n.map((n,r)=>r===t?{...n,value:e.target.value}:n)),placeholder:`Header value`}),a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>it(e=>e.filter((e,n)=>n!==t)),children:`Remove`})]},`mcp-header-${t}`))}):a(`div`,{className:`tcp-subtle text-xs`,children:"Add arbitrary request headers such as `X-MCP-Insiders` or vendor feature flags."})]}),a(`label`,{className:`inline-flex items-center gap-2 text-sm text-slate-200`,children:[a(`input`,{type:`checkbox`,className:`accent-slate-400`,checked:at,onChange:e=>ot(e.target.checked)}),Ye===`oauth`?`Start sign-in after save`:`Connect after save`]})]}),a(`div`,{className:`tcp-confirm-actions mt-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>We(!1),children:`Cancel`}),a(`button`,{type:`submit`,className:`tcp-btn-primary`,disabled:yr.isPending,children:[a(`i`,{"data-lucide":`save`}),ai?`Save MCP server and start sign-in`:`Save MCP server`]})]})]})]})]}):null})]})})}function cx({routeId:e,pageProps:t}){switch(Er(e)){case`chat`:return a(fa,{...t});case`planner`:return a(is,{...t});case`workflows`:return a(ls,{...t});case`marketplace`:return a(ds,{...t});case`studio`:return a(Xl,{...t});case`automations`:case`packs`:case`teams`:return a(ng,{...t});case`experiments`:return a(pg,{...t});case`coding`:return a(k_,{...t});case`agents`:return a(ib,{...t});case`channels`:return a(A_,{...t});case`mcp`:return a(sx,{...t});case`packs-detail`:return a(I_,{...t});case`orchestrator`:return a(uv,{...t});case`bug-monitor`:return a(zy,{...t});case`files`:return a(Vv,{...t});case`memory`:return a(Gv,{...t});case`teams-detail`:return a(ib,{...t});case`runs`:return a(Kv,{...t});case`approvals`:return a(Qv,{...t});case`settings`:return a(sx,{...t});default:return a(Wr,{...t})}}var lx={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.`},planner:{title:`Planner`,subtitle:`Advanced long-horizon intent, multi-agent planning, and governed handoff.`},studio:{title:`Studio`,subtitle:`Advanced template-first workflow builder with reusable role prompts and visual stages.`},automations:{title:`Automations`,subtitle:`Create, Calendar, Library, and Run History.`},experiments:{title:`Experiments`,subtitle:`Hidden by default. Turn this on in Settings when you need experimental surfaces.`},coding:{title:`Coder`,subtitle:`Durable coder runs, project intake, and repository work.`},agents:{title:`Agents`,subtitle:`Search reusable roles, inspect routines, and manage workflow-ready agent drafts.`},orchestrator:{title:`Task Board`,subtitle:`Plan-driven task execution with workspace visibility and approvals.`},memory:{title:`Memory`,subtitle:`Searchable memory records and operational context snapshots.`},runs:{title:`Runs`,subtitle:`Live operations overview with queue state and per-run inspection.`},approvals:{title:`Approvals Inbox`,subtitle:`Pending human approvals across every workflow that has paused on a gate.`},settings:{title:`Settings`,subtitle:`Provider defaults, identity, themes, and runtime diagnostics.`},channels:{title:`Channels`,subtitle:`Chat integrations, tool scope, and channel configuration.`},"bug-monitor":{title:`Bug Monitor`,subtitle:`Issue detection, draft review, and GitHub publishing controls.`},packs:{title:`Packs`,subtitle:`Starter packs and pack installation paths.`},teams:{title:`Teams`,subtitle:`Team instances, approvals, and shared execution state.`},mcp:{title:`MCP`,subtitle:`Catalog, readiness, and generated integration details.`},files:{title:`Files`,subtitle:`Managed uploads, artifacts, and exports.`},"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 ux({identity:e,currentRoute:t,providerLocked:n,navRoutes:i,onNavigate:c,onPaletteOpen:u,onThemeCycle:d,onLogout:f,statusBar:h,routeKey:g,navigationLock:_,children:v,providerGate:y}){let[b,x]=r(!1),S=String(e.botAvatarUrl||``).trim(),[C,w]=r(S?`custom`:`default`),T=Xn(),E=!!_;m(()=>{x(!1)},[t]),m(()=>{try{Yr()}catch{}},[i,t,b,h.bugMonitor?.enabled,h.bugMonitor?.monitoringActive,h.bugMonitor?.paused,h.bugMonitor?.pendingIncidents,h.bugMonitor?.blocked]),m(()=>{w(S?`custom`:`default`)},[S]);let D=lx[t]||{title:String(i.find(([e])=>e===t)?.[1]||`Control Panel`),subtitle:`Desktop-inspired operations UI for Tandem.`},O=o(()=>i.find(([e])=>e===t)||null,[t,i]),k=o(()=>{let e=h.bugMonitor;return e?.enabled?e.blocked?{toneClass:`blocked`,label:`Bug Monitor blocked`,shortLabel:`Blocked`}:e.paused?{toneClass:`paused`,label:`Bug Monitor paused`,shortLabel:`Paused`}:e.pendingIncidents>0?{toneClass:`incidents`,label:`Bug Monitor incidents: ${e.pendingIncidents}`,shortLabel:`${e.pendingIncidents} incident${e.pendingIncidents===1?``:`s`}`}:e.monitoringActive?{toneClass:`watching`,label:`Bug Monitor watching`,shortLabel:`Watching`}:{toneClass:`ready`,label:`Bug Monitor ready`,shortLabel:`Ready`}:null},[h.bugMonitor]),A=()=>C===`fallback`?a(`span`,{className:`text-sm font-semibold uppercase`,children:String(e.botName||`T`).trim().slice(0,1)||`T`}):a(`img`,{src:C===`custom`?S:`/icon.png`,alt:e.botName||`Tandem`,className:`block h-full w-full object-contain p-0.5`,onError:()=>w(e=>e===`custom`?`default`:`fallback`)}),j=()=>i.map(([e,r,i])=>{let o=t===e,l=n&&e!==`settings`||E;return a(`button`,{type:`button`,title:r,disabled:l,className:`tcp-rail-icon ${o?`active`:``} ${l?`locked`:``}`,onClick:()=>c(e),children:[o?a(s.span,{layoutId:`tcp-icon-indicator`,className:`tcp-rail-icon-indicator`}):null,a(`i`,{"data-lucide":i})]},e)}),M=(e=!1)=>i.map(([r,i,o])=>{let s=t===r,l=n&&r!==`settings`||E;return a(`button`,{type:`button`,disabled:l,className:`tcp-context-link ${s?`active`:``} ${l?`locked`:``}`,onClick:()=>{c(r),e&&x(!1)},children:[a(`span`,{className:`inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":o}),a(`span`,{children:i})]}),s?a(`span`,{className:`tcp-context-link-dot`}):null]},r)}),N=(t=!1)=>a(p,{children:[t?a(`div`,{className:`tcp-context-hero`,children:[a(rr,{className:`tcp-context-hero-glow`}),a(`div`,{className:`relative z-10 flex items-center gap-3`,children:[a(`div`,{className:`tcp-brand-avatar h-11 w-11`,children:A()}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:e.controlPanelName||`${e.botName} Control Panel`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Workspace navigation and system status`})]})]})]}):null,a(`div`,{className:`tcp-context-section ${t?``:`xl:hidden`}`.trim(),children:[a(`div`,{className:`tcp-context-section-label`,children:`Navigation`}),a(`nav`,{className:`grid gap-1`,children:M(t)})]}),t?a(`div`,{className:`tcp-context-section`,children:[a(`div`,{className:`tcp-context-section-label`,children:`System`}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Engine`}),h.engineHealthy?a(cr,{tone:`ok`,text:`healthy`}):a(cr,{tone:`warn`,text:`checking`})]}),a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Provider`}),a(`span`,{className:h.providerBadge,children:h.providerText})]}),a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Active runs`}),h.activeRuns>0?a(cr,{tone:`live`,text:String(h.activeRuns)}):a(`span`,{className:`tcp-badge tcp-badge-ghost`,children:`idle`})]}),k?a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Bug Monitor`}),a(`button`,{type:`button`,className:`tcp-bug-monitor-pill ${k.toneClass}`,disabled:E,title:h.bugMonitor?.lastError?`${k.label}: ${h.bugMonitor.lastError}`:k.label,onClick:()=>{c(`bug-monitor`),t&&x(!1)},children:[a(`i`,{"data-lucide":`bug-play`}),a(`span`,{className:`tcp-bug-monitor-dot`,"aria-hidden":`true`}),a(`span`,{children:k.shortLabel})]})]}):null]})]}):null,a(`div`,{className:`tcp-context-section mt-auto`,children:[a(`div`,{className:`tcp-context-section-label`,children:`Actions`}),a(`div`,{className:`grid gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn w-full justify-start`,onClick:()=>{u(),t&&x(!1)},children:[a(`i`,{"data-lucide":`search`}),`Command palette`]}),a(`button`,{type:`button`,className:`tcp-btn w-full justify-start`,onClick:()=>{d(),t&&x(!1)},children:[a(`i`,{"data-lucide":`paint-bucket`}),`Cycle theme`]}),a(`button`,{type:`button`,className:`tcp-btn w-full justify-start`,onClick:()=>{f(),t&&x(!1)},children:[a(`i`,{"data-lucide":`log-out`}),`Logout`]})]})]})]});return a(`div`,{className:`tcp-shell ${t===`chat`?`tcp-shell-chat`:``}`.trim(),children:[a(rr,{className:`tcp-shell-background`,children:[a(`div`,{className:`tcp-shell-glow tcp-shell-glow-a`}),a(`div`,{className:`tcp-shell-glow tcp-shell-glow-b`})]}),a(`aside`,{className:`tcp-icon-rail hidden xl:flex`,children:[a(`button`,{type:`button`,className:`tcp-rail-brand`,disabled:E,onClick:()=>c(`dashboard`),children:a(`div`,{className:`tcp-brand-avatar h-10 w-10`,children:A()})}),a(`nav`,{className:`tcp-rail-nav`,children:j()}),a(`div`,{className:`tcp-rail-footer`,children:[a(ur,{title:`Command palette`,onClick:u,disabled:E,children:a(`i`,{"data-lucide":`search`})}),a(ur,{title:`Cycle theme`,onClick:d,disabled:E,children:a(`i`,{"data-lucide":`paint-bucket`})}),a(ur,{title:`Logout`,onClick:f,disabled:E,children:a(`i`,{"data-lucide":`log-out`})}),a(`div`,{className:`mt-2 flex justify-center`,children:h.engineHealthy?a(cr,{tone:`ok`}):a(cr,{tone:`warn`})})]})]}),a(`aside`,{className:`tcp-context-rail hidden lg:flex xl:hidden`,children:N(!1)}),a(`main`,{className:`tcp-main-shell ${t===`chat`?`tcp-main-shell-fill`:``}`.trim(),children:[a(`section`,{className:`tcp-mobile-topbar lg:hidden`,children:[a(`button`,{type:`button`,className:`tcp-btn h-10 px-3`,disabled:E,onClick:()=>x(!0),children:[a(`i`,{"data-lucide":`menu`}),`Menu`]}),a(`div`,{className:`min-w-0 flex-1`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:D.title}),a(`div`,{className:`tcp-subtle truncate text-xs`,children:O?.[1]||D.subtitle})]}),k?a(`button`,{type:`button`,className:`tcp-bug-monitor-pill ${k.toneClass}`,disabled:E,title:h.bugMonitor?.lastError?`${k.label}: ${h.bugMonitor.lastError}`:k.label,onClick:()=>c(`bug-monitor`),children:[a(`i`,{"data-lucide":`bug-play`}),a(`span`,{className:`tcp-bug-monitor-dot`,"aria-hidden":`true`})]}):null,h.activeRuns>0?a(cr,{tone:`live`,text:String(h.activeRuns)}):null]}),a(`section`,{className:`tcp-topbar`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Tandem Control`}),a(`h1`,{className:`tcp-main-title`,children:D.title}),a(`p`,{className:`tcp-subtle mt-1 line-clamp-2`,children:D.subtitle})]}),a(`div`,{className:`tcp-topbar-status`,children:[k?a(`button`,{type:`button`,className:`tcp-bug-monitor-pill ${k.toneClass}`,disabled:E,title:h.bugMonitor?.lastError?`${k.label}: ${h.bugMonitor.lastError}`:k.label,onClick:()=>c(`bug-monitor`),children:[a(`i`,{"data-lucide":`bug-play`}),a(`span`,{className:`tcp-bug-monitor-dot`,"aria-hidden":`true`}),a(`span`,{children:k.shortLabel})]}):null,a(`span`,{className:h.providerBadge,children:h.providerText}),h.engineHealthy?a(cr,{tone:`ok`,text:`Engine healthy`}):a(cr,{tone:`warn`,text:`Checking engine`}),h.activeRuns>0?a(cr,{tone:`live`,text:`${h.activeRuns} run`}):a(`span`,{className:`tcp-badge tcp-badge-ghost`,children:`No active runs`})]})]}),a(l,{mode:`wait`,children:a(s.section,{className:`tcp-main-content ${t===`chat`||t===`automations`?`tcp-main-content-fill`:``}`.trim(),initial:T?!1:{opacity:0,y:18},animate:T?void 0:{opacity:1,y:0},exit:T?void 0:{opacity:0,y:-14},transition:T?void 0:{duration:Kn.duration.normal,ease:Kn.easing.standard},children:v},g)})]}),a(l,{children:b?a(s.div,{className:`tcp-mobile-drawer lg:hidden`,initial:T?!1:{opacity:0},animate:T?void 0:{opacity:1},exit:T?void 0:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-mobile-drawer-backdrop`,"aria-label":`Close navigation`,onClick:()=>x(!1)}),a(s.aside,{className:`tcp-mobile-drawer-panel`,initial:T?!1:{x:`-100%`},animate:T?void 0:{x:0},exit:T?void 0:{x:`-100%`},transition:T?void 0:Kn.spring.drawer,children:[a(`div`,{className:`mb-3 flex items-center justify-between`,children:[a(`div`,{children:[a(`div`,{className:`text-sm font-semibold`,children:e.botName}),a(`div`,{className:`tcp-subtle text-xs`,children:D.title})]}),a(ur,{title:`Close`,onClick:()=>x(!1),children:a(`i`,{"data-lucide":`x`})})]}),N(!0)]})]}):null}),a(l,{children:y||null}),a(l,{children:_?a(s.div,{className:`tcp-confirm-overlay`,style:{zIndex:180},initial:T?!1:{opacity:0},animate:T?void 0:{opacity:1},exit:T?void 0:{opacity:0},children:[a(`div`,{className:`tcp-confirm-backdrop`,"aria-hidden":`true`}),a(s.div,{className:`tcp-confirm-dialog w-[min(36rem,calc(100vw-2rem))]`,role:`alertdialog`,"aria-live":`assertive`,initial:T?!1:{opacity:0,y:10,scale:.985},animate:T?void 0:{opacity:1,y:0,scale:1},exit:T?void 0:{opacity:0,y:6,scale:.985},transition:T?void 0:{duration:Kn.duration.normal,ease:Kn.easing.standard},children:a(`div`,{className:`flex items-center gap-3`,children:[a(vo,{className:`h-12 w-12 shrink-0`,mode:`compact`}),a(`div`,{className:`min-w-0`,children:[a(`h3`,{className:`tcp-confirm-title`,children:_.title}),a(`p`,{className:`tcp-confirm-message`,children:_.message})]})]})})]}):null})]})}function dx(e){let t=String(e||``).trim().toLowerCase();return!!t&&t!==`ollama`&&t!==`llama_cpp`&&t!==`llama.cpp`&&t!==`local`&&t!==`openai-codex`}function fx(e){if(!e||typeof e!=`object`)return!1;let t=String(e.auth_kind||e.authKind||``).trim().toLowerCase(),n=String(e.status||``).trim().toLowerCase();return t!==`oauth`||n===`reauth_required`||n===`expired`||n===`error`?!1:e.connected===!0||n===`connected`||n===`configured`}function px(e,t){let n=String(t||``).trim().toLowerCase();if(!n||!e||typeof e!=`object`)return!1;let r=e=>!e||typeof e!=`object`?!1:!!(fx(e)||e.has_key===!0||e.hasKey===!0||e.configured===!0&&!dx(n));return r(e[n])||r(e.providers?.[n])}function mx(e,t){let n=String(t||``).trim().toLowerCase();if(!n||!e||typeof e!=`object`)return null;let r=e[n];if(r&&typeof r==`object`)return r;let i=e.providers?.[n];return i&&typeof i==`object`?i:null}function hx(e,t,n){let r=String(e?.default||e?.selected_model?.provider_id||``).trim(),i=e?.providers?.[r]||{},a=String(i.default_model||i.defaultModel||e?.selected_model?.model_id||``).trim(),o=new Set,s=e=>{if(!e||typeof e!=`object`)return;let t=e.providers&&typeof e.providers==`object`?e.providers:e;if(!(!t||typeof t!=`object`))for(let[e,n]of Object.entries(t)){if(!n||typeof n!=`object`)continue;let t=String(e||``).trim().toLowerCase();if(!t)continue;let r=String(n.status||n.statusText||``).trim().toLowerCase();(n.connected===!0||r===`connected`||r===`configured`)&&o.add(t)}};if(Array.isArray(t?.connected))for(let e of t.connected){let t=String(e||``).trim().toLowerCase();t&&o.add(t)}s(n);let c=mx(n,r),l=px(n,r),u=!!r&&!!a&&(!dx(r)||l);return{ready:u,defaultProvider:r,defaultModel:a,connected:[...o],error:``,needsOnboarding:!u,defaultProviderAuthKind:String(c?.auth_kind||c?.authKind||``).trim().toLowerCase(),defaultProviderSource:String(c?.source||``).trim().toLowerCase(),defaultProviderManagedBy:String(c?.managed_by||c?.managedBy||``).trim().toLowerCase()}}var gx=`tandem_control_panel_token`,_x=new Set([`packs`,`teams`,`channels`,`mcp`,`files`,`packs-detail`,`teams-detail`]);function vx(){try{return localStorage.getItem(gx)||``}catch{return``}}function yx(e){try{localStorage.setItem(gx,e)}catch{}}function bx(){try{localStorage.removeItem(gx)}catch{}}function xx(e,t){return y({queryKey:[`provider`,`status`],enabled:t&&!!e,refetchInterval:t?15e3:!1,queryFn:async()=>{if(!e)return{ready:!1,defaultProvider:``,defaultModel:``,connected:[],error:``,needsOnboarding:!1,defaultProviderAuthKind:``,defaultProviderSource:``,defaultProviderManagedBy:``};try{let[t,n]=await Promise.all([e.providers.config(),e.providers.authStatus().catch(()=>({}))]);return hx(t,null,n)}catch(e){return{ready:!1,defaultProvider:``,defaultModel:``,connected:[],error:e instanceof Error?e.message:String(e),needsOnboarding:!1,defaultProviderAuthKind:``,defaultProviderSource:``,defaultProviderManagedBy:``}}}})}function Sx(e,t){return y({queryKey:[`identity`],enabled:t&&!!e,refetchInterval:t?3e4:!1,queryFn:async()=>{if(!e)return{botName:`Tandem`,botAvatarUrl:``,controlPanelName:`Tandem Control Panel`};try{let e=(await Tc(`/api/engine/config/identity`,{method:`GET`}))?.identity||{},t=String(e?.bot?.canonical_name||e?.bot?.canonicalName||``).trim(),n=e?.bot?.aliases||{},r=String(e?.bot?.avatar_url||e?.bot?.avatarUrl||``).trim(),i=String(n?.control_panel||n?.controlPanel||``).trim(),a=t||`Tandem`;return{botName:a,botAvatarUrl:r,controlPanelName:i||`${a} Control Panel`}}catch{return{botName:`Tandem`,botAvatarUrl:``,controlPanelName:`Tandem Control Panel`}}}})}function Cx(e){return y({queryKey:[`bug-monitor`,`status`],enabled:e,refetchInterval:e?1e4:!1,queryFn:async()=>{try{return await Tc(`/api/engine/bug-monitor/status`,{method:`GET`})}catch{return null}}})}function wx({controlPanelName:e,controlPanelMode:t,controlPanelModeReason:n,errorMessage:i,onRetry:o,onCheckEngine:s}){let[c,l]=r(``),[u,d]=r(!1);return a(`main`,{className:`relative min-h-screen overflow-hidden px-5 py-8`,children:[a(rr,{className:`tcp-shell-background`,children:[a(`div`,{className:`tcp-shell-glow tcp-shell-glow-a`}),a(`div`,{className:`tcp-shell-glow tcp-shell-glow-b`})]}),a(`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:[a(`section`,{className:`grid gap-4`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Tandem Control`}),a(`h1`,{className:`tcp-page-title max-w-3xl`,children:`Reconnecting your session.`}),a(`p`,{className:`tcp-subtle max-w-2xl text-base`,children:`The control panel still has your session, but the engine is temporarily unavailable. We'll reconnect automatically as soon as it responds again.`})]}),a(dr,{title:e,subtitle:t===`aca`?`ACA install detected. Waiting for the Tandem engine to restore the existing session.`:`Standalone install detected. Waiting for the Tandem engine to restore the existing session.`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-950/30 p-3`,children:[a(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[a(`div`,{className:`font-medium`,children:`Session recovery`}),a(cr,{tone:u?`ok`:`warn`,text:u?`Engine reachable`:`Reconnecting`})]}),a(`p`,{className:`tcp-subtle text-xs`,children:`Existing auth is intact. The panel is waiting for the engine before reloading the app shell.`}),n?a(`p`,{className:`tcp-subtle mt-2 text-xs`,children:n}):null]}),a(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[a(`button`,{type:`button`,className:`tcp-btn-primary w-full`,onClick:o,children:[a(`i`,{"data-lucide":`refresh-cw`}),`Retry now`]}),a(`button`,{type:`button`,className:`tcp-btn w-full`,onClick:async()=>{try{let e=await s();d(!0),l(e)}catch(e){d(!1),l(e instanceof Error?e.message:String(e))}},children:[a(`i`,{"data-lucide":`activity`}),`Check engine`]})]}),a(`div`,{className:`min-h-[1.2rem] text-sm ${u?`text-lime-300`:`text-amber-200`}`,children:c||i})]})})]})]})}function Tx(){let e=_(),{toast:t}=Mr(),[n,i]=r(Qn()),[l,u]=r(!1),[d,f]=r(null),[g,v]=r(!1),b=c(!1),S=c(null);S.current===null&&(S.current=vx().trim());let[C,w]=r(()=>!!S.current),{route:T,navigate:E}=kr({canNavigate:h((e,t)=>!d||e===t,[d])});m(()=>{$n(n)},[n]);let D=y({queryKey:[`auth`,`me`],enabled:!C,retry:(e,t)=>wc(t)&&e<4,retryDelay:e=>Math.min(1e3*2**e,5e3),refetchInterval:e=>wc(e.state.error)?5e3:e.state.data?3e4:!1,refetchOnWindowFocus:!0,queryFn:()=>Tc(`/api/auth/me`,{method:`GET`,cache:`no-store`})}),O=wc(D.error),k=D.data?.ok===!0,A=o(()=>k?new gn({baseUrl:`/api/engine`,token:`session`}):null,[k]),j=xx(A,k),M=Sx(A,k),N=Ec(k),P=Dc(k),F=Cx(k),I=Oc(),L=String(I.data?.control_panel_mode||(I.data?.aca_integration?`aca`:`standalone`)).trim()||`standalone`,R=L===`aca`,z=c(!1),[ee,B]=r(()=>db(!1));m(()=>{!k||!I.isFetched||z.current||(z.current=!0,B(db(R)))},[R,k,I.isFetched]),m(()=>{z.current&&fb(ee)},[ee]),m(()=>{try{Yr()}catch{}},[k,ee,T]),m(()=>{d&&T!==`automations`&&f(null)},[d,T]),m(()=>{d&&u(!1)},[d]),m(()=>{if(!d)return;let e=e=>(e.preventDefault(),e.returnValue=``,``);return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[d]);let V=x({mutationFn:async({token:e})=>{await Tc(`/api/auth/login`,{method:`POST`,body:JSON.stringify({token:e})})},onSuccess:(n,r)=>{r.remember?yx(r.token):bx(),e.invalidateQueries({queryKey:[`auth`,`me`]}),t(`ok`,`Signed in.`),E(`dashboard`)},onError:e=>{let n=e instanceof Error?e.message:String(e);t(wc(e)?`info`:`err`,n)}});m(()=>{if(C||k||O||V.isPending||b.current)return;let e=vx().trim();if(!e){b.current=!0;return}b.current=!0,V.mutate({token:e,remember:!0})},[C,O,k,V]),m(()=>{if(!C||V.isPending)return;let e=S.current||``;if(b.current=!0,!e){w(!1);return}V.mutate({token:e,remember:!0},{onError:()=>{bx(),S.current=``},onSettled:()=>{w(!1)}})},[C,V]);let H=h(async()=>{await Tc(`/api/auth/logout`,{method:`POST`}).catch(()=>{}),e.removeQueries({queryKey:[`auth`]}),e.removeQueries({queryKey:[`control-panel`]}),e.removeQueries({queryKey:[`provider`]}),e.removeQueries({queryKey:[`identity`]}),e.invalidateQueries({queryKey:[`auth`,`me`]}),t(`info`,`Logged out.`)},[e,t]),te=o(()=>new Set([`chat`,`planner`,`studio`,`agents`,`orchestrator`,`teams`,`experiments`]),[]),U=!!j.data?.needsOnboarding,ne=k&&U;m(()=>{if(!ne){v(!1);return}te.has(T)&&(E(`settings`),g||(v(!0),t(`info`,`Set provider + default model in Providers first to unlock the control panel.`)))},[te,E,g,ne,T,t]);let re=ne&&te.has(T)?`settings`:T,ie=h(async()=>{await e.invalidateQueries({queryKey:[`provider`,`status`]})},[e]),ae=h(async()=>{await e.invalidateQueries({queryKey:[`identity`]})},[e]),W=h((e,t)=>{B(n=>{let r=R&&cb.has(e),i={...n,[e]:r?!0:t};return i[e]===n[e]?n:i})},[R]),oe=h(()=>{B(e=>{let t={...e};for(let[e]of Cr)t[e]=!0;return t})},[]),se=h(()=>{B(lb(R))},[R]),ce=o(()=>pb(ee),[ee]),le=o(()=>({acaMode:R,routeVisibility:ee,setRouteVisibility:W,showAllSections:oe,resetNavigation:se}),[R,ee,se,W,oe]),ue=h(e=>{let t=er(e);return i(t.id),t},[i]),de=M.data||{botName:`Tandem`,botAvatarUrl:``,controlPanelName:`Tandem Control Panel`},fe={client:A,api:Tc,toast:t,navigate:E,currentRoute:re,providerStatus:{ready:!!j.data?.ready,defaultProvider:j.data?.defaultProvider||``,defaultModel:j.data?.defaultModel||``,connected:j.data?.connected||[],error:j.data?.error||``,needsOnboarding:!!j.data?.needsOnboarding,defaultProviderAuthKind:j.data?.defaultProviderAuthKind||``,defaultProviderSource:j.data?.defaultProviderSource||``,defaultProviderManagedBy:j.data?.defaultProviderManagedBy||``},identity:de,refreshProviderStatus:ie,refreshIdentityStatus:ae,providerHints:xr,themes:Gn,setTheme:ue,themeId:n,navigation:le,navigationLock:d,setNavigationLock:f},pe=o(()=>{let e=Sr.filter(([e])=>ee[e]!==!1&&!_x.has(e)).map(([e,t])=>({id:`route:${e}`,label:`Go to ${t}`,group:`Routes`,onSelect:()=>E(e)})),n=[{id:`action:new-chat`,label:`New chat session`,group:`Actions`,onSelect:()=>{window.dispatchEvent(new CustomEvent(`tcp:new-chat`)),E(`chat`)}},{id:`action:start-engine-check`,label:`Check engine health`,group:`Actions`,onSelect:async()=>{try{let e=await Tc(`/api/system/health`);t(`info`,`Engine ${e?.engine?.ready||e?.engine?.healthy?`healthy`:`unhealthy`}: ${e?.engineUrl||`n/a`}`)}catch(e){let n=e instanceof Error?e.message:String(e);t(wc(e)?`info`:`err`,n)}}},{id:`action:open-settings`,label:`Open provider settings`,group:`Actions`,onSelect:()=>E(`settings`)},...ee.orchestrator===!1?[]:[{id:`action:open-task-board`,label:`Open task board`,group:`Actions`,onSelect:()=>E(`orchestrator`)}]];return[...e,...n]},[ee,E,t]);if(_r(()=>{d||u(e=>!e)}),!k)return O?a(wx,{controlPanelName:de.controlPanelName,controlPanelMode:L,controlPanelModeReason:String(I.data?.control_panel_mode_reason||``).trim(),errorMessage:D.error?.message||`Engine is reconnecting.`,onRetry:()=>{D.refetch()},onCheckEngine:async()=>{let e=await Tc(`/api/system/health`,{cache:`no-store`});return`Engine check: ${e?.engine?.ready||e?.engine?.healthy?`healthy`:`unhealthy`} at ${e?.engineUrl||`n/a`}`}}):a(gr,{loginMutation:V,savedToken:vx(),controlPanelName:de.controlPanelName,controlPanelMode:L,controlPanelModeReason:String(I.data?.control_panel_mode_reason||``).trim(),onCheckEngine:async()=>{let e=await Tc(`/api/system/health`);return`Engine check: ${e?.engine?.ready||e?.engine?.healthy?`healthy`:`unhealthy`} at ${e?.engineUrl||`n/a`}`}});let G=j.data?.ready?`tcp-badge-ok`:`tcp-badge-warn`,K=j.data?.ready?`${j.data?.defaultProvider||`none`}/${j.data?.defaultModel||`none`}`:`provider setup required`,me=F.data||null,he=me?.status||me||null,ge=!!he?.config?.enabled,_e=Number(he?.runtime?.pending_incidents||0),ve=!!he?.runtime?.monitoring_active,ye=!!he?.runtime?.paused,be=!!he?.readiness?.ingest_ready,xe=!!he?.readiness?.publish_ready,Se=String(he?.runtime?.last_runtime_error||he?.last_error||``).trim();return a(p,{children:[a(ux,{identity:de,currentRoute:re,providerLocked:ne,navRoutes:ce,onNavigate:E,onPaletteOpen:()=>u(!0),onThemeCycle:()=>ue(Jn(n)),onLogout:H,navigationLock:d,statusBar:{engineHealthy:!!(N.data?.engine?.ready||N.data?.engine?.healthy),providerBadge:G,providerText:K,activeRuns:+!![`planning`,`awaiting_approval`,`running`].includes(String(P.data?.status||``).toLowerCase()),bugMonitor:ge?{enabled:!0,monitoringActive:ve,paused:ye,pendingIncidents:_e,blocked:!be,lastError:ve&&!xe&&Se?`Watching locally only. ${Se}`:Se}:null},routeKey:re,providerGate:ne&&re!==`settings`?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:a(s.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:[a(`h3`,{className:`tcp-confirm-title`,children:`Provider Setup Required`}),a(`p`,{className:`tcp-confirm-message`,children:`Configure provider and default model in Providers to unlock all sections.`}),a(`div`,{className:`tcp-confirm-actions`,children:a(`button`,{className:`tcp-btn-primary`,onClick:()=>E(`settings`),children:`Open Providers`})})]})}):null,children:a(cx,{routeId:re,pageProps:fe})}),a(vr,{open:l,onClose:()=>u(!1),actions:pe})]})}function Ex(){return a(jr,{children:a(Tx,{})})}var Dx=new ot({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),Ox=document.getElementById(`app`);if(!Ox)throw Error(`Missing #app host`);g(Ox).render(a(u,{children:a(v,{client:Dx,children:a(Ex,{})})}));
7377
+ Tandem will store it on this server and reuse it for Codex sessions.`}),a(`div`,{className:`grid gap-1 text-xs tcp-subtle`,children:[a(`div`,{children:`You can paste the JSON directly, or choose the file from a signed-in machine.`}),dn?a(`div`,{children:[`Loaded file: `,dn]}):null]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:!E||!Pe.trim()||Tr.isPending||Sr.isPending,onClick:()=>Tr.mutate({providerId:t,authJson:Pe}),children:[a(`i`,{"data-lucide":`upload`}),w?`Replace hosted Codex session`:`Import pasted auth.json`]}),a(`button`,{type:`button`,className:`tcp-btn`,disabled:Tr.isPending||Sr.isPending,onClick:()=>un.current?.click(),children:[a(`i`,{"data-lucide":`file-up`}),`Choose auth.json file`]}),S?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!E||br.isPending||wr.isPending,onClick:()=>{Ce(e=>{if(!e[t])return e;let n={...e};return delete n[t],n}),wr.mutate({providerId:t})},children:[a(`i`,{"data-lucide":`link-2`}),`Use Local Codex Session`]}):null,t===kb&&w&&!h?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:Zn.isPending,onClick:()=>Zn.mutate({providerId:t,modelId:r||`gpt-5.4`}),children:[a(`i`,{"data-lucide":`sparkles`}),`Use for Tandem Runs`]}):null,a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!w||Sr.isPending||Tr.isPending||C,onClick:()=>Sr.mutate({providerId:t}),children:[a(`i`,{"data-lucide":`unlink`}),`Disconnect`]})]})]}):a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,disabled:!E||C||Sr.isPending,onClick:()=>br.mutate({providerId:t}),children:[a(`i`,{"data-lucide":`log-in`}),w?`Reconnect Codex Account`:`Connect Codex Account`]}),wn&&t===kb&&S?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!E||br.isPending||wr.isPending,onClick:()=>{Ce(e=>{if(!e[t])return e;let n={...e};return delete n[t],n}),wr.mutate({providerId:t})},children:[a(`i`,{"data-lucide":`link-2`}),`Use Local Codex Session`]}):null,t===kb&&w&&!h?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:Zn.isPending,onClick:()=>Zn.mutate({providerId:t,modelId:r||`gpt-5.4`}),children:[a(`i`,{"data-lucide":`sparkles`}),`Use for Tandem Runs`]}):null,a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,disabled:!w||Sr.isPending||C,onClick:()=>Sr.mutate({providerId:t}),children:[a(`i`,{"data-lucide":`unlink`}),`Disconnect`]}),C?a(`button`,{type:`button`,className:`tcp-btn h-10 px-4 text-sm`,onClick:()=>window.open(`https://chatgpt.com/codex`,`_blank`,`noopener,noreferrer`),children:[a(`i`,{"data-lucide":`external-link`}),`Open Codex`]}):null]})]}):a(`form`,{onSubmit:e=>{e.preventDefault();let n=e.currentTarget.elements.namedItem(`apiKey`),r=String(n?.value||``).trim();r&&(yr.mutate({providerId:t,apiKey:r}),n.value=``)},className:`flex gap-2`,children:[a(`input`,{name:`apiKey`,className:`tcp-input`,placeholder:String(d?.placeholder||`Set ${t} API key`)}),a(`button`,{className:`tcp-btn`,type:`submit`,children:[a(`i`,{"data-lucide":`save`}),`Save`]})]})]})]},t)}):a(Pr,{text:`No provider catalog is available yet. You can still enter a model ID manually for custom providers.`})]}):null})]})}):null,F===`search`?a(dr,{title:`Web Search`,subtitle:"Configure the engine's `websearch` backend and provider keys.",actions:a(lr,{children:[a(X,{tone:kn.data?.settings?.has_brave_key?`ok`:`warn`,children:[`Brave`,` `,kn.data?.settings?.has_brave_key?`configured`:`missing`]}),a(X,{tone:kn.data?.settings?.has_exa_key?`ok`:`warn`,children:[`Exa`,` `,kn.data?.settings?.has_exa_key?`configured`:`missing`]}),a(`button`,{className:`tcp-btn`,onClick:()=>kr.mutate({query:ce.trim()}),disabled:!kn.data?.available||!ce.trim()||kr.isPending,children:[a(`i`,{"data-lucide":kr.isPending?`loader-circle`:`search`}),kr.isPending?`Testing...`:`Test search`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>Dr.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),brave_api_key:ae.trim()||void 0,exa_api_key:oe.trim()||void 0}),disabled:!kn.data?.available||Dr.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save`]})]}),children:kn.data?.available?a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4 text-sm`,children:[a(`div`,{className:`font-medium`,children:`Engine env file`}),a(`div`,{className:`tcp-subtle mt-1 break-all`,children:kn.data?.managed_env_path||`/etc/tandem/engine.env`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:kn.data?.restart_hint||`Changes apply immediately.`})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Backend`}),a(`select`,{className:`tcp-select`,value:B,onChange:e=>V(e.target.value),children:[a(`option`,{value:`auto`,children:`Auto failover`}),a(`option`,{value:`brave`,children:`Brave Search`}),a(`option`,{value:`exa`,children:`Exa`}),a(`option`,{value:`searxng`,children:`SearxNG`}),a(`option`,{value:`tandem`,children:`Tandem hosted search`}),a(`option`,{value:`none`,children:`Disable websearch`})]})]}),a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Timeout (ms)`}),a(`input`,{className:`tcp-input`,type:`number`,min:1e3,max:12e4,value:re,onInput:e=>ie(e.target.value)})]})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Tandem search URL`}),a(`input`,{className:`tcp-input`,placeholder:`https://search.tandem.ac`,value:H,onInput:e=>te(e.target.value)}),a(`span`,{className:`tcp-subtle text-xs`,children:"Only used when backend is set to `tandem` or `auto`. This is the hosted Tandem search router, not the SearXNG endpoint."})]}),a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`SearxNG URL`}),a(`input`,{className:`tcp-input`,placeholder:`http://127.0.0.1:8080`,value:U,onInput:e=>ne(e.target.value)}),a(`span`,{className:`tcp-subtle text-xs`,children:"Only used when backend is `searxng` or `auto`."})]})]}),a(`div`,{className:`grid gap-3 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Search test`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:"Runs `websearch` against the currently running engine config and renders the result as markdown below."})]}),a(X,{tone:`warn`,children:`Tests live engine config`})]}),a(`div`,{className:`grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]`,children:[a(`input`,{className:`tcp-input`,placeholder:`Try a test query like autonomous AI agentic workflows`,value:ce,onInput:e=>le(e.target.value)}),a(`button`,{className:`tcp-btn`,onClick:()=>kr.mutate({query:ce.trim()}),disabled:!kn.data?.available||!ce.trim()||kr.isPending,children:[a(`i`,{"data-lucide":kr.isPending?`loader-circle`:`play`}),kr.isPending?`Running...`:`Run test`]})]}),ue?.markdown?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[a(X,{tone:`ok`,children:[`Backend`,` `,String(ue.parsed_output?.backend||ue.metadata?.backend||`unknown`)]}),ue.parsed_output?.configured_backend?a(X,{tone:`info`,children:[`Configured`,` `,String(ue.parsed_output.configured_backend)]}):null,ue.metadata?.error?a(X,{tone:`warn`,children:String(ue.metadata.error).replaceAll(`_`,` `)}):null]}),a(`div`,{className:`tcp-markdown tcp-markdown-ai max-h-[320px] overflow-auto rounded-xl border border-slate-700/60 bg-black/20 p-3 text-sm`,dangerouslySetInnerHTML:{__html:Xr(ue.markdown||``)}})]}):null]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:`Brave Search key`}),a(X,{tone:kn.data?.settings?.has_brave_key?`ok`:`warn`,children:kn.data?.settings?.has_brave_key?`Saved`:`Missing`})]}),a(`input`,{className:`tcp-input`,type:`password`,placeholder:`Paste Brave Search key`,value:ae,onInput:e=>W(e.target.value)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>Dr.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),brave_api_key:ae.trim()||void 0}),disabled:!ae.trim()||Dr.isPending,children:`Save Brave Key`}),kn.data?.settings?.has_brave_key?a(`button`,{className:`tcp-btn`,onClick:()=>Dr.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),clear_brave_key:!0}),disabled:Dr.isPending,children:`Remove`}):null]})]}),a(`div`,{className:`grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:`Exa key`}),a(X,{tone:kn.data?.settings?.has_exa_key?`ok`:`warn`,children:kn.data?.settings?.has_exa_key?`Saved`:`Missing`})]}),a(`input`,{className:`tcp-input`,type:`password`,placeholder:`Paste Exa API key`,value:oe,onInput:e=>se(e.target.value)}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>Dr.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),exa_api_key:oe.trim()||void 0}),disabled:!oe.trim()||Dr.isPending,children:`Save Exa Key`}),kn.data?.settings?.has_exa_key?a(`button`,{className:`tcp-btn`,onClick:()=>Dr.mutate({backend:B,tandem_url:H,searxng_url:U,timeout_ms:Number.parseInt(re||`10000`,10),clear_exa_key:!0}),disabled:Dr.isPending,children:`Remove`}):null]})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:"`auto` tries the configured backends with failover. If Brave is rate-limited and Exa is configured, the engine can continue with Exa instead of returning a generic unavailable message."})]}):a(Pr,{text:kn.data?.reason||`Search settings are only editable here when the panel points at a local engine host or a Tandem-hosted managed server.`})}):null,F===`scheduler`?a(dr,{title:`Automation Scheduler`,subtitle:`Controls parallel execution of automation runs. Restart tandem-engine after changing.`,actions:a(lr,{children:a(`button`,{className:`tcp-btn-primary`,onClick:()=>Or.mutate({mode:fe,max_concurrent_runs:G?Number.parseInt(G,10):null}),disabled:!An.data?.available||Or.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save`]})}),children:An.data?.available?a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4 text-sm`,children:[a(`div`,{className:`font-medium`,children:`Engine env file`}),a(`div`,{className:`tcp-subtle mt-1 break-all`,children:An.data?.managed_env_path||`/etc/tandem/engine.env`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:An.data?.restart_hint||`Restart tandem-engine after changing scheduler mode.`})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Mode`}),a(`select`,{className:`tcp-select`,value:fe,onChange:e=>pe(e.target.value),children:[a(`option`,{value:`multi`,children:`Multi — parallel runs (recommended)`}),a(`option`,{value:`single`,children:`Single — one run at a time`})]})]}),a(`label`,{className:`grid gap-1 text-sm`,children:[a(`span`,{className:`tcp-subtle text-xs uppercase tracking-[0.18em]`,children:`Max concurrent runs`}),a(`input`,{className:`tcp-input`,type:`number`,min:1,max:32,placeholder:`8 (default)`,value:G,onInput:e=>K(e.target.value)})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:`Multi mode allows several automation runs to execute concurrently. Max concurrent runs caps parallelism. Changes require a tandem-engine restart to take effect.`})]}):a(Pr,{text:An.data?.reason||`Scheduler settings are only editable here when the panel points at a local engine host or a Tandem-hosted managed server.`})}):null,F===`identity`?a(dr,{title:`Identity preview`,subtitle:`Live preview of how the assistant appears across the panel.`,actions:a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>C().then(()=>n(`ok`,`Identity refreshed.`)),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh identity`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>jr.mutate(),disabled:jr.isPending,children:[a(`i`,{"data-lucide":`save`}),`Save`]})]}),children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{className:`inline-flex items-center gap-3`,children:[a(`span`,{className:`tcp-brand-avatar inline-grid h-12 w-12 rounded-xl`,children:a(`img`,{src:j||`/icon.png`,alt:k||`Tandem`,className:`block h-full w-full object-contain p-1`})}),a(`div`,{children:[a(`div`,{className:`font-semibold`,children:k||`Tandem`}),a(`div`,{className:`tcp-subtle text-xs`,children:N||`Control Center`})]})]}),a(lr,{children:[a(`button`,{className:`tcp-icon-btn`,title:`Upload avatar`,"aria-label":`Upload avatar`,onClick:()=>ln.current?.click(),children:a(`i`,{"data-lucide":`pencil`})}),a(`button`,{className:`tcp-icon-btn`,title:`Clear avatar`,"aria-label":`Clear avatar`,onClick:()=>M(``),children:a(`i`,{"data-lucide":`trash-2`})})]})]})}),a(`input`,{className:`tcp-input`,value:k,onInput:e=>A(e.target.value),placeholder:`Bot name`}),a(`input`,{className:`tcp-input`,value:N,onInput:e=>P(e.target.value),placeholder:`Control panel alias`}),a(`input`,{className:`tcp-input`,value:j,onInput:e=>M(e.target.value),placeholder:`Avatar URL or data URL`}),a(`input`,{ref:ln,type:`file`,accept:`image/*`,className:`hidden`,onChange:e=>Hr(e.target.files?.[0]||null)})]})}):null,F===`theme`?a(dr,{title:`Theme studio`,subtitle:`Preview tiles with richer feedback and immediate switching.`,children:a(ub,{themes:g,themeId:b,onChange:v})}):null,F===`channels`?a(dr,{title:`Channel connections`,subtitle:`Telegram, Discord, and Slack delivery setup and live listener status.`,actions:a(lr,{children:[a(X,{tone:fi?`ok`:`warn`,children:[fi,`/`,Ab.length,` connected`]}),a(`button`,{className:`tcp-btn`,onClick:()=>void Mr(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh channels`]})]}),children:a(`div`,{className:`grid gap-3`,children:Ab.map(e=>{let t=qn.data?.[e]||{},n=Jn.data?.[e]||{},r=q[e]||Zb(e,t),i=Ve[e],o=(Yn.data||{})[e]?.slice()||[],c=String(Le[e]||``).trim(),u=o.find(e=>e.scope_id===c)||null,d=u?nx(u):c||`Channel default`,f=c?`scope`:`channel`,p=ex(Xn.data?.[e]||Qb()),m=Gr.map(e=>`mcp.${Ic(e.name)}.`),h=new Set(p.enabled_mcp_tools.filter(e=>m.some(t=>e.startsWith(t)))),g=r.securityProfile===`public_demo`,_=px(e,t),v=!mx(e,r,t);return a(`div`,{className:`tcp-list-item grid gap-3`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-semibold capitalize`,children:e}),a(`div`,{className:`tcp-subtle text-xs`,children:e===`telegram`?`Bot token, allowed users, style profile, and optional model override.`:e===`discord`?`Bot token, allowed users, mention policy, guild targeting, and optional model override.`:`Bot token, allowed users, mention policy, default channel, and optional model override.`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:n.connected?`ok`:`warn`,children:n.connected?`Connected`:n.enabled?`Configured`:`Disconnected`}),a(X,{tone:t.has_token?`info`:`warn`,children:t.has_token?`Token saved`:`No token`})]})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`input`,{className:`tcp-input`,type:`password`,placeholder:t.has_token?String(t.token_masked||`****`):`Paste ${e} bot token`,value:r.botToken,onInput:t=>J(n=>({...n,[e]:{...r,botToken:t.target.value}}))}),t.has_token&&!r.botToken?a(`div`,{className:`tcp-subtle text-xs`,children:`Token is already stored. Enter a new token only if you want to replace it.`}):null,a(`input`,{className:`tcp-input`,placeholder:`Allowed users (comma separated)`,value:r.allowedUsers,onInput:t=>J(n=>({...n,[e]:{...r,allowedUsers:t.target.value}}))})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`select`,{className:`tcp-input`,value:r.securityProfile,onInput:t=>J(n=>({...n,[e]:{...r,securityProfile:t.target.value}})),children:[a(`option`,{value:`operator`,children:`Operator`}),a(`option`,{value:`trusted_team`,children:`Trusted team`}),a(`option`,{value:`public_demo`,children:`Public demo`})]}),e===`telegram`?a(`input`,{className:`tcp-input`,placeholder:`Style profile`,value:r.styleProfile,onInput:t=>J(n=>({...n,[e]:{...r,styleProfile:t.target.value}}))}):null,e===`discord`?a(`input`,{className:`tcp-input`,placeholder:`Guild ID (optional)`,value:r.guildId,onInput:t=>J(n=>({...n,[e]:{...r,guildId:t.target.value}}))}):null,e===`slack`?a(`input`,{className:`tcp-input`,placeholder:`Default channel ID`,value:r.channelId,onInput:t=>J(n=>({...n,[e]:{...r,channelId:t.target.value}}))}):null,a(`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:[a(`input`,{type:`checkbox`,checked:r.mentionOnly,onChange:t=>J(n=>({...n,[e]:{...r,mentionOnly:t.target.checked}}))}),`Mention only`]})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-3 flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Channel model override`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Pick the provider and model this channel should use. Leave both blank to inherit Tandem's global default.`})]}),a(X,{tone:r.modelProviderId&&r.modelId?`ok`:`info`,children:r.modelProviderId&&r.modelId?`Custom model`:`Global default`})]}),a(ma,{providerLabel:`Provider`,modelLabel:`Model`,draft:{provider:r.modelProviderId,model:r.modelId},providers:Sn,onChange:({provider:t,model:n})=>J(i=>({...i,[e]:{...r,modelProviderId:t,modelId:n}})),inheritLabel:`Use global default`}),a(`div`,{className:`mt-2 tcp-subtle text-xs`,children:r.modelProviderId&&r.modelId?a(`span`,{children:[`Selected model: `,a(`strong`,{children:r.modelProviderId}),` /`,` `,a(`strong`,{children:r.modelId})]}):En.provider&&En.model?a(`span`,{children:[`Inheriting Tandem default:`,` `,a(`strong`,{children:En.provider}),` /`,` `,a(`strong`,{children:En.model})]}):a(`span`,{children:`No global default model is configured yet.`})})]}),r.securityProfile===`public_demo`?a(`div`,{className:`tcp-subtle text-xs`,children:"Public demo mode blocks operator commands, file/workspace access, MCP access, shell access, and tool-scope widening. Memory stays confined to this channel's quarantined public namespace, and `/help` still advertises restricted capabilities for security."}):null,a(`div`,{className:`tcp-subtle text-xs`,children:[`Active sessions: `,Number(n.active_sessions||0),n.last_error?` · Last error: ${n.last_error}`:``]}),i?.hints?.length?a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3 text-xs`,children:[a(`div`,{className:`mb-1 font-medium`,children:`Verification hints`}),a(`div`,{className:`grid gap-1`,children:i.hints.map((t,n)=>a(`div`,{className:`tcp-subtle`,children:t},`${e}-hint-${n}`))})]}):null,a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn-primary`,disabled:Fr.isPending||!v,onClick:()=>Fr.mutate(e),children:[a(`i`,{"data-lucide":`save`}),`Save`]}),e===`discord`?a(`button`,{className:`tcp-btn`,disabled:Lr.isPending,onClick:()=>Lr.mutate(`discord`),children:[a(`i`,{"data-lucide":`shield-check`}),`Verify`]}):null,a(`button`,{className:`tcp-btn-danger`,disabled:Ir.isPending||!_,onClick:()=>Ir.mutate(e),children:[a(`i`,{"data-lucide":`trash-2`}),`Remove`]})]}),a(s.div,{layout:!0,className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-3 flex flex-wrap items-start justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:`Channel tool scope`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Built-in tools and MCP servers available to `,e,` sessions.`]}),p.enabled_tools.some(e=>e!==Nb)?a(`div`,{className:`mt-1 text-xs text-amber-300`,children:[`Explicit built-in allowlist is active for this`,` `,f,`.`]}):null,g?a(`div`,{className:`mt-1 text-xs text-slate-400`,children:`Public demo profile can only expose web and quarantined public-memory tools here. File, shell, MCP, and operator-facing tools stay disabled even if saved in channel preferences.`}):null]}),a(`div`,{className:`flex flex-wrap items-center gap-2`,children:[a(`button`,{className:`tcp-btn`,disabled:Nr.isPending,onClick:()=>Nr.mutate({channel:e,scopeId:c||null,payload:{reset:!0}}),children:`Reset scope`}),a(`button`,{className:`tcp-btn`,"aria-expanded":!!ze[e],onClick:()=>Be(t=>({...t,[e]:!t[e]})),children:[a(`span`,{children:ze[e]?`Hide`:`Show`}),a(`i`,{"data-lucide":`chevron-down`,className:`h-4 w-4 transition-transform duration-200 ${ze[e]?`rotate-180`:``}`})]})]})]}),a(`div`,{className:`mb-3 grid gap-3 md:grid-cols-[minmax(0,1fr)_320px] md:items-end`,children:[a(`div`,{className:`grid gap-1`,children:[a(`div`,{className:`tcp-subtle text-xs`,children:c?`Editing ${d}. Saving here stores a scope-specific override on top of the ${e} default.`:`Editing the ${e} default. Pick a conversation scope to override one specific ${e} thread, room, or chat.`}),a(`div`,{className:`tcp-subtle text-[11px]`,children:o.length?`${o.length} known scope${o.length===1?``:`s`} discovered from channel sessions.`:`No scoped conversations discovered yet.`})]}),a(`label`,{className:`grid gap-1`,children:[a(`span`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`Conversation scope`}),a(`select`,{className:`tcp-input`,value:c,onChange:t=>Re(n=>({...n,[e]:t.target.value})),children:[a(`option`,{value:``,children:`Channel default`}),c&&!o.some(e=>e.scope_id===c)?a(`option`,{value:c,children:d}):null,o.map(e=>a(`option`,{value:e.scope_id,children:nx(e)},e.scope_id))]})]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:[p.enabled_mcp_servers.length?`${p.enabled_mcp_servers.length} MCP server${p.enabled_mcp_servers.length===1?``:`s`} enabled for this ${f}.`:g?`MCP servers stay disabled in public demo mode.`:`No MCP servers enabled for this ${f}.`,p.enabled_mcp_tools.length?` ${p.enabled_mcp_tools.length} exact MCP tool${p.enabled_mcp_tools.length===1?``:`s`} also selected.`:``,` ${cx(r.securityProfile,Nb)?rx(p,Nb)?`Workflow drafts from chat are enabled.`:`Workflow drafts from chat are disabled.`:`Workflow drafts stay disabled in public demo mode.`}`]}),a(l,{initial:!1,children:ze[e]?a(s.div,{initial:{opacity:0,height:0,y:-6},animate:{opacity:1,height:`auto`,y:0},exit:{opacity:0,height:0,y:-6},transition:{duration:.22,ease:[.22,1,.36,1]},className:`overflow-hidden`,children:a(`div`,{className:`grid gap-3 pt-3`,children:[a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`Workflow planning`}),a(`label`,{className:`flex items-center justify-between rounded-xl border border-slate-700/60 bg-slate-950/30 px-3 py-2 text-sm`,children:[a(`div`,{className:`flex flex-col`,children:[a(`span`,{className:`font-mono text-xs`,children:`Allow workflow drafts from chat`}),a(`span`,{className:`tcp-subtle text-[11px]`,children:"Stores the `tandem.workflow_planner` pseudo-tool in this channel scope without changing the normal tool allowlist."})]}),a(`input`,{type:`checkbox`,checked:rx(p,Nb),disabled:Nr.isPending||!cx(r.securityProfile,Nb),onChange:t=>Nr.mutate({channel:e,scopeId:c||null,payload:ix(p,Nb,t.currentTarget.checked)})})]})]}),Mb.map(t=>a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:t.label}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:t.tools.map(t=>{let n=cx(r.securityProfile,t),i=lx(p,t,r.securityProfile);return a(`label`,{className:`flex items-center justify-between rounded-xl border border-slate-700/60 bg-slate-950/30 px-3 py-2 text-sm`,children:[a(`div`,{className:`flex flex-col`,children:[a(`span`,{className:`font-mono text-xs`,children:t}),n?null:a(`span`,{className:`tcp-subtle text-[11px]`,children:`Disabled by security profile`})]}),a(`input`,{type:`checkbox`,checked:i,disabled:Nr.isPending||!n,onChange:n=>Nr.mutate({channel:e,scopeId:c||null,payload:ix(p,t,n.currentTarget.checked)})})]},`${e}-tool-${t}`)})})]},`${e}-${t.label}`)),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`MCP servers`}),Gr.length?a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:Gr.map(t=>{let n=!g&&p.enabled_mcp_servers.includes(t.name);return a(`label`,{className:`flex items-center justify-between rounded-xl border border-slate-700/60 bg-slate-950/30 px-3 py-2 text-sm`,children:[a(`div`,{className:`flex flex-col`,children:[a(`span`,{className:`font-mono text-xs`,children:t.name}),g?a(`span`,{className:`tcp-subtle text-[11px]`,children:`Disabled by security profile`}):null]}),a(`input`,{type:`checkbox`,checked:n,disabled:Nr.isPending||g,onChange:n=>Nr.mutate({channel:e,scopeId:c||null,payload:ax(p,t.name,n.currentTarget.checked)})})]},`${e}-mcp-${t.name}`)})}):a(`div`,{className:`tcp-subtle text-xs`,children:g?`MCP servers stay disabled in public demo mode.`:`No MCP servers configured yet.`})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-subtle text-[11px] uppercase tracking-[0.24em]`,children:`Exact MCP tools`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Choose exact tool names for this `,f,`. This narrows access without changing the whole-server toggles above.`]}),Gr.length?a(`div`,{className:`grid gap-3`,children:[Gr.map(t=>{let n=Yb(Array.isArray(t.toolCache)?t.toolCache:[]),r=ox(p,t.name,n);return a(Hc,{title:t.name,subtitle:t.connected?t.enabled?`Connected and enabled globally. Pick the exact tools this scope can use.`:`Connected, but disabled globally. Exact selections are saved here and will apply if the server is enabled.`:`This server is disconnected. Exact selections are saved here and will apply when it reconnects.`,discoveredTools:n,value:r,disabled:Nr.isPending||g,collapsible:!0,defaultCollapsed:!0,emptyText:`No MCP tools have been discovered for this server yet.`,onChange:r=>Nr.mutate({channel:e,scopeId:c||null,payload:sx(p,t.name,n,r)})},`${e}-exact-mcp-${t.name}`)}),p.enabled_mcp_tools.filter(e=>!h.has(e)).length?a(Hc,{title:`Saved exact tools not currently matched`,subtitle:`These exact MCP tools are still stored for this scope, but no discovered server is currently exposing them.`,discoveredTools:[],value:p.enabled_mcp_tools.filter(e=>!h.has(e)),disabled:Nr.isPending||g,emptyText:`All saved exact MCP tools currently match a discovered server.`,onChange:t=>Nr.mutate({channel:e,scopeId:c||null,payload:{...p,enabled_mcp_tools:$b([...p.enabled_mcp_tools.filter(e=>h.has(e)),...t===null?[]:t])}})}):null]}):a(`div`,{className:`tcp-subtle text-xs`,children:g?`Exact MCP tools stay disabled in public demo mode.`:`No MCP servers configured yet.`})]})]})},`${e}-tool-scope-body`):null})]})]},e)})})}):null,F===`mcp`?a(dr,{title:`MCP connections`,subtitle:`Configured MCP servers, connection state, and discovered tool coverage. Per-channel exact tool scopes live under Channels.`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:Qr?`ok`:`warn`,children:[Qr,`/`,Gr.length,` connected`]}),a(X,{tone:`info`,children:[Kr.length,` tools`]}),a(`button`,{className:`tcp-btn`,onClick:()=>I(`channels`),children:`Channel scopes`}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>Si(),children:[a(`i`,{"data-lucide":`plus`}),`Add MCP server`]}),a(`button`,{className:`tcp-btn`,onClick:()=>void Rr(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Reload`]})]}),children:a(`div`,{className:`grid gap-3`,children:[Gr.length?Gr.map(e=>{let t=Object.keys(e.headers||{}).filter(Boolean),n=Array.isArray(e.toolCache)?e.toolCache.length:0;return a(`div`,{className:`tcp-list-item grid gap-2`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-semibold`,children:e.name}),a(`div`,{className:`tcp-subtle text-sm`,children:e.transport||`No transport set`})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:e.connected?`ok`:`warn`,children:e.connected?`Connected`:`Disconnected`}),a(X,{tone:e.enabled?`info`:`warn`,children:e.enabled?`Enabled`:`Disabled`}),String(e.authKind||``).trim().toLowerCase()===`oauth`?a(X,{tone:`info`,children:`OAuth`}):null,a(X,{tone:`info`,children:[n,` tools`]})]})]}),e.lastError?a(`div`,{className:`rounded-xl border border-rose-700/60 bg-rose-950/20 px-2 py-1 text-xs text-rose-300`,children:e.lastError}):null,e.lastAuthChallenge?a(`div`,{className:`rounded-xl border border-amber-700/60 bg-amber-950/20 px-3 py-2 text-xs text-amber-100`,children:[a(`div`,{className:`font-medium`,children:`OAuth authorization pending`}),a(`div`,{className:`tcp-subtle mt-1`,children:String(e.lastAuthChallenge.message||``).trim()||`Open the authorization URL to finish connecting this MCP server.`}),a(`div`,{className:`tcp-subtle mt-1`,children:`Tandem will keep checking for completion automatically while this page is open.`}),String(e.lastAuthChallenge.authorization_url||e.lastAuthChallenge.authorizationUrl||e.authorizationUrl||``).trim()?a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(`a`,{className:`tcp-btn inline-flex h-8 px-3 text-xs`,href:String(e.lastAuthChallenge.authorization_url||e.lastAuthChallenge.authorizationUrl||e.authorizationUrl||``).trim(),target:`_blank`,rel:`noreferrer`,children:`Open auth URL`}),a(`button`,{type:`button`,className:`tcp-btn inline-flex h-8 px-3 text-xs`,disabled:Br.isPending,onClick:()=>Br.mutate({action:`authenticate`,server:e}),children:`Mark sign-in complete`})]}):null]}):null,a(`div`,{className:`tcp-subtle text-xs`,children:t.length?`Auth headers: ${t.join(`, `)}`:`No stored auth headers.`}),a(Hc,{title:`Tool access`,subtitle:`Leave all discovered tools selected to expose the full MCP server, or uncheck tools to hide them from agents and workflows.`,discoveredTools:Array.isArray(e.toolCache)?e.toolCache:[],value:e.allowedTools,disabled:zr.isPending,onChange:t=>zr.mutate({serverName:e.name,allowedTools:t})}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>Si(e),children:`Edit`}),a(`button`,{className:`tcp-btn`,disabled:Br.isPending,onClick:()=>Br.mutate({action:e.connected?`disconnect`:`connect`,server:e}),children:e.connected?`Disconnect`:`Connect`}),a(`button`,{className:`tcp-btn`,disabled:Br.isPending,onClick:()=>Br.mutate({action:`refresh`,server:e}),children:`Refresh`}),a(`button`,{className:`tcp-btn`,disabled:Br.isPending,onClick:()=>Br.mutate({action:`toggle-enabled`,server:e}),children:e.enabled?`Disable`:`Enable`}),a(`button`,{className:`tcp-btn-danger`,disabled:Br.isPending,onClick:()=>Br.mutate({action:`delete`,server:e}),children:`Delete`})]})]},e.name)}):a(`div`,{className:`grid gap-3`,children:[a(Pr,{text:`No MCP servers configured.`}),a(`div`,{className:`flex justify-start`,children:a(`button`,{className:`tcp-btn-primary`,onClick:()=>Si(),children:[a(`i`,{"data-lucide":`plus`}),`Add MCP server`]})})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Discovered tools`}),a(`pre`,{className:`tcp-code max-h-56 overflow-auto whitespace-pre-wrap break-words`,children:Kr.length?Kr.slice(0,250).join(`
7378
+ `):`No MCP tools discovered yet. Connect a server first.`})]})]})}):null,F===`bug_monitor`?a(dr,{title:`Bug monitor`,actions:a(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[a(X,{tone:$r.runtime?.monitoring_active?$r.readiness?.publish_ready?`ok`:`info`:$r.readiness?.ingest_ready?`info`:`warn`,children:$r.runtime?.monitoring_active?$r.readiness?.publish_ready?`Monitoring`:`Watching locally`:$r.readiness?.ingest_ready?`Ready`:`Not ready`}),Y||$r.runtime?.paused?a(X,{tone:`warn`,children:`Paused`}):null,a(X,{tone:`info`,children:[Number($r.runtime?.pending_incidents||0),` incidents`]}),a(X,{tone:`info`,children:[Number($r.pending_drafts||0),` pending drafts`]}),a(X,{tone:`info`,children:[Number($r.pending_posts||0),` post attempts`]}),a(`button`,{className:`tcp-icon-btn`,title:`Reload status`,"aria-label":`Reload status`,onClick:()=>Promise.all([Vn.refetch(),Hn.refetch(),Un.refetch(),Wn.refetch()]).then(()=>n(`ok`,`Bug Monitor status refreshed.`)),children:a(`i`,{"data-lucide":`refresh-cw`})}),a(`button`,{className:`tcp-icon-btn`,title:Y||$r.runtime?.paused?`Resume monitoring`:`Pause monitoring`,"aria-label":Y||$r.runtime?.paused?`Resume monitoring`:`Pause monitoring`,disabled:pr.isPending,onClick:()=>pr.mutate({action:Y||$r.runtime?.paused?`resume`:`pause`}),children:a(`i`,{"data-lucide":Y||$r.runtime?.paused?`play`:`pause`})}),a(`button`,{className:`tcp-icon-btn`,title:`Refresh capability bindings`,"aria-label":`Refresh capability bindings`,disabled:nr.isPending,onClick:()=>nr.mutate(),children:a(`i`,{"data-lucide":`rotate-cw`})}),a(`button`,{className:`tcp-icon-btn`,title:`Copy debug payload`,"aria-label":`Copy debug payload`,onClick:()=>void Ci(),children:a(`i`,{"data-lucide":`copy`})}),a(`button`,{className:`tcp-icon-btn`,title:`Open GitHub MCP guide`,"aria-label":`Open GitHub MCP guide`,onClick:()=>_e(!0),children:a(`i`,{"data-lucide":`book-open`})})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Reporter state`}),a(`button`,{type:`button`,className:`tcp-list-item text-left ${pt?`ring-1 ring-emerald-400/40`:``}`,onClick:()=>mt(e=>!e),children:[a(`div`,{className:`font-medium`,children:pt?Y?`Paused`:`Enabled`:`Disabled`}),a(`div`,{className:`tcp-subtle text-xs`,children:pt?Y?`Monitoring is paused. Resume to process new failures.`:`Failure events can be analyzed once readiness is green.`:`No reporter work will execute.`})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Local directory`}),a(`div`,{className:`rounded-xl border border-sky-500/20 bg-sky-500/10 p-3 text-xs text-sky-100`,children:[a(`div`,{className:`font-semibold`,children:`Hosted path map`}),a(`div`,{className:`mt-1 tcp-subtle`,children:[`Coder syncs source checkouts into `,a(`code`,{children:vb}),`. For Bug Monitor analysis, select the repo folder itself, usually`,` `,a(`code`,{children:vi}),`.`]}),a(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,type:`button`,onClick:()=>_t(vi),children:[a(`i`,{"data-lucide":`badge-check`}),`Use recommended path`]}),a(`button`,{className:`tcp-btn h-8 px-3 text-xs`,type:`button`,onClick:()=>{on(vb),cn(``),rn(!0)},children:[a(`i`,{"data-lucide":`folder-open`}),`Browse synced repos`]})]})]}),a(`div`,{className:`grid gap-2 md:grid-cols-[auto_1fr_auto]`,children:[a(`button`,{className:`tcp-btn`,type:`button`,onClick:()=>{on(String(gt||`/`).trim()||`/`),cn(``),rn(!0)},children:[a(`i`,{"data-lucide":`folder-open`}),`Browse`]}),a(`input`,{className:`tcp-input`,readOnly:!0,value:gt,placeholder:`No local directory selected. Use Browse.`}),a(`button`,{className:`tcp-btn`,type:`button`,onClick:()=>_t(``),disabled:!gt,children:[a(`i`,{"data-lucide":`x`}),`Clear`]})]}),a(`div`,{className:`tcp-subtle text-xs`,children:gt?`Reporter analysis root: ${gt}${yi?` (${yi})`:``}`:`Defaults to the engine workspace root if not set.`}),bi?a(`div`,{className:`rounded-xl border border-amber-500/25 bg-amber-500/10 p-3 text-xs text-amber-100`,children:[a(`div`,{className:`font-semibold`,children:`Setup check`}),a(`div`,{className:`mt-1`,children:bi})]}):a(`div`,{className:`rounded-xl border border-emerald-500/20 bg-emerald-500/10 p-3 text-xs text-emerald-100`,children:[a(`div`,{className:`font-semibold`,children:`Source checkout ready`}),a(`div`,{className:`mt-1`,children:`Bug Monitor triage will inspect this repo path and require concrete source-file reads before it marks research complete.`})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Target repo`}),a(`input`,{className:`tcp-input`,value:vt,onChange:e=>yt(e.target.value),placeholder:`owner/repo`})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`MCP server`}),a(`select`,{className:`tcp-input`,value:bt,onChange:e=>xt(e.target.value),children:[a(`option`,{value:``,children:`Select an MCP server`}),Gr.map(e=>a(`option`,{value:e.name,children:e.name},e.name))]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Provider preference`}),a(`select`,{className:`tcp-input`,value:St,onChange:e=>Ct(e.target.value),children:[a(`option`,{value:`auto`,children:`Auto`}),a(`option`,{value:`official_github`,children:`Official GitHub`}),a(`option`,{value:`composio`,children:`Composio`}),a(`option`,{value:`arcade`,children:`Arcade`})]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Provider`}),a(`select`,{className:`tcp-input`,value:wt,onChange:e=>{let t=e.target.value;Tt(t),Dt(``)},children:[a(`option`,{value:``,children:`Select a provider`}),Ur.map(e=>a(`option`,{value:String(e?.id||``),children:String(e?.id||``)},String(e?.id||``)))]})]}),a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`Model`}),a(`input`,{className:`tcp-input`,value:Et,onChange:e=>Dt(e.target.value),list:`bug-monitor-models`,disabled:!wt,placeholder:wt?`Type or paste a model id`:`Choose a provider first`,spellCheck:!1}),a(`datalist`,{id:`bug-monitor-models`,children:ci.map(e=>a(`option`,{value:e},e))}),a(`div`,{className:`tcp-subtle text-xs`,children:wt?ci.length?`${ci.length} suggested models from provider catalog`:`No provider catalog models available. Manual model ids are allowed.`:`Select a provider to load model suggestions.`})]}),a(`div`,{className:`grid gap-2 md:col-span-2`,children:[a(`span`,{className:`text-xs uppercase tracking-[0.24em] tcp-subtle`,children:`GitHub posting`}),a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`button`,{type:`button`,className:`tcp-list-item text-left ${Ot&&!At?`ring-1 ring-emerald-400/40`:``}`,onClick:()=>{kt(e=>!e),At&&Ot&&jt(!1)},children:[a(`div`,{className:`font-medium`,children:`Auto-create new issues`}),a(`div`,{className:`tcp-subtle text-xs`,children:Ot?`New drafts post to GitHub automatically.`:`New drafts stay internal until published manually.`})]}),a(`button`,{type:`button`,className:`tcp-list-item text-left ${At?`ring-1 ring-amber-400/40`:``}`,onClick:()=>{jt(e=>{let t=!e;return t&&kt(!1),t})},children:[a(`div`,{className:`font-medium`,children:`Require approval`}),a(`div`,{className:`tcp-subtle text-xs`,children:At?`New drafts wait for a manual publish click.`:`Approval gate disabled.`})]}),a(`button`,{type:`button`,className:`tcp-list-item text-left ${Mt?`ring-1 ring-sky-400/40`:``}`,onClick:()=>Nt(e=>!e),children:[a(`div`,{className:`font-medium`,children:`Auto-comment matches`}),a(`div`,{className:`tcp-subtle text-xs`,children:Mt?`Open matching GitHub issues receive new evidence comments.`:`Matching issues are detected but not updated automatically.`})]})]})]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn-primary`,disabled:tr.isPending,title:`Save Bug Monitor settings`,"aria-label":`Save Bug Monitor settings`,onClick:()=>tr.mutate(),children:[a(`i`,{"data-lucide":`save`}),tr.isPending?`Saving...`:null]}),a(`button`,{className:`tcp-icon-btn`,title:`Add MCP server`,"aria-label":`Add MCP server`,onClick:()=>Si(),children:a(`i`,{"data-lucide":`plus`})}),a(`button`,{className:`tcp-icon-btn`,title:`Open setup guide`,"aria-label":`Open setup guide`,onClick:()=>_e(!0),children:a(`i`,{"data-lucide":`external-link`})}),a(`button`,{className:`tcp-icon-btn`,title:`Refresh capability bindings`,"aria-label":`Refresh capability bindings`,disabled:nr.isPending,onClick:()=>nr.mutate(),children:a(`i`,{"data-lucide":`rotate-cw`})}),a(`button`,{className:`tcp-icon-btn`,title:`Copy debug payload`,"aria-label":`Copy debug payload`,onClick:()=>void Ci(),children:a(`i`,{"data-lucide":`copy`})}),oi?a(`button`,{className:`tcp-icon-btn`,title:oi.connected?`Refresh selected MCP`:`Connect selected MCP`,"aria-label":oi.connected?`Refresh selected MCP`:`Connect selected MCP`,disabled:Br.isPending,onClick:()=>Br.mutate({action:oi.connected?`refresh`:`connect`,server:oi}),children:a(`i`,{"data-lucide":oi.connected?`refresh-cw`:`plug-zap`})}):null]}),a(`div`,{className:`grid gap-3 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Readiness`}),a(`div`,{className:`mt-1 text-sm`,children:$r.runtime?.monitoring_active?$r.readiness?.publish_ready?`Monitoring`:`Watching locally`:$r.runtime?.paused||Y?`Paused`:$r.readiness?.ingest_ready?`Ready`:`Blocked`}),a(`div`,{className:`tcp-subtle text-xs`,children:$r.runtime?.last_runtime_error||$r.last_error||`No blocking issue reported.`}),!$r.readiness?.publish_ready&&Array.isArray($r.missing_required_capabilities)&&$r.missing_required_capabilities.length?a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Missing: `,$r.missing_required_capabilities.join(`, `)]}):null]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Selected MCP`}),a(`div`,{className:`mt-1 text-sm`,children:oi?.name||`None selected`}),a(`div`,{className:`tcp-subtle text-xs`,children:oi?oi.connected?`Connected`:`Disconnected`:`No server selected`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Bindings: `,$r.binding_source_version||`unknown version`,$r.bindings_last_merged_at_ms?` · merged ${new Date($r.bindings_last_merged_at_ms).toLocaleString()}`:``]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Local directory:`,` `,gt||String($r.config?.workspace_root||``).trim()||`engine workspace root`]}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Last event:`,` `,String($r.runtime?.last_incident_event_type||``).trim()||`No incidents processed yet`]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Model route`}),a(`div`,{className:`mt-1 break-all text-sm`,children:$r.selected_model?.provider_id&&$r.selected_model?.model_id?`${$r.selected_model.provider_id} / ${$r.selected_model.model_id}`:`No dedicated model selected`}),a(`div`,{className:`tcp-subtle text-xs`,children:$r.readiness?.selected_model_ready?`Available`:`Fail-closed when unavailable`}),a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`Last processed:`,` `,$r.runtime?.last_processed_at_ms?new Date(Number($r.runtime.last_processed_at_ms)).toLocaleString():`Not processed yet`]})]})]}),a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:`Capability readiness`}),a(`div`,{className:`tcp-subtle mt-2 grid gap-1 text-xs`,children:[a(`div`,{children:[`github.list_issues:`,` `,$r.required_capabilities?.github_list_issues?`ready`:`missing`]}),a(`div`,{children:[`github.get_issue:`,` `,$r.required_capabilities?.github_get_issue?`ready`:`missing`]}),a(`div`,{children:[`github.create_issue:`,` `,$r.required_capabilities?.github_create_issue?`ready`:`missing`]}),a(`div`,{children:[`github.comment_on_issue:`,` `,$r.required_capabilities?.github_comment_on_issue?`ready`:`missing`]})]}),Array.isArray($r.resolved_capabilities)&&$r.resolved_capabilities.length?a(`div`,{className:`tcp-subtle mt-3 grid gap-1 text-xs`,children:$r.resolved_capabilities.map((e,t)=>a(`div`,{children:[String(e.capability_id||`unknown`),`:`,` `,String(e.tool_name||`unresolved`)]},`${e.capability_id||`cap`}-${t}`))}):null,Array.isArray($r.selected_server_binding_candidates)&&$r.selected_server_binding_candidates.length?a(`div`,{className:`tcp-subtle mt-3 grid gap-1 text-xs`,children:$r.selected_server_binding_candidates.map((e,t)=>a(`div`,{children:[String(e.capability_id||`unknown`),`:`,` `,String(e.binding_tool_name||`unknown`),e.matched?` · matched`:` · candidate`]},`${e.capability_id||`candidate`}-${t}`))}):null,Array.isArray($r.discovered_mcp_tools)&&$r.discovered_mcp_tools.length?a(`div`,{className:`mt-3`,children:[a(`div`,{className:`tcp-subtle text-xs font-medium`,children:`Discovered MCP tools`}),a(`pre`,{className:`tcp-code mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs`,children:$r.discovered_mcp_tools.join(`
7379
+ `)})]}):a(`div`,{className:`tcp-subtle mt-3 text-xs`,children:`No MCP tools were discovered for the selected server.`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`font-medium`,children:`Posting policy`}),a(`div`,{className:`tcp-subtle mt-2 grid gap-1 text-xs`,children:[a(`div`,{children:[`New issues:`,` `,At?`Manual publish`:Ot?`Auto-create`:`Internal draft only`]}),a(`div`,{children:[`Matched open issues:`,` `,Mt?`Auto-comment`:`Detect only`]}),a(`div`,{children:`Dedupe: Fingerprint marker + label`}),a(`div`,{children:`Labels: bug-monitor`}),a(`div`,{children:`Workspace write tools: Disabled`}),a(`div`,{children:`Model fallback: Fail closed`})]})]})]}),a(cb,{projects:ei,watcher:ti,projectsJson:Pt,projectsJsonError:It,intakeKeys:ai,createdRawKey:Rt,isCreatingKey:rr.isPending,disablingKeyId:Bt,resettingSourceKey:Ht,replayingSourceKey:Wt,actionResult:Kt,onProjectsJsonChange:e=>{Ft(e);try{let t=JSON.parse(e||`[]`);Lt(Array.isArray(t)?``:`monitored_projects must be a JSON array`)}catch(e){Lt(e instanceof Error?e.message:`Invalid JSON`)}},onCreateKey:e=>rr.mutate(e),onDisableKey:e=>or.mutate(e),onClearCreatedRawKey:()=>zt(``),onResetSourceOffset:e=>sr.mutate(e),onReplayLatestSourceCandidate:e=>cr.mutate(e)}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Recent incidents`}),ri.length?a(`div`,{className:`grid gap-2`,children:ri.map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:e.title||e.event_type}),a(X,{tone:e.last_error?`warn`:`info`,children:e.status})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.event_type,` · seen`,` `,Number(e.occurrence_count||0),`x`,` · `,e.updated_at_ms?new Date(e.updated_at_ms).toLocaleString():`time unavailable`]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.workspace_root||`engine workspace root`}),e.last_error?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.last_error}):null,e.detail?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.detail}):null,a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-icon-btn`,title:`Replay triage for this incident`,"aria-label":`Replay triage for this incident`,disabled:gr.isPending,onClick:()=>gr.mutate({incidentId:e.incident_id}),children:a(`i`,{"data-lucide":`rotate-cw`})}),e.triage_run_id?a(`span`,{className:`tcp-subtle text-xs`,children:[`triage run: `,e.triage_run_id]}):null,e.draft_id?a(`span`,{className:`tcp-subtle text-xs`,children:[`draft: `,e.draft_id]}):null]})]},e.incident_id))}):a(Pr,{text:`No Bug Monitor incidents yet.`})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Recent reporter drafts`}),ni.length?a(`div`,{className:`grid gap-2`,children:ni.map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:e.title||e.fingerprint}),a(X,{tone:e.status===`approval_required`?`warn`:`info`,children:e.status})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.repo,` ·`,` `,e.issue_number?`issue #${e.issue_number}`:`draft only`,` `,`·`,` `,e.created_at_ms?new Date(e.created_at_ms).toLocaleString():`time unavailable`]}),e.github_status?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[`GitHub: `,e.github_status,e.matched_issue_number?` · matched #${e.matched_issue_number}${e.matched_issue_state?` (${e.matched_issue_state})`:``}`:``]}):null,e.detail?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.detail}):null,e.last_post_error?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.last_post_error}):null,e.triage_run_id?a(`div`,{className:`tcp-subtle mt-2 text-xs`,children:[`triage run: `,e.triage_run_id]}):null,e.status===`approval_required`?a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn-primary`,disabled:ur.isPending,title:`Approve draft`,"aria-label":`Approve draft`,onClick:()=>ur.mutate({draftId:e.draft_id,decision:`approve`}),children:[a(`i`,{"data-lucide":`check`}),ur.isPending?`Updating...`:null]}),a(`button`,{className:`tcp-icon-btn`,title:`Deny draft`,"aria-label":`Deny draft`,disabled:ur.isPending,onClick:()=>ur.mutate({draftId:e.draft_id,decision:`deny`}),children:a(`i`,{"data-lucide":`x`})})]}):null,e.issue_number?null:a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-icon-btn`,title:`Publish this draft to GitHub now`,"aria-label":`Publish this draft to GitHub now`,disabled:_r.isPending,onClick:()=>_r.mutate({draftId:e.draft_id}),children:a(`i`,{"data-lucide":`bug-play`})}),a(`button`,{className:`tcp-icon-btn`,title:`Recheck GitHub for an existing matching issue`,"aria-label":`Recheck GitHub for an existing matching issue`,disabled:vr.isPending,onClick:()=>vr.mutate({draftId:e.draft_id}),children:a(`i`,{"data-lucide":`refresh-cw`})})]}),(e.github_issue_url||e.github_comment_url)&&a(`div`,{className:`mt-3 flex flex-wrap gap-2 text-xs`,children:[e.github_issue_url?a(`a`,{className:`tcp-btn`,href:e.github_issue_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Open issue`]}):null,e.github_comment_url?a(`a`,{className:`tcp-btn`,href:e.github_comment_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`message-square`}),`Open comment`]}):null]}),(e.status===`draft_ready`||e.status===`triage_queued`)&&!e.triage_run_id?a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:a(`button`,{className:`tcp-icon-btn`,title:`Create triage run`,"aria-label":`Create triage run`,disabled:fr.isPending,onClick:()=>fr.mutate({draftId:e.draft_id}),children:a(`i`,{"data-lucide":`sparkles`})})}):null]},e.draft_id))}):a(Pr,{text:`No Bug Monitor drafts yet.`})]}),a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-900/20 p-3`,children:[a(`div`,{className:`mb-2 font-medium`,children:`Recent GitHub posts`}),ii.length?a(`div`,{className:`grid gap-2`,children:ii.map(e=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[a(`div`,{className:`font-medium`,children:e.operation}),a(X,{tone:e.status===`posted`?`ok`:`warn`,children:e.status})]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:[e.repo,e.issue_number?` · issue #${e.issue_number}`:``,e.updated_at_ms?` · ${new Date(e.updated_at_ms).toLocaleString()}`:``]}),e.error?a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.error}):null,a(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[e.issue_url?a(`a`,{className:`tcp-btn`,href:e.issue_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Open issue`]}):null,e.comment_url?a(`a`,{className:`tcp-btn`,href:e.comment_url,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`message-square`}),`Open comment`]}):null]})]},e.post_id))}):a(Pr,{text:`No GitHub post attempts yet.`})]})]})}):null,F===`maintenance`?a(dr,{title:`Managed worktree cleanup`,subtitle:`Scan repo-local .tandem/worktrees entries, keep live runtime worktrees, and remove stale or orphaned leftovers.`,actions:a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>{tn(null),xn.refetch()},children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh root`]}),a(`button`,{className:`tcp-btn`,onClick:()=>In.mutate({repoRoot:Jt.trim(),dryRun:!0}),disabled:In.isPending||!Jt.trim(),children:[a(`i`,{"data-lucide":`search`}),`Preview stale worktrees`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>In.mutate({repoRoot:Jt.trim(),dryRun:Xt}),disabled:In.isPending||!Jt.trim(),children:[a(`i`,{"data-lucide":`trash-2`}),In.isPending?`Cleaning up...`:Xt?`Run preview`:`Clean stale worktrees`]})]}),children:a(`div`,{className:`grid gap-4`,children:[a(`label`,{className:`grid gap-2`,children:[a(`span`,{className:`text-sm font-medium`,children:`Repository root`}),a(`input`,{className:`tcp-input`,value:Jt,onInput:e=>Yt(e.target.value),placeholder:`/absolute/path/to/repo`})]}),a(`label`,{className:`flex items-center gap-3 text-sm`,children:[a(`input`,{type:`checkbox`,checked:Xt,onChange:e=>Zt(e.target.checked)}),`Use dry run when clicking the primary action`]}),a(`div`,{className:`grid gap-3 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Detected workspace root`}),a(`div`,{className:`mt-1 break-all text-xs`,children:String(xn.data?.workspace_root||`Unavailable`)})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Cleanup target`}),a(`div`,{className:`mt-1 break-all text-xs`,children:en?.managed_root||`${Jt||`repo`}/.tandem/worktrees`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Host mode`}),a(`div`,{className:`mt-1 text-xs`,children:[wn?`Local engine`:`Remote engine`,` ·`,` `,Tn?`hosted-managed`:`self-managed`]})]})]}),In.isPending?a(s.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},className:`rounded-2xl border border-cyan-500/30 bg-cyan-500/10 px-4 py-3`,children:a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`text-sm font-medium`,children:`Cleanup running`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:Ti})]}),a(s.div,{className:`h-2 w-24 overflow-hidden rounded-full bg-slate-800`,initial:!1,children:a(s.div,{className:`h-full rounded-full bg-cyan-400`,animate:{x:[`-100%`,`120%`]},transition:{duration:1.2,repeat:1/0,ease:`easeInOut`}})})]})}):null,en?a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`grid gap-3 md:grid-cols-4`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Tracked active`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:en.active_paths?.length||0})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Stale candidates`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:en.stale_paths?.length||0})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Removed`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:(en.cleaned_worktrees?.length||0)+(en.orphan_dirs_removed?.length||0)})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Failures`}),a(`div`,{className:`mt-1 text-2xl font-semibold`,children:en.failures?.length||0})]})]}),a(`div`,{className:`rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{children:[a(`div`,{className:`font-medium`,children:en.dry_run?`Preview results`:`Cleanup log`}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:en.repo_root||Jt})]}),a(X,{tone:(en.failures?.length||0)>0?`warn`:en.dry_run?`info`:`ok`,children:en.dry_run?`Dry run`:`Applied`})]}),a(`div`,{className:`mt-3 grid gap-2`,children:[a(l,{initial:!1,children:Ei.map((e,t)=>a(s.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.18,delay:t*.03},className:`tcp-list-item`,children:a(`div`,{className:`flex items-start justify-between gap-3`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`text-sm font-medium break-all`,children:e.title}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:e.detail})]}),a(X,{tone:e.tone,children:e.kind===`orphan_removed`?`orphan`:e.kind.replaceAll(`_`,` `)})]})},`${e.kind}-${e.title}-${t}`))}),Ei.length?null:a(`div`,{className:`tcp-subtle text-xs`,children:`No stale managed worktrees were detected for this repository.`})]})]})]}):null,a(`div`,{className:`tcp-subtle text-xs`,children:[`This action only targets repo-local managed worktrees under`,` `,a(`code`,{children:`.tandem/worktrees`}),` and skips paths that the current Tandem process still tracks as active.`]})]})}):null,F===`browser`?a(dr,{title:`Browser readiness`,subtitle:`Operational browser status, diagnostics, and recovery actions.`,actions:a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>void jn.refetch(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh browser status`]}),a(`button`,{className:`tcp-btn`,onClick:()=>Pn.mutate(),disabled:Pn.isPending,children:[a(`i`,{"data-lucide":`download`}),Pn.isPending?`Installing sidecar...`:`Install sidecar`]}),a(`button`,{className:`tcp-btn`,onClick:()=>Fn.mutate(),disabled:Fn.isPending,children:[a(`i`,{"data-lucide":`globe`}),Fn.isPending?`Running smoke test...`:`Run smoke test`]}),a(`button`,{className:`tcp-btn`,onClick:()=>he(!0),children:[a(`i`,{"data-lucide":`activity`}),`Diagnostics`]})]}),children:[a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Status`}),a(`div`,{className:`mt-1 text-sm`,children:jn.data?jn.data.runnable?`Ready`:jn.data.enabled?`Blocked`:`Disabled`:`Unknown`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Headless default: `,jn.data?.headless_default?`yes`:`no`]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Sidecar`}),a(`div`,{className:`mt-1 break-all text-sm`,children:jn.data?.sidecar?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:jn.data?.sidecar?.version||`No version detected`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Browser`}),a(`div`,{className:`mt-1 break-all text-sm`,children:jn.data?.browser?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:jn.data?.browser?.version||jn.data?.browser?.channel||`No version detected`})]})]}),li.length?a(`div`,{className:`mt-3 grid gap-2`,children:li.map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:e.code||`browser_issue`}),a(`div`,{className:`tcp-subtle text-xs`,children:e.message||`Unknown browser issue.`})]},`${e.code||`issue`}-${t}`))}):null,Mn?a(`div`,{className:`mt-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm`,children:[a(`div`,{className:`font-medium`,children:[`Smoke test passed`,Mn.title?`: ${Mn.title}`:``]}),a(`div`,{className:`tcp-subtle mt-1 text-xs`,children:Mn.final_url||Mn.url||`No URL returned`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Load state: `,Mn.load_state||`unknown`,` · elements:`,` `,String(Mn.element_count??0),` · closed:`,` `,Mn.closed?`yes`:`no`]}),Mn.excerpt?a(`pre`,{className:`tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words`,children:Mn.excerpt}):null]}):null]}):null]})}),a(hr,{open:ge,onClose:()=>_e(!1),title:`Official GitHub MCP guide`,children:a(`div`,{className:`grid gap-3`,children:[a(`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.`}),a(`div`,{className:`grid gap-2 md:grid-cols-2`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Transport URL`}),a(`div`,{className:`mt-1 break-all text-sm`,children:`https://api.githubcopilot.com/mcp/`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Use this as the MCP server transport in Tandem Settings.`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Auth mode`}),a(`div`,{className:`mt-1 text-sm`,children:`Authorization Bearer`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Paste a GitHub token in the MCP server dialog and use bearer auth.`})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Recommended setup`}),a(`div`,{className:`tcp-list-item text-sm`,children:["1. Open `Add MCP server`.",a(`br`,{}),"2. Name it `github` or another stable name.",a(`br`,{}),"3. Set transport to `https://api.githubcopilot.com/mcp/`.",a(`br`,{}),"4. Set auth mode to `Authorization Bearer`.",a(`br`,{}),`5. Paste a GitHub Personal Access Token.`,a(`br`,{}),`6. Save, connect, then select that MCP server in Bug Monitor settings.`]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Token guidance`}),a(`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.`})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Direct links`}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(`a`,{className:`tcp-btn`,href:`https://github.com/github/github-mcp-server?tab=readme-ov-file`,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`GitHub MCP README`]}),a(`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:[a(`i`,{"data-lucide":`external-link`}),`GitHub Docs`]})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Issue tools to expect`}),a(`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.`})]})]})}),a(l,{children:nn?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-confirm-backdrop`,"aria-label":`Close Bug Monitor workspace dialog`,onClick:()=>{rn(!1),cn(``)}}),a(s.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:[a(`h3`,{className:`tcp-confirm-title`,children:`Select Bug Monitor Directory`}),a(`p`,{className:`tcp-confirm-message`,children:[`Current: `,_i||`n/a`]}),a(`div`,{className:`mb-3 rounded-xl border border-white/10 bg-black/20 p-3 text-xs`,children:[a(`div`,{className:`font-semibold text-slate-100`,children:`Where should I go?`}),a(`div`,{className:`tcp-subtle mt-1`,children:[`Hosted installs share Coder repositories at`,` `,a(`code`,{children:vb}),`. Choose the repo folder, for example`,` `,a(`code`,{children:vi}),`. The`,` `,a(`code`,{children:bb}),` folder is runtime state, not the source checkout.`]})]}),a(`div`,{className:`mb-2 flex flex-wrap gap-2`,children:[a(`button`,{className:`tcp-btn`,onClick:()=>{gi&&on(gi)},disabled:!gi,children:[a(`i`,{"data-lucide":`arrow-up-circle`}),`Up`]}),a(`button`,{className:`tcp-btn`,onClick:()=>{on(vb),cn(``)},children:[a(`i`,{"data-lucide":`folder-git-2`}),`Synced repos`]}),a(`button`,{className:`tcp-btn-primary`,onClick:()=>{_i&&(_t(_i),rn(!1),cn(``),n(`ok`,`Bug Monitor directory selected: ${_i}`))},children:[a(`i`,{"data-lucide":`badge-check`}),`Select This Folder`]}),a(`button`,{className:`tcp-btn`,onClick:()=>{rn(!1),cn(``)},children:[a(`i`,{"data-lucide":`x`}),`Close`]})]}),a(`div`,{className:`mb-2`,children:a(`input`,{className:`tcp-input`,placeholder:`Type to filter folders...`,value:sn,onInput:e=>cn(e.target.value)})}),a(`div`,{className:`max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2`,children:hi.length?hi.map(e=>{let t=String(e?.path||``),n=Cb(t);return a(`button`,{className:`tcp-list-item mb-1 w-full text-left`,onClick:()=>on(t),children:[a(`i`,{"data-lucide":`folder-open`}),a(`span`,{className:`min-w-0`,children:[a(`span`,{className:`block truncate`,children:String(e?.name||e?.path||``)}),n?a(`span`,{className:`tcp-subtle block text-xs`,children:n}):null]})]},String(e?.path||e?.name))}):a(Pr,{text:mi?`No folders match your search.`:`No subdirectories in this folder.`})})]})]}):null}),a(hr,{open:me,onClose:()=>he(!1),title:`Browser diagnostics`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`grid gap-2 md:grid-cols-3`,children:[a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Status`}),a(`div`,{className:`mt-1 text-sm`,children:jn.data?jn.data.runnable?`Ready`:jn.data.enabled?`Blocked`:`Disabled`:`Unknown`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Headless default: `,jn.data?.headless_default?`yes`:`no`]})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Sidecar`}),a(`div`,{className:`mt-1 break-all text-sm`,children:jn.data?.sidecar?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:jn.data?.sidecar?.version||`No version detected`})]}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:`Browser`}),a(`div`,{className:`mt-1 break-all text-sm`,children:jn.data?.browser?.path||`Not found`}),a(`div`,{className:`tcp-subtle text-xs`,children:jn.data?.browser?.version||jn.data?.browser?.channel||`No version detected`})]})]}),a(lr,{children:[a(`button`,{className:`tcp-btn`,onClick:()=>void jn.refetch(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh browser status`]}),a(`button`,{className:`tcp-btn`,onClick:()=>Pn.mutate(),disabled:Pn.isPending,children:[a(`i`,{"data-lucide":`download`}),Pn.isPending?`Installing sidecar...`:`Install sidecar`]}),a(`button`,{className:`tcp-btn`,onClick:()=>Fn.mutate(),disabled:Fn.isPending,children:[a(`i`,{"data-lucide":`globe`}),Fn.isPending?`Running smoke test...`:`Run smoke test`]}),a(`button`,{className:`tcp-btn`,onClick:()=>t(`/api/engine/browser/status`,{method:`GET`}).then(()=>n(`ok`,`Browser diagnostics refreshed.`)).catch(e=>n(`err`,e instanceof Error?e.message:String(e))),children:[a(`i`,{"data-lucide":`activity`}),`Re-run diagnostics`]})]}),jn.isLoading?a(Pr,{text:`Loading browser diagnostics...`}):jn.data?a(p,{children:[li.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Blocking issues`}),li.map((e,t)=>a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:e.code||`browser_issue`}),a(`div`,{className:`tcp-subtle text-xs`,children:e.message||`Unknown browser issue.`})]},`${e.code||`issue`}-${t}`))]}):a(`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.`}),Mn?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Latest smoke test`}),a(`div`,{className:`tcp-list-item`,children:[a(`div`,{className:`text-sm font-medium`,children:Mn.title||`Smoke test`}),a(`div`,{className:`tcp-subtle text-xs`,children:Mn.final_url||Mn.url||`No URL returned`}),a(`div`,{className:`tcp-subtle text-xs`,children:[`Load state: `,Mn.load_state||`unknown`,` · elements:`,` `,String(Mn.element_count??0),` · closed:`,` `,Mn.closed?`yes`:`no`]}),Mn.excerpt?a(`pre`,{className:`tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words`,children:Mn.excerpt}):null]})]}):null,ui.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Recommendations`}),ui.map((e,t)=>a(`div`,{className:`tcp-list-item text-sm`,children:e},`browser-recommendation-${t}`))]}):null,di.length?a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`text-sm font-medium`,children:`Install hints`}),di.map((e,t)=>a(`div`,{className:`tcp-list-item text-sm`,children:e},`browser-install-hint-${t}`))]}):null,jn.data?.last_error?a(`div`,{className:`tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-3 text-xs`,children:[`Last error: `,jn.data.last_error]}):null]}):a(Pr,{text:`Browser diagnostics are unavailable.`})]})}),a(l,{children:Ue?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-confirm-backdrop`,"aria-label":`Close MCP server dialog`,onClick:()=>We(!1)}),a(s.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:[a(`div`,{className:`mb-3 flex items-start justify-between gap-3`,children:[a(`div`,{children:[a(`h3`,{className:`tcp-confirm-title`,children:st?`Edit MCP Server`:`Add MCP Server`}),a(`p`,{className:`tcp-confirm-message`,children:`Configure transport and auth without leaving Settings.`})]}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-2`,onClick:()=>We(!1),children:a(`i`,{"data-lucide":`x`})})]}),a(`form`,{className:`flex min-h-0 flex-1 flex-col gap-3 overflow-hidden`,onSubmit:e=>{e.preventDefault(),Vr.mutate()},children:[a(`div`,{className:`tcp-settings-tabs`,children:[a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${lt===`catalog`?`active`:``}`,onClick:()=>ut(`catalog`),children:[a(`i`,{"data-lucide":`blocks`}),`Built-in packs`]}),a(`button`,{type:`button`,className:`tcp-settings-tab tcp-settings-tab-underline ${lt===`manual`?`active`:``}`,onClick:()=>ut(`manual`),children:[a(`i`,{"data-lucide":`square-pen`}),`Manual`]})]}),lt===`catalog`?a(`div`,{className:`grid min-h-0 flex-1 content-start gap-3 overflow-hidden`,children:[a(`div`,{className:`flex items-center justify-between gap-3`,children:[a(`div`,{className:`tcp-subtle text-sm`,children:qr.generatedAt?`Built-in MCP packs · generated ${qr.generatedAt}`:`Built-in MCP packs`}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>void zn.refetch(),children:[a(`i`,{"data-lucide":`refresh-cw`}),`Refresh`]})]}),a(`input`,{className:`tcp-input`,value:dt,onInput:e=>ft(e.target.value),placeholder:`Search built-in MCP packs`}),a(`div`,{className:`grid min-h-0 flex-1 auto-rows-max content-start gap-2 overflow-y-auto pr-1 md:grid-cols-2`,children:Zr.length?Zr.map(e=>{let t=Jr.has(String(e.serverConfigName||e.slug||``).toLowerCase());return a(`div`,{className:`tcp-list-item grid h-full min-h-[8.5rem] content-start gap-2`,children:[a(`div`,{className:`flex flex-wrap items-start justify-between gap-2`,children:[a(`div`,{children:[a(`div`,{className:`font-semibold`,children:e.name}),a(`div`,{className:`tcp-subtle text-xs`,children:[e.slug,e.requiresSetup?` · setup required`:``]})]}),a(`div`,{className:`flex flex-wrap gap-2`,children:[a(X,{tone:`info`,children:[e.toolCount,` tools`]}),e.authKind===`oauth`?a(X,{tone:`info`,children:`OAuth`}):a(X,{tone:e.requiresAuth?`warn`:`ok`,children:e.requiresAuth?`Auth`:`Authless`})]})]}),a(`div`,{className:`tcp-subtle line-clamp-2 text-xs`,children:e.description||e.transportUrl}),a(`div`,{className:`tcp-subtle break-all text-xs`,children:e.transportUrl}),e.authKind===`oauth`?a(`div`,{className:`rounded-xl border border-sky-700/40 bg-sky-950/20 px-3 py-2 text-xs text-sky-100`,children:`Save this pack to start browser sign-in. Tandem will keep the MCP in a pending state until the authorization completes.`}):null,a(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>{let t=e.transportUrl,r=Ib(e.serverConfigName||e.slug||e.name);Ke(r),Je(t),Xe(e.authKind===`oauth`?`oauth`:r===`github`||zb(t)?`bearer`:`none`),e.authKind===`oauth`&&Qe(``),nt(r===`github`||zb(t)?`default`:``),it([]),ut(`manual`),n(`ok`,e.authKind===`oauth`?`Loaded ${e.name}. Save to start browser sign-in.`:`Loaded ${e.name}. Review and save when ready.`)},children:`Use pack`}),e.documentationUrl?a(`a`,{className:`tcp-btn h-8 px-3 text-xs`,href:e.documentationUrl,target:`_blank`,rel:`noreferrer`,children:[a(`i`,{"data-lucide":`external-link`}),`Docs`]}):null,t?a(X,{tone:`ok`,children:`added`}):null]})]},e.slug)}):a(Pr,{text:`No built-in MCP packs match this search.`})})]}):a(p,{children:[a(`div`,{className:`grid gap-3 md:grid-cols-2`,children:[a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Name`}),a(`input`,{className:`tcp-input`,value:Ge,onInput:e=>Ke(e.target.value),placeholder:`mcp-server`})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Auth mode`}),a(`select`,{className:`tcp-select`,value:Ye,onChange:e=>{let t=e.target.value;Xe(t),t===`oauth`&&Qe(``)},children:[a(`option`,{value:`none`,children:`No Auth Header`}),a(`option`,{value:`auto`,children:`Auto`}),a(`option`,{value:`oauth`,children:`OAuth`}),a(`option`,{value:`x-api-key`,children:`x-api-key`}),a(`option`,{value:`bearer`,children:`Authorization Bearer`}),a(`option`,{value:`custom`,children:`Custom Header`})]})]})]}),a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Transport URL`}),a(`input`,{className:`tcp-input`,value:qe,onInput:e=>{let t=e.target.value;if(Je(t),zb(t)&&!String(tt||``).trim()&&nt(`default`),!String(Ge||``).trim()||Ge===`mcp-server`){let e=Lb(t);e&&Ke(e)}qb(qr,Ge,t)===`oauth`&&(Ye===`none`||Ye===`auto`)&&(Xe(`oauth`),Qe(``))},placeholder:`https://example.com/mcp`})]}),Ye===`custom`?a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Custom header name`}),a(`input`,{className:`tcp-input`,value:$e,onInput:e=>et(e.target.value),placeholder:`X-My-Token`})]}):null,Ye===`oauth`?a(`div`,{className:`grid gap-2 rounded-xl border border-sky-700/50 bg-sky-950/20 px-3 py-3 text-xs text-sky-100`,children:[a(`div`,{className:`font-medium`,children:`OAuth sign-in flow`}),a(`div`,{children:ki}),a(`div`,{className:`tcp-subtle text-xs text-sky-100/80`,children:Ai?`Saving this server will immediately start the browser handoff.`:"Turn on `Connect after save` to launch the authorization flow as soon as the server is saved."}),a(`div`,{className:`tcp-subtle text-xs text-sky-100/80`,children:Oi})]}):a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Token`}),a(`input`,{className:`tcp-input`,type:`password`,value:Ze,onInput:e=>Qe(e.target.value),placeholder:`token`}),a(`div`,{className:`tcp-subtle text-xs`,children:Oi})]}),ji?a(`div`,{className:`grid gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`GitHub toolsets`}),a(`input`,{className:`tcp-input`,value:tt,onInput:e=>nt(e.target.value),placeholder:`default,projects`}),a(`div`,{className:`tcp-subtle text-xs`,children:"Sent as `X-MCP-Toolsets`. Built-in GitHub starts with `default`; add values like `projects`, `issues`, or `pull_requests`."})]}):null,a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`flex items-center justify-between gap-2`,children:[a(`label`,{className:`text-sm font-medium`,children:`Additional headers`}),a(`button`,{type:`button`,className:`tcp-btn h-8 px-3 text-xs`,onClick:()=>it(e=>[...e,{key:``,value:``}]),children:[a(`i`,{"data-lucide":`plus`}),`Add header`]})]}),rt.length?a(`div`,{className:`grid gap-2`,children:rt.map((e,t)=>a(`div`,{className:`grid gap-2 md:grid-cols-[1fr_1fr_auto]`,children:[a(`input`,{className:`tcp-input`,value:e.key,onInput:e=>it(n=>n.map((n,r)=>r===t?{...n,key:e.target.value}:n)),placeholder:`Header name`}),a(`input`,{className:`tcp-input`,value:e.value,onInput:e=>it(n=>n.map((n,r)=>r===t?{...n,value:e.target.value}:n)),placeholder:`Header value`}),a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>it(e=>e.filter((e,n)=>n!==t)),children:`Remove`})]},`mcp-header-${t}`))}):a(`div`,{className:`tcp-subtle text-xs`,children:"Add arbitrary request headers such as `X-MCP-Insiders` or vendor feature flags."})]}),a(`label`,{className:`inline-flex items-center gap-2 text-sm text-slate-200`,children:[a(`input`,{type:`checkbox`,className:`accent-slate-400`,checked:at,onChange:e=>ot(e.target.checked)}),Ye===`oauth`?`Start sign-in after save`:`Connect after save`]})]}),a(`div`,{className:`tcp-confirm-actions mt-2`,children:[a(`button`,{type:`button`,className:`tcp-btn`,onClick:()=>We(!1),children:`Cancel`}),a(`button`,{type:`submit`,className:`tcp-btn-primary`,disabled:Vr.isPending,children:[a(`i`,{"data-lucide":`save`}),Ai?`Save MCP server and start sign-in`:`Save MCP server`]})]})]})]})]}):null})]})})}function yx({routeId:e,pageProps:t}){switch(Er(e)){case`chat`:return a(fa,{...t});case`planner`:return a(is,{...t});case`workflows`:return a(ls,{...t});case`marketplace`:return a(ds,{...t});case`studio`:return a(Xl,{...t});case`automations`:case`packs`:case`teams`:return a(ng,{...t});case`experiments`:return a(pg,{...t});case`coding`:return a(k_,{...t});case`agents`:return a(ib,{...t});case`channels`:return a(A_,{...t});case`mcp`:return a(vx,{...t});case`packs-detail`:return a(I_,{...t});case`orchestrator`:return a(uv,{...t});case`bug-monitor`:return a(zy,{...t});case`files`:return a(Vv,{...t});case`memory`:return a(Gv,{...t});case`teams-detail`:return a(ib,{...t});case`runs`:return a(Kv,{...t});case`approvals`:return a(Qv,{...t});case`settings`:return a(vx,{...t});default:return a(Wr,{...t})}}var bx={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.`},planner:{title:`Planner`,subtitle:`Advanced long-horizon intent, multi-agent planning, and governed handoff.`},studio:{title:`Studio`,subtitle:`Advanced template-first workflow builder with reusable role prompts and visual stages.`},automations:{title:`Automations`,subtitle:`Create, Calendar, Library, and Run History.`},experiments:{title:`Experiments`,subtitle:`Hidden by default. Turn this on in Settings when you need experimental surfaces.`},coding:{title:`Coder`,subtitle:`Durable coder runs, project intake, and repository work.`},agents:{title:`Agents`,subtitle:`Search reusable roles, inspect routines, and manage workflow-ready agent drafts.`},orchestrator:{title:`Task Board`,subtitle:`Plan-driven task execution with workspace visibility and approvals.`},memory:{title:`Memory`,subtitle:`Searchable memory records and operational context snapshots.`},runs:{title:`Runs`,subtitle:`Live operations overview with queue state and per-run inspection.`},approvals:{title:`Approvals Inbox`,subtitle:`Pending human approvals across every workflow that has paused on a gate.`},settings:{title:`Settings`,subtitle:`Provider defaults, identity, themes, and runtime diagnostics.`},channels:{title:`Channels`,subtitle:`Chat integrations, tool scope, and channel configuration.`},"bug-monitor":{title:`Bug Monitor`,subtitle:`Issue detection, draft review, and GitHub publishing controls.`},packs:{title:`Packs`,subtitle:`Starter packs and pack installation paths.`},teams:{title:`Teams`,subtitle:`Team instances, approvals, and shared execution state.`},mcp:{title:`MCP`,subtitle:`Catalog, readiness, and generated integration details.`},files:{title:`Files`,subtitle:`Managed uploads, artifacts, and exports.`},"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 xx({identity:e,currentRoute:t,providerLocked:n,navRoutes:i,onNavigate:c,onPaletteOpen:u,onThemeCycle:d,onLogout:f,statusBar:h,routeKey:g,navigationLock:_,children:v,providerGate:y}){let[b,x]=r(!1),S=String(e.botAvatarUrl||``).trim(),[C,w]=r(S?`custom`:`default`),T=Xn(),E=!!_;m(()=>{x(!1)},[t]),m(()=>{try{Yr()}catch{}},[i,t,b,h.bugMonitor?.enabled,h.bugMonitor?.monitoringActive,h.bugMonitor?.paused,h.bugMonitor?.pendingIncidents,h.bugMonitor?.blocked]),m(()=>{w(S?`custom`:`default`)},[S]);let D=bx[t]||{title:String(i.find(([e])=>e===t)?.[1]||`Control Panel`),subtitle:`Desktop-inspired operations UI for Tandem.`},O=o(()=>i.find(([e])=>e===t)||null,[t,i]),k=o(()=>{let e=h.bugMonitor;return e?.enabled?e.blocked?{toneClass:`blocked`,label:`Bug Monitor blocked`,shortLabel:`Blocked`}:e.paused?{toneClass:`paused`,label:`Bug Monitor paused`,shortLabel:`Paused`}:e.pendingIncidents>0?{toneClass:`incidents`,label:`Bug Monitor incidents: ${e.pendingIncidents}`,shortLabel:`${e.pendingIncidents} incident${e.pendingIncidents===1?``:`s`}`}:e.monitoringActive?{toneClass:`watching`,label:`Bug Monitor watching`,shortLabel:`Watching`}:{toneClass:`ready`,label:`Bug Monitor ready`,shortLabel:`Ready`}:null},[h.bugMonitor]),A=()=>C===`fallback`?a(`span`,{className:`text-sm font-semibold uppercase`,children:String(e.botName||`T`).trim().slice(0,1)||`T`}):a(`img`,{src:C===`custom`?S:`/icon.png`,alt:e.botName||`Tandem`,className:`block h-full w-full object-contain p-0.5`,onError:()=>w(e=>e===`custom`?`default`:`fallback`)}),j=()=>i.map(([e,r,i])=>{let o=t===e,l=n&&e!==`settings`||E;return a(`button`,{type:`button`,title:r,disabled:l,className:`tcp-rail-icon ${o?`active`:``} ${l?`locked`:``}`,onClick:()=>c(e),children:[o?a(s.span,{layoutId:`tcp-icon-indicator`,className:`tcp-rail-icon-indicator`}):null,a(`i`,{"data-lucide":i})]},e)}),M=(e=!1)=>i.map(([r,i,o])=>{let s=t===r,l=n&&r!==`settings`||E;return a(`button`,{type:`button`,disabled:l,className:`tcp-context-link ${s?`active`:``} ${l?`locked`:``}`,onClick:()=>{c(r),e&&x(!1)},children:[a(`span`,{className:`inline-flex items-center gap-2`,children:[a(`i`,{"data-lucide":o}),a(`span`,{children:i})]}),s?a(`span`,{className:`tcp-context-link-dot`}):null]},r)}),N=(t=!1)=>a(p,{children:[t?a(`div`,{className:`tcp-context-hero`,children:[a(rr,{className:`tcp-context-hero-glow`}),a(`div`,{className:`relative z-10 flex items-center gap-3`,children:[a(`div`,{className:`tcp-brand-avatar h-11 w-11`,children:A()}),a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:e.controlPanelName||`${e.botName} Control Panel`}),a(`div`,{className:`tcp-subtle text-xs`,children:`Workspace navigation and system status`})]})]})]}):null,a(`div`,{className:`tcp-context-section ${t?``:`xl:hidden`}`.trim(),children:[a(`div`,{className:`tcp-context-section-label`,children:`Navigation`}),a(`nav`,{className:`grid gap-1`,children:M(t)})]}),t?a(`div`,{className:`tcp-context-section`,children:[a(`div`,{className:`tcp-context-section-label`,children:`System`}),a(`div`,{className:`grid gap-2`,children:[a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Engine`}),h.engineHealthy?a(cr,{tone:`ok`,text:`healthy`}):a(cr,{tone:`warn`,text:`checking`})]}),a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Provider`}),a(`span`,{className:h.providerBadge,children:h.providerText})]}),a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Active runs`}),h.activeRuns>0?a(cr,{tone:`live`,text:String(h.activeRuns)}):a(`span`,{className:`tcp-badge tcp-badge-ghost`,children:`idle`})]}),k?a(`div`,{className:`tcp-context-stat`,children:[a(`span`,{className:`tcp-subtle text-xs`,children:`Bug Monitor`}),a(`button`,{type:`button`,className:`tcp-bug-monitor-pill ${k.toneClass}`,disabled:E,title:h.bugMonitor?.lastError?`${k.label}: ${h.bugMonitor.lastError}`:k.label,onClick:()=>{c(`bug-monitor`),t&&x(!1)},children:[a(`i`,{"data-lucide":`bug-play`}),a(`span`,{className:`tcp-bug-monitor-dot`,"aria-hidden":`true`}),a(`span`,{children:k.shortLabel})]})]}):null]})]}):null,a(`div`,{className:`tcp-context-section mt-auto`,children:[a(`div`,{className:`tcp-context-section-label`,children:`Actions`}),a(`div`,{className:`grid gap-2`,children:[a(`button`,{type:`button`,className:`tcp-btn w-full justify-start`,onClick:()=>{u(),t&&x(!1)},children:[a(`i`,{"data-lucide":`search`}),`Command palette`]}),a(`button`,{type:`button`,className:`tcp-btn w-full justify-start`,onClick:()=>{d(),t&&x(!1)},children:[a(`i`,{"data-lucide":`paint-bucket`}),`Cycle theme`]}),a(`button`,{type:`button`,className:`tcp-btn w-full justify-start`,onClick:()=>{f(),t&&x(!1)},children:[a(`i`,{"data-lucide":`log-out`}),`Logout`]})]})]})]});return a(`div`,{className:`tcp-shell ${t===`chat`?`tcp-shell-chat`:``}`.trim(),children:[a(rr,{className:`tcp-shell-background`,children:[a(`div`,{className:`tcp-shell-glow tcp-shell-glow-a`}),a(`div`,{className:`tcp-shell-glow tcp-shell-glow-b`})]}),a(`aside`,{className:`tcp-icon-rail hidden xl:flex`,children:[a(`button`,{type:`button`,className:`tcp-rail-brand`,disabled:E,onClick:()=>c(`dashboard`),children:a(`div`,{className:`tcp-brand-avatar h-10 w-10`,children:A()})}),a(`nav`,{className:`tcp-rail-nav`,children:j()}),a(`div`,{className:`tcp-rail-footer`,children:[a(ur,{title:`Command palette`,onClick:u,disabled:E,children:a(`i`,{"data-lucide":`search`})}),a(ur,{title:`Cycle theme`,onClick:d,disabled:E,children:a(`i`,{"data-lucide":`paint-bucket`})}),a(ur,{title:`Logout`,onClick:f,disabled:E,children:a(`i`,{"data-lucide":`log-out`})}),a(`div`,{className:`mt-2 flex justify-center`,children:h.engineHealthy?a(cr,{tone:`ok`}):a(cr,{tone:`warn`})})]})]}),a(`aside`,{className:`tcp-context-rail hidden lg:flex xl:hidden`,children:N(!1)}),a(`main`,{className:`tcp-main-shell ${t===`chat`?`tcp-main-shell-fill`:``}`.trim(),children:[a(`section`,{className:`tcp-mobile-topbar lg:hidden`,children:[a(`button`,{type:`button`,className:`tcp-btn h-10 px-3`,disabled:E,onClick:()=>x(!0),children:[a(`i`,{"data-lucide":`menu`}),`Menu`]}),a(`div`,{className:`min-w-0 flex-1`,children:[a(`div`,{className:`truncate text-sm font-semibold`,children:D.title}),a(`div`,{className:`tcp-subtle truncate text-xs`,children:O?.[1]||D.subtitle})]}),k?a(`button`,{type:`button`,className:`tcp-bug-monitor-pill ${k.toneClass}`,disabled:E,title:h.bugMonitor?.lastError?`${k.label}: ${h.bugMonitor.lastError}`:k.label,onClick:()=>c(`bug-monitor`),children:[a(`i`,{"data-lucide":`bug-play`}),a(`span`,{className:`tcp-bug-monitor-dot`,"aria-hidden":`true`})]}):null,h.activeRuns>0?a(cr,{tone:`live`,text:String(h.activeRuns)}):null]}),a(`section`,{className:`tcp-topbar`,children:[a(`div`,{className:`min-w-0`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Tandem Control`}),a(`h1`,{className:`tcp-main-title`,children:D.title}),a(`p`,{className:`tcp-subtle mt-1 line-clamp-2`,children:D.subtitle})]}),a(`div`,{className:`tcp-topbar-status`,children:[k?a(`button`,{type:`button`,className:`tcp-bug-monitor-pill ${k.toneClass}`,disabled:E,title:h.bugMonitor?.lastError?`${k.label}: ${h.bugMonitor.lastError}`:k.label,onClick:()=>c(`bug-monitor`),children:[a(`i`,{"data-lucide":`bug-play`}),a(`span`,{className:`tcp-bug-monitor-dot`,"aria-hidden":`true`}),a(`span`,{children:k.shortLabel})]}):null,a(`span`,{className:h.providerBadge,children:h.providerText}),h.engineHealthy?a(cr,{tone:`ok`,text:`Engine healthy`}):a(cr,{tone:`warn`,text:`Checking engine`}),h.activeRuns>0?a(cr,{tone:`live`,text:`${h.activeRuns} run`}):a(`span`,{className:`tcp-badge tcp-badge-ghost`,children:`No active runs`})]})]}),a(l,{mode:`wait`,children:a(s.section,{className:`tcp-main-content ${t===`chat`||t===`automations`?`tcp-main-content-fill`:``}`.trim(),initial:T?!1:{opacity:0,y:18},animate:T?void 0:{opacity:1,y:0},exit:T?void 0:{opacity:0,y:-14},transition:T?void 0:{duration:Kn.duration.normal,ease:Kn.easing.standard},children:v},g)})]}),a(l,{children:b?a(s.div,{className:`tcp-mobile-drawer lg:hidden`,initial:T?!1:{opacity:0},animate:T?void 0:{opacity:1},exit:T?void 0:{opacity:0},children:[a(`button`,{type:`button`,className:`tcp-mobile-drawer-backdrop`,"aria-label":`Close navigation`,onClick:()=>x(!1)}),a(s.aside,{className:`tcp-mobile-drawer-panel`,initial:T?!1:{x:`-100%`},animate:T?void 0:{x:0},exit:T?void 0:{x:`-100%`},transition:T?void 0:Kn.spring.drawer,children:[a(`div`,{className:`mb-3 flex items-center justify-between`,children:[a(`div`,{children:[a(`div`,{className:`text-sm font-semibold`,children:e.botName}),a(`div`,{className:`tcp-subtle text-xs`,children:D.title})]}),a(ur,{title:`Close`,onClick:()=>x(!1),children:a(`i`,{"data-lucide":`x`})})]}),N(!0)]})]}):null}),a(l,{children:y||null}),a(l,{children:_?a(s.div,{className:`tcp-confirm-overlay`,style:{zIndex:180},initial:T?!1:{opacity:0},animate:T?void 0:{opacity:1},exit:T?void 0:{opacity:0},children:[a(`div`,{className:`tcp-confirm-backdrop`,"aria-hidden":`true`}),a(s.div,{className:`tcp-confirm-dialog w-[min(36rem,calc(100vw-2rem))]`,role:`alertdialog`,"aria-live":`assertive`,initial:T?!1:{opacity:0,y:10,scale:.985},animate:T?void 0:{opacity:1,y:0,scale:1},exit:T?void 0:{opacity:0,y:6,scale:.985},transition:T?void 0:{duration:Kn.duration.normal,ease:Kn.easing.standard},children:a(`div`,{className:`flex items-center gap-3`,children:[a(vo,{className:`h-12 w-12 shrink-0`,mode:`compact`}),a(`div`,{className:`min-w-0`,children:[a(`h3`,{className:`tcp-confirm-title`,children:_.title}),a(`p`,{className:`tcp-confirm-message`,children:_.message})]})]})})]}):null})]})}function Sx(e){let t=String(e||``).trim().toLowerCase();return!!t&&t!==`ollama`&&t!==`llama_cpp`&&t!==`llama.cpp`&&t!==`local`&&t!==`openai-codex`}function Cx(e){if(!e||typeof e!=`object`)return!1;let t=String(e.auth_kind||e.authKind||``).trim().toLowerCase(),n=String(e.status||``).trim().toLowerCase();return t!==`oauth`||n===`reauth_required`||n===`expired`||n===`error`?!1:e.connected===!0||n===`connected`||n===`configured`}function wx(e,t){let n=String(t||``).trim().toLowerCase();if(!n||!e||typeof e!=`object`)return!1;let r=e=>!e||typeof e!=`object`?!1:!!(Cx(e)||e.has_key===!0||e.hasKey===!0||e.configured===!0&&!Sx(n));return r(e[n])||r(e.providers?.[n])}function Tx(e,t){let n=String(t||``).trim().toLowerCase();if(!n||!e||typeof e!=`object`)return null;let r=e[n];if(r&&typeof r==`object`)return r;let i=e.providers?.[n];return i&&typeof i==`object`?i:null}function Ex(e,t,n){let r=String(e?.default||e?.selected_model?.provider_id||``).trim(),i=e?.providers?.[r]||{},a=String(i.default_model||i.defaultModel||e?.selected_model?.model_id||``).trim(),o=new Set,s=e=>{if(!e||typeof e!=`object`)return;let t=e.providers&&typeof e.providers==`object`?e.providers:e;if(!(!t||typeof t!=`object`))for(let[e,n]of Object.entries(t)){if(!n||typeof n!=`object`)continue;let t=String(e||``).trim().toLowerCase();if(!t)continue;let r=String(n.status||n.statusText||``).trim().toLowerCase();(n.connected===!0||r===`connected`||r===`configured`)&&o.add(t)}};if(Array.isArray(t?.connected))for(let e of t.connected){let t=String(e||``).trim().toLowerCase();t&&o.add(t)}s(n);let c=Tx(n,r),l=wx(n,r),u=!!r&&!!a&&(!Sx(r)||l);return{ready:u,defaultProvider:r,defaultModel:a,connected:[...o],error:``,needsOnboarding:!u,defaultProviderAuthKind:String(c?.auth_kind||c?.authKind||``).trim().toLowerCase(),defaultProviderSource:String(c?.source||``).trim().toLowerCase(),defaultProviderManagedBy:String(c?.managed_by||c?.managedBy||``).trim().toLowerCase()}}var Dx=`tandem_control_panel_token`,Ox=new Set([`packs`,`teams`,`channels`,`mcp`,`files`,`packs-detail`,`teams-detail`]);function kx(){try{return localStorage.getItem(Dx)||``}catch{return``}}function Ax(e){try{localStorage.setItem(Dx,e)}catch{}}function jx(){try{localStorage.removeItem(Dx)}catch{}}function Mx(e,t){return y({queryKey:[`provider`,`status`],enabled:t&&!!e,refetchInterval:t?15e3:!1,queryFn:async()=>{if(!e)return{ready:!1,defaultProvider:``,defaultModel:``,connected:[],error:``,needsOnboarding:!1,defaultProviderAuthKind:``,defaultProviderSource:``,defaultProviderManagedBy:``};try{let[t,n]=await Promise.all([e.providers.config(),e.providers.authStatus().catch(()=>({}))]);return Ex(t,null,n)}catch(e){return{ready:!1,defaultProvider:``,defaultModel:``,connected:[],error:e instanceof Error?e.message:String(e),needsOnboarding:!1,defaultProviderAuthKind:``,defaultProviderSource:``,defaultProviderManagedBy:``}}}})}function Nx(e,t){return y({queryKey:[`identity`],enabled:t&&!!e,refetchInterval:t?3e4:!1,queryFn:async()=>{if(!e)return{botName:`Tandem`,botAvatarUrl:``,controlPanelName:`Tandem Control Panel`};try{let e=(await Tc(`/api/engine/config/identity`,{method:`GET`}))?.identity||{},t=String(e?.bot?.canonical_name||e?.bot?.canonicalName||``).trim(),n=e?.bot?.aliases||{},r=String(e?.bot?.avatar_url||e?.bot?.avatarUrl||``).trim(),i=String(n?.control_panel||n?.controlPanel||``).trim(),a=t||`Tandem`;return{botName:a,botAvatarUrl:r,controlPanelName:i||`${a} Control Panel`}}catch{return{botName:`Tandem`,botAvatarUrl:``,controlPanelName:`Tandem Control Panel`}}}})}function Px(e){return y({queryKey:[`bug-monitor`,`status`],enabled:e,refetchInterval:e?1e4:!1,queryFn:async()=>{try{return await Tc(`/api/engine/bug-monitor/status`,{method:`GET`})}catch{return null}}})}function Fx({controlPanelName:e,controlPanelMode:t,controlPanelModeReason:n,errorMessage:i,onRetry:o,onCheckEngine:s}){let[c,l]=r(``),[u,d]=r(!1);return a(`main`,{className:`relative min-h-screen overflow-hidden px-5 py-8`,children:[a(rr,{className:`tcp-shell-background`,children:[a(`div`,{className:`tcp-shell-glow tcp-shell-glow-a`}),a(`div`,{className:`tcp-shell-glow tcp-shell-glow-b`})]}),a(`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:[a(`section`,{className:`grid gap-4`,children:[a(`div`,{className:`tcp-page-eyebrow`,children:`Tandem Control`}),a(`h1`,{className:`tcp-page-title max-w-3xl`,children:`Reconnecting your session.`}),a(`p`,{className:`tcp-subtle max-w-2xl text-base`,children:`The control panel still has your session, but the engine is temporarily unavailable. We'll reconnect automatically as soon as it responds again.`})]}),a(dr,{title:e,subtitle:t===`aca`?`ACA install detected. Waiting for the Tandem engine to restore the existing session.`:`Standalone install detected. Waiting for the Tandem engine to restore the existing session.`,children:a(`div`,{className:`grid gap-3`,children:[a(`div`,{className:`rounded-xl border border-slate-700/60 bg-slate-950/30 p-3`,children:[a(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[a(`div`,{className:`font-medium`,children:`Session recovery`}),a(cr,{tone:u?`ok`:`warn`,text:u?`Engine reachable`:`Reconnecting`})]}),a(`p`,{className:`tcp-subtle text-xs`,children:`Existing auth is intact. The panel is waiting for the engine before reloading the app shell.`}),n?a(`p`,{className:`tcp-subtle mt-2 text-xs`,children:n}):null]}),a(`div`,{className:`grid gap-2 sm:grid-cols-2`,children:[a(`button`,{type:`button`,className:`tcp-btn-primary w-full`,onClick:o,children:[a(`i`,{"data-lucide":`refresh-cw`}),`Retry now`]}),a(`button`,{type:`button`,className:`tcp-btn w-full`,onClick:async()=>{try{let e=await s();d(!0),l(e)}catch(e){d(!1),l(e instanceof Error?e.message:String(e))}},children:[a(`i`,{"data-lucide":`activity`}),`Check engine`]})]}),a(`div`,{className:`min-h-[1.2rem] text-sm ${u?`text-lime-300`:`text-amber-200`}`,children:c||i})]})})]})]})}function Ix(){let e=_(),{toast:t}=Mr(),[n,i]=r(Qn()),[l,u]=r(!1),[d,f]=r(null),[g,v]=r(!1),b=c(!1),S=c(null);S.current===null&&(S.current=kx().trim());let[C,w]=r(()=>!!S.current),{route:T,navigate:E}=kr({canNavigate:h((e,t)=>!d||e===t,[d])});m(()=>{$n(n)},[n]);let D=y({queryKey:[`auth`,`me`],enabled:!C,retry:(e,t)=>wc(t)&&e<4,retryDelay:e=>Math.min(1e3*2**e,5e3),refetchInterval:e=>wc(e.state.error)?5e3:e.state.data?3e4:!1,refetchOnWindowFocus:!0,queryFn:()=>Tc(`/api/auth/me`,{method:`GET`,cache:`no-store`})}),O=wc(D.error),k=D.data?.ok===!0,A=o(()=>k?new gn({baseUrl:`/api/engine`,token:`session`}):null,[k]),j=Mx(A,k),M=Nx(A,k),N=Ec(k),P=Dc(k),F=Px(k),I=Oc(),L=String(I.data?.control_panel_mode||(I.data?.aca_integration?`aca`:`standalone`)).trim()||`standalone`,R=L===`aca`,z=c(!1),[ee,B]=r(()=>hb(!1));m(()=>{!k||!I.isFetched||z.current||(z.current=!0,B(hb(R)))},[R,k,I.isFetched]),m(()=>{z.current&&gb(ee)},[ee]),m(()=>{try{Yr()}catch{}},[k,ee,T]),m(()=>{d&&T!==`automations`&&f(null)},[d,T]),m(()=>{d&&u(!1)},[d]),m(()=>{if(!d)return;let e=e=>(e.preventDefault(),e.returnValue=``,``);return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[d]);let V=x({mutationFn:async({token:e})=>{await Tc(`/api/auth/login`,{method:`POST`,body:JSON.stringify({token:e})})},onSuccess:(n,r)=>{r.remember?Ax(r.token):jx(),e.invalidateQueries({queryKey:[`auth`,`me`]}),t(`ok`,`Signed in.`),E(`dashboard`)},onError:e=>{let n=e instanceof Error?e.message:String(e);t(wc(e)?`info`:`err`,n)}});m(()=>{if(C||k||O||V.isPending||b.current)return;let e=kx().trim();if(!e){b.current=!0;return}b.current=!0,V.mutate({token:e,remember:!0})},[C,O,k,V]),m(()=>{if(!C||V.isPending)return;let e=S.current||``;if(b.current=!0,!e){w(!1);return}V.mutate({token:e,remember:!0},{onError:()=>{jx(),S.current=``},onSettled:()=>{w(!1)}})},[C,V]);let H=h(async()=>{await Tc(`/api/auth/logout`,{method:`POST`}).catch(()=>{}),e.removeQueries({queryKey:[`auth`]}),e.removeQueries({queryKey:[`control-panel`]}),e.removeQueries({queryKey:[`provider`]}),e.removeQueries({queryKey:[`identity`]}),e.invalidateQueries({queryKey:[`auth`,`me`]}),t(`info`,`Logged out.`)},[e,t]),te=o(()=>new Set([`chat`,`planner`,`studio`,`agents`,`orchestrator`,`teams`,`experiments`]),[]),U=!!j.data?.needsOnboarding,ne=k&&U;m(()=>{if(!ne){v(!1);return}te.has(T)&&(E(`settings`),g||(v(!0),t(`info`,`Set provider + default model in Providers first to unlock the control panel.`)))},[te,E,g,ne,T,t]);let re=ne&&te.has(T)?`settings`:T,ie=h(async()=>{await e.invalidateQueries({queryKey:[`provider`,`status`]})},[e]),ae=h(async()=>{await e.invalidateQueries({queryKey:[`identity`]})},[e]),W=h((e,t)=>{B(n=>{let r=R&&fb.has(e),i={...n,[e]:r?!0:t};return i[e]===n[e]?n:i})},[R]),oe=h(()=>{B(e=>{let t={...e};for(let[e]of Cr)t[e]=!0;return t})},[]),se=h(()=>{B(pb(R))},[R]),ce=o(()=>_b(ee),[ee]),le=o(()=>({acaMode:R,routeVisibility:ee,setRouteVisibility:W,showAllSections:oe,resetNavigation:se}),[R,ee,se,W,oe]),ue=h(e=>{let t=er(e);return i(t.id),t},[i]),de=M.data||{botName:`Tandem`,botAvatarUrl:``,controlPanelName:`Tandem Control Panel`},fe={client:A,api:Tc,toast:t,navigate:E,currentRoute:re,providerStatus:{ready:!!j.data?.ready,defaultProvider:j.data?.defaultProvider||``,defaultModel:j.data?.defaultModel||``,connected:j.data?.connected||[],error:j.data?.error||``,needsOnboarding:!!j.data?.needsOnboarding,defaultProviderAuthKind:j.data?.defaultProviderAuthKind||``,defaultProviderSource:j.data?.defaultProviderSource||``,defaultProviderManagedBy:j.data?.defaultProviderManagedBy||``},identity:de,refreshProviderStatus:ie,refreshIdentityStatus:ae,providerHints:xr,themes:Gn,setTheme:ue,themeId:n,navigation:le,navigationLock:d,setNavigationLock:f},pe=o(()=>{let e=Sr.filter(([e])=>ee[e]!==!1&&!Ox.has(e)).map(([e,t])=>({id:`route:${e}`,label:`Go to ${t}`,group:`Routes`,onSelect:()=>E(e)})),n=[{id:`action:new-chat`,label:`New chat session`,group:`Actions`,onSelect:()=>{window.dispatchEvent(new CustomEvent(`tcp:new-chat`)),E(`chat`)}},{id:`action:start-engine-check`,label:`Check engine health`,group:`Actions`,onSelect:async()=>{try{let e=await Tc(`/api/system/health`);t(`info`,`Engine ${e?.engine?.ready||e?.engine?.healthy?`healthy`:`unhealthy`}: ${e?.engineUrl||`n/a`}`)}catch(e){let n=e instanceof Error?e.message:String(e);t(wc(e)?`info`:`err`,n)}}},{id:`action:open-settings`,label:`Open provider settings`,group:`Actions`,onSelect:()=>E(`settings`)},...ee.orchestrator===!1?[]:[{id:`action:open-task-board`,label:`Open task board`,group:`Actions`,onSelect:()=>E(`orchestrator`)}]];return[...e,...n]},[ee,E,t]);if(_r(()=>{d||u(e=>!e)}),!k)return O?a(Fx,{controlPanelName:de.controlPanelName,controlPanelMode:L,controlPanelModeReason:String(I.data?.control_panel_mode_reason||``).trim(),errorMessage:D.error?.message||`Engine is reconnecting.`,onRetry:()=>{D.refetch()},onCheckEngine:async()=>{let e=await Tc(`/api/system/health`,{cache:`no-store`});return`Engine check: ${e?.engine?.ready||e?.engine?.healthy?`healthy`:`unhealthy`} at ${e?.engineUrl||`n/a`}`}}):a(gr,{loginMutation:V,savedToken:kx(),controlPanelName:de.controlPanelName,controlPanelMode:L,controlPanelModeReason:String(I.data?.control_panel_mode_reason||``).trim(),onCheckEngine:async()=>{let e=await Tc(`/api/system/health`);return`Engine check: ${e?.engine?.ready||e?.engine?.healthy?`healthy`:`unhealthy`} at ${e?.engineUrl||`n/a`}`}});let G=j.data?.ready?`tcp-badge-ok`:`tcp-badge-warn`,K=j.data?.ready?`${j.data?.defaultProvider||`none`}/${j.data?.defaultModel||`none`}`:`provider setup required`,me=F.data||null,he=me?.status||me||null,ge=!!he?.config?.enabled,_e=Number(he?.runtime?.pending_incidents||0),ve=!!he?.runtime?.monitoring_active,ye=!!he?.runtime?.paused,be=!!he?.readiness?.ingest_ready,xe=!!he?.readiness?.publish_ready,Se=String(he?.runtime?.last_runtime_error||he?.last_error||``).trim();return a(p,{children:[a(xx,{identity:de,currentRoute:re,providerLocked:ne,navRoutes:ce,onNavigate:E,onPaletteOpen:()=>u(!0),onThemeCycle:()=>ue(Jn(n)),onLogout:H,navigationLock:d,statusBar:{engineHealthy:!!(N.data?.engine?.ready||N.data?.engine?.healthy),providerBadge:G,providerText:K,activeRuns:+!![`planning`,`awaiting_approval`,`running`].includes(String(P.data?.status||``).toLowerCase()),bugMonitor:ge?{enabled:!0,monitoringActive:ve,paused:ye,pendingIncidents:_e,blocked:!be,lastError:ve&&!xe&&Se?`Watching locally only. ${Se}`:Se}:null},routeKey:re,providerGate:ne&&re!==`settings`?a(s.div,{className:`tcp-confirm-overlay`,initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:a(s.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:[a(`h3`,{className:`tcp-confirm-title`,children:`Provider Setup Required`}),a(`p`,{className:`tcp-confirm-message`,children:`Configure provider and default model in Providers to unlock all sections.`}),a(`div`,{className:`tcp-confirm-actions`,children:a(`button`,{className:`tcp-btn-primary`,onClick:()=>E(`settings`),children:`Open Providers`})})]})}):null,children:a(yx,{routeId:re,pageProps:fe})}),a(vr,{open:l,onClose:()=>u(!1),actions:pe})]})}function Lx(){return a(jr,{children:a(Ix,{})})}var Rx=new ot({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),zx=document.getElementById(`app`);if(!zx)throw Error(`Missing #app host`);g(zx).render(a(u,{children:a(v,{client:Rx,children:a(Lx,{})})}));