@frumu/tandem-panel 0.4.11 → 0.4.13
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,10 +1,10 @@
|
|
|
1
|
-
import{u as e,d as w,A as
|
|
2
|
-
`);E=O.pop()??"";let k="";for(const z of O)if(z.startsWith("data:"))k+=z.slice(5).trimStart();else if(z===""&&k){const A=Ml(k);A&&(yield A),k=""}}}finally{N.releaseLock()}}function $l(a){const t=new AbortController;for(const n of a){if(n.aborted){t.abort(n.reason);break}n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}const da=a=>typeof a=="string"&&a.trim().length>0?a:null,Ol=a=>{try{const t=as.parse(a);if(t)return t}catch{const t=a.run||null;if(t)try{const n=as.parse(t);if(n)return n}catch{}}throw new Error("Run ID missing in engine response")};class El{constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.timeoutMs=t.timeoutMs??2e4;const n=this._request.bind(this);this.sessions=new Bl(this.baseUrl,this.token,this.timeoutMs,n),this.permissions=new Fl(n),this.questions=new Kl(n),this.providers=new Ll(n),this.identity=new Wl(n),this.channels=new zl(n),this.mcp=new Jl(n,this._requestText.bind(this));const r=()=>this.token;this.routines=new Zl(this.baseUrl,r,n),this.automations=new tc(this.baseUrl,r,n),this.automationsV2=new ac(this.baseUrl,r,n),this.optimizations=new nc(n),this.workflowPlans=new ec(n),this.memory=new Ql(n),this.skills=new Gl(n),this.packs=new Hl(n),this.capabilities=new Vl(n),this.resources=new Yl(this.baseUrl,r,n),this.browser=new Dl(n),this.workflows=new jl(this.baseUrl,r,n),this.bugMonitor=new Ul(n),this.coder=new Xl(n),this.agentTeams=new rc(n),this.missions=new sc(n)}setToken(t){this.token=t,this.sessions.setToken(t)}async health(){const t=await this._request("/global/health");return Ft(wl,t,"/global/health",200)}async listToolIds(){return this._request("/tool/ids")}async listTools(){const t=await this._request("/tool");return Array.isArray(t)?t:[]}async executeTool(t,n){return this._request("/tool/execute",{method:"POST",body:JSON.stringify({tool:t,args:n??{}})})}stream(t,n,r){const s=new URLSearchParams({sessionID:t});n&&s.set("runID",n);const c=`${this.baseUrl}/event?${s.toString()}`;return tn(c,this.token,r)}globalStream(t){const n=`${this.baseUrl}/global/event`;return tn(n,this.token,t)}async runEvents(t,n){const r=new URLSearchParams;n?.sinceSeq!==void 0&&r.set("since_seq",String(n.sinceSeq)),n?.tail!==void 0&&r.set("tail",String(n.tail));const s=r.toString()?`?${r.toString()}`:"",c=await this._request(`/run/${encodeURIComponent(t)}/events${s}`);return Array.isArray(c)?c:[]}async _request(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let c;try{c=await fetch(`${this.baseUrl}${t}`,{...n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(c.status!==204){if(!c.ok){const d=await c.text().catch(()=>"");throw new Error(`Request failed (${c.status} ${c.statusText}): ${d}`)}return c.json()}}async _requestText(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let c;try{c=await fetch(`${this.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(!c.ok){const d=await c.text().catch(()=>"");throw new Error(`Request failed (${c.status} ${c.statusText}): ${d}`)}return c.text()}}class Dl{constructor(t){this.req=t}async status(){return this.req("/browser/status")}async install(){return this.req("/browser/install",{method:"POST"})}async smokeTest(t){return this.req("/browser/smoke-test",{method:"POST",body:JSON.stringify(t??{})})}}class jl{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){const n=await this.req("/workflows")??{},r=Array.isArray(n.workflows)?n.workflows:[];return{workflows:r,count:typeof n.count=="number"?n.count:r.length}}async get(t){return(await this.req(`/workflows/${encodeURIComponent(t)}`)).workflow??{}}async validate(t){return this.req("/workflows/validate",{method:"POST",body:JSON.stringify(t??{})})}async simulate(t){return this.req("/workflows/simulate",{method:"POST",body:JSON.stringify(t)})}events(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId,s=t?.run_id??t?.runId;r&&n.set("workflow_id",r),s&&n.set("run_id",s);const c=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/workflows/events${c}`,this.getToken(),{signal:t?.signal})}async listRuns(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r),t?.limit!==void 0&&n.set("limit",String(t.limit));const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflows/runs${s}`)??{},u=Array.isArray(d.runs)?d.runs:[];return{runs:u,count:typeof d.count=="number"?d.count:u.length}}async getRun(t){return(await this.req(`/workflows/runs/${encodeURIComponent(t)}`)).run??{}}async run(t,n){return this.req(`/workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}async listHooks(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r);const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflow-hooks${s}`)??{},u=Array.isArray(d.hooks)?d.hooks:[];return{hooks:u,count:typeof d.count=="number"?d.count:u.length}}async patchHook(t,n){return this.req(`/workflow-hooks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}}class Ul{constructor(t){this.req=t}async getConfig(){return this.req("/config/bug-monitor")}async patchConfig(t){return this.req("/config/bug-monitor",{method:"PATCH",body:JSON.stringify(t)})}async getStatus(){return this.req("/bug-monitor/status")}async recomputeStatus(){return this.req("/bug-monitor/status/recompute",{method:"POST"})}async pause(){return this.req("/bug-monitor/pause",{method:"POST"})}async resume(){return this.req("/bug-monitor/resume",{method:"POST"})}async debug(){return this.req("/bug-monitor/debug")}async listIncidents(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/incidents${n}`)}async getIncident(t){return(await this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}`)).incident??{}}async replayIncident(t,n){return this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}/replay`,{method:"POST",body:JSON.stringify(n??{})})}async listDrafts(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/drafts${n}`)}async listPosts(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/posts${n}`)}async getDraft(t){return(await this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}`)).draft??{}}async approveDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async denyDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n})})}async report(t){return this.req("/bug-monitor/report",{method:"POST",body:JSON.stringify(t)})}async createTriageRun(t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-run`,{method:"POST"})}async createTriageSummary(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/issue-draft`,{method:"POST",body:JSON.stringify(n??{})})}async publishDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/publish`,{method:"POST",body:JSON.stringify(n??{})})}async recheckMatch(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/recheck-match`,{method:"POST",body:JSON.stringify(n??{})})}}class Bl{constructor(t,n,r,s){this.baseUrl=t,this.token=n,this.timeoutMs=r,this.req=s}setToken(t){this.token=t}async create(t={}){const n={title:t.title??"Tandem SDK Session",directory:t.directory??"."};return t.permissions&&(n.permission=t.permissions),t.model&&t.provider&&(n.model={providerID:t.provider,modelID:t.model},n.provider=t.provider),(await this.req("/session",{method:"POST",body:JSON.stringify(n)})).id}async list(t={}){const n=new URLSearchParams;t.q&&n.set("q",t.q),t.page!==void 0&&n.set("page",String(t.page)),t.pageSize!==void 0&&n.set("page_size",String(t.pageSize)),t.archived!==void 0&&n.set("archived",String(t.archived)),t.scope&&n.set("scope",t.scope),t.workspace&&n.set("workspace",t.workspace);const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/session${r}`);return Ft(ns,s,"/session",200)}async get(t){const n=await this.req(`/session/${encodeURIComponent(t)}`);return Ft(Yn,n,`/session/${t}`,200)}async update(t,n){const r=await this.req(`/session/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Ft(Yn,r,`/session/${t}`,200)}async archive(t){return this.update(t,{archived:!0})}async delete(t){await this.req(`/session/${encodeURIComponent(t)}`,{method:"DELETE"})}async messages(t){return this.req(`/session/${encodeURIComponent(t)}/message`)}async todos(t){const n=await this.req(`/session/${encodeURIComponent(t)}/todo`);return Array.isArray(n)?n:n.todos??[]}async activeRun(t){const n=await this.req(`/session/${encodeURIComponent(t)}/run`);return Ft(xl,n,`/session/${t}/run`,200)}async promptAsync(t,n,r,s){return this.promptAsyncParts(t,[{type:"text",text:n}],r,s)}async promptAsyncParts(t,n,r,s){const c={parts:n};r?.provider&&r?.model&&(c.model={providerID:r.provider,modelID:r.model}),s?.toolMode&&(c.toolMode=s.toolMode),s?.toolAllowlist?.length&&(c.toolAllowlist=s.toolAllowlist),s?.contextMode&&(c.contextMode=s.contextMode);const d=`/session/${encodeURIComponent(t)}/prompt_async?return=run`,u=new AbortController,p=setTimeout(()=>u.abort(),this.timeoutMs);let N;try{N=await fetch(`${this.baseUrl}${d}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(c),signal:u.signal})}finally{clearTimeout(p)}if(N.status===409){const C=(await N.json().catch(()=>({}))).activeRun,O=da(C?.runID)||da(C?.runId)||da(C?.run_id);if(O)return{runId:O}}if(!N.ok){const x=await N.text().catch(()=>"");throw new Error(`promptAsyncParts failed (${N.status}): ${x}`)}const E=await N.json();return{runId:Ol(E)}}async promptSync(t,n){const r={parts:[{type:"text",text:n}]},s=await this.req(`/session/${encodeURIComponent(t)}/prompt_sync`,{method:"POST",body:JSON.stringify(r)});return da(s.reply)||da(s.text)||da(s.output)||""}async abort(t){return this.req(`/session/${encodeURIComponent(t)}/abort`,{method:"POST",body:JSON.stringify({})})}async cancel(t){return this.req(`/session/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})})}async cancelRun(t,n){return this.req(`/session/${encodeURIComponent(t)}/run/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})})}async fork(t){const n=await this.req(`/session/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify({})});return Ft(Yn,n,`/session/${t}/fork`,200)}async diff(t){return this.req(`/session/${encodeURIComponent(t)}/diff`)}async revert(t){return this.req(`/session/${encodeURIComponent(t)}/revert`,{method:"POST",body:JSON.stringify({})})}async unrevert(t){return this.req(`/session/${encodeURIComponent(t)}/unrevert`,{method:"POST",body:JSON.stringify({})})}async children(t){const n=await this.req(`/session/${encodeURIComponent(t)}/children`);return Ft(ns,n,`/session/${t}/children`,200).sessions}async summarize(t){return this.req(`/session/${encodeURIComponent(t)}/summarize`,{method:"POST",body:JSON.stringify({})})}async attach(t,n){return this.req(`/session/${encodeURIComponent(t)}/attach`,{method:"POST",body:JSON.stringify({target_workspace:n})})}}class Fl{constructor(t){this.req=t}async list(){return this.req("/permission")}async reply(t,n){const r=await this.req(`/permission/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({reply:n})});if(!r.ok)throw new Error(`Permission reply rejected: ${r.error??t}`);return{ok:!0}}}class Kl{constructor(t){this.req=t}async list(){const t=await this.req("/question");return Array.isArray(t)?{questions:t}:t}async reply(t,n){return this.req(`/question/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({answer:n})})}async reject(t){return this.req(`/question/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({})})}}class Ll{constructor(t){this.req=t}async catalog(){return this.req("/provider")}async config(){return this.req("/config/providers")}async setDefaults(t,n){await this.req("/config",{method:"PATCH",body:JSON.stringify({default_provider:t,providers:{[t]:{default_model:n}}})})}async setApiKey(t,n){await this.req(`/auth/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({apiKey:n})})}async authStatus(){return this.req("/provider/auth")}}class Wl{constructor(t){this.req=t}async get(){return this.req("/config/identity")}async patch(t){return this.req("/config/identity",{method:"PATCH",body:JSON.stringify(t)})}}class zl{constructor(t){this.req=t}async config(){return this.req("/channels/config")}async status(){return this.req("/channels/status")}async put(t,n){return this.req(`/channels/${t}`,{method:"PUT",body:JSON.stringify(n)})}async delete(t){return this.req(`/channels/${t}`,{method:"DELETE"})}async verify(t,n={}){return this.req(`/channels/${t}/verify`,{method:"POST",body:JSON.stringify(n)})}async toolPreferences(t){return this.req(`/channels/${t}/tool-preferences`)}async setToolPreferences(t,n){return this.req(`/channels/${t}/tool-preferences`,{method:"PUT",body:JSON.stringify(n)})}}class Jl{constructor(t,n){this.req=t,this.reqText=n}async list(){return this.req("/mcp")}async listTools(){return this.req("/mcp/tools")}async listResources(){const t=await this.req("/mcp/resources");return Array.isArray(t)?t:[]}async add(t){return this.req("/mcp",{method:"POST",body:JSON.stringify(t)})}async connect(t){return this.req(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})}async disconnect(t){return this.req(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})}async refresh(t){return this.req(`/mcp/${encodeURIComponent(t)}/refresh`,{method:"POST"})}async setEnabled(t,n){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:n})})}async delete(t){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})}async auth(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"POST",body:JSON.stringify(n??{})})}async deleteAuth(t){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"DELETE"})}async authCallback(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth/callback`,{method:"POST",body:JSON.stringify(n)})}async authenticate(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth/authenticate`,{method:"POST",body:JSON.stringify(n??{})})}async catalogToml(t){if(!this.reqText)throw new Error("Text request helper unavailable");return this.reqText(`/mcp/catalog/${encodeURIComponent(t)}/toml`)}}class Ql{constructor(t){this.req=t}async put(t){return this.req("/memory/put",{method:"POST",body:JSON.stringify(t)})}async search(t){const n=await this.req("/memory/search",{method:"POST",body:JSON.stringify(t)});return Ft(Il,n,"/memory/search",200)}async list(t){const n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset)),t?.userId&&n.set("user_id",t.userId);const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/memory${r}`);return Ft(_l,s,"/memory",200)}async delete(t){return this.req(`/memory/${encodeURIComponent(t)}`,{method:"DELETE"})}async promote(t){return this.req("/memory/promote",{method:"POST",body:JSON.stringify(t)})}async demote(t){const n={id:t.id,run_id:t.runId};return this.req("/memory/demote",{method:"POST",body:JSON.stringify(n)})}async audit(t){const n=new URLSearchParams;t?.run_id&&n.set("run_id",t.run_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/memory/audit${r}`);return Array.isArray(s)?{entries:s,count:s.length}:s}async contextResolveUri(t){const n=await this.req("/memory/context/resolve",{method:"POST",body:JSON.stringify({uri:t})});return Ft(Pl,n,"/memory/context/resolve",200)}async contextTree(t,n){const r=new URLSearchParams;r.set("uri",t),n!==void 0&&r.set("max_depth",String(n));const s=r.toString()?`?${r.toString()}`:"",c=await this.req(`/memory/context/tree${s}`);return Ft(Tl,c,"/memory/context/tree",200)}async contextGenerateLayers(t){return this.req("/memory/context/layers/generate",{method:"POST",body:JSON.stringify({node_id:t})})}async contextDistill(t,n){const r=await this.req("/memory/context/distill",{method:"POST",body:JSON.stringify({session_id:t,conversation:n})});return Ft(Rl,r,"/memory/context/distill",200)}}class Gl{constructor(t){this.req=t}async list(t){const n=t?`?location=${encodeURIComponent(t)}`:"",r=await this.req(`/skills${n}`);return Array.isArray(r)?{skills:r,count:r.length}:r}async get(t){return this.req(`/skills/${encodeURIComponent(t)}`)}async import(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath,location:t.location,namespace:t.namespace,conflict_policy:t.conflict_policy??t.conflictPolicy};return this.req("/skills/import",{method:"POST",body:JSON.stringify(n)})}async preview(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath,location:t.location,namespace:t.namespace,conflict_policy:t.conflict_policy??t.conflictPolicy};return this.req("/skills/import/preview",{method:"POST",body:JSON.stringify(n)})}async templates(){const t=await this.req("/skills/templates");return Array.isArray(t)?{templates:t,count:t.length}:t}async catalog(){const t=await this.req("/skills/catalog"),n=Array.isArray(t)?t:[];return{skills:n,count:n.length}}async validate(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath};return this.req("/skills/validate",{method:"POST",body:JSON.stringify(n)})}async match(t){const n={goal:t.goal,max_matches:t.max_matches??t.maxMatches,threshold:t.threshold};return this.req("/skills/router/match",{method:"POST",body:JSON.stringify(n)})}async evalBenchmark(t){const n={threshold:t.threshold,cases:t.cases.map(r=>({prompt:r.prompt,expected_skill:r.expected_skill??r.expectedSkill}))};return this.req("/skills/evals/benchmark",{method:"POST",body:JSON.stringify(n)})}async evalTriggers(t){const n={skill_name:t.skill_name??t.skillName,prompts:t.prompts,threshold:t.threshold};return this.req("/skills/evals/triggers",{method:"POST",body:JSON.stringify(n)})}async compile(t){const n={skill_name:t.skill_name??t.skillName,goal:t.goal,threshold:t.threshold,max_matches:t.max_matches??t.maxMatches,schedule:t.schedule};return this.req("/skills/compile",{method:"POST",body:JSON.stringify(n)})}async generate(t){return this.req("/skills/generate",{method:"POST",body:JSON.stringify(t)})}async generateInstall(t){const n={prompt:t.prompt,threshold:t.threshold,location:t.location,conflict_policy:t.conflictPolicy,artifacts:t.artifacts?{"SKILL.md":t.artifacts["SKILL.md"],"workflow.yaml":t.artifacts["workflow.yaml"],"automation.example.yaml":t.artifacts["automation.example.yaml"]}:void 0};return this.req("/skills/generate/install",{method:"POST",body:JSON.stringify(n)})}}class Hl{constructor(t){this.req=t}async list(){return this.req("/packs")}async inspect(t){return this.req(`/packs/${encodeURIComponent(t)}`)}async install(t){return this.req("/packs/install",{method:"POST",body:JSON.stringify(t)})}async installFromAttachment(t){return this.req("/packs/install_from_attachment",{method:"POST",body:JSON.stringify(t)})}async uninstall(t){return this.req("/packs/uninstall",{method:"POST",body:JSON.stringify(t)})}async export(t){return this.req("/packs/export",{method:"POST",body:JSON.stringify(t)})}async detect(t){return this.req("/packs/detect",{method:"POST",body:JSON.stringify(t)})}async updates(t){const r=await this.req(`/packs/${encodeURIComponent(t)}/updates`)||{},s=Array.isArray(r.updates)?r.updates:[];return{pack_id:da(r.pack_id)??void 0,name:da(r.name)??void 0,current_version:da(r.current_version)??void 0,updates:s}}async update(t,n){const r=await this.req(`/packs/${encodeURIComponent(t)}/update`,{method:"POST",body:JSON.stringify(n??{})});return{updated:!!r.updated,pack_id:da(r.pack_id)??void 0,name:da(r.name)??void 0,current_version:da(r.current_version)??void 0,target_version:da(r.target_version)??void 0,reason:da(r.reason)??void 0}}}class Vl{constructor(t){this.req=t}async getBindings(){return(await this.req("/capabilities/bindings")).bindings}async setBindings(t){return this.req("/capabilities/bindings",{method:"PUT",body:JSON.stringify(t)})}async discovery(){return this.req("/capabilities/discovery")}async resolve(t){return this.req("/capabilities/resolve",{method:"POST",body:JSON.stringify(t)})}async readiness(t){return this.req("/capabilities/readiness",{method:"POST",body:JSON.stringify(t)})}}class Yl{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(t){const n=new URLSearchParams;t?.prefix&&n.set("prefix",t.prefix),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/resource${r}`);return Ft(kl,s,"/resource",200)}async write(t){return this.req("/resource",{method:"PUT",body:JSON.stringify(t)})}async get(t){const n=await this.req(`/resource/${encodeURIComponent(t)}`);return Ft(ei,n,`/resource/${t}`,200)}async putKey(t,n,r){const s=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({value:n,...r??{}})});return Ft(rs,s,`/resource/${t}`,200)}async patchKey(t,n){const r=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Ft(rs,r,`/resource/${t}`,200)}async delete(t,n){return this.req("/resource",{method:"DELETE",body:JSON.stringify({key:t,...n})})}async deleteKey(t){return this.req(`/resource/${encodeURIComponent(t)}`,{method:"DELETE"})}events(t){const n=new URLSearchParams;t?.sinceSeq!==void 0&&n.set("since_seq",String(t.sinceSeq)),t?.tail!==void 0&&n.set("tail",String(t.tail));const r=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/resource/events${r}`,this.getToken())}}class Xl{constructor(t){this.req=t}async createRun(t){return this.req("/coder/runs",{method:"POST",body:JSON.stringify(t)})}async listRuns(t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit));const r=t?.workflow_mode??t?.workflowMode,s=t?.repo_slug??t?.repoSlug;r&&n.set("workflow_mode",r),s&&n.set("repo_slug",s);const c=n.toString()?`?${n.toString()}`:"",u=await this.req(`/coder/runs${c}`)??{},p=Array.isArray(u.runs)?u.runs:[];return{runs:p,count:typeof u.count=="number"?u.count:p.length}}async getRun(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}`)??{};return{...r,coderRun:r.coder_run??void 0,coder_run:r.coder_run??void 0,run:r.run??void 0}}async getProjectBinding(t){const r=await this.req(`/coder/projects/${encodeURIComponent(t)}/bindings`)??{};return{...r,binding:r.binding??null}}async putProjectBinding(t,n){const s=await this.req(`/coder/projects/${encodeURIComponent(t)}/bindings`,{method:"PUT",body:JSON.stringify(n)})??{};return{...s,binding:s.binding}}async getProjectGithubInbox(t){const r=await this.req(`/coder/projects/${encodeURIComponent(t)}/github-project/inbox`)??{};return{...r,items:Array.isArray(r.items)?r.items:[],binding:r.binding,project_id:String(r.project_id||r.projectId||""),schema_drift:!!(r.schema_drift??r.schemaDrift),live_schema_fingerprint:String(r.live_schema_fingerprint||r.liveSchemaFingerprint||"")}}async intakeProjectItem(t,n){const s=await this.req(`/coder/projects/${encodeURIComponent(t)}/github-project/intake`,{method:"POST",body:JSON.stringify(n)})??{};return{...s,coder_run:s.coder_run??void 0,coderRun:s.coder_run??void 0,run:s.run??void 0}}async executeNext(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-next`,{method:"POST",body:JSON.stringify(n??{})})}async executeAll(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-all`,{method:"POST",body:JSON.stringify(n??{})})}async createFollowOnRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/follow-on-run`,{method:"POST",body:JSON.stringify(n)})}async approveRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async cancelRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n})})}async listArtifacts(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/artifacts`)??{},s=Array.isArray(r.artifacts)?r.artifacts:[];return{...r,artifacts:s,count:typeof r.count=="number"?r.count:s.length}}async getMemoryHits(t,n){const r=new URLSearchParams;n?.query&&r.set("q",n.query),n?.limit!==void 0&&r.set("limit",String(n.limit));const s=r.toString()?`?${r.toString()}`:"",d=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-hits${s}`)??{},u=Array.isArray(d.hits)?d.hits:[];return{...d,hits:u,count:typeof d.count=="number"?d.count:u.length}}async createTriageInspectionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-inspection-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageReproductionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-reproduction-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewEvidence(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-evidence`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixValidationReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-validation-report`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrDraft(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-draft`,{method:"POST",body:JSON.stringify(n??{})})}async submitPr(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-submit`,{method:"POST",body:JSON.stringify(n??{})})}async createMergeReadinessReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-readiness-report`,{method:"POST",body:JSON.stringify(n)})}async createMergeRecommendationSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-recommendation-summary`,{method:"POST",body:JSON.stringify(n)})}async listMemoryCandidates(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`)??{},s=Array.isArray(r.candidates)?r.candidates:[];return{...r,candidates:s,count:typeof r.count=="number"?r.count:s.length}}async createMemoryCandidate(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`,{method:"POST",body:JSON.stringify(n)})}async promoteMemoryCandidate(t,n,r){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates/${encodeURIComponent(n)}/promote`,{method:"POST",body:JSON.stringify(r??{})})}}class Zl{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){return this.req("/routines")}async create(t){const n={...t};return"prompt"in n&&!("entrypoint"in n)&&(n.entrypoint=n.prompt),this.req("/routines",{method:"POST",body:JSON.stringify(n)})}async update(t,n){return this.req(`/routines/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){await this.req(`/routines/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const n=await this.req(`/routines/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return Ft(Xs,n,`/routines/${t}/run_now`,200)}async listRuns(t){const n=new URLSearchParams;t?.routine_id&&n.set("routine_id",t.routine_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return this.req(`/routines/runs${r}`)}async getRunsForRoutine(t,n=25){return this.req(`/routines/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){const n=await this.req(`/routines/runs/${encodeURIComponent(t)}`);return Ft(Zs,n,`/routines/runs/${t}`,200)}async listArtifacts(t){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/routines/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.routine_id??t?.routineId;r&&n.set("routine_id",r);const s=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/routines/events${s}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class ec{constructor(t){this.req=t}async preview(t){return this.req("/workflow-plans/preview",{method:"POST",body:JSON.stringify({prompt:t.prompt,schedule:t.schedule,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,workspace_root:t.workspace_root??t.workspaceRoot,operator_preferences:t.operator_preferences??t.operatorPreferences})})}async apply(t){return this.req("/workflow-plans/apply",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId,plan:t.plan,creator_id:t.creator_id??t.creatorId,pack_builder_export:t.pack_builder_export??t.packBuilderExport})})}async chatStart(t){return this.req("/workflow-plans/chat/start",{method:"POST",body:JSON.stringify({prompt:t.prompt,schedule:t.schedule,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,workspace_root:t.workspace_root??t.workspaceRoot,operator_preferences:t.operator_preferences??t.operatorPreferences})})}async get(t){return this.req(`/workflow-plans/${encodeURIComponent(t)}`)}async chatMessage(t){return this.req("/workflow-plans/chat/message",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId,message:t.message})})}async chatReset(t){return this.req("/workflow-plans/chat/reset",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId})})}}class tc{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){return this.req("/automations")}async create(t){return this.req("/automations",{method:"POST",body:JSON.stringify(t)})}async update(t,n){return this.req(`/automations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){await this.req(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const n=await this.req(`/automations/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return Ft(Xs,n,`/automations/${t}/run_now`,200)}async listRuns(t){const n=new URLSearchParams;t?.automation_id&&n.set("automation_id",t.automation_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return this.req(`/automations/runs${r}`)}async getRunsForAutomation(t,n=25){return this.req(`/automations/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){const n=await this.req(`/automations/runs/${encodeURIComponent(t)}`);return Ft(Zs,n,`/automations/runs/${t}`,200)}async listArtifacts(t){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/automations/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const c=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/automations/events${c}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class ac{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async create(t){return this.req("/automations/v2",{method:"POST",body:JSON.stringify(t)})}async list(){return this.req("/automations/v2")}async get(t){return this.req(`/automations/v2/${encodeURIComponent(t)}`)}async update(t,n){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})})}async pause(t,n){return this.req(`/automations/v2/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resume(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({})})}async listRuns(t,n=50){return this.req(`/automations/v2/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}`)}async pauseRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async recoverRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/recover`,{method:"POST",body:JSON.stringify({reason:n??""})})}async repairRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/repair`,{method:"POST",body:JSON.stringify(n)})}async retryTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({reason:r??""})})}async previewTaskReset(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/reset_preview`)}async continueTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/continue`,{method:"POST",body:JSON.stringify({reason:r??""})})}async requeueTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/requeue`,{method:"POST",body:JSON.stringify({reason:r??""})})}async claimBacklogTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/backlog/tasks/${encodeURIComponent(n)}/claim`,{method:"POST",body:JSON.stringify(r||{})})}async requeueBacklogTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/backlog/tasks/${encodeURIComponent(n)}/requeue`,{method:"POST",body:JSON.stringify({reason:r??""})})}async cancelRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n??""})})}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const c=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/automations/v2/events${c}`,this.getToken(),{signal:t?.signal})}}class nc{constructor(t){this.req=t}async list(){return this.req("/optimizations")}async create(t){return this.req("/optimizations",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.req(`/optimizations/${encodeURIComponent(t)}`)}async action(t,n){return this.req(`/optimizations/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)})}async listExperiments(t){return this.req(`/optimizations/${encodeURIComponent(t)}/experiments`)}async getExperiment(t,n){return this.req(`/optimizations/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}`)}async applyWinner(t,n){return this.req(`/optimizations/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}`,{method:"POST",body:JSON.stringify({})})}}class rc{constructor(t){this.req=t}async listTemplates(){return this.req("/agent-team/templates")}async createTemplate(t){return this.req("/agent-team/templates",{method:"POST",body:JSON.stringify(t)})}async updateTemplate(t,n){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async deleteTemplate(t){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"DELETE"})}async composeStandup(t){return this.req("/agent-standup/compose",{method:"POST",body:JSON.stringify({name:t.name,workspace_root:t.workspaceRoot,schedule:t.schedule,participant_template_ids:t.participantTemplateIds,report_path_template:t.reportPathTemplate})})}async listInstances(t){const n=new URLSearchParams;t?.missionID&&n.set("missionID",t.missionID),t?.parentInstanceID&&n.set("parentInstanceID",t.parentInstanceID),t?.status&&n.set("status",t.status);const r=n.toString()?`?${n.toString()}`:"";return this.req(`/agent-team/instances${r}`)}async listMissions(){return this.req("/agent-team/missions")}async listApprovals(){return this.req("/agent-team/approvals")}async spawn(t){return this.req("/agent-team/spawn",{method:"POST",body:JSON.stringify(t)})}async approveSpawn(t,n){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denySpawn(t,n){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}}class sc{constructor(t){this.req=t}async list(){return this.req("/mission")}async create(t){return this.req("/mission",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.req(`/mission/${encodeURIComponent(t)}`)}async applyEvent(t,n){return this.req(`/mission/${encodeURIComponent(t)}/event`,{method:"POST",body:JSON.stringify({event:n})})}}const nr="charcoal_fire",cn=[{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)"}}],Ca={duration:{normal:.22},easing:{standard:[.22,1,.36,1]},spring:{gentle:{type:"spring",stiffness:220,damping:26,mass:.9},snappy:{type:"spring",stiffness:320,damping:30,mass:.82},drawer:{type:"spring",stiffness:340,damping:34,mass:.82}}};function jr(a){let t=String(a||"").trim()||nr;return t==="web_control"&&(t=nr),cn.find(n=>n.id===t)||cn[0]}function ic(a){const t=jr(a).id,n=cn.findIndex(r=>r.id===t);return n<0?nr:cn[(n+1)%cn.length].id}function ai(a,t=typeof document<"u"?document.documentElement:null){const n=jr(a);if(!t)return n;for(const[r,s]of Object.entries(n.cssVars))s!=null&&t.style.setProperty(r,s);return t.dataset.theme=n.id,t.style.colorScheme=n.id==="porcelain"?"light":"dark",n}function ni(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const ri="tandem.themeId";function oc(){try{const a=localStorage.getItem(ri);return jr(a).id}catch{return nr}}function lc(a){return ai(a)}function cc(a){const t=ai(a);try{localStorage.setItem(ri,t.id)}catch{}return t}function Dn(){const[a,t]=w(()=>ni());return fe(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>t(n.matches);return r(),typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>n.removeEventListener("change",r)):(n.addListener(r),()=>n.removeListener(r))},[]),a}function dc(a,t,n){return Math.min(n,Math.max(t,a))}function rr({className:a="",children:t}){return e("div",{className:`tcp-glow-layer ${a}`.trim(),children:t})}function gn({className:a="",children:t}){const n=Dn();return e($e.div,{className:a,initial:n?!1:{opacity:0,y:14},animate:n?void 0:{opacity:1,y:0},exit:n?void 0:{opacity:0,y:-10},transition:n?void 0:{duration:Ca.duration.normal,ease:Ca.easing.standard},children:t})}function uc({className:a="",children:t}){const n=Dn();return e($e.div,{className:a,initial:n?!1:"hidden",animate:n?void 0:"show",variants:n?void 0:{hidden:{},show:{transition:{staggerChildren:.06,delayChildren:.02}}},children:t})}function si({className:a="",children:t,as:n="div"}){const r=Dn(),s=n==="section"?$e.section:n==="article"?$e.article:$e.div;return e(s,{className:a,variants:r?void 0:{hidden:{opacity:0,y:12,scale:.985},show:{opacity:1,y:0,scale:1,transition:{duration:Ca.duration.normal,ease:Ca.easing.standard}}},initial:r?!1:"hidden",animate:r?void 0:"show",children:t})}function mc({value:a,format:t=r=>String(r),className:n=""}){const r=Dn(),[s,c]=w(()=>Number(a||0)),d=qt(Number(a||0));return fe(()=>{const u=Number(a||0);if(!Number.isFinite(u)){c(0),d.current=0;return}if(r){c(u),d.current=u;return}const p=d.current,N=u-p;if(!N){c(u),d.current=u;return}const E=performance.now();let x=0;const C=O=>{const k=dc((O-E)/420,0,1),z=1-Math.pow(1-k,3),A=p+N*z;c(A),k<1?x=window.requestAnimationFrame(C):d.current=u};return x=window.requestAnimationFrame(C),()=>window.cancelAnimationFrame(x)},[r,a]),e("span",{className:n,children:t(Number.isFinite(s)?s:0)})}function va({tone:a="ok",text:t,className:n=""}){return e("span",{className:`tcp-status-pulse ${a} ${n}`.trim(),children:[e("span",{className:"tcp-status-pulse-dot","aria-hidden":"true"}),t?e("span",{children:t}):null]})}function ya({className:a="",children:t}){return e("div",{className:`tcp-toolbar ${a}`.trim(),children:t})}function An({className:a="",title:t,children:n,...r}){return e("button",{type:"button",title:t,className:`tcp-icon-btn ${a}`.trim(),...r,children:n})}function we({tone:a="info",className:t="",children:n}){return e("span",{className:`${a==="ok"?"tcp-badge-ok":a==="warn"?"tcp-badge-warn":a==="err"?"tcp-badge-err":a==="ghost"?"tcp-badge tcp-badge-ghost":"tcp-badge-info"} ${t}`.trim(),children:n})}function hr({active:a=!1,className:t="",children:n,...r}){return e("button",{type:"button",className:`tcp-filter-chip ${a?"active":""} ${t}`.trim(),...r,children:n})}function ot({title:a,subtitle:t,actions:n,className:r="",children:s}){return e(si,{as:"section",className:`tcp-panel-card ${r}`.trim(),children:[a||t||n?e("div",{className:"tcp-panel-card-head",children:[e("div",{className:"min-w-0",children:[a?e("h3",{className:"tcp-title",children:a}):null,t?e("p",{className:"tcp-subtle mt-1",children:t}):null]}),n?e("div",{className:"shrink-0",children:n}):null]}):null,s]})}function pc({text:a,title:t="Nothing here yet",action:n,className:r=""}){return e("div",{className:`tcp-empty-state ${r}`.trim(),children:[e("div",{className:"tcp-empty-state-orb"}),e("div",{className:"relative z-10",children:[e("div",{className:"tcp-empty-state-title",children:t}),e("p",{className:"tcp-subtle mt-1",children:a}),n?e("div",{className:"mt-3",children:n}):null]})]})}function hc({eyebrow:a,title:t,subtitle:n,badges:r,actions:s,className:c=""}){return e(si,{className:`tcp-page-header ${c}`.trim(),children:[e(rr,{className:"tcp-page-header-glow"}),e("div",{className:"relative z-10 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between",children:[e("div",{className:"min-w-0",children:[a?e("div",{className:"tcp-page-eyebrow",children:a}):null,e("h1",{className:"tcp-page-title",children:t}),n?e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:n}):null,r?e("div",{className:"mt-3 flex flex-wrap gap-2",children:r}):null]}),s?e(ya,{className:"justify-start lg:justify-end",children:s}):null]})]})}function Rn({className:a="",mainClassName:t="",asideClassName:n="",main:r,aside:s}){return e("div",{className:`tcp-split-view ${a}`.trim(),children:[e("div",{className:`min-w-0 ${t}`.trim(),children:r}),s?e("div",{className:`min-w-0 ${n}`.trim(),children:s}):null]})}function sr({open:a,title:t,onClose:n,children:r}){const s=Dn();return e(Mt,{children:a?e($e.div,{className:"tcp-drawer-root",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-drawer-backdrop","aria-label":"Close",onClick:n}),e($e.aside,{className:"tcp-drawer-panel",initial:s?!1:{x:"100%"},animate:s?void 0:{x:0},exit:s?void 0:{x:"100%"},transition:s?void 0:Ca.spring.drawer,children:[e("div",{className:"tcp-drawer-head",children:[e("div",{className:"min-w-0",children:t?e("h3",{className:"tcp-title",children:t}):null}),e(An,{title:"Close drawer",onClick:n,children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})]}):null})}function gc({loginMutation:a,savedToken:t,onCheckEngine:n,controlPanelName:r}){const[s,c]=w(t),[d,u]=w(!0),[p,N]=w(""),[E,x]=w(!1);return e("main",{className:"relative min-h-screen overflow-hidden px-5 py-8",children:[e(rr,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("div",{className:"relative z-10 mx-auto grid min-h-[calc(100vh-4rem)] w-full max-w-6xl items-center gap-6 lg:grid-cols-[1.05fr_0.95fr]",children:[e("section",{className:"grid gap-4",children:[e("div",{className:"tcp-page-eyebrow",children:"Tandem Control"}),e("h1",{className:"tcp-page-title max-w-3xl",children:"Sign in to continue."}),e("p",{className:"tcp-subtle max-w-2xl text-base",children:"Enter your engine token to access chat, orchestrator, automations, memory, live feed, and settings."})]}),e(ot,{title:r,subtitle:"Authenticate against your Tandem engine to continue.",children:e("form",{className:"grid gap-3",onSubmit:C=>{if(C.preventDefault(),!s.trim()){x(!1),N("Token is required.");return}a.mutate({token:s.trim(),remember:d})},children:[e("label",{className:"text-sm tcp-subtle",children:"Engine token"}),e("input",{className:"tcp-input",type:"password",value:s,onInput:C=>c(C.target.value),placeholder:"tk_...",autoComplete:"off"}),e("label",{className:"inline-flex items-center gap-2 text-xs tcp-subtle",children:[e("input",{type:"checkbox",className:"h-4 w-4 accent-slate-400",checked:d,onChange:C=>u(C.target.checked)}),"Remember token on this browser"]}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{disabled:a.isPending,type:"submit",className:"tcp-btn-primary w-full",children:[e("i",{"data-lucide":"key-round"}),"Sign in"]}),e("button",{type:"button",className:"tcp-btn w-full",onClick:async()=>{try{const C=await n();x(!0),N(C)}catch(C){x(!1),N(C instanceof Error?C.message:String(C))}},children:[e("i",{"data-lucide":"activity"}),"Check engine"]})]}),e("div",{className:`min-h-[1.2rem] text-sm ${E?"text-lime-300":"text-rose-300"}`,children:a.error?.message||p}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e("div",{className:"font-medium",children:"Readiness"}),e(va,{tone:E?"ok":"warn",text:E?"Engine reachable":"Waiting"})]}),e("p",{className:"tcp-subtle text-xs",children:"Connectivity checks are non-destructive and help verify the local panel can reach the engine before authentication."})]})]})})]})]})}function fc(a){fe(()=>{const t=n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="k"&&(n.preventDefault(),a())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[a])}function bc({open:a,onClose:t,actions:n}){const[r,s]=w("");fe(()=>{a||s("")},[a]),fe(()=>{if(!a)return;const d=u=>{u.key==="Escape"&&t()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[a,t]);const c=K(()=>{const d=r.trim().toLowerCase();return d?n.filter(u=>`${u.label} ${u.group}`.toLowerCase().includes(d)):n},[n,r]);return e(Mt,{children:a?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:e($e.div,{className:"tcp-doc-dialog w-[min(44rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},transition:{duration:.16,ease:"easeOut"},onClick:d=>d.stopPropagation(),children:[e("div",{className:"tcp-doc-header",children:[e("h3",{className:"tcp-doc-title",children:"Command Palette"}),e("kbd",{className:"tcp-subtle text-xs",children:"Ctrl/Cmd + K"})]}),e("div",{className:"p-3",children:[e("input",{autoFocus:!0,value:r,onInput:d=>s(d.target.value),placeholder:"Jump to route or action",className:"tcp-input"}),e("div",{className:"mt-3 grid max-h-[50vh] gap-2 overflow-auto",children:[c.map(d=>e("button",{type:"button",className:"tcp-btn w-full justify-between",onClick:()=>{d.onSelect(),t()},children:[e("span",{className:"inline-flex items-center gap-1.5",children:[e("i",{"data-lucide":"list"}),e("span",{children:d.label})]}),e("span",{className:"tcp-subtle text-xs",children:d.group})]},d.id)),c.length?null:e("p",{className:"tcp-subtle px-1 py-2",children:"No matching action."})]})]})]})}):null})}const ii=[["dashboard","Dashboard","home"],["chat","Chat","message-square"],["studio","Studio","network"],["automations","Automations","bot"],["coding","Coding","code"],["agents","Agents","users"],["orchestrator","Orchestrator","sparkles"],["memory","Memory","database"],["feed","Live Feed","radio"],["settings","Settings","settings"],["packs","Packs","package"],["teams","Teams","users"],["channels","Channels","message-circle"],["mcp","MCP","link"],["bug-monitor","Bug Monitor","bug-play"],["files","Files","folder-open"],["packs-detail","Packs","package"],["teams-detail","Teams","users"]],vc=ii.filter(([a])=>["dashboard","chat","studio","automations","coding","agents","orchestrator","memory","feed","settings"].includes(a)),oi={openai:{label:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",placeholder:"sk-proj-..."},anthropic:{label:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",placeholder:"sk-ant-..."},google:{label:"Google",keyUrl:"https://aistudio.google.com/app/apikey",placeholder:"AIza..."},groq:{label:"Groq",keyUrl:"https://console.groq.com/keys",placeholder:"gsk_..."},mistral:{label:"Mistral",keyUrl:"https://console.mistral.ai/api-keys/",placeholder:"..."},together:{label:"Together",keyUrl:"https://api.together.xyz/settings/api-keys",placeholder:"..."},cohere:{label:"Cohere",keyUrl:"https://dashboard.cohere.com/api-keys",placeholder:"..."},openrouter:{label:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",placeholder:"sk-or-v1-..."},azure:{label:"Azure OpenAI",keyUrl:"https://portal.azure.com/",placeholder:"..."},bedrock:{label:"Bedrock",keyUrl:"https://console.aws.amazon.com/bedrock/",placeholder:"..."},vertex:{label:"Vertex",keyUrl:"https://console.cloud.google.com/vertex-ai",placeholder:"..."},copilot:{label:"GitHub Copilot",keyUrl:"https://github.com/settings/tokens",placeholder:"ghp_..."},ollama:{label:"Ollama",keyUrl:"",placeholder:"No key required"}},li=ii,yc=vc,wc=new Map([["packs","automations"],["teams","automations"],["swarm","orchestrator"],["failure-reporter","bug-monitor"]]),xc=new Set(li.map(([a])=>a));function Ur(a,t="dashboard"){const n=wc.get(String(a||"").trim());return n||(xc.has(a)?a:t)}function ss(a="dashboard"){const t=(window.location.hash||`#/${a}`).replace(/^#\//,"");return Ur(t.split("?")[0].split("/")[0].trim(),a)}function kc(a){window.location.hash=`#/${a}`}function Nc(){const[a,t]=w(()=>ss());fe(()=>{const r=()=>t(ss());return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]);const n=mt(r=>{const s=Ur(r);if(window.location.hash!==`#/${s}`){kc(s);return}t(s)},[]);return{route:a,navigate:n}}const ci=Wi({toast:()=>{}});function _c({children:a}){const[t,n]=w([]),r=mt((c,d)=>{const u=Math.random().toString(36).slice(2);n(p=>[...p,{id:u,kind:c,text:d}].slice(-4)),window.setTimeout(()=>{n(p=>p.filter(N=>N.id!==u))},3500)},[]),s=K(()=>({toast:r}),[r]);return e(ci.Provider,{value:s,children:[a,e("div",{className:"toasts","aria-live":"polite","aria-atomic":"true",children:e(Mt,{children:t.map(c=>e($e.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-${c.kind}`,children:c.text},c.id))})})]})}function Sc(){return zi(ci)}function Wt({title:a,subtitle:t,children:n,actions:r,className:s}){return e(ot,{title:a,subtitle:t,actions:r,className:s||"",children:n})}function Le({text:a,title:t,action:n}){return e(pc,{text:a,title:t,action:n})}function Yt(a){return JSON.stringify(a,null,2)}function gr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Ic(a){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(Number(a||0))}function Cc(a){const{api:t,client:n,navigate:r,providerStatus:s}=a,[c,d]=w(""),u=new Set(["workflow","bug_monitor_triage"]),p=Y({queryKey:["dashboard","health"],queryFn:()=>t("/api/system/health"),refetchInterval:15e3}),N=Y({queryKey:["dashboard","sessions"],queryFn:()=>n.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),E=Y({queryKey:["dashboard","routines"],queryFn:()=>n.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),x=Y({queryKey:["dashboard","swarm"],queryFn:()=>t("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),C=Y({queryKey:["dashboard","workflow-context-runs"],queryFn:()=>t("/api/engine/context/runs?limit=12").catch(()=>({runs:[]})),refetchInterval:6e3}),O=Y({queryKey:["dashboard","workflow-context-run",c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}`).catch(()=>({run:null}))}),k=Y({queryKey:["dashboard","workflow-context-blackboard",c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}/blackboard`).catch(()=>({blackboard:null}))}),z=gr(N.data,"sessions"),A=gr(E.data,"routines"),G=gr(C.data,"runs").filter(q=>u.has(String(q?.run_type||"").trim().toLowerCase())),B=!!(p.data?.engine?.ready||p.data?.engine?.healthy),ae=String(x.data?.status||"unknown"),S=["planning","awaiting_approval","running","executing"].includes(ae.toLowerCase()),I=G.filter(q=>["queued","planning","running","awaiting_approval"].includes(String(q?.status||"").trim().toLowerCase())),H=K(()=>[{label:"Recent sessions",value:z.length,tone:"info",helper:"Latest active conversation surfaces"},{label:"Automations",value:A.length,tone:"ok",helper:"Configured routines and schedules"},{label:"Swarm status",value:S?1:0,tone:S?"warn":"ghost",helper:ae},{label:"Provider ready",value:s.ready?1:0,tone:s.ready?"ok":"warn",helper:s.ready?s.defaultModel:"Needs setup"},{label:"Context runs",value:G.length,tone:I.length?"warn":"info",helper:I.length?`${I.length} active`:"Workflow + triage visibility"}],[I.length,s.defaultModel,s.ready,A.length,z.length,S,ae,G.length]);return e(gn,{className:"grid gap-4",children:[e(ot,{className:"overflow-hidden",children:[e("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Overview"}),e("h1",{className:"tcp-page-title",children:"Command center"}),e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:"A higher-signal home screen with animated state, quick entry points, and a clearer read on what the system is doing right now."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e(we,{tone:B?"ok":"warn",children:B?"Engine healthy":"Engine checking"}),e(we,{tone:s.ready?"ok":"warn",children:s.ready?s.defaultProvider:"Provider setup required"}),S?e(va,{tone:"live",text:`Swarm ${ae}`}):e(we,{tone:"ghost",children:["Swarm ",ae]})]})]}),e("div",{className:"grid gap-3",children:e(ya,{className:"justify-start",children:[e("button",{className:"tcp-btn-primary w-full sm:w-auto",onClick:()=>r("chat"),children:[e("i",{"data-lucide":"message-square"}),"Chat session"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"sparkles"}),"Plan work"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Automations"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("coding"),children:[e("i",{"data-lucide":"code"}),"Coding workflows"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("settings"),children:[e("i",{"data-lucide":"settings"}),"Configure runtime"]})]})})]}),e("div",{className:"mt-5",children:[e("div",{className:"dashboard-kpis",children:H.map(q=>e("div",{children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("span",{className:"dashboard-kpi-label",children:q.label}),e(we,{tone:q.tone,children:q.helper})]}),e("strong",{children:e(mc,{value:q.value,format:Ic})})]},q.label))}),e("div",{className:"mt-4 dashboard-bars",children:[e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Engine readiness"}),e("span",{className:"dashboard-bar-count",children:B?"100%":"45%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:"dashboard-bar-fill completed",style:{width:B?"100%":"45%"}})})]}),e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Provider confidence"}),e("span",{className:"dashboard-bar-count",children:s.ready?"100%":"30%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${s.ready?"running":"queued"}`,style:{width:s.ready?"100%":"30%"}})})]}),e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Automation activity"}),e("span",{className:"dashboard-bar-count",children:[A.length," routines"]})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${A.length?"scheduled":"manual"}`,style:{width:`${Math.min(100,Math.max(12,A.length*12))}%`}})})]})]})]})]}),e(Rn,{main:e(ot,{title:"Recent sessions",subtitle:"Latest conversations, ready to reopen.",children:e("div",{className:"grid gap-2",children:z.length?z.map(q=>e("button",{className:"tcp-list-item text-left",onClick:()=>r("chat"),children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"messages-square"}),String(q.title||q.id||"Session")]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(q.id||q.session_id||"")})]},String(q.id||q.session_id||Math.random()))):e(Le,{text:"Start a conversation to populate recent sessions here."})})}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Context visibility",subtitle:"Recent workflow and failure-triage context runs with their current projection state.",children:[e(ya,{className:"mb-3",children:[e(we,{tone:I.length?"warn":"info",children:[G.length," recent"]}),e("button",{className:"tcp-btn",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]})]}),e("div",{className:"grid gap-2",children:G.length?G.slice(0,5).map(q=>e("button",{className:"tcp-list-item text-left",onClick:()=>d(String(q?.run_id||"").trim()),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:String(q?.objective||q?.run_id||"Context run")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e(we,{tone:"ghost",children:String(q?.run_type||"context")}),e(we,{tone:["failed","cancelled"].includes(String(q?.status||"").toLowerCase())?"err":["running","queued","planning"].includes(String(q?.status||"").toLowerCase())?"warn":"ok",children:String(q?.status||"unknown")})]})]}),e("div",{className:"tcp-subtle text-xs",children:String(q?.run_id||"")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Array.isArray(q?.tasks)?q.tasks.length:0," tasks ·"," ",Array.isArray(q?.steps)?q.steps.length:0," steps"]})]},String(q?.run_id||Math.random()))):e(Le,{text:"Workflow and failure-triage context runs will appear here once they execute."})})]}),e(ot,{title:"Automation snapshot",subtitle:"Schedules and run-ready routines.",children:[e(ya,{className:"mb-3",children:[e(we,{tone:"info",children:[A.length," loaded"]}),e("button",{className:"tcp-btn",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Manage"]})]}),e("div",{className:"grid gap-2",children:A.length?A.slice(0,4).map(q=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:String(q.name||q.id||"Routine")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(q.schedule||q.status||"manual")})]},String(q.id||q.routine_id||Math.random()))):e(Le,{text:"No routines are configured yet."})})]}),e(ot,{title:"Health notes",subtitle:"Direct links for the next likely action.",children:e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"activity"}),"Engine endpoint"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(p.data?.engineUrl||"Unavailable")})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"radio"}),"Swarm"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:["Status: ",ae]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"database"}),"Memory & feed"]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>r("memory"),children:"Open memory"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>r("feed"),children:"Open live feed"})]})]})]})})]})}),e(sr,{open:!!c,onClose:()=>d(""),title:c||"Workflow context run",children:c?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(O.data?.run?.objective||c)}),e(we,{tone:"info",children:String(O.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["type: ",String(O.data?.run?.run_type||"workflow")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium mb-2",children:"Projected blackboard"}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(k.data?.blackboard?.tasks)?k.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(k.data?.blackboard?.artifacts)?k.data.blackboard.artifacts.length:0]})]}),e("pre",{className:"tcp-code",children:Yt({run:O.data?.run||null,blackboard:k.data?.blackboard||null})})]}):null})]})}const Ac={Activity:fl,Archive:gl,ArrowLeftToLine:hl,ArrowUpCircle:pl,BadgeCheck:ml,Binary:ul,Bug:dl,BugPlay:cl,Bot:ll,BookOpen:ol,Check:il,ChevronDown:sl,ChevronRight:rl,ClipboardList:nl,Clock:al,Clock3:tl,Copy:el,CopyPlus:Zo,Code:Xo,ExternalLink:Yo,Cpu:Vo,Database:Ho,Download:Go,FileUp:Qo,Filter:Jo,FilterX:zo,FlaskConical:Wo,FolderOpen:Lo,History:Ko,Home:Fo,Info:Bo,KeyRound:Uo,Link:jo,LoaderCircle:Do,List:Eo,LogOut:Oo,MessageCircle:$o,MessageSquare:Mo,MessagesSquare:qo,Menu:Ro,MonitorCog:To,Network:Po,Paperclip:Ao,Package:Co,PaintBucket:Io,Pencil:So,Play:_o,PlugZap:No,Plus:ko,Pause:xo,Radio:wo,RefreshCw:yo,RotateCw:vo,Save:bo,Search:fo,Send:go,Settings:ho,Settings2:po,ShieldAlert:mo,ShieldCheck:uo,SlidersHorizontal:co,Sparkles:lo,Siren:oo,Share2:io,Shield:so,Square:ro,Trash2:no,TriangleAlert:ao,X:to,XCircle:eo,Users:Zi,Workflow:Xi},Ar=new Set;let Pr=0;function Pc(){Pr=0;const a=[...Ar];Ar.clear();for(const t of a)Yi({icons:Ac,attrs:{width:"16",height:"16","stroke-width":"1.8"},...t?{root:t}:{}})}function wa(a){Ar.add(a||null),!Pr&&(Pr=window.requestAnimationFrame(Pc))}Ys.setOptions({gfm:!0,breaks:!0});function dn(a){const t=String(a||""),n=Ys.parse(t,{async:!1});return vl.sanitize(n)}const Tr="tcp.chat.session";function di(a){return String(a?.id||a?.session_id||a?.sessionID||"").trim()}function Tc(a){const t=String(a?.title||a?.name||"").trim();if(t)return t;const n=di(a);return n?`Session ${n.slice(0,8)}`:"Session"}function Rc(a){return Array.isArray(a)?a:Array.isArray(a?.sessions)?a.sessions:[]}function qc(a){return String(a?.title||"").trim().toLowerCase().startsWith("__provider_test__")}function is(a){return Rc(a).filter(t=>!qc(t)).map(t=>({id:di(t),title:Tc(t),raw:t})).filter(t=>!!t.id)}async function Mc(a,t){try{const n=await a.sessions.list({pageSize:50}),r=is(n);if(r.length>0)return r}catch{}try{const n=await t("/api/engine/session?page_size=50",{method:"GET"});return is(n)}catch{return[]}}function os(){try{return localStorage.getItem(Tr)||""}catch{return""}}function $c(a){try{a?localStorage.setItem(Tr,a):localStorage.removeItem(Tr)}catch{}}function Oc(a){return Array.isArray(a)?a.map(n=>n?typeof n=="string"?n:typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:"":"").filter(Boolean).join(`
|
|
3
|
-
`).trim():""}function
|
|
4
|
-
`).trim()}return""}function jc(a,t){return a==="assistant"?t||"Assistant":a==="user"?"User":a==="system"?"System":a||"Assistant"}function Uc(a,t,n){const r=Ec(a),s=Dc(a),c=r==="assistant"||r==="system";return{id:String(a?.id||a?.messageID||a?.message_id||a?.event_id||`${r}-${t}`).trim()||`${r}-${t}`,role:r,displayRole:jc(r,n),text:s,markdown:c}}function ui(a,t){return(Array.isArray(a)?a:Array.isArray(a?.messages)?a.messages:[]).map((r,s)=>Uc(r,s,t))}const ls=new Set(["tool.called","tool_call.started","session.tool_call"]),cs=new Set(["tool.result","tool_call.completed","tool_call.failed","session.tool_result"]),Bc=new Set(["run.complete","run.completed","session.run.finished","session.run.completed"]),Fc=new Set(["run.failed","session.run.failed","run.cancelled","run.canceled","session.run.cancelled","session.run.canceled"]);function mi(a){return String(a||"").trim().replace(/\s+/g," ").replace(/[<>]/g,"")}function sn(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return mi(t.tool||t.name||t.toolName||t.tool_id||t.toolID||n.tool||n.name||n.toolName||"")}function kn(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return String(t.callID||t.toolCallID||t.tool_call_id||t.id||n.callID||n.toolCallID||n.tool_call_id||n.id||"").trim()}function fr(a,t=""){const n=a?.properties||{};return String(a?.runId||a?.runID||a?.run_id||n.runID||n.runId||n.run_id||n.run?.id||t).trim()}function Kn(a){if(!a)return null;const t=a.request||a.approval||a.permission||{},n=String(a.id||a.requestID||a.requestId||a.approvalID||t.id||t.requestID||"").trim();return n?{id:n,tool:mi(a.tool||t.tool||t.name||"tool")||"tool",permission:String(a.permission||t.permission||"").trim(),pattern:String(a.pattern||t.pattern||"").trim(),sessionId:String(a.sessionId||a.sessionID||a.session_id||t.sessionId||t.sessionID||"").trim(),status:String(a.status||t.status||"").trim().toLowerCase()}:null}function ds(a){const t=String(a||"").trim().toLowerCase();return t?t.includes("approved")||t.includes("rejected")||t.includes("denied")||t.includes("resolved")||t.includes("expired")||t.includes("cancel")||t.includes("complete")||t.includes("done")||t.includes("timeout")?!1:t.includes("pending")||t.includes("request")||t.includes("ask")||t.includes("await")||t.includes("open")||t.includes("queue")||t.includes("new")||t.includes("progress")||t==="unknown":!0}function Kc(a,t){const n=t&&typeof t=="object"?t:{},r=String(a||"").trim()||"pack.event",s=String(n.path||"").trim(),c=String(n.attachment_id||n.attachmentId||"").trim(),d=String(n.connector||"").trim(),u=String(n.channel_id||n.channelId||"").trim(),p=String(n.sender_id||n.senderId||"").trim(),N=String(n.name||"").trim(),E=String(n.version||"").trim(),x=String(n.error||"").trim(),C=[];N&&C.push(N),E&&C.push(E),s&&C.push(s),d&&C.push(d),u&&C.push(`channel=${u}`),p&&C.push(`sender=${p}`);const O=C.join(" · ");return{id:`${r}:${c||s||N||"event"}`,type:r,path:s,attachmentId:c,connector:d,channelId:u,senderId:p,error:x,summary:O||r,at:Date.now()}}const qn=new Map;function pi(a,t){return`${t?"cred":"anon"}:${a}`}function Lc(a,t=!0){const n=pi(a,t),r=qn.get(n);if(r&&!r.closed)return r;const s=new EventSource(a,{withCredentials:t}),c={source:s,listeners:new Set,errorListeners:new Set,refs:0,closed:!1};return s.onmessage=d=>{for(const u of[...c.listeners])try{u(d)}catch{}},s.onerror=d=>{for(const u of[...c.errorListeners])try{u(d)}catch{}s.readyState===EventSource.CLOSED&&(c.closed=!0,qn.delete(n))},qn.set(n,c),c}function Br(a,t,n={}){const r=n.withCredentials!==!1,s=pi(a,r),c=Lc(a,r);return c.refs+=1,c.listeners.add(t),typeof n.onError=="function"&&c.errorListeners.add(n.onError),()=>{const d=qn.get(s);d&&(d.listeners.delete(t),typeof n.onError=="function"&&d.errorListeners.delete(n.onError),d.refs=Math.max(0,d.refs-1),d.refs===0&&(d.closed=!0,d.source.close(),qn.delete(s)))}}const Wc="control-panel",hi="tandem_control_panel_chat_auto_approve_tools",zc="tandem.automations.plannerSeed",Jc={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 us(a=""){const t=String(a).toLowerCase().split(".").pop()||"";return Jc[t]||"application/octet-stream"}function Qc(a="",t=""){if(!a||!t)return t||"";const n=String(a).replace(/[\\/]+$/,""),r=String(t).replace(/^[\\/]+/,"");return`${n}/${r}`}function Gc(a){const t=Number(a||0);return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function br(a,t){return!a||!t?!0:String(a).trim()===String(t).trim()}function Hc(a){const t=String(a||"").trim();return t!=="server.connected"&&t!=="engine.lifecycle.ready"}function Vc(a){return a==="completed"?"chat-tool-chip-ok":a==="failed"?"chat-tool-chip-failed":"chat-tool-chip-running"}function Yc(){try{return localStorage.getItem(hi)==="1"}catch{return!1}}function Xc(a){try{localStorage.setItem(hi,a?"1":"0")}catch{}}function Zc(a){try{const t=String(a?.prompt||a?.goal||"").trim();if(!t)return;sessionStorage.setItem(zc,JSON.stringify({prompt:t,plan_source:String(a?.plan_source||"chat_setup").trim()||"chat_setup"}))}catch{}}function Va(a){return a instanceof Error?a.message:String(a)}function ed(a){return a.decision==="pass_through"?null:a.intent_kind==="provider_setup"?{title:"Provider setup",body:`Configure ${a.slots.provider_ids[0]||"a provider"} in Settings.`,cta:"Open Settings",actionType:"open_provider_setup",payload:a.proposed_action.payload||{}}:a.intent_kind==="integration_setup"?{title:"Tool connection",body:`Connect ${a.slots.integration_targets[0]||"the matching tool"} through MCP.`,cta:"Open MCP",actionType:"open_mcp_setup",payload:a.proposed_action.payload||{}}:a.intent_kind==="automation_create"?{title:"Automation setup",body:a.slots.goal||"Create an automation from this request.",cta:"Open Automations",actionType:"open_automations",payload:a.proposed_action.payload||{}}:{title:"Setup help",body:a.clarifier?.question||"Choose a setup path.",cta:"Open Settings",actionType:"open_provider_setup",payload:a.proposed_action.payload||{},clarifier:a.clarifier||void 0}}function td({client:a,api:t,toast:n,providerStatus:r,identity:s,navigate:c}){const d=na(),u=!!Vs(),p=qt(null),N=qt(null),E=qt(null),x=qt(null),C=qt(null),O=qt(!0),k=qt(null),z=qt(null),[A,G]=w([]),[B,ae]=w(!1),[S,I]=w(os()),[H,q]=w([]),[ye,y]=w(!1),[v,U]=w(""),[ue,ee]=w([]),[Oe,Ee]=w([]),[We,ne]=w(!1),[ce,M]=w(""),[me,Re]=w(!1),[qe,se]=w([]),[Ue,Me]=w(new Set),[ze,X]=w([]),[Ve,re]=w(new Set),[Ce,gt]=w([]),[ie,L]=w(new Set),[st,pt]=w(Yc()),[lt,Ct]=w(!1),[De,$t]=w([]),[yt,Ut]=w(null),[Je,Ge]=w(null),nt=K(()=>A.find(j=>j.id===S)?.title||"Chat",[S,A]);fe(()=>(O.current=!0,()=>{O.current=!1,C.current?.abort(),k.current&&window.clearTimeout(k.current),z.current&&window.clearTimeout(z.current)}),[]),fe(()=>{const h=p.current;h&&wa(h)},[A,ue,Oe,Ce,qe,ze,H,B,me,ce]),fe(()=>{$c(S)},[S]),fe(()=>{const h=N.current;h&&(h.style.height="0px",h.style.height=`${Math.min(h.scrollHeight,180)}px`)},[v]),fe(()=>{const h=x.current;h&&(h.scrollTop=h.scrollHeight)},[H,ce,me]);const ve=mt(async()=>{const h=await Mc(a,t);O.current&&(G(h),I(j=>{if(j&&h.some(W=>W.id===j))return j;const Q=os();return Q&&h.some(W=>W.id===Q)?Q:h[0]?.id||""}))},[t,a]),_e=mt(async()=>{const h=String(r.defaultProvider||"").trim(),j=String(r.defaultModel||"").trim();if(h&&j)return{providerID:h,modelID:j};try{const Q=await a.providers.config(),W=String(Q?.default||"").trim(),V=String(Q?.providers?.[W]?.defaultModel||"").trim();if(W&&V)return{providerID:W,modelID:V}}catch{}return null},[a.providers,r.defaultModel,r.defaultProvider]),Ye=mt(async()=>{const h=await _e(),j={title:`Chat ${new Date().toLocaleTimeString()}`};h&&(j.provider=h.providerID,j.model=h.modelID);const Q=await a.sessions.create(j),W=String(Q||"").trim();if(!W)throw new Error("Failed to create session.");return I(W),await ve(),W},[a.sessions,ve,_e]),le=mt(h=>{const j=ui(h,s.botName||"Assistant");q(j)},[s.botName]),it=mt(async()=>{if(!S){q([]);return}y(!0);try{const h=await a.sessions.messages(S).catch(()=>({messages:[]}));if(!O.current)return;le(h)}finally{O.current&&y(!1)}},[a.sessions,le,S]),_=mt(()=>{se([]),Me(new Set)},[]),J=mt(()=>{X([]),re(new Set)},[]),be=mt((h,j,Q="")=>{const W=String(h||"").trim();if(!W)return;let V=!0;Q&&(Me(ge=>{if(ge.has(Q))return V=!1,ge;const Be=new Set(ge);return Be.add(Q),Be.size>1e3?new Set([Q]):Be}),!V)||se(ge=>[{id:`${W}:${j}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:W,status:j,at:Date.now()},...ge].slice(0,80))},[]),je=mt((h,j)=>{const Q=Kc(h,j);if(!String(Q.type).toLowerCase().startsWith("pack."))return;let V=!0;re(ge=>{if(ge.has(Q.id))return V=!1,ge;const Be=new Set(ge);return Be.add(Q.id),Be.size>400?new Set([Q.id]):Be}),V&&X(ge=>[Q,...ge].slice(0,80))},[]),o=mt(h=>{ds(h?.status||"")&>(j=>{const Q=j.findIndex(W=>W.id===h.id);if(Q>=0){const W=[...j];return W[Q]={...W[Q],...h},W}return[h,...j]})},[]),f=mt(h=>{gt(j=>j.filter(Q=>Q.id!==h))},[]),R=mt(async()=>{const h=await a.permissions.list().catch(()=>({requests:[]})),Q=(Array.isArray(h?.requests)?h.requests:[]).map(W=>Kn(W)).filter(W=>!!W).filter(W=>br(W.sessionId,S)).filter(W=>ds(W.status));O.current&>(Q.slice(0,80))},[a.permissions,S]),P=mt(async(h,j,Q=!1)=>{if(!(!h||ie.has(h))){L(V=>{const ge=new Set(V);return ge.add(h),ge});try{await a.permissions.reply(h,j),f(h),Q||n("ok",`Permission ${j==="deny"?"denied":"approved"} (${h}).`)}catch(V){Q||n("err",Va(V))}finally{L(V=>{const ge=new Set(V);return ge.delete(h),ge}),R()}}},[a.permissions,ie,R,f,n]),$=mt(async()=>{if(!(!st||lt||Ce.length===0)){Ct(!0);try{for(const h of[...Ce])await P(h.id,"always",!0)}finally{O.current&&Ct(!1)}}},[st,lt,Ce,P]),Xe=mt(h=>(Array.isArray(h)?h:Array.isArray(h?.tools)?h.tools:[]).map(Q=>{if(typeof Q=="string")return Q;const W=Q||{};return String(W.name||W.id||W.tool||"").trim()}).filter(Boolean),[]),et=mt(async()=>{try{const h=await a.listTools?.().catch(()=>null);let j=Xe(h||[]);if(!j.length){const Q=await t("/api/engine/tool",{method:"GET"}).catch(()=>[]);j=Xe(Q||[])}if(O.current){const Q=[...new Set(j)].sort((W,V)=>W.localeCompare(V));$t(Q)}}catch{O.current&&$t([])}},[t,a,Xe]),bt=mt(h=>new Promise((j,Q)=>{const W=`${Date.now()}-${Math.random().toString(16).slice(2)}`;Ee(ge=>[...ge,{id:W,name:h.name,progress:0,error:""}]);const V=new XMLHttpRequest;V.open("POST",`/api/files/upload?dir=${encodeURIComponent(Wc)}`),V.withCredentials=!0,V.responseType="json",V.setRequestHeader("x-file-name",encodeURIComponent(h.name)),V.upload.onprogress=ge=>{if(!ge.lengthComputable)return;const Be=ge.loaded/ge.total*100;Ee(ht=>ht.map(ct=>ct.id===W?{...ct,progress:Be}:ct))},V.onerror=()=>{Ee(ge=>ge.map(Be=>Be.id===W?{...Be,error:"Network error"}:Be)),window.setTimeout(()=>{Ee(ge=>ge.filter(Be=>Be.id!==W))},1200),Q(new Error(`Upload failed: ${h.name}`))},V.onload=()=>{const ge=V.response||{};if(V.status<200||V.status>=300||ge?.ok===!1){const Be=String(ge?.error||`Upload failed (${V.status})`);Ee(ht=>ht.map(ct=>ct.id===W?{...ct,error:Be}:ct)),window.setTimeout(()=>{Ee(ht=>ht.filter(ct=>ct.id!==W))},1600),Q(new Error(Be));return}Ee(Be=>Be.filter(ht=>ht.id!==W)),j(ge)},V.send(h)}),[]),Ot=mt(async h=>{const j=[...h||[]];if(!j.length)return;let Q=0;for(const W of j)try{const V=await bt(W);ee(ge=>[{name:String(V?.name||W.name),path:String(V?.path||W.name),size:Number(V?.size||W.size||0),mime:W.type||us(String(V?.name||W.name)),url:String(V?.absPath||Qc(V?.root,V?.path)||V?.path||W.name)},...ge]),Q+=1}catch(V){n("err",Va(V))}Q>0&&n("ok",`Uploaded ${Q} file${Q===1?"":"s"}.`)},[n,bt]),Ae=mt(async h=>{if(await a.sessions.delete(h),G(j=>j.filter(Q=>Q.id!==h)),Ut(null),n("ok","Session deleted."),S===h){const j=A.find(Q=>Q.id!==h)?.id||"";if(j)I(j);else{const Q=await Ye();I(Q)}}},[a.sessions,Ye,S,A,n]),xt=mt((h,j)=>{const Q=String(h||"").trim();if(!Q)return;const W=j>0?`
|
|
1
|
+
import{u as e,d as w,A as Rt,y as fe,T as F,q as ft,R as co,x as uo,k as la,h as mo,e as po,f as ho}from"./preact-vendor-jo0muZ28.js";import{u as V,a as ca,b as ke,c as go,Q as fo}from"./react-query-wD0mx2Xi.js";import{c as ie,o as Ut,d as fn,r as Yr,e as bn,f as fa,g as Ja,h as bo,W as vo,U as yo,C as wo,X as xo,T as ko,j as No,S as _o,k as So,l as Io,m as Co,p as Ao,q as Po,t as To,u as Ro,v as Mo,w as qo,x as $o,y as Oo,z as Eo,R as Do,A as jo,B as Uo,P as Bo,D as Fo,E as Lo,F as Ko,G as Wo,H as zo,I as Jo,J as Qo,N as Ho,K as Go,L as Vo,O as Yo,V as Xo,Y as Zo,Z as el,_ as tl,$ as al,a0 as nl,a1 as rl,a2 as sl,a3 as il,a4 as ol,a5 as ll,a6 as cl,a7 as dl,a8 as ul,a9 as ml,aa as pl,ab as hl,ac as gl,ad as fl,ae as bl,af as vl,ag as yl,ah as wl,ai as xl,aj as kl,ak as Nl,al as _l,am as Sl,an as Il,ao as Cl,ap as Al,aq as Pl,ar as Tl,as as Rl,at as Ml,au as ql,av as $l,aw as Ol,ax as wr,ay as El}from"./vendor-BB3fzNns.js";import{m as Re,A as Mt,u as pi}from"./motion-BCvrfAt1.js";import{g as hi,p as Dl}from"./markdown-DMcD1LHz.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const c of s)if(c.type==="childList")for(const d of c.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function n(s){const c={};return s.integrity&&(c.integrity=s.integrity),s.referrerPolicy&&(c.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?c.credentials="include":s.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(s){if(s.ep)return;s.ep=!0;const c=n(s);fetch(s.href,c)}})();class jl extends Error{constructor(t,n,r,s){super(`Tandem API Validation Error [${n}] at ${t}: ${r.length} issues found.`),this.endpoint=t,this.status=n,this.issues=r,this.rawSnippet=s,this.name="TandemValidationError"}}const ys=ie().or(Ut({id:ie().optional(),runID:ie().optional(),runId:ie().optional(),run_id:ie().optional(),sessionID:ie().optional(),sessionId:ie().optional(),session_id:ie().optional(),missionID:ie().optional(),missionId:ie().optional(),mission_id:ie().optional(),instanceID:ie().optional(),instanceId:ie().optional(),instance_id:ie().optional()})).transform(a=>typeof a=="string"?a:a.id||a.runID||a.runId||a.run_id||a.sessionID||a.sessionId||a.session_id||a.missionID||a.missionId||a.mission_id||a.instanceID||a.instanceId||a.instance_id);fn().transform(a=>a);Yr(ie(),fn()).transform(a=>a);const Ul=Ut({ready:bn().optional(),phase:ie().optional(),workspace_root:ie().optional(),workspaceRoot:ie().optional()}).passthrough().transform(a=>({...a,workspaceRoot:a.workspace_root??a.workspaceRoot})),cr=Ut({id:ie(),title:ie(),created_at_ms:fa().optional(),createdAtMs:fa().optional(),directory:ie().optional(),workspace_root:ie().optional(),workspaceRoot:ie().optional(),archived:bn().optional()}).passthrough().transform(a=>({...a,createdAtMs:a.created_at_ms??a.createdAtMs??0,workspaceRoot:a.workspace_root??a.workspaceRoot})),ws=Ut({sessions:Ja(cr).optional().default([]),count:fa().optional().default(0)}).passthrough(),Bl=Ut({active:Ut({runID:ie().optional(),runId:ie().optional(),run_id:ie().optional(),attachEventStream:ie().optional()}).passthrough().nullable().optional()}).passthrough().transform(a=>a.active?{active:{...a.active,runId:a.active.runId||a.active.runID||a.active.run_id}}:{active:null}),gi=Ut({ok:bn().optional(),runID:ie().optional(),runId:ie().optional(),run_id:ie().optional(),status:ie().optional()}).passthrough().transform(a=>({...a,runId:a.runId||a.runID||a.run_id})),fi=Ut({id:ie().optional(),runID:ie().optional(),runId:ie().optional(),run_id:ie().optional(),routine_id:ie().optional(),automation_id:ie().optional(),status:ie().optional(),started_at_ms:fa().optional(),finished_at_ms:fa().optional()}).passthrough().transform(a=>({...a,runId:a.runId||a.runID||a.run_id,routineId:a.routine_id,automationId:a.automation_id,startedAtMs:a.started_at_ms,finishedAtMs:a.finished_at_ms})),xs=Ut({ok:bn().default(!0),rev:fa().optional()}).passthrough(),bi=Ut({key:ie(),value:fn(),rev:fa().optional(),updated_at_ms:fa().optional(),updated_by:ie().optional()}).passthrough().transform(a=>({...a,updatedAtMs:a.updated_at_ms,updatedBy:a.updated_by})),Fl=Ut({items:Ja(bi).optional().default([]),count:fa().optional().default(0)}).passthrough(),Ll=Ut({id:ie().optional(),text:ie().optional(),content:ie().optional(),user_id:ie().optional(),userID:ie().optional(),source_type:ie().optional(),sourceType:ie().optional(),tags:Ja(ie()).optional(),source:ie().optional(),session_id:ie().optional(),sessionID:ie().optional(),run_id:ie().optional(),runID:ie().optional()}).passthrough().transform(a=>({...a,text:a.text||a.content,content:a.content||a.text,userId:a.userID||a.user_id,sourceType:a.sourceType||a.source_type,sessionId:a.session_id||a.sessionID,runId:a.run_id||a.runID})),Kl=Ut({items:Ja(Ll).optional().default([]),count:fa().optional().default(0)}).passthrough(),Wl=Ut({id:ie(),text:ie().optional(),content:ie().optional(),score:fa().optional(),source_type:ie().optional(),sourceType:ie().optional(),run_id:ie().optional(),runID:ie().optional(),tags:Ja(ie()).optional()}).passthrough().transform(a=>({...a,text:a.text||a.content,content:a.content||a.text,sourceType:a.sourceType||a.source_type,runId:a.runID||a.run_id})),zl=Ut({results:Ja(Wl).optional().default([]),count:fa().optional().default(0)}).passthrough(),vi=Ut({id:ie(),uri:ie(),parent_uri:ie().optional(),node_type:ie(),created_at:ie(),updated_at:ie(),metadata:Yr(ie(),fn()).optional()}).passthrough(),Jl=Ut({l0_preview:ie().optional(),l1_preview:ie().optional(),has_l2:bn()}).passthrough(),Ql=Ut({node:vi,children:Ja(fn()).optional().default([]),layer_summary:Jl.optional()}).passthrough(),Hl=Ut({node:vi.optional()}).passthrough(),Gl=Ut({tree:Ja(Ql).optional().default([])}).passthrough(),Vl=Ut({ok:bn(),distillation_id:ie().optional(),session_id:ie().optional(),facts_extracted:fa().optional()}).passthrough(),Yl=Ut({type:ie(),properties:Yr(ie(),fn()).optional().default({}),sessionID:ie().optional(),session_id:ie().optional(),sessionId:ie().optional(),runID:ie().optional(),run_id:ie().optional(),runId:ie().optional(),timestamp:ie().optional()}).passthrough().transform(a=>({...a,properties:a.properties,sessionId:a.sessionId||a.sessionID||a.session_id,runId:a.runId||a.runID||a.run_id}));function Jt(a,t,n,r){const s=a.safeParse(t);if(!s.success){const c=JSON.stringify(t).substring(0,200);throw new jl(n,r,s.error.issues,c)}return s.data}function Xl(a){const t=a.trim();if(!t||t===": keep-alive"||t.startsWith(":"))return null;try{const n=JSON.parse(t),r=Yl.safeParse(n);return r.success?r.data:null}catch{return null}}async function*tn(a,t,n){const r=n?.connectTimeoutMs??3e4,s=new AbortController,c=setTimeout(()=>s.abort(),r),d=n?.signal?Zl([s.signal,n.signal]):s.signal;let u;try{u=await fetch(a,{headers:{Accept:"text/event-stream",Authorization:`Bearer ${t}`,"Cache-Control":"no-cache"},signal:d})}finally{clearTimeout(c)}if(!u.ok){const x=await u.text().catch(()=>"");throw new Error(`SSE connect failed (${u.status} ${u.statusText}): ${x}`)}if(!u.body)throw new Error("SSE response has no body");const p=new TextDecoder,N=u.body.getReader();let E="";try{for(;;){const{done:x,value:A}=await N.read();if(x)break;E+=p.decode(A,{stream:!0});const O=E.split(`
|
|
2
|
+
`);E=O.pop()??"";let _="";for(const z of O)if(z.startsWith("data:"))_+=z.slice(5).trimStart();else if(z===""&&_){const P=Xl(_);P&&(yield P),_=""}}}finally{N.releaseLock()}}function Zl(a){const t=new AbortController;for(const n of a){if(n.aborted){t.abort(n.reason);break}n.addEventListener("abort",()=>t.abort(n.reason),{once:!0})}return t.signal}const ma=a=>typeof a=="string"&&a.trim().length>0?a:null,ec=a=>{try{const t=ys.parse(a);if(t)return t}catch{const t=a.run||null;if(t)try{const n=ys.parse(t);if(n)return n}catch{}}throw new Error("Run ID missing in engine response")};class tc{constructor(t){this.baseUrl=t.baseUrl.replace(/\/+$/,""),this.token=t.token,this.timeoutMs=t.timeoutMs??2e4;const n=this._request.bind(this);this.sessions=new sc(this.baseUrl,this.token,this.timeoutMs,n),this.permissions=new ic(n),this.questions=new oc(n),this.providers=new lc(n),this.identity=new cc(n),this.channels=new dc(n),this.mcp=new uc(n,this._requestText.bind(this));const r=()=>this.token;this.routines=new vc(this.baseUrl,r,n),this.automations=new wc(this.baseUrl,r,n),this.automationsV2=new xc(this.baseUrl,r,n),this.optimizations=new kc(n),this.workflowPlans=new yc(n),this.memory=new mc(n),this.skills=new pc(n),this.packs=new hc(n),this.capabilities=new gc(n),this.resources=new fc(this.baseUrl,r,n),this.browser=new ac(n),this.workflows=new nc(this.baseUrl,r,n),this.bugMonitor=new rc(n),this.coder=new bc(n),this.agentTeams=new Nc(n),this.missions=new _c(n)}setToken(t){this.token=t,this.sessions.setToken(t)}async health(){const t=await this._request("/global/health");return Jt(Ul,t,"/global/health",200)}async listToolIds(){return this._request("/tool/ids")}async listTools(){const t=await this._request("/tool");return Array.isArray(t)?t:[]}async executeTool(t,n){return this._request("/tool/execute",{method:"POST",body:JSON.stringify({tool:t,args:n??{}})})}stream(t,n,r){const s=new URLSearchParams({sessionID:t});n&&s.set("runID",n);const c=`${this.baseUrl}/event?${s.toString()}`;return tn(c,this.token,r)}globalStream(t){const n=`${this.baseUrl}/global/event`;return tn(n,this.token,t)}async runEvents(t,n){const r=new URLSearchParams;n?.sinceSeq!==void 0&&r.set("since_seq",String(n.sinceSeq)),n?.tail!==void 0&&r.set("tail",String(n.tail));const s=r.toString()?`?${r.toString()}`:"",c=await this._request(`/run/${encodeURIComponent(t)}/events${s}`);return Array.isArray(c)?c:[]}async _request(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let c;try{c=await fetch(`${this.baseUrl}${t}`,{...n,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(c.status!==204){if(!c.ok){const d=await c.text().catch(()=>"");throw new Error(`Request failed (${c.status} ${c.statusText}): ${d}`)}return c.json()}}async _requestText(t,n={}){const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeoutMs);let c;try{c=await fetch(`${this.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${this.token}`,...n.headers??{}},signal:r.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Error(`Request timed out after ${this.timeoutMs}ms: ${t}`):d}finally{clearTimeout(s)}if(!c.ok){const d=await c.text().catch(()=>"");throw new Error(`Request failed (${c.status} ${c.statusText}): ${d}`)}return c.text()}}class ac{constructor(t){this.req=t}async status(){return this.req("/browser/status")}async install(){return this.req("/browser/install",{method:"POST"})}async smokeTest(t){return this.req("/browser/smoke-test",{method:"POST",body:JSON.stringify(t??{})})}}class nc{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){const n=await this.req("/workflows")??{},r=Array.isArray(n.workflows)?n.workflows:[];return{workflows:r,count:typeof n.count=="number"?n.count:r.length}}async get(t){return(await this.req(`/workflows/${encodeURIComponent(t)}`)).workflow??{}}async validate(t){return this.req("/workflows/validate",{method:"POST",body:JSON.stringify(t??{})})}async simulate(t){return this.req("/workflows/simulate",{method:"POST",body:JSON.stringify(t)})}events(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId,s=t?.run_id??t?.runId;r&&n.set("workflow_id",r),s&&n.set("run_id",s);const c=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/workflows/events${c}`,this.getToken(),{signal:t?.signal})}async listRuns(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r),t?.limit!==void 0&&n.set("limit",String(t.limit));const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflows/runs${s}`)??{},u=Array.isArray(d.runs)?d.runs:[];return{runs:u,count:typeof d.count=="number"?d.count:u.length}}async getRun(t){return(await this.req(`/workflows/runs/${encodeURIComponent(t)}`)).run??{}}async run(t,n){return this.req(`/workflows/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}async listHooks(t){const n=new URLSearchParams,r=t?.workflow_id??t?.workflowId;r&&n.set("workflow_id",r);const s=n.toString()?`?${n.toString()}`:"",d=await this.req(`/workflow-hooks${s}`)??{},u=Array.isArray(d.hooks)?d.hooks:[];return{hooks:u,count:typeof d.count=="number"?d.count:u.length}}async patchHook(t,n){return this.req(`/workflow-hooks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}}class rc{constructor(t){this.req=t}async getConfig(){return this.req("/config/bug-monitor")}async patchConfig(t){return this.req("/config/bug-monitor",{method:"PATCH",body:JSON.stringify(t)})}async getStatus(){return this.req("/bug-monitor/status")}async recomputeStatus(){return this.req("/bug-monitor/status/recompute",{method:"POST"})}async pause(){return this.req("/bug-monitor/pause",{method:"POST"})}async resume(){return this.req("/bug-monitor/resume",{method:"POST"})}async debug(){return this.req("/bug-monitor/debug")}async listIncidents(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/incidents${n}`)}async getIncident(t){return(await this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}`)).incident??{}}async replayIncident(t,n){return this.req(`/bug-monitor/incidents/${encodeURIComponent(t)}/replay`,{method:"POST",body:JSON.stringify(n??{})})}async listDrafts(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/drafts${n}`)}async listPosts(t){const n=t?.limit!==void 0?`?limit=${t.limit}`:"";return this.req(`/bug-monitor/posts${n}`)}async getDraft(t){return(await this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}`)).draft??{}}async approveDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async denyDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n})})}async report(t){return this.req("/bug-monitor/report",{method:"POST",body:JSON.stringify(t)})}async createTriageRun(t){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-run`,{method:"POST"})}async createTriageSummary(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/issue-draft`,{method:"POST",body:JSON.stringify(n??{})})}async publishDraft(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/publish`,{method:"POST",body:JSON.stringify(n??{})})}async recheckMatch(t,n){return this.req(`/bug-monitor/drafts/${encodeURIComponent(t)}/recheck-match`,{method:"POST",body:JSON.stringify(n??{})})}}class sc{constructor(t,n,r,s){this.baseUrl=t,this.token=n,this.timeoutMs=r,this.req=s}setToken(t){this.token=t}async create(t={}){const n={title:t.title??"Tandem SDK Session",directory:t.directory??"."};return t.permissions&&(n.permission=t.permissions),t.model&&t.provider&&(n.model={providerID:t.provider,modelID:t.model},n.provider=t.provider),(await this.req("/session",{method:"POST",body:JSON.stringify(n)})).id}async list(t={}){const n=new URLSearchParams;t.q&&n.set("q",t.q),t.page!==void 0&&n.set("page",String(t.page)),t.pageSize!==void 0&&n.set("page_size",String(t.pageSize)),t.archived!==void 0&&n.set("archived",String(t.archived)),t.scope&&n.set("scope",t.scope),t.workspace&&n.set("workspace",t.workspace);const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/session${r}`);return Jt(ws,s,"/session",200)}async get(t){const n=await this.req(`/session/${encodeURIComponent(t)}`);return Jt(cr,n,`/session/${t}`,200)}async update(t,n){const r=await this.req(`/session/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Jt(cr,r,`/session/${t}`,200)}async archive(t){return this.update(t,{archived:!0})}async delete(t){await this.req(`/session/${encodeURIComponent(t)}`,{method:"DELETE"})}async messages(t){return this.req(`/session/${encodeURIComponent(t)}/message`)}async todos(t){const n=await this.req(`/session/${encodeURIComponent(t)}/todo`);return Array.isArray(n)?n:n.todos??[]}async activeRun(t){const n=await this.req(`/session/${encodeURIComponent(t)}/run`);return Jt(Bl,n,`/session/${t}/run`,200)}async promptAsync(t,n,r,s){return this.promptAsyncParts(t,[{type:"text",text:n}],r,s)}async promptAsyncParts(t,n,r,s){const c={parts:n};r?.provider&&r?.model&&(c.model={providerID:r.provider,modelID:r.model}),s?.toolMode&&(c.toolMode=s.toolMode),s?.toolAllowlist?.length&&(c.toolAllowlist=s.toolAllowlist),s?.contextMode&&(c.contextMode=s.contextMode);const d=`/session/${encodeURIComponent(t)}/prompt_async?return=run`,u=new AbortController,p=setTimeout(()=>u.abort(),this.timeoutMs);let N;try{N=await fetch(`${this.baseUrl}${d}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`},body:JSON.stringify(c),signal:u.signal})}finally{clearTimeout(p)}if(N.status===409){const A=(await N.json().catch(()=>({}))).activeRun,O=ma(A?.runID)||ma(A?.runId)||ma(A?.run_id);if(O)return{runId:O}}if(!N.ok){const x=await N.text().catch(()=>"");throw new Error(`promptAsyncParts failed (${N.status}): ${x}`)}const E=await N.json();return{runId:ec(E)}}async promptSync(t,n){const r={parts:[{type:"text",text:n}]},s=await this.req(`/session/${encodeURIComponent(t)}/prompt_sync`,{method:"POST",body:JSON.stringify(r)});return ma(s.reply)||ma(s.text)||ma(s.output)||""}async abort(t){return this.req(`/session/${encodeURIComponent(t)}/abort`,{method:"POST",body:JSON.stringify({})})}async cancel(t){return this.req(`/session/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})})}async cancelRun(t,n){return this.req(`/session/${encodeURIComponent(t)}/run/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})})}async fork(t){const n=await this.req(`/session/${encodeURIComponent(t)}/fork`,{method:"POST",body:JSON.stringify({})});return Jt(cr,n,`/session/${t}/fork`,200)}async diff(t){return this.req(`/session/${encodeURIComponent(t)}/diff`)}async revert(t){return this.req(`/session/${encodeURIComponent(t)}/revert`,{method:"POST",body:JSON.stringify({})})}async unrevert(t){return this.req(`/session/${encodeURIComponent(t)}/unrevert`,{method:"POST",body:JSON.stringify({})})}async children(t){const n=await this.req(`/session/${encodeURIComponent(t)}/children`);return Jt(ws,n,`/session/${t}/children`,200).sessions}async summarize(t){return this.req(`/session/${encodeURIComponent(t)}/summarize`,{method:"POST",body:JSON.stringify({})})}async attach(t,n){return this.req(`/session/${encodeURIComponent(t)}/attach`,{method:"POST",body:JSON.stringify({target_workspace:n})})}}class ic{constructor(t){this.req=t}async list(){return this.req("/permission")}async reply(t,n){const r=await this.req(`/permission/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({reply:n})});if(!r.ok)throw new Error(`Permission reply rejected: ${r.error??t}`);return{ok:!0}}}class oc{constructor(t){this.req=t}async list(){const t=await this.req("/question");return Array.isArray(t)?{questions:t}:t}async reply(t,n){return this.req(`/question/${encodeURIComponent(t)}/reply`,{method:"POST",body:JSON.stringify({answer:n})})}async reject(t){return this.req(`/question/${encodeURIComponent(t)}/reject`,{method:"POST",body:JSON.stringify({})})}}class lc{constructor(t){this.req=t}async catalog(){return this.req("/provider")}async config(){return this.req("/config/providers")}async setDefaults(t,n){await this.req("/config",{method:"PATCH",body:JSON.stringify({default_provider:t,providers:{[t]:{default_model:n}}})})}async setApiKey(t,n){await this.req(`/auth/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({apiKey:n})})}async authStatus(){return this.req("/provider/auth")}}class cc{constructor(t){this.req=t}async get(){return this.req("/config/identity")}async patch(t){return this.req("/config/identity",{method:"PATCH",body:JSON.stringify(t)})}}class dc{constructor(t){this.req=t}async config(){return this.req("/channels/config")}async status(){return this.req("/channels/status")}async put(t,n){return this.req(`/channels/${t}`,{method:"PUT",body:JSON.stringify(n)})}async delete(t){return this.req(`/channels/${t}`,{method:"DELETE"})}async verify(t,n={}){return this.req(`/channels/${t}/verify`,{method:"POST",body:JSON.stringify(n)})}async toolPreferences(t){return this.req(`/channels/${t}/tool-preferences`)}async setToolPreferences(t,n){return this.req(`/channels/${t}/tool-preferences`,{method:"PUT",body:JSON.stringify(n)})}}class uc{constructor(t,n){this.req=t,this.reqText=n}async list(){return this.req("/mcp")}async listTools(){return this.req("/mcp/tools")}async listResources(){const t=await this.req("/mcp/resources");return Array.isArray(t)?t:[]}async add(t){return this.req("/mcp",{method:"POST",body:JSON.stringify(t)})}async connect(t){return this.req(`/mcp/${encodeURIComponent(t)}/connect`,{method:"POST"})}async disconnect(t){return this.req(`/mcp/${encodeURIComponent(t)}/disconnect`,{method:"POST"})}async refresh(t){return this.req(`/mcp/${encodeURIComponent(t)}/refresh`,{method:"POST"})}async setEnabled(t,n){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:n})})}async delete(t){return this.req(`/mcp/${encodeURIComponent(t)}`,{method:"DELETE"})}async auth(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"POST",body:JSON.stringify(n??{})})}async deleteAuth(t){return this.req(`/mcp/${encodeURIComponent(t)}/auth`,{method:"DELETE"})}async authCallback(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth/callback`,{method:"POST",body:JSON.stringify(n)})}async authenticate(t,n){return this.req(`/mcp/${encodeURIComponent(t)}/auth/authenticate`,{method:"POST",body:JSON.stringify(n??{})})}async catalogToml(t){if(!this.reqText)throw new Error("Text request helper unavailable");return this.reqText(`/mcp/catalog/${encodeURIComponent(t)}/toml`)}}class mc{constructor(t){this.req=t}async put(t){return this.req("/memory/put",{method:"POST",body:JSON.stringify(t)})}async search(t){const n=await this.req("/memory/search",{method:"POST",body:JSON.stringify(t)});return Jt(zl,n,"/memory/search",200)}async list(t){const n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.offset!==void 0&&n.set("offset",String(t.offset)),t?.userId&&n.set("user_id",t.userId);const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/memory${r}`);return Jt(Kl,s,"/memory",200)}async delete(t){return this.req(`/memory/${encodeURIComponent(t)}`,{method:"DELETE"})}async promote(t){return this.req("/memory/promote",{method:"POST",body:JSON.stringify(t)})}async demote(t){const n={id:t.id,run_id:t.runId};return this.req("/memory/demote",{method:"POST",body:JSON.stringify(n)})}async audit(t){const n=new URLSearchParams;t?.run_id&&n.set("run_id",t.run_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/memory/audit${r}`);return Array.isArray(s)?{entries:s,count:s.length}:s}async contextResolveUri(t){const n=await this.req("/memory/context/resolve",{method:"POST",body:JSON.stringify({uri:t})});return Jt(Hl,n,"/memory/context/resolve",200)}async contextTree(t,n){const r=new URLSearchParams;r.set("uri",t),n!==void 0&&r.set("max_depth",String(n));const s=r.toString()?`?${r.toString()}`:"",c=await this.req(`/memory/context/tree${s}`);return Jt(Gl,c,"/memory/context/tree",200)}async contextGenerateLayers(t){return this.req("/memory/context/layers/generate",{method:"POST",body:JSON.stringify({node_id:t})})}async contextDistill(t,n){const r=await this.req("/memory/context/distill",{method:"POST",body:JSON.stringify({session_id:t,conversation:n})});return Jt(Vl,r,"/memory/context/distill",200)}}class pc{constructor(t){this.req=t}async list(t){const n=t?`?location=${encodeURIComponent(t)}`:"",r=await this.req(`/skills${n}`);return Array.isArray(r)?{skills:r,count:r.length}:r}async get(t){return this.req(`/skills/${encodeURIComponent(t)}`)}async import(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath,location:t.location,namespace:t.namespace,conflict_policy:t.conflict_policy??t.conflictPolicy};return this.req("/skills/import",{method:"POST",body:JSON.stringify(n)})}async preview(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath,location:t.location,namespace:t.namespace,conflict_policy:t.conflict_policy??t.conflictPolicy};return this.req("/skills/import/preview",{method:"POST",body:JSON.stringify(n)})}async templates(){const t=await this.req("/skills/templates");return Array.isArray(t)?{templates:t,count:t.length}:t}async catalog(){const t=await this.req("/skills/catalog"),n=Array.isArray(t)?t:[];return{skills:n,count:n.length}}async validate(t){const n={content:t.content,file_or_path:t.file_or_path??t.fileOrPath};return this.req("/skills/validate",{method:"POST",body:JSON.stringify(n)})}async match(t){const n={goal:t.goal,max_matches:t.max_matches??t.maxMatches,threshold:t.threshold};return this.req("/skills/router/match",{method:"POST",body:JSON.stringify(n)})}async evalBenchmark(t){const n={threshold:t.threshold,cases:t.cases.map(r=>({prompt:r.prompt,expected_skill:r.expected_skill??r.expectedSkill}))};return this.req("/skills/evals/benchmark",{method:"POST",body:JSON.stringify(n)})}async evalTriggers(t){const n={skill_name:t.skill_name??t.skillName,prompts:t.prompts,threshold:t.threshold};return this.req("/skills/evals/triggers",{method:"POST",body:JSON.stringify(n)})}async compile(t){const n={skill_name:t.skill_name??t.skillName,goal:t.goal,threshold:t.threshold,max_matches:t.max_matches??t.maxMatches,schedule:t.schedule};return this.req("/skills/compile",{method:"POST",body:JSON.stringify(n)})}async generate(t){return this.req("/skills/generate",{method:"POST",body:JSON.stringify(t)})}async generateInstall(t){const n={prompt:t.prompt,threshold:t.threshold,location:t.location,conflict_policy:t.conflictPolicy,artifacts:t.artifacts?{"SKILL.md":t.artifacts["SKILL.md"],"workflow.yaml":t.artifacts["workflow.yaml"],"automation.example.yaml":t.artifacts["automation.example.yaml"]}:void 0};return this.req("/skills/generate/install",{method:"POST",body:JSON.stringify(n)})}}class hc{constructor(t){this.req=t}async list(){return this.req("/packs")}async inspect(t){return this.req(`/packs/${encodeURIComponent(t)}`)}async install(t){return this.req("/packs/install",{method:"POST",body:JSON.stringify(t)})}async installFromAttachment(t){return this.req("/packs/install_from_attachment",{method:"POST",body:JSON.stringify(t)})}async uninstall(t){return this.req("/packs/uninstall",{method:"POST",body:JSON.stringify(t)})}async export(t){return this.req("/packs/export",{method:"POST",body:JSON.stringify(t)})}async detect(t){return this.req("/packs/detect",{method:"POST",body:JSON.stringify(t)})}async updates(t){const r=await this.req(`/packs/${encodeURIComponent(t)}/updates`)||{},s=Array.isArray(r.updates)?r.updates:[];return{pack_id:ma(r.pack_id)??void 0,name:ma(r.name)??void 0,current_version:ma(r.current_version)??void 0,updates:s}}async update(t,n){const r=await this.req(`/packs/${encodeURIComponent(t)}/update`,{method:"POST",body:JSON.stringify(n??{})});return{updated:!!r.updated,pack_id:ma(r.pack_id)??void 0,name:ma(r.name)??void 0,current_version:ma(r.current_version)??void 0,target_version:ma(r.target_version)??void 0,reason:ma(r.reason)??void 0}}}class gc{constructor(t){this.req=t}async getBindings(){return(await this.req("/capabilities/bindings")).bindings}async setBindings(t){return this.req("/capabilities/bindings",{method:"PUT",body:JSON.stringify(t)})}async discovery(){return this.req("/capabilities/discovery")}async resolve(t){return this.req("/capabilities/resolve",{method:"POST",body:JSON.stringify(t)})}async readiness(t){return this.req("/capabilities/readiness",{method:"POST",body:JSON.stringify(t)})}}class fc{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(t){const n=new URLSearchParams;t?.prefix&&n.set("prefix",t.prefix),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"",s=await this.req(`/resource${r}`);return Jt(Fl,s,"/resource",200)}async write(t){return this.req("/resource",{method:"PUT",body:JSON.stringify(t)})}async get(t){const n=await this.req(`/resource/${encodeURIComponent(t)}`);return Jt(bi,n,`/resource/${t}`,200)}async putKey(t,n,r){const s=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({value:n,...r??{}})});return Jt(xs,s,`/resource/${t}`,200)}async patchKey(t,n){const r=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Jt(xs,r,`/resource/${t}`,200)}async delete(t,n){return this.req("/resource",{method:"DELETE",body:JSON.stringify({key:t,...n})})}async deleteKey(t){return this.req(`/resource/${encodeURIComponent(t)}`,{method:"DELETE"})}events(t){const n=new URLSearchParams;t?.sinceSeq!==void 0&&n.set("since_seq",String(t.sinceSeq)),t?.tail!==void 0&&n.set("tail",String(t.tail));const r=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/resource/events${r}`,this.getToken())}}class bc{constructor(t){this.req=t}async createRun(t){return this.req("/coder/runs",{method:"POST",body:JSON.stringify(t)})}async listRuns(t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit));const r=t?.workflow_mode??t?.workflowMode,s=t?.repo_slug??t?.repoSlug;r&&n.set("workflow_mode",r),s&&n.set("repo_slug",s);const c=n.toString()?`?${n.toString()}`:"",u=await this.req(`/coder/runs${c}`)??{},p=Array.isArray(u.runs)?u.runs:[];return{runs:p,count:typeof u.count=="number"?u.count:p.length}}async getRun(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}`)??{};return{...r,coderRun:r.coder_run??void 0,coder_run:r.coder_run??void 0,run:r.run??void 0}}async getProjectBinding(t){const r=await this.req(`/coder/projects/${encodeURIComponent(t)}/bindings`)??{};return{...r,binding:r.binding??null}}async putProjectBinding(t,n){const s=await this.req(`/coder/projects/${encodeURIComponent(t)}/bindings`,{method:"PUT",body:JSON.stringify(n)})??{};return{...s,binding:s.binding}}async getProjectGithubInbox(t){const r=await this.req(`/coder/projects/${encodeURIComponent(t)}/github-project/inbox`)??{};return{...r,items:Array.isArray(r.items)?r.items:[],binding:r.binding,project_id:String(r.project_id||r.projectId||""),schema_drift:!!(r.schema_drift??r.schemaDrift),live_schema_fingerprint:String(r.live_schema_fingerprint||r.liveSchemaFingerprint||"")}}async intakeProjectItem(t,n){const s=await this.req(`/coder/projects/${encodeURIComponent(t)}/github-project/intake`,{method:"POST",body:JSON.stringify(n)})??{};return{...s,coder_run:s.coder_run??void 0,coderRun:s.coder_run??void 0,run:s.run??void 0}}async executeNext(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-next`,{method:"POST",body:JSON.stringify(n??{})})}async executeAll(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/execute-all`,{method:"POST",body:JSON.stringify(n??{})})}async createFollowOnRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/follow-on-run`,{method:"POST",body:JSON.stringify(n)})}async approveRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n})})}async cancelRun(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n})})}async listArtifacts(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/artifacts`)??{},s=Array.isArray(r.artifacts)?r.artifacts:[];return{...r,artifacts:s,count:typeof r.count=="number"?r.count:s.length}}async getMemoryHits(t,n){const r=new URLSearchParams;n?.query&&r.set("q",n.query),n?.limit!==void 0&&r.set("limit",String(n.limit));const s=r.toString()?`?${r.toString()}`:"",d=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-hits${s}`)??{},u=Array.isArray(d.hits)?d.hits:[];return{...d,hits:u,count:typeof d.count=="number"?d.count:u.length}}async createTriageInspectionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-inspection-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageReproductionReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-reproduction-report`,{method:"POST",body:JSON.stringify(n)})}async createTriageSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/triage-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewEvidence(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-evidence`,{method:"POST",body:JSON.stringify(n)})}async createPrReviewSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-review-summary`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixValidationReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-validation-report`,{method:"POST",body:JSON.stringify(n)})}async createIssueFixSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/issue-fix-summary`,{method:"POST",body:JSON.stringify(n)})}async createPrDraft(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-draft`,{method:"POST",body:JSON.stringify(n??{})})}async submitPr(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/pr-submit`,{method:"POST",body:JSON.stringify(n??{})})}async createMergeReadinessReport(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-readiness-report`,{method:"POST",body:JSON.stringify(n)})}async createMergeRecommendationSummary(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/merge-recommendation-summary`,{method:"POST",body:JSON.stringify(n)})}async listMemoryCandidates(t){const r=await this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`)??{},s=Array.isArray(r.candidates)?r.candidates:[];return{...r,candidates:s,count:typeof r.count=="number"?r.count:s.length}}async createMemoryCandidate(t,n){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates`,{method:"POST",body:JSON.stringify(n)})}async promoteMemoryCandidate(t,n,r){return this.req(`/coder/runs/${encodeURIComponent(t)}/memory-candidates/${encodeURIComponent(n)}/promote`,{method:"POST",body:JSON.stringify(r??{})})}}class vc{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){return this.req("/routines")}async create(t){const n={...t};return"prompt"in n&&!("entrypoint"in n)&&(n.entrypoint=n.prompt),this.req("/routines",{method:"POST",body:JSON.stringify(n)})}async update(t,n){return this.req(`/routines/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){await this.req(`/routines/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const n=await this.req(`/routines/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return Jt(gi,n,`/routines/${t}/run_now`,200)}async listRuns(t){const n=new URLSearchParams;t?.routine_id&&n.set("routine_id",t.routine_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return this.req(`/routines/runs${r}`)}async getRunsForRoutine(t,n=25){return this.req(`/routines/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){const n=await this.req(`/routines/runs/${encodeURIComponent(t)}`);return Jt(fi,n,`/routines/runs/${t}`,200)}async listArtifacts(t){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/routines/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.routine_id??t?.routineId;r&&n.set("routine_id",r);const s=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/routines/events${s}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/routines/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class yc{constructor(t){this.req=t}async preview(t){return this.req("/workflow-plans/preview",{method:"POST",body:JSON.stringify({prompt:t.prompt,schedule:t.schedule,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,workspace_root:t.workspace_root??t.workspaceRoot,operator_preferences:t.operator_preferences??t.operatorPreferences})})}async apply(t){return this.req("/workflow-plans/apply",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId,plan:t.plan,creator_id:t.creator_id??t.creatorId,pack_builder_export:t.pack_builder_export??t.packBuilderExport})})}async chatStart(t){return this.req("/workflow-plans/chat/start",{method:"POST",body:JSON.stringify({prompt:t.prompt,schedule:t.schedule,plan_source:t.plan_source??t.planSource,allowed_mcp_servers:t.allowed_mcp_servers??t.allowedMcpServers,workspace_root:t.workspace_root??t.workspaceRoot,operator_preferences:t.operator_preferences??t.operatorPreferences})})}async get(t){return this.req(`/workflow-plans/${encodeURIComponent(t)}`)}async chatMessage(t){return this.req("/workflow-plans/chat/message",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId,message:t.message})})}async chatReset(t){return this.req("/workflow-plans/chat/reset",{method:"POST",body:JSON.stringify({plan_id:t.plan_id??t.planId})})}}class wc{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async list(){return this.req("/automations")}async create(t){return this.req("/automations",{method:"POST",body:JSON.stringify(t)})}async update(t,n){return this.req(`/automations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){await this.req(`/automations/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){const n=await this.req(`/automations/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})});return Jt(gi,n,`/automations/${t}/run_now`,200)}async listRuns(t){const n=new URLSearchParams;t?.automation_id&&n.set("automation_id",t.automation_id),t?.limit!==void 0&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return this.req(`/automations/runs${r}`)}async getRunsForAutomation(t,n=25){return this.req(`/automations/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){const n=await this.req(`/automations/runs/${encodeURIComponent(t)}`);return Jt(fi,n,`/automations/runs/${t}`,200)}async listArtifacts(t){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`)}async approveRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denyRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}async pauseRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async history(t,n){const r=n!==void 0?`?limit=${n}`:"",s=await this.req(`/automations/${encodeURIComponent(t)}/history${r}`);return Array.isArray(s)?{history:s,count:s.length}:s}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const c=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/automations/events${c}`,this.getToken(),{signal:t?.signal})}addArtifact(t,n){return this.req(`/automations/runs/${encodeURIComponent(t)}/artifacts`,{method:"POST",body:JSON.stringify(n)})}}class xc{constructor(t,n,r){this.baseUrl=t,this.getToken=n,this.req=r}async create(t){return this.req("/automations/v2",{method:"POST",body:JSON.stringify(t)})}async list(){return this.req("/automations/v2")}async get(t){return this.req(`/automations/v2/${encodeURIComponent(t)}`)}async update(t,n){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async delete(t){return this.req(`/automations/v2/${encodeURIComponent(t)}`,{method:"DELETE"})}async runNow(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/run_now`,{method:"POST",body:JSON.stringify({})})}async pause(t,n){return this.req(`/automations/v2/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resume(t){return this.req(`/automations/v2/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({})})}async listRuns(t,n=50){return this.req(`/automations/v2/${encodeURIComponent(t)}/runs?limit=${n}`)}async getRun(t){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}`)}async pauseRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/pause`,{method:"POST",body:JSON.stringify({reason:n??""})})}async resumeRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/resume`,{method:"POST",body:JSON.stringify({reason:n??""})})}async recoverRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/recover`,{method:"POST",body:JSON.stringify({reason:n??""})})}async repairRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/repair`,{method:"POST",body:JSON.stringify(n)})}async retryTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({reason:r??""})})}async previewTaskReset(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/reset_preview`)}async continueTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/continue`,{method:"POST",body:JSON.stringify({reason:r??""})})}async requeueTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/tasks/${encodeURIComponent(n)}/requeue`,{method:"POST",body:JSON.stringify({reason:r??""})})}async claimBacklogTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/backlog/tasks/${encodeURIComponent(n)}/claim`,{method:"POST",body:JSON.stringify(r||{})})}async requeueBacklogTask(t,n,r){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/backlog/tasks/${encodeURIComponent(n)}/requeue`,{method:"POST",body:JSON.stringify({reason:r??""})})}async cancelRun(t,n){return this.req(`/automations/v2/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({reason:n??""})})}events(t){const n=new URLSearchParams,r=t?.automation_id??t?.automationId,s=t?.run_id??t?.runId;r&&n.set("automation_id",r),s&&n.set("run_id",s);const c=n.toString()?`?${n.toString()}`:"";return tn(`${this.baseUrl}/automations/v2/events${c}`,this.getToken(),{signal:t?.signal})}}class kc{constructor(t){this.req=t}async list(){return this.req("/optimizations")}async create(t){return this.req("/optimizations",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.req(`/optimizations/${encodeURIComponent(t)}`)}async action(t,n){return this.req(`/optimizations/${encodeURIComponent(t)}/actions`,{method:"POST",body:JSON.stringify(n)})}async listExperiments(t){return this.req(`/optimizations/${encodeURIComponent(t)}/experiments`)}async getExperiment(t,n){return this.req(`/optimizations/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}`)}async applyWinner(t,n){return this.req(`/optimizations/${encodeURIComponent(t)}/experiments/${encodeURIComponent(n)}`,{method:"POST",body:JSON.stringify({})})}}class Nc{constructor(t){this.req=t}async listTemplates(){return this.req("/agent-team/templates")}async createTemplate(t){return this.req("/agent-team/templates",{method:"POST",body:JSON.stringify(t)})}async updateTemplate(t,n){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async deleteTemplate(t){return this.req(`/agent-team/templates/${encodeURIComponent(t)}`,{method:"DELETE"})}async composeStandup(t){return this.req("/agent-standup/compose",{method:"POST",body:JSON.stringify({name:t.name,workspace_root:t.workspaceRoot,schedule:t.schedule,participant_template_ids:t.participantTemplateIds,report_path_template:t.reportPathTemplate})})}async listInstances(t){const n=new URLSearchParams;t?.missionID&&n.set("missionID",t.missionID),t?.parentInstanceID&&n.set("parentInstanceID",t.parentInstanceID),t?.status&&n.set("status",t.status);const r=n.toString()?`?${n.toString()}`:"";return this.req(`/agent-team/instances${r}`)}async listMissions(){return this.req("/agent-team/missions")}async listApprovals(){return this.req("/agent-team/approvals")}async spawn(t){return this.req("/agent-team/spawn",{method:"POST",body:JSON.stringify(t)})}async approveSpawn(t,n){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/approve`,{method:"POST",body:JSON.stringify({reason:n??""})})}async denySpawn(t,n){return this.req(`/agent-team/approvals/spawn/${encodeURIComponent(t)}/deny`,{method:"POST",body:JSON.stringify({reason:n??""})})}}class _c{constructor(t){this.req=t}async list(){return this.req("/mission")}async create(t){return this.req("/mission",{method:"POST",body:JSON.stringify(t)})}async get(t){return this.req(`/mission/${encodeURIComponent(t)}`)}async applyEvent(t,n){return this.req(`/mission/${encodeURIComponent(t)}/event`,{method:"POST",body:JSON.stringify({event:n})})}}const gr="charcoal_fire",mn=[{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)"}}],Ra={duration:{normal:.22},easing:{standard:[.22,1,.36,1]},spring:{gentle:{type:"spring",stiffness:220,damping:26,mass:.9},snappy:{type:"spring",stiffness:320,damping:30,mass:.82},drawer:{type:"spring",stiffness:340,damping:34,mass:.82}}};function Xr(a){let t=String(a||"").trim()||gr;return t==="web_control"&&(t=gr),mn.find(n=>n.id===t)||mn[0]}function Sc(a){const t=Xr(a).id,n=mn.findIndex(r=>r.id===t);return n<0?gr:mn[(n+1)%mn.length].id}function yi(a,t=typeof document<"u"?document.documentElement:null){const n=Xr(a);if(!t)return n;for(const[r,s]of Object.entries(n.cssVars))s!=null&&t.style.setProperty(r,s);return t.dataset.theme=n.id,t.style.colorScheme=n.id==="porcelain"?"light":"dark",n}function wi(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const xi="tandem.themeId";function Ic(){try{const a=localStorage.getItem(xi);return Xr(a).id}catch{return gr}}function Cc(a){return yi(a)}function Ac(a){const t=yi(a);try{localStorage.setItem(xi,t.id)}catch{}return t}function Ln(){const[a,t]=w(()=>wi());return fe(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia("(prefers-reduced-motion: reduce)"),r=()=>t(n.matches);return r(),typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>n.removeEventListener("change",r)):(n.addListener(r),()=>n.removeListener(r))},[]),a}function Pc(a,t,n){return Math.min(n,Math.max(t,a))}function fr({className:a="",children:t}){return e("div",{className:`tcp-glow-layer ${a}`.trim(),children:t})}function vn({className:a="",children:t}){const n=Ln();return e(Re.div,{className:a,initial:n?!1:{opacity:0,y:14},animate:n?void 0:{opacity:1,y:0},exit:n?void 0:{opacity:0,y:-10},transition:n?void 0:{duration:Ra.duration.normal,ease:Ra.easing.standard},children:t})}function Tc({className:a="",children:t}){const n=Ln();return e(Re.div,{className:a,initial:n?!1:"hidden",animate:n?void 0:"show",variants:n?void 0:{hidden:{},show:{transition:{staggerChildren:.06,delayChildren:.02}}},children:t})}function ki({className:a="",children:t,as:n="div"}){const r=Ln(),s=n==="section"?Re.section:n==="article"?Re.article:Re.div;return e(s,{className:a,variants:r?void 0:{hidden:{opacity:0,y:12,scale:.985},show:{opacity:1,y:0,scale:1,transition:{duration:Ra.duration.normal,ease:Ra.easing.standard}}},initial:r?!1:"hidden",animate:r?void 0:"show",children:t})}function Rc({value:a,format:t=r=>String(r),className:n=""}){const r=Ln(),[s,c]=w(()=>Number(a||0)),d=Rt(Number(a||0));return fe(()=>{const u=Number(a||0);if(!Number.isFinite(u)){c(0),d.current=0;return}if(r){c(u),d.current=u;return}const p=d.current,N=u-p;if(!N){c(u),d.current=u;return}const E=performance.now();let x=0;const A=O=>{const _=Pc((O-E)/420,0,1),z=1-Math.pow(1-_,3),P=p+N*z;c(P),_<1?x=window.requestAnimationFrame(A):d.current=u};return x=window.requestAnimationFrame(A),()=>window.cancelAnimationFrame(x)},[r,a]),e("span",{className:n,children:t(Number.isFinite(s)?s:0)})}function ya({tone:a="ok",text:t,className:n=""}){return e("span",{className:`tcp-status-pulse ${a} ${n}`.trim(),children:[e("span",{className:"tcp-status-pulse-dot","aria-hidden":"true"}),t?e("span",{children:t}):null]})}function wa({className:a="",children:t}){return e("div",{className:`tcp-toolbar ${a}`.trim(),children:t})}function qn({className:a="",title:t,children:n,...r}){return e("button",{type:"button",title:t,className:`tcp-icon-btn ${a}`.trim(),...r,children:n})}function ve({tone:a="info",className:t="",children:n}){return e("span",{className:`${a==="ok"?"tcp-badge-ok":a==="warn"?"tcp-badge-warn":a==="err"?"tcp-badge-err":a==="ghost"?"tcp-badge tcp-badge-ghost":"tcp-badge-info"} ${t}`.trim(),children:n})}function Ar({active:a=!1,className:t="",children:n,...r}){return e("button",{type:"button",className:`tcp-filter-chip ${a?"active":""} ${t}`.trim(),...r,children:n})}function ot({title:a,subtitle:t,actions:n,className:r="",children:s}){return e(ki,{as:"section",className:`tcp-panel-card ${r}`.trim(),children:[a||t||n?e("div",{className:"tcp-panel-card-head",children:[e("div",{className:"min-w-0",children:[a?e("h3",{className:"tcp-title",children:a}):null,t?e("p",{className:"tcp-subtle mt-1",children:t}):null]}),n?e("div",{className:"shrink-0",children:n}):null]}):null,s]})}function Mc({text:a,title:t="Nothing here yet",action:n,className:r=""}){return e("div",{className:`tcp-empty-state ${r}`.trim(),children:[e("div",{className:"tcp-empty-state-orb"}),e("div",{className:"relative z-10",children:[e("div",{className:"tcp-empty-state-title",children:t}),e("p",{className:"tcp-subtle mt-1",children:a}),n?e("div",{className:"mt-3",children:n}):null]})]})}function qc({eyebrow:a,title:t,subtitle:n,badges:r,actions:s,className:c=""}){return e(ki,{className:`tcp-page-header ${c}`.trim(),children:[e(fr,{className:"tcp-page-header-glow"}),e("div",{className:"relative z-10 flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between",children:[e("div",{className:"min-w-0",children:[a?e("div",{className:"tcp-page-eyebrow",children:a}):null,e("h1",{className:"tcp-page-title",children:t}),n?e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:n}):null,r?e("div",{className:"mt-3 flex flex-wrap gap-2",children:r}):null]}),s?e(wa,{className:"justify-start lg:justify-end",children:s}):null]})]})}function En({className:a="",mainClassName:t="",asideClassName:n="",main:r,aside:s}){return e("div",{className:`tcp-split-view ${a}`.trim(),children:[e("div",{className:`min-w-0 ${t}`.trim(),children:r}),s?e("div",{className:`min-w-0 ${n}`.trim(),children:s}):null]})}function br({open:a,title:t,onClose:n,children:r}){const s=Ln();return e(Mt,{children:a?e(Re.div,{className:"tcp-drawer-root",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-drawer-backdrop","aria-label":"Close",onClick:n}),e(Re.aside,{className:"tcp-drawer-panel",initial:s?!1:{x:"100%"},animate:s?void 0:{x:0},exit:s?void 0:{x:"100%"},transition:s?void 0:Ra.spring.drawer,children:[e("div",{className:"tcp-drawer-head",children:[e("div",{className:"min-w-0",children:t?e("h3",{className:"tcp-title",children:t}):null}),e(qn,{title:"Close drawer",onClick:n,children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:r})]})]}):null})}function $c({loginMutation:a,savedToken:t,onCheckEngine:n,controlPanelName:r}){const[s,c]=w(t),[d,u]=w(!0),[p,N]=w(""),[E,x]=w(!1);return e("main",{className:"relative min-h-screen overflow-hidden px-5 py-8",children:[e(fr,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("div",{className:"relative z-10 mx-auto grid min-h-[calc(100vh-4rem)] w-full max-w-6xl items-center gap-6 lg:grid-cols-[1.05fr_0.95fr]",children:[e("section",{className:"grid gap-4",children:[e("div",{className:"tcp-page-eyebrow",children:"Tandem Control"}),e("h1",{className:"tcp-page-title max-w-3xl",children:"Sign in to continue."}),e("p",{className:"tcp-subtle max-w-2xl text-base",children:"Enter your engine token to access chat, orchestrator, automations, memory, live feed, and settings."})]}),e(ot,{title:r,subtitle:"Authenticate against your Tandem engine to continue.",children:e("form",{className:"grid gap-3",onSubmit:A=>{if(A.preventDefault(),!s.trim()){x(!1),N("Token is required.");return}a.mutate({token:s.trim(),remember:d})},children:[e("label",{className:"text-sm tcp-subtle",children:"Engine token"}),e("input",{className:"tcp-input",type:"password",value:s,onInput:A=>c(A.target.value),placeholder:"tk_...",autoComplete:"off"}),e("label",{className:"inline-flex items-center gap-2 text-xs tcp-subtle",children:[e("input",{type:"checkbox",className:"h-4 w-4 accent-slate-400",checked:d,onChange:A=>u(A.target.checked)}),"Remember token on this browser"]}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{disabled:a.isPending,type:"submit",className:"tcp-btn-primary w-full",children:[e("i",{"data-lucide":"key-round"}),"Sign in"]}),e("button",{type:"button",className:"tcp-btn w-full",onClick:async()=>{try{const A=await n();x(!0),N(A)}catch(A){x(!1),N(A instanceof Error?A.message:String(A))}},children:[e("i",{"data-lucide":"activity"}),"Check engine"]})]}),e("div",{className:`min-h-[1.2rem] text-sm ${E?"text-lime-300":"text-rose-300"}`,children:a.error?.message||p}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e("div",{className:"font-medium",children:"Readiness"}),e(ya,{tone:E?"ok":"warn",text:E?"Engine reachable":"Waiting"})]}),e("p",{className:"tcp-subtle text-xs",children:"Connectivity checks are non-destructive and help verify the local panel can reach the engine before authentication."})]})]})})]})]})}function Oc(a){fe(()=>{const t=n=>{(n.metaKey||n.ctrlKey)&&n.key.toLowerCase()==="k"&&(n.preventDefault(),a())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[a])}function Ec({open:a,onClose:t,actions:n}){const[r,s]=w("");fe(()=>{a||s("")},[a]),fe(()=>{if(!a)return;const d=u=>{u.key==="Escape"&&t()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[a,t]);const c=F(()=>{const d=r.trim().toLowerCase();return d?n.filter(u=>`${u.label} ${u.group}`.toLowerCase().includes(d)):n},[n,r]);return e(Mt,{children:a?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:e(Re.div,{className:"tcp-doc-dialog w-[min(44rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},transition:{duration:.16,ease:"easeOut"},onClick:d=>d.stopPropagation(),children:[e("div",{className:"tcp-doc-header",children:[e("h3",{className:"tcp-doc-title",children:"Command Palette"}),e("kbd",{className:"tcp-subtle text-xs",children:"Ctrl/Cmd + K"})]}),e("div",{className:"p-3",children:[e("input",{autoFocus:!0,value:r,onInput:d=>s(d.target.value),placeholder:"Jump to route or action",className:"tcp-input"}),e("div",{className:"mt-3 grid max-h-[50vh] gap-2 overflow-auto",children:[c.map(d=>e("button",{type:"button",className:"tcp-btn w-full justify-between",onClick:()=>{d.onSelect(),t()},children:[e("span",{className:"inline-flex items-center gap-1.5",children:[e("i",{"data-lucide":"list"}),e("span",{children:d.label})]}),e("span",{className:"tcp-subtle text-xs",children:d.group})]},d.id)),c.length?null:e("p",{className:"tcp-subtle px-1 py-2",children:"No matching action."})]})]})]})}):null})}const Ni=[["dashboard","Dashboard","home"],["chat","Chat","message-square"],["studio","Studio","network"],["automations","Automations","bot"],["coding","Coding","code"],["agents","Agents","users"],["orchestrator","Orchestrator","sparkles"],["memory","Memory","database"],["feed","Live Feed","radio"],["settings","Settings","settings"],["packs","Packs","package"],["teams","Teams","users"],["channels","Channels","message-circle"],["mcp","MCP","link"],["bug-monitor","Bug Monitor","bug-play"],["files","Files","folder-open"],["packs-detail","Packs","package"],["teams-detail","Teams","users"]],Dc=Ni.filter(([a])=>["dashboard","chat","studio","automations","coding","agents","orchestrator","memory","feed","settings"].includes(a)),_i={openai:{label:"OpenAI",keyUrl:"https://platform.openai.com/api-keys",placeholder:"sk-proj-..."},anthropic:{label:"Anthropic",keyUrl:"https://console.anthropic.com/settings/keys",placeholder:"sk-ant-..."},google:{label:"Google",keyUrl:"https://aistudio.google.com/app/apikey",placeholder:"AIza..."},groq:{label:"Groq",keyUrl:"https://console.groq.com/keys",placeholder:"gsk_..."},mistral:{label:"Mistral",keyUrl:"https://console.mistral.ai/api-keys/",placeholder:"..."},together:{label:"Together",keyUrl:"https://api.together.xyz/settings/api-keys",placeholder:"..."},cohere:{label:"Cohere",keyUrl:"https://dashboard.cohere.com/api-keys",placeholder:"..."},openrouter:{label:"OpenRouter",keyUrl:"https://openrouter.ai/settings/keys",placeholder:"sk-or-v1-..."},azure:{label:"Azure OpenAI",keyUrl:"https://portal.azure.com/",placeholder:"..."},bedrock:{label:"Bedrock",keyUrl:"https://console.aws.amazon.com/bedrock/",placeholder:"..."},vertex:{label:"Vertex",keyUrl:"https://console.cloud.google.com/vertex-ai",placeholder:"..."},copilot:{label:"GitHub Copilot",keyUrl:"https://github.com/settings/tokens",placeholder:"ghp_..."},ollama:{label:"Ollama",keyUrl:"",placeholder:"No key required"}},Si=Ni,jc=Dc,Uc=new Map([["packs","automations"],["teams","automations"],["swarm","orchestrator"],["failure-reporter","bug-monitor"]]),Bc=new Set(Si.map(([a])=>a));function Zr(a,t="dashboard"){const n=Uc.get(String(a||"").trim());return n||(Bc.has(a)?a:t)}function ks(a="dashboard"){const t=(window.location.hash||`#/${a}`).replace(/^#\//,"");return Zr(t.split("?")[0].split("/")[0].trim(),a)}function Fc(a){window.location.hash=`#/${a}`}function Lc(){const[a,t]=w(()=>ks());fe(()=>{const r=()=>t(ks());return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]);const n=ft(r=>{const s=Zr(r);if(window.location.hash!==`#/${s}`){Fc(s);return}t(s)},[]);return{route:a,navigate:n}}const Ii=co({toast:()=>{}});function Kc({children:a}){const[t,n]=w([]),r=ft((c,d)=>{const u=Math.random().toString(36).slice(2);n(p=>[...p,{id:u,kind:c,text:d}].slice(-4)),window.setTimeout(()=>{n(p=>p.filter(N=>N.id!==u))},3500)},[]),s=F(()=>({toast:r}),[r]);return e(Ii.Provider,{value:s,children:[a,e("div",{className:"toasts","aria-live":"polite","aria-atomic":"true",children:e(Mt,{children:t.map(c=>e(Re.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-${c.kind}`,children:c.text},c.id))})})]})}function Wc(){return uo(Ii)}function Yt({title:a,subtitle:t,children:n,actions:r,className:s}){return e(ot,{title:a,subtitle:t,actions:r,className:s||"",children:n})}function je({text:a,title:t,action:n}){return e(Mc,{text:a,title:t,action:n})}function aa(a){return JSON.stringify(a,null,2)}function Pr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function zc(a){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(Number(a||0))}function Jc(a){const{api:t,client:n,navigate:r,providerStatus:s}=a,[c,d]=w(""),u=new Set(["workflow","bug_monitor_triage"]),p=V({queryKey:["dashboard","health"],queryFn:()=>t("/api/system/health"),refetchInterval:15e3}),N=V({queryKey:["dashboard","sessions"],queryFn:()=>n.sessions.list({pageSize:8}).catch(()=>[]),refetchInterval:15e3}),E=V({queryKey:["dashboard","routines"],queryFn:()=>n.routines.list().catch(()=>({routines:[]})),refetchInterval:2e4}),x=V({queryKey:["dashboard","swarm"],queryFn:()=>t("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),A=V({queryKey:["dashboard","workflow-context-runs"],queryFn:()=>t("/api/engine/context/runs?limit=12").catch(()=>({runs:[]})),refetchInterval:6e3}),O=V({queryKey:["dashboard","workflow-context-run",c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}`).catch(()=>({run:null}))}),_=V({queryKey:["dashboard","workflow-context-blackboard",c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}/blackboard`).catch(()=>({blackboard:null}))}),z=Pr(N.data,"sessions"),P=Pr(E.data,"routines"),Q=Pr(A.data,"runs").filter(M=>u.has(String(M?.run_type||"").trim().toLowerCase())),B=!!(p.data?.engine?.ready||p.data?.engine?.healthy),ne=String(x.data?.status||"unknown"),I=["planning","awaiting_approval","running","executing"].includes(ne.toLowerCase()),C=Q.filter(M=>["queued","planning","running","awaiting_approval"].includes(String(M?.status||"").trim().toLowerCase())),H=F(()=>[{label:"Recent sessions",value:z.length,tone:"info",helper:"Latest active conversation surfaces"},{label:"Automations",value:P.length,tone:"ok",helper:"Configured routines and schedules"},{label:"Swarm status",value:I?1:0,tone:I?"warn":"ghost",helper:ne},{label:"Provider ready",value:s.ready?1:0,tone:s.ready?"ok":"warn",helper:s.ready?s.defaultModel:"Needs setup"},{label:"Context runs",value:Q.length,tone:C.length?"warn":"info",helper:C.length?`${C.length} active`:"Workflow + triage visibility"}],[C.length,s.defaultModel,s.ready,P.length,z.length,I,ne,Q.length]);return e(vn,{className:"grid gap-4",children:[e(ot,{className:"overflow-hidden",children:[e("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Overview"}),e("h1",{className:"tcp-page-title",children:"Command center"}),e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:"A higher-signal home screen with animated state, quick entry points, and a clearer read on what the system is doing right now."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e(ve,{tone:B?"ok":"warn",children:B?"Engine healthy":"Engine checking"}),e(ve,{tone:s.ready?"ok":"warn",children:s.ready?s.defaultProvider:"Provider setup required"}),I?e(ya,{tone:"live",text:`Swarm ${ne}`}):e(ve,{tone:"ghost",children:["Swarm ",ne]})]})]}),e("div",{className:"grid gap-3",children:e(wa,{className:"justify-start",children:[e("button",{className:"tcp-btn-primary w-full sm:w-auto",onClick:()=>r("chat"),children:[e("i",{"data-lucide":"message-square"}),"Chat session"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"sparkles"}),"Plan work"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Automations"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("coding"),children:[e("i",{"data-lucide":"code"}),"Coding workflows"]}),e("button",{className:"tcp-btn w-full sm:w-auto",onClick:()=>r("settings"),children:[e("i",{"data-lucide":"settings"}),"Configure runtime"]})]})})]}),e("div",{className:"mt-5",children:[e("div",{className:"dashboard-kpis",children:H.map(M=>e("div",{children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("span",{className:"dashboard-kpi-label",children:M.label}),e(ve,{tone:M.tone,children:M.helper})]}),e("strong",{children:e(Rc,{value:M.value,format:zc})})]},M.label))}),e("div",{className:"mt-4 dashboard-bars",children:[e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Engine readiness"}),e("span",{className:"dashboard-bar-count",children:B?"100%":"45%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:"dashboard-bar-fill completed",style:{width:B?"100%":"45%"}})})]}),e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Provider confidence"}),e("span",{className:"dashboard-bar-count",children:s.ready?"100%":"30%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${s.ready?"running":"queued"}`,style:{width:s.ready?"100%":"30%"}})})]}),e("div",{className:"dashboard-bar-row",children:[e("div",{className:"dashboard-bar-meta",children:[e("span",{children:"Automation activity"}),e("span",{className:"dashboard-bar-count",children:[P.length," routines"]})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${P.length?"scheduled":"manual"}`,style:{width:`${Math.min(100,Math.max(12,P.length*12))}%`}})})]})]})]})]}),e(En,{main:e(ot,{title:"Recent sessions",subtitle:"Latest conversations, ready to reopen.",children:e("div",{className:"grid gap-2",children:z.length?z.map(M=>e("button",{className:"tcp-list-item text-left",onClick:()=>r("chat"),children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"messages-square"}),String(M.title||M.id||"Session")]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(M.id||M.session_id||"")})]},String(M.id||M.session_id||Math.random()))):e(je,{text:"Start a conversation to populate recent sessions here."})})}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Context visibility",subtitle:"Recent workflow and failure-triage context runs with their current projection state.",children:[e(wa,{className:"mb-3",children:[e(ve,{tone:C.length?"warn":"info",children:[Q.length," recent"]}),e("button",{className:"tcp-btn",onClick:()=>r("orchestrator"),children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]})]}),e("div",{className:"grid gap-2",children:Q.length?Q.slice(0,5).map(M=>e("button",{className:"tcp-list-item text-left",onClick:()=>d(String(M?.run_id||"").trim()),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:String(M?.objective||M?.run_id||"Context run")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e(ve,{tone:"ghost",children:String(M?.run_type||"context")}),e(ve,{tone:["failed","cancelled"].includes(String(M?.status||"").toLowerCase())?"err":["running","queued","planning"].includes(String(M?.status||"").toLowerCase())?"warn":"ok",children:String(M?.status||"unknown")})]})]}),e("div",{className:"tcp-subtle text-xs",children:String(M?.run_id||"")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Array.isArray(M?.tasks)?M.tasks.length:0," tasks ·"," ",Array.isArray(M?.steps)?M.steps.length:0," steps"]})]},String(M?.run_id||Math.random()))):e(je,{text:"Workflow and failure-triage context runs will appear here once they execute."})})]}),e(ot,{title:"Automation snapshot",subtitle:"Schedules and run-ready routines.",children:[e(wa,{className:"mb-3",children:[e(ve,{tone:"info",children:[P.length," loaded"]}),e("button",{className:"tcp-btn",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Manage"]})]}),e("div",{className:"grid gap-2",children:P.length?P.slice(0,4).map(M=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:String(M.name||M.id||"Routine")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(M.schedule||M.status||"manual")})]},String(M.id||M.routine_id||Math.random()))):e(je,{text:"No routines are configured yet."})})]}),e(ot,{title:"Health notes",subtitle:"Direct links for the next likely action.",children:e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"activity"}),"Engine endpoint"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(p.data?.engineUrl||"Unavailable")})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"radio"}),"Swarm"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:["Status: ",ne]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":"database"}),"Memory & feed"]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>r("memory"),children:"Open memory"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>r("feed"),children:"Open live feed"})]})]})]})})]})}),e(br,{open:!!c,onClose:()=>d(""),title:c||"Workflow context run",children:c?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(O.data?.run?.objective||c)}),e(ve,{tone:"info",children:String(O.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["type: ",String(O.data?.run?.run_type||"workflow")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium mb-2",children:"Projected blackboard"}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(_.data?.blackboard?.tasks)?_.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(_.data?.blackboard?.artifacts)?_.data.blackboard.artifacts.length:0]})]}),e("pre",{className:"tcp-code",children:aa({run:O.data?.run||null,blackboard:_.data?.blackboard||null})})]}):null})]})}const Qc={Activity:Ol,Archive:$l,ArrowLeftToLine:ql,ArrowUpCircle:Ml,BadgeCheck:Rl,Binary:Tl,Bug:Pl,BugPlay:Al,Bot:Cl,BookOpen:Il,Check:Sl,ChevronDown:_l,ChevronRight:Nl,ClipboardList:kl,Clock:xl,Clock3:wl,Copy:yl,CopyPlus:vl,Code:bl,ExternalLink:fl,Cpu:gl,Database:hl,Download:pl,FileUp:ml,Filter:ul,FilterX:dl,FlaskConical:cl,FolderOpen:ll,History:ol,Home:il,Info:sl,KeyRound:rl,Link:nl,LoaderCircle:al,List:tl,LogOut:el,MessageCircle:Zo,MessageSquare:Xo,MessagesSquare:Yo,Menu:Vo,MonitorCog:Go,Network:Ho,Paperclip:Qo,Package:Jo,PaintBucket:zo,Pencil:Wo,Play:Ko,PlugZap:Lo,Plus:Fo,Pause:Bo,Radio:Uo,RefreshCw:jo,RotateCw:Do,Save:Eo,Search:Oo,Send:$o,Settings:qo,Settings2:Mo,ShieldAlert:Ro,ShieldCheck:To,SlidersHorizontal:Po,Sparkles:Ao,Siren:Co,Share2:Io,Shield:So,Square:_o,Trash2:No,TriangleAlert:ko,X:xo,XCircle:wo,Users:yo,Workflow:vo},Lr=new Set;let Kr=0;function Hc(){Kr=0;const a=[...Lr];Lr.clear();for(const t of a)bo({icons:Qc,attrs:{width:"16",height:"16","stroke-width":"1.8"},...t?{root:t}:{}})}function xa(a){Lr.add(a||null),!Kr&&(Kr=window.requestAnimationFrame(Hc))}hi.setOptions({gfm:!0,breaks:!0});function pn(a){const t=String(a||""),n=hi.parse(t,{async:!1});return Dl.sanitize(n)}const Wr="tcp.chat.session";function Ci(a){return String(a?.id||a?.session_id||a?.sessionID||"").trim()}function Gc(a){const t=String(a?.title||a?.name||"").trim();if(t)return t;const n=Ci(a);return n?`Session ${n.slice(0,8)}`:"Session"}function Vc(a){return Array.isArray(a)?a:Array.isArray(a?.sessions)?a.sessions:[]}function Yc(a){return String(a?.title||"").trim().toLowerCase().startsWith("__provider_test__")}function Ns(a){return Vc(a).filter(t=>!Yc(t)).map(t=>({id:Ci(t),title:Gc(t),raw:t})).filter(t=>!!t.id)}async function Xc(a,t){try{const n=await a.sessions.list({pageSize:50}),r=Ns(n);if(r.length>0)return r}catch{}try{const n=await t("/api/engine/session?page_size=50",{method:"GET"});return Ns(n)}catch{return[]}}function _s(){try{return localStorage.getItem(Wr)||""}catch{return""}}function Zc(a){try{a?localStorage.setItem(Wr,a):localStorage.removeItem(Wr)}catch{}}function ed(a){return Array.isArray(a)?a.map(n=>n?typeof n=="string"?n:typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:"":"").filter(Boolean).join(`
|
|
3
|
+
`).trim():""}function td(a){return String(a?.info?.role||a?.role||a?.message_role||a?.type||a?.author||"assistant").trim().toLowerCase()}function ad(a){const t=ed(a?.parts);if(t)return t;const n=[a?.content,a?.text,a?.message,a?.delta,a?.body].map(s=>typeof s=="string"?s:"").find(s=>s.trim().length>0);if(n)return n.trim();const r=a?.content;if(Array.isArray(r)){const s=r.map(c=>c?typeof c=="string"?c:typeof c?.text=="string"?c.text:typeof c?.content=="string"?c.content:"":"").filter(Boolean);if(s.length)return s.join(`
|
|
4
|
+
`).trim()}return""}function nd(a,t){return a==="assistant"?t||"Assistant":a==="user"?"User":a==="system"?"System":a||"Assistant"}function rd(a,t,n){const r=td(a),s=ad(a),c=r==="assistant"||r==="system";return{id:String(a?.id||a?.messageID||a?.message_id||a?.event_id||`${r}-${t}`).trim()||`${r}-${t}`,role:r,displayRole:nd(r,n),text:s,markdown:c}}function Ai(a,t){return(Array.isArray(a)?a:Array.isArray(a?.messages)?a.messages:[]).map((r,s)=>rd(r,s,t))}const Ss=new Set(["tool.called","tool_call.started","session.tool_call"]),Is=new Set(["tool.result","tool_call.completed","tool_call.failed","session.tool_result"]),sd=new Set(["run.complete","run.completed","session.run.finished","session.run.completed"]),id=new Set(["run.failed","session.run.failed","run.cancelled","run.canceled","session.run.cancelled","session.run.canceled"]);function Pi(a){return String(a||"").trim().replace(/\s+/g," ").replace(/[<>]/g,"")}function ln(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return Pi(t.tool||t.name||t.toolName||t.tool_id||t.toolID||n.tool||n.name||n.toolName||"")}function Cn(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return String(t.callID||t.toolCallID||t.tool_call_id||t.id||n.callID||n.toolCallID||n.tool_call_id||n.id||"").trim()}function Tr(a,t=""){const n=a?.properties||{};return String(a?.runId||a?.runID||a?.run_id||n.runID||n.runId||n.run_id||n.run?.id||t).trim()}function er(a){if(!a)return null;const t=a.request||a.approval||a.permission||{},n=String(a.id||a.requestID||a.requestId||a.approvalID||t.id||t.requestID||"").trim();return n?{id:n,tool:Pi(a.tool||t.tool||t.name||"tool")||"tool",permission:String(a.permission||t.permission||"").trim(),pattern:String(a.pattern||t.pattern||"").trim(),sessionId:String(a.sessionId||a.sessionID||a.session_id||t.sessionId||t.sessionID||"").trim(),status:String(a.status||t.status||"").trim().toLowerCase()}:null}function Cs(a){const t=String(a||"").trim().toLowerCase();return t?t.includes("approved")||t.includes("rejected")||t.includes("denied")||t.includes("resolved")||t.includes("expired")||t.includes("cancel")||t.includes("complete")||t.includes("done")||t.includes("timeout")?!1:t.includes("pending")||t.includes("request")||t.includes("ask")||t.includes("await")||t.includes("open")||t.includes("queue")||t.includes("new")||t.includes("progress")||t==="unknown":!0}function od(a,t){const n=t&&typeof t=="object"?t:{},r=String(a||"").trim()||"pack.event",s=String(n.path||"").trim(),c=String(n.attachment_id||n.attachmentId||"").trim(),d=String(n.connector||"").trim(),u=String(n.channel_id||n.channelId||"").trim(),p=String(n.sender_id||n.senderId||"").trim(),N=String(n.name||"").trim(),E=String(n.version||"").trim(),x=String(n.error||"").trim(),A=[];N&&A.push(N),E&&A.push(E),s&&A.push(s),d&&A.push(d),u&&A.push(`channel=${u}`),p&&A.push(`sender=${p}`);const O=A.join(" · ");return{id:`${r}:${c||s||N||"event"}`,type:r,path:s,attachmentId:c,connector:d,channelId:u,senderId:p,error:x,summary:O||r,at:Date.now()}}const Dn=new Map;function Ti(a,t){return`${t?"cred":"anon"}:${a}`}function ld(a,t=!0){const n=Ti(a,t),r=Dn.get(n);if(r&&!r.closed)return r;const s=new EventSource(a,{withCredentials:t}),c={source:s,listeners:new Set,errorListeners:new Set,refs:0,closed:!1};return s.onmessage=d=>{for(const u of[...c.listeners])try{u(d)}catch{}},s.onerror=d=>{for(const u of[...c.errorListeners])try{u(d)}catch{}s.readyState===EventSource.CLOSED&&(c.closed=!0,Dn.delete(n))},Dn.set(n,c),c}function es(a,t,n={}){const r=n.withCredentials!==!1,s=Ti(a,r),c=ld(a,r);return c.refs+=1,c.listeners.add(t),typeof n.onError=="function"&&c.errorListeners.add(n.onError),()=>{const d=Dn.get(s);d&&(d.listeners.delete(t),typeof n.onError=="function"&&d.errorListeners.delete(n.onError),d.refs=Math.max(0,d.refs-1),d.refs===0&&(d.closed=!0,d.source.close(),Dn.delete(s)))}}const cd="control-panel",Ri="tandem_control_panel_chat_auto_approve_tools",dd="tandem.automations.plannerSeed",ud={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 As(a=""){const t=String(a).toLowerCase().split(".").pop()||"";return ud[t]||"application/octet-stream"}function md(a="",t=""){if(!a||!t)return t||"";const n=String(a).replace(/[\\/]+$/,""),r=String(t).replace(/^[\\/]+/,"");return`${n}/${r}`}function pd(a){const t=Number(a||0);return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Rr(a,t){return!a||!t?!0:String(a).trim()===String(t).trim()}function hd(a){const t=String(a||"").trim();return t!=="server.connected"&&t!=="engine.lifecycle.ready"}function gd(a){return a==="completed"?"chat-tool-chip-ok":a==="failed"?"chat-tool-chip-failed":"chat-tool-chip-running"}function fd(){try{return localStorage.getItem(Ri)==="1"}catch{return!1}}function bd(a){try{localStorage.setItem(Ri,a?"1":"0")}catch{}}function vd(a){try{const t=String(a?.prompt||a?.goal||"").trim();if(!t)return;sessionStorage.setItem(dd,JSON.stringify({prompt:t,plan_source:String(a?.plan_source||"chat_setup").trim()||"chat_setup"}))}catch{}}function Va(a){return a instanceof Error?a.message:String(a)}function yd(a){return a.decision==="pass_through"?null:a.intent_kind==="provider_setup"?{title:"Provider setup",body:`Configure ${a.slots.provider_ids[0]||"a provider"} in Settings.`,cta:"Open Settings",actionType:"open_provider_setup",payload:a.proposed_action.payload||{}}:a.intent_kind==="integration_setup"?{title:"Tool connection",body:`Connect ${a.slots.integration_targets[0]||"the matching tool"} through MCP.`,cta:"Open MCP",actionType:"open_mcp_setup",payload:a.proposed_action.payload||{}}:a.intent_kind==="automation_create"?{title:"Automation setup",body:a.slots.goal||"Create an automation from this request.",cta:"Open Automations",actionType:"open_automations",payload:a.proposed_action.payload||{}}:{title:"Setup help",body:a.clarifier?.question||"Choose a setup path.",cta:"Open Settings",actionType:"open_provider_setup",payload:a.proposed_action.payload||{},clarifier:a.clarifier||void 0}}function wd({client:a,api:t,toast:n,providerStatus:r,identity:s,navigate:c}){const d=ca(),u=!!pi(),p=Rt(null),N=Rt(null),E=Rt(null),x=Rt(null),A=Rt(null),O=Rt(!0),_=Rt(null),z=Rt(null),[P,Q]=w([]),[B,ne]=w(!1),[I,C]=w(_s()),[H,M]=w([]),[xe,y]=w(!1),[v,j]=w(""),[he,ee]=w([]),[qe,$e]=w([]),[Le,re]=w(!1),[me,q]=w(""),[ge,Pe]=w(!1),[Te,se]=w([]),[Oe,Me]=w(new Set),[He,Y]=w([]),[Ze,ae]=w(new Set),[Ae,St]=w([]),[oe,W]=w(new Set),[lt,xt]=w(fd()),[rt,Et]=w(!1),[Fe,Bt]=w([]),[At,$t]=w(null),[We,ze]=w(null),tt=F(()=>P.find(U=>U.id===I)?.title||"Chat",[I,P]);fe(()=>(O.current=!0,()=>{O.current=!1,A.current?.abort(),_.current&&window.clearTimeout(_.current),z.current&&window.clearTimeout(z.current)}),[]),fe(()=>{const h=p.current;h&&xa(h)},[P,he,qe,Ae,Te,He,H,B,ge,me]),fe(()=>{Zc(I)},[I]),fe(()=>{const h=N.current;h&&(h.style.height="0px",h.style.height=`${Math.min(h.scrollHeight,180)}px`)},[v]),fe(()=>{const h=x.current;h&&(h.scrollTop=h.scrollHeight)},[H,me,ge]);const be=ft(async()=>{const h=await Xc(a,t);O.current&&(Q(h),C(U=>{if(U&&h.some(L=>L.id===U))return U;const J=_s();return J&&h.some(L=>L.id===J)?J:h[0]?.id||""}))},[t,a]),Se=ft(async()=>{const h=String(r.defaultProvider||"").trim(),U=String(r.defaultModel||"").trim();if(h&&U)return{providerID:h,modelID:U};try{const J=await a.providers.config(),L=String(J?.default||"").trim(),X=String(J?.providers?.[L]?.defaultModel||"").trim();if(L&&X)return{providerID:L,modelID:X}}catch{}return null},[a.providers,r.defaultModel,r.defaultProvider]),Ve=ft(async()=>{const h=await Se(),U={title:`Chat ${new Date().toLocaleTimeString()}`};h&&(U.provider=h.providerID,U.model=h.modelID);const J=await a.sessions.create(U),L=String(J||"").trim();if(!L)throw new Error("Failed to create session.");return C(L),await be(),L},[a.sessions,be,Se]),ce=ft(h=>{const U=Ai(h,s.botName||"Assistant");M(U)},[s.botName]),dt=ft(async()=>{if(!I){M([]);return}y(!0);try{const h=await a.sessions.messages(I).catch(()=>({messages:[]}));if(!O.current)return;ce(h)}finally{O.current&&y(!1)}},[a.sessions,ce,I]),S=ft(()=>{se([]),Me(new Set)},[]),G=ft(()=>{Y([]),ae(new Set)},[]),ue=ft((h,U,J="")=>{const L=String(h||"").trim();if(!L)return;let X=!0;J&&(Me(ye=>{if(ye.has(J))return X=!1,ye;const Ue=new Set(ye);return Ue.add(J),Ue.size>1e3?new Set([J]):Ue}),!X)||se(ye=>[{id:`${L}:${U}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:L,status:U,at:Date.now()},...ye].slice(0,80))},[]),Ke=ft((h,U)=>{const J=od(h,U);if(!String(J.type).toLowerCase().startsWith("pack."))return;let X=!0;ae(ye=>{if(ye.has(J.id))return X=!1,ye;const Ue=new Set(ye);return Ue.add(J.id),Ue.size>400?new Set([J.id]):Ue}),X&&Y(ye=>[J,...ye].slice(0,80))},[]),l=ft(h=>{Cs(h?.status||"")&&St(U=>{const J=U.findIndex(L=>L.id===h.id);if(J>=0){const L=[...U];return L[J]={...L[J],...h},L}return[h,...U]})},[]),b=ft(h=>{St(U=>U.filter(J=>J.id!==h))},[]),T=ft(async()=>{const h=await a.permissions.list().catch(()=>({requests:[]})),J=(Array.isArray(h?.requests)?h.requests:[]).map(L=>er(L)).filter(L=>!!L).filter(L=>Rr(L.sessionId,I)).filter(L=>Cs(L.status));O.current&&St(J.slice(0,80))},[a.permissions,I]),R=ft(async(h,U,J=!1)=>{if(!(!h||oe.has(h))){W(X=>{const ye=new Set(X);return ye.add(h),ye});try{await a.permissions.reply(h,U),b(h),J||n("ok",`Permission ${U==="deny"?"denied":"approved"} (${h}).`)}catch(X){J||n("err",Va(X))}finally{W(X=>{const ye=new Set(X);return ye.delete(h),ye}),T()}}},[a.permissions,oe,T,b,n]),$=ft(async()=>{if(!(!lt||rt||Ae.length===0)){Et(!0);try{for(const h of[...Ae])await R(h.id,"always",!0)}finally{O.current&&Et(!1)}}},[lt,rt,Ae,R]),Ye=ft(h=>(Array.isArray(h)?h:Array.isArray(h?.tools)?h.tools:[]).map(J=>{if(typeof J=="string")return J;const L=J||{};return String(L.name||L.id||L.tool||"").trim()}).filter(Boolean),[]),Xe=ft(async()=>{try{const h=await a.listTools?.().catch(()=>null);let U=Ye(h||[]);if(!U.length){const J=await t("/api/engine/tool",{method:"GET"}).catch(()=>[]);U=Ye(J||[])}if(O.current){const J=[...new Set(U)].sort((L,X)=>L.localeCompare(X));Bt(J)}}catch{O.current&&Bt([])}},[t,a,Ye]),Ot=ft(h=>new Promise((U,J)=>{const L=`${Date.now()}-${Math.random().toString(16).slice(2)}`;$e(ye=>[...ye,{id:L,name:h.name,progress:0,error:""}]);const X=new XMLHttpRequest;X.open("POST",`/api/files/upload?dir=${encodeURIComponent(cd)}`),X.withCredentials=!0,X.responseType="json",X.setRequestHeader("x-file-name",encodeURIComponent(h.name)),X.upload.onprogress=ye=>{if(!ye.lengthComputable)return;const Ue=ye.loaded/ye.total*100;$e(st=>st.map(vt=>vt.id===L?{...vt,progress:Ue}:vt))},X.onerror=()=>{$e(ye=>ye.map(Ue=>Ue.id===L?{...Ue,error:"Network error"}:Ue)),window.setTimeout(()=>{$e(ye=>ye.filter(Ue=>Ue.id!==L))},1200),J(new Error(`Upload failed: ${h.name}`))},X.onload=()=>{const ye=X.response||{};if(X.status<200||X.status>=300||ye?.ok===!1){const Ue=String(ye?.error||`Upload failed (${X.status})`);$e(st=>st.map(vt=>vt.id===L?{...vt,error:Ue}:vt)),window.setTimeout(()=>{$e(st=>st.filter(vt=>vt.id!==L))},1600),J(new Error(Ue));return}$e(Ue=>Ue.filter(st=>st.id!==L)),U(ye)},X.send(h)}),[]),Ft=ft(async h=>{const U=[...h||[]];if(!U.length)return;let J=0;for(const L of U)try{const X=await Ot(L);ee(ye=>[{name:String(X?.name||L.name),path:String(X?.path||L.name),size:Number(X?.size||L.size||0),mime:L.type||As(String(X?.name||L.name)),url:String(X?.absPath||md(X?.root,X?.path)||X?.path||L.name)},...ye]),J+=1}catch(X){n("err",Va(X))}J>0&&n("ok",`Uploaded ${J} file${J===1?"":"s"}.`)},[n,Ot]),Ie=ft(async h=>{if(await a.sessions.delete(h),Q(U=>U.filter(J=>J.id!==h)),$t(null),n("ok","Session deleted."),I===h){const U=P.find(J=>J.id!==h)?.id||"";if(U)C(U);else{const J=await Ve();C(J)}}},[a.sessions,Ve,I,P,n]),Pt=ft((h,U)=>{const J=String(h||"").trim();if(!J)return;const L=U>0?`
|
|
5
5
|
|
|
6
|
-
${j} attachment${j===1?"":"s"}`:"";q(V=>[...V,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",displayRole:"User",text:`${Q}${W}`,markdown:!1}])},[]),At=mt(async()=>{if(We)return;const h=v.trim(),j=[...ue],Q=h||(j.length?"Please analyze the attached file(s).":"");if(Q){try{const W=await t("/api/engine/setup/understand",{method:"POST",body:JSON.stringify({surface:"control_panel_chat",session_id:S||void 0,text:Q,channel:null,trigger:{source:"direct_message",is_direct_message:!0,was_explicitly_mentioned:!1,is_reply_to_bot:!1},scope:{kind:"direct",id:S||"control-panel-chat"}})});if(W.decision!=="pass_through"){const V=ed(W);if(V){Ge(V),U("");return}}}catch{}U(""),ne(!0),xt(Q,j.length);try{let W=S;if(W||(W=await Ye()),!W)throw new Error("No active session.");const V=await _e();if(!V)throw new Error("No default provider/model configured. Set it in Settings before sending chat.");const ge=j.map(Ne=>({type:"file",mime:Ne.mime||us(Ne.name||Ne.path),filename:Ne.name||Ne.path||"attachment",url:Ne.url||Ne.path}));ge.push({type:"text",text:Q});const Be=async()=>{const Ne=await fetch(`/api/engine/session/${encodeURIComponent(W)}/run`,{method:"GET",credentials:"include"});if(!Ne.ok)return"";const pe=await Ne.json().catch(()=>({}));return pe?.active?.runID||pe?.active?.runId||pe?.active?.run_id||""},ht=async()=>{const Ne=await Be().catch(()=>"");Ne&&await fetch(`/api/engine/session/${encodeURIComponent(W)}/run/${encodeURIComponent(Ne)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent(W)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{});for(let pe=0;pe<50;pe+=1){if(!await Be().catch(()=>""))return!0;await new Promise(He=>window.setTimeout(He,200))}return!1},ct=async()=>fetch(`/api/engine/session/${encodeURIComponent(W)}/prompt_async?return=run`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({parts:ge,model:{providerID:V.providerID,modelID:V.modelID}})});let kt=await ct(),tt="";if(kt.status===409){if(!await ht())throw new Error("Session has a stuck active run. Cancel it and retry.");if(kt=await ct(),kt.ok){const pe=await kt.json().catch(()=>({}));tt=pe?.runID||pe?.runId||pe?.run_id||""}else{if(kt.status===409)throw new Error("Session is still busy with another run. Retry in a moment.");{const pe=await kt.text().catch(()=>"");throw new Error(`prompt_async retry failed (${kt.status}): ${pe}`)}}}else if(kt.ok){const Ne=await kt.json().catch(()=>({}));tt=Ne?.runID||Ne?.runId||Ne?.run_id||""}else{const Ne=await kt.text().catch(()=>"");throw new Error(`prompt_async failed (${kt.status}): ${Ne}`)}if(!tt)throw new Error("No run ID returned from engine.");j.length&&ee([]),M(""),Re(!0);const Nt=new AbortController;C.current?.abort(),C.current=Nt;let Bt=!1,Jt=!1,vt="";const dt=3e4,Ie=18e4,Pe=async(Ne,pe)=>{const ut=Date.now();for(;Date.now()-ut<pe;){const He=await Be().catch(()=>Ne);if(await it(),!He||He!==Ne)return!0;await new Promise(_t=>window.setTimeout(_t,350))}return!1},ha=()=>{k.current&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{Jt=!0,vt="no-events-timeout",Nt.abort("no-events-timeout")},dt)};ha(),z.current&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{Jt=!0,vt="max-stream-window",Nt.abort("max-stream-window")},Ie);try{for await(const Ne of a.stream(W,tt,{signal:Nt.signal})){const pe=Ne;if(Hc(pe.type)&&ha(),pe.type==="approval.requested"||pe.type==="permission.request"||pe.type==="permission.asked"){const He=Kn(pe.properties||{});He&&br(He.sessionId,W)?(o(He),$()):R()}if(pe.type==="approval.resolved"||pe.type==="permission.resolved"||pe.type==="permission.replied"){const He=Kn(pe.properties||{});He?.id&&f(He.id),R()}String(pe.type||"").toLowerCase().startsWith("pack.")&&je(pe.type,pe.properties||{});const ut=fr(pe);if(!(ut&&ut!==tt)){if(pe.type==="session.response"){const He=String(pe.properties?.delta||"");if(!He)continue;Bt=!0,Re(!1),M(_t=>`${_t}${He}`)}if(ls.has(pe.type)){const He=sn(pe.properties)||"tool",_t=kn(pe.properties);be(He,"started",`${_t||ut||tt}:${He}:started`)}if(cs.has(pe.type)){const He=sn(pe.properties)||"tool",_t=kn(pe.properties),Kt=String(pe.properties?.status||pe.properties?.state||"").toLowerCase(),ia=pe.type==="tool_call.failed"||Kt.includes("fail")||Kt.includes("error")||!!pe.properties?.error;be(He,ia?"failed":"completed",`${_t||ut||tt}:${He}:${ia?"failed":"completed"}`)}if(pe.type==="message.part.updated"){const He=pe.properties?.part||{},_t=String(He.type||"").trim().toLowerCase().replace(/_/g,"-"),Kt=sn(He)||sn(pe.properties),ia=kn(He),Et=He?.state,Qt=String((Et&&typeof Et=="object"?Et.status:Et)||He.status||"").trim().toLowerCase(),Pt=!!He.error||!!(Et&&typeof Et=="object"&&Et.error)||Qt.includes("fail")||Qt.includes("error")||Qt.includes("deny")||Qt.includes("reject")||Qt.includes("cancel"),Xt=!!He.result||!!He.output||!!(Et&&typeof Et=="object"&&(Et.output||Et.result))||Qt.includes("done")||Qt.includes("complete")||Qt.includes("success");if(Kt&&(_t==="tool"||_t==="tool-invocation")){const Zt=Pt?"failed":Xt?"completed":"started";be(Kt,Zt,`${ia||ut||tt}:${Kt}:${Zt}`)}Kt&&_t==="tool-result"&&be(Kt,Pt?"failed":"completed",`${ia||ut||tt}:${Kt}:${Pt?"failed":"completed"}`)}if(Fc.has(pe.type))throw new Error(String(pe.properties?.error||"Run failed."));if((pe.type==="session.updated"||pe.type==="session.status")&&String(pe.properties?.status||"").toLowerCase()==="idle"||Bc.has(pe.type))break}}}catch(Ne){const pe=String(Ne?.message||Ne||"").toLowerCase();if(!(Jt||pe.includes("abort")||pe.includes("terminated")||pe.includes("networkerror")))throw Ne}finally{k.current&&window.clearTimeout(k.current),z.current&&window.clearTimeout(z.current)}if(Jt){const Ne=await Pe(tt,45e3);if(await it(),!Ne)throw new Error("Run stream timed out and the run is still active. Check logs and retry.")}if(Bt||Re(!0),await it(),await new Promise(Ne=>window.setTimeout(Ne,180)),await it(),await new Promise(Ne=>window.setTimeout(Ne,220)),await it(),!Bt&&await Be().catch(()=>"")===tt)if(await Pe(tt,3e4))await it();else throw new Error(`Run ${tt} is still active without a final response (${vt||"stream-ended"}).`);M(""),Re(!1),await ve(),await d.invalidateQueries({queryKey:["chat"]}).catch(()=>{})}catch(W){const V=Va(W),ge=V.includes("no-events-timeout")||V.includes("max-stream-window")||V.includes("AbortError")||V.toLowerCase().includes("terminated")?"Run stream timed out before events were received. Check engine/provider logs and retry.":V;n("err",ge),await it()}finally{O.current&&(ne(!1),Re(!1))}}},[t,xt,$,a,Ye,v,d,je,be,it,R,ve,f,_e,S,We,n,ue,o]);fe(()=>{ve(),et();const h=async()=>{const Q=await Ye().catch(()=>"");Q&&I(Q),ae(!1)};window.addEventListener("tcp:new-chat",h);const j=window.setInterval(()=>{ve()},8e3);return()=>{window.removeEventListener("tcp:new-chat",h),window.clearInterval(j)}},[Ye,et,ve]),fe(()=>{S&&(C.current?.abort(),ae(!1),_(),J(),R(),it())},[it,R,J,_,S]),fe(()=>{S||q([])},[S]),fe(()=>{!S&&A.length===0&&Ye().catch(()=>{})},[Ye,S,A.length]),fe(()=>{Xc(st),st&&$()},[st,$]),fe(()=>{const h=window.setInterval(()=>{S&&R()},2500);return()=>window.clearInterval(h)},[R,S]),fe(()=>{const h=Br("/api/global/event",j=>{let Q=null;try{Q=JSON.parse(String(j.data||"{}"))}catch{return}const W=String(Q?.type||"").trim();if(!W)return;const V=Q?.properties||{},ge=Kn(V);if(ge&&br(ge.sessionId,S)&&((W==="approval.requested"||W==="permission.request"||W==="permission.asked")&&o(ge),(W==="approval.resolved"||W==="permission.resolved"||W==="permission.replied")&&f(ge.id)),W.toLowerCase().startsWith("pack.")&&je(W,V),ls.has(W)){const Be=sn(V)||"tool",ht=kn(V),ct=fr(Q,"global");be(Be,"started",`${ht||ct}:${Be}:started`)}if(cs.has(W)){const Be=sn(V)||"tool",ht=kn(V),ct=fr(Q,"global"),kt=String(V?.status||V?.state||"").toLowerCase(),tt=W==="tool_call.failed"||kt.includes("fail")||!!V?.error;be(Be,tt?"failed":"completed",`${ht||ct}:${Be}:${tt?"failed":"completed"}`)}},{withCredentials:!0});return()=>h()},[je,be,f,S,o]);const te=ue.length,Se=!ye&&!H.length&&!me&&!ce;return e("div",{ref:p,className:"chat-layout chat-layout-fill min-w-0 min-h-0 h-full w-full flex-1",children:[e($e.aside,{className:`chat-sessions-panel ${B?"open":""}`,initial:!1,animate:u?{x:B?0:"-104%"}:{x:B?0:"-104%",transition:{duration:.18,ease:"easeOut"}},children:[e("div",{className:"chat-sessions-header",children:[e("h3",{className:"chat-sessions-title",children:[e("i",{"data-lucide":"history"}),"Sessions"]}),e("div",{className:"flex items-center gap-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{Ye().catch(h=>n("err",Va(h))),ae(!1)},children:[e("i",{"data-lucide":"plus"}),"New"]}),e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{ve()},children:e("i",{"data-lucide":"refresh-cw"})})]})]}),e("div",{className:"chat-session-list",children:[e(Mt,{children:A.map(h=>e($e.div,{className:"chat-session-row",initial:u?!1:{opacity:0,y:6},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-6},children:[e("button",{type:"button",className:`chat-session-btn ${h.id===S?"active":""}`,title:h.id,onClick:()=>{I(h.id),ae(!1)},children:e("span",{className:"block truncate",children:h.title})}),e("button",{type:"button",className:"chat-session-del",title:"Delete session",onClick:()=>Ut({id:h.id,title:h.title}),children:e("i",{"data-lucide":"trash-2"})})]},h.id))}),A.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No sessions yet."})]})]}),e(Mt,{children:B?e($e.button,{type:"button",className:"chat-scrim open","aria-label":"Close sessions",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>ae(!1)}):null}),e("div",{className:"chat-workspace min-h-0 min-w-0",children:[e("section",{className:"chat-main-shell flex min-h-0 min-w-0 flex-col overflow-hidden",children:[e("header",{className:"chat-main-header shrink-0",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Sessions",onClick:()=>ae(h=>!h),children:e("i",{"data-lucide":"history"})}),e("div",{className:"chat-main-dot"}),e("h3",{className:"tcp-title chat-main-title",children:nt}),De.length?e("span",{className:"chat-main-tools",children:[De.length," tools"]}):null]}),Je?e("div",{className:"mx-3 mb-2 rounded-xl border border-amber-500/30 bg-amber-500/8 p-3",children:[e("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"tcp-title text-sm",children:Je.title}),e("div",{className:"tcp-subtle text-sm",children:Je.body})]}),e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>Ge(null),children:"Dismiss"})]}),Je.clarifier?e("div",{className:"mb-2 flex flex-wrap gap-2",children:Je.clarifier.options.map(h=>e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>Ge({title:h.id==="provider_setup"?"Provider setup":h.id==="integration_setup"?"Tool connection":"Automation setup",body:h.id==="provider_setup"?"Open Settings to configure a provider.":h.id==="integration_setup"?"Open MCP to connect the tool you need.":"Open Automations to build the workflow.",cta:h.id==="provider_setup"?"Open Settings":h.id==="integration_setup"?"Open MCP":"Open Automations",actionType:h.id==="provider_setup"?"open_provider_setup":h.id==="integration_setup"?"open_mcp_setup":"open_automations",payload:Je.payload}),children:h.label},h.id))}):null,e("button",{type:"button",className:"tcp-btn",onClick:()=>{Je.actionType==="open_provider_setup"?c("settings"):Je.actionType==="open_mcp_setup"?c("mcp"):Je.actionType==="open_automations"&&(Zc(Je.payload),c("automations"))},children:Je.cta})]}):null,e("div",{ref:x,className:`chat-messages mb-2 min-h-0 min-w-0 flex-1 overflow-auto p-3 ${Se?"chat-messages-empty":"space-y-2"}`,children:[ye&&!H.length?e("p",{className:"chat-rail-empty",children:"Loading messages..."}):null,Se?e("div",{className:"chat-empty-state",children:e("p",{className:"chat-rail-empty",children:"No messages yet. Send a prompt to start."})}):null,e(Mt,{initial:!1,children:H.map(h=>{const j=h.role==="assistant"||h.role==="system",Q=j?"assistant":"user";return e($e.article,{className:`chat-msg ${Q}`,initial:u?!1:{opacity:0,y:4},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-4},children:[e("div",{className:"chat-msg-role",children:j?e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:h.displayRole})]}):h.displayRole}),h.markdown?e("div",{className:"tcp-markdown tcp-markdown-ai",dangerouslySetInnerHTML:{__html:dn(h.text||"")}}):e("pre",{className:"chat-msg-pre",children:h.text})]},h.id)})}),me||ce?e("article",{className:"chat-msg assistant",children:[e("div",{className:"chat-msg-role",children:e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:s.botName||"Assistant"})]})}),me&&!ce?e("div",{className:"tcp-thinking","aria-live":"polite",children:[e("span",{children:"Thinking"}),e("i",{}),e("i",{}),e("i",{})]}):null,ce?e("pre",{className:"chat-msg-pre",children:ce}):null]}):null]}),e("div",{className:"chat-composer shrink-0",children:[e("div",{className:`chat-attach-row mb-2 ${te?"":"hidden"}`,children:[e("span",{className:"tcp-subtle",children:[te," attached"]}),e("div",{className:"chat-files-line",children:ue.map((h,j)=>e("span",{className:"chat-file-pill min-w-0",children:[e("span",{className:"chat-file-pill-name",title:h.path,children:h.path}),e("span",{className:"chat-file-pill-size",children:Gc(h.size)}),e("button",{type:"button",className:"chat-file-pill-btn chat-file-pill-btn-danger",title:"Remove from list",onClick:()=>ee(Q=>Q.filter((W,V)=>V!==j)),children:e("i",{"data-lucide":"x"})})]},`${h.path}-${j}`))})]}),Oe.length?e("div",{className:"mb-2 grid gap-1.5",children:Oe.map(h=>{const j=Math.max(0,Math.min(100,Number(h.progress||0)));return e("div",{className:"chat-upload-card",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2 text-xs",children:[e("span",{className:"chat-upload-name truncate",children:h.name}),e("span",{className:h.error?"chat-upload-meta-error":"chat-upload-meta",children:h.error||`${j.toFixed(0)}%`})]}),e("div",{className:"chat-upload-bar",children:e("div",{className:"chat-upload-bar-fill",style:{width:`${j}%`}})})]},h.id)})}):null,e("div",{className:"chat-input-wrap",children:[e("input",{ref:E,type:"file",className:"hidden",multiple:!0,onChange:h=>{Ot(h.target.files),h.target.value=""}}),e("button",{type:"button",className:"chat-icon-btn chat-icon-btn-inner",title:"Attach files",onClick:()=>E.current?.click(),children:e("i",{"data-lucide":"paperclip"})}),e("textarea",{ref:N,rows:1,value:v,className:"tcp-input chat-input-with-clip chat-input-modern resize-none",placeholder:"Ask anything... (Enter to send, Shift+Enter newline)",onInput:h=>U(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),At())}}),e("button",{type:"button",className:"chat-send-btn",title:"Send",disabled:We,onClick:()=>{At()},children:e("i",{"data-lucide":"send"})})]})]})]}),e("aside",{className:"chat-right-rail hidden min-h-0 flex-col gap-3 overflow-hidden xl:flex",children:[e("section",{className:"min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tools"}),e("span",{className:"chat-rail-count",children:De.length})]}),e("div",{className:"chat-tools-list",children:De.length?De.slice(0,32).map(h=>e("button",{type:"button",className:"chat-tool-pill",title:`Insert ${h}`,onClick:()=>{U(j=>j.trim()?`${j} ${h}`:h),N.current?.focus()},children:h},h)):e("p",{className:"chat-rail-empty",children:"No tools loaded."})})]}),e("section",{className:"min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Approvals"}),e("span",{className:"chat-rail-count",children:Ce.length})]}),e("div",{className:"mb-2 flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",disabled:!Ce.length||lt,onClick:async()=>{const h=Ce.map(Q=>Q.id).filter(Boolean);if(!h.length)return;for(const Q of h)await P(Q,"once",!0);await R();const j=h.filter(Q=>Ce.some(W=>String(W.id||"").trim()===Q)).length;j>0?n("warn",`${j} request${j===1?"":"s"} still pending (likely stale/expired).`):n("ok",`Approved ${h.length} pending request${h.length===1?"":"s"}.`)},children:"Approve all"}),e("label",{className:"chat-auto-approve-label",children:[e("input",{type:"checkbox",className:"chat-auto-approve-checkbox",checked:st,onChange:h=>pt(h.target.checked)}),"Auto"]})]}),e("div",{className:"chat-tools-activity",children:Ce.length?Ce.slice(0,20).map(h=>{const j=ie.has(h.id),Q=[h.permission,h.pattern].filter(Boolean).join(" ");return e("article",{className:"chat-pack-event-card",children:[e("div",{className:"chat-pack-event-title truncate",title:h.id,children:h.tool}),e("div",{className:"chat-pack-event-summary mt-0.5",children:Q||h.id}),e("div",{className:"mt-1 flex gap-1",children:[e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:j,onClick:()=>{P(h.id,"once")},children:"Allow"}),e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:j,onClick:()=>{P(h.id,"always")},children:"Always"}),e("button",{className:"tcp-btn-danger h-6 px-1.5 text-[10px]",disabled:j,onClick:()=>{P(h.id,"deny")},children:"Deny"})]})]},h.id)}):e("p",{className:"chat-rail-empty",children:"No pending approvals."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Pack Events"}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:"chat-rail-count",children:ze.length}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:()=>{J()},children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]})]}),e("div",{className:"chat-tools-activity",children:ze.length?ze.slice(0,20).map(h=>e($e.article,{className:"chat-pack-event-card",initial:u?!1:{opacity:0,y:6},animate:u?void 0:{opacity:1,y:0},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"chat-pack-event-title truncate",title:h.type,children:h.type}),e("span",{className:"chat-pack-event-time",children:new Date(h.at).toLocaleTimeString()})]}),e("div",{className:"chat-pack-event-summary mt-0.5",children:h.summary}),h.error?e("div",{className:"chat-pack-event-error mt-1",children:h.error}):null,e("div",{className:"mt-1 flex flex-wrap gap-1",children:[e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:()=>c("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Packs"]}),h.path?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const j=await t("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:h.path,source:{kind:"control_panel_chat",event:"pack.detected"}})});n("ok",`Installed ${j?.installed?.name||"pack"} ${j?.installed?.version||""}`.trim())}catch(j){n("err",`Install failed: ${Va(j)}`)}},children:[e("i",{"data-lucide":"download"}),"Install path"]}):null,h.path&&h.attachmentId?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const j=await t("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:h.attachmentId,path:h.path,connector:h.connector||void 0,channel_id:h.channelId||void 0,sender_id:h.senderId||void 0})});n("ok",`Installed ${j?.installed?.name||"pack"} ${j?.installed?.version||""}`.trim())}catch(j){n("err",`Install failed: ${Va(j)}`)}},children:[e("i",{"data-lucide":"paperclip"}),"Install attach"]}):null]})]},`${h.id}-${h.at}`)):e("p",{className:"chat-rail-empty",children:"No pack events yet."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tool Activity"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:_,children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]}),e("div",{className:"chat-tools-activity",children:qe.length?qe.slice(0,24).map(h=>e("div",{className:`chat-tool-chip ${Vc(h.status)}`,children:[h.tool,": ",h.status]},h.id)):e("p",{className:"chat-rail-empty",children:"No tool events yet."})})]})]})]}),e(Mt,{children:yt?e($e.div,{className:"tcp-confirm-overlay",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>Ut(null),children:e($e.div,{className:"tcp-confirm-dialog",initial:u?!1:{opacity:0,y:8,scale:.98},animate:u?void 0:{opacity:1,y:0,scale:1},exit:u?void 0:{opacity:0,y:6,scale:.98},onClick:h=>h.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Delete session"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:yt.title})," and all its messages."]}),e("div",{className:"tcp-confirm-actions",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>Ut(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{type:"button",className:"tcp-btn-danger",onClick:()=>{Ae(yt.id).catch(h=>n("err",Va(h)))},children:[e("i",{"data-lucide":"trash-2"}),"Delete session"]})]})]})}):null})]})}function fn(a){return a?.checkpoint||{}}function Rr(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function ms(a){const t=a?.properties||{};return String(a?.run_id||a?.runId||a?.runID||t?.run_id||t?.runId||t?.runID||t?.run?.id||"").trim()}function Ia(a){return String(a?.type||a?.event_type||a?.event||"").trim()}function un(a){const t=a?.properties||{},n=a?.timestamp_ms||a?.timestampMs||t?.timestamp_ms||t?.timestampMs||t?.firedAtMs||Date.now(),r=Number(n);return Number.isFinite(r)?r:Date.now()}function cr(a){const t=a?.properties||a||{};return String(t?.reason||t?.detail||t?.error?.message||t?.error||t?.message||t?.status||"").trim()}function gi(a,t=""){return String(a?.properties?.sessionID||a?.sessionID||t||"").trim()}function Fr(a,t,n){return(Array.isArray(a?.[t])?a[t]:Array.isArray(a?.[n])?a[n]:[]).map(s=>String(s||"").trim()).filter(Boolean)}function Ya(a){return Array.isArray(a)?a.map(t=>String(t||"").trim()).filter(Boolean):[]}function Kr(a){return Fr(fn(a),"completed_nodes","completedNodes")}function fi(a){return String(a?.status||a?.content?.status||"").trim().toLowerCase()}function bi(a){const t=new Set(Fr(fn(a),"blocked_nodes","blockedNodes"));for(const{nodeId:n,value:r}of Wr(a))fi(r)==="blocked"&&t.add(n);return Array.from(t)}function ad(a){const t=new Set;for(const{nodeId:n,value:r}of Wr(a)){const s=fi(r);(s==="verify_failed"||s==="failed")&&t.add(n)}return Array.from(t)}function Lr(a){return Fr(fn(a),"pending_nodes","pendingNodes")}function ps(a){return Kr(a).length}function nd(a){return Lr(a).length}function Xn(a){return bi(a).length}function La(a){const t=String(a?.status||"").trim().toLowerCase();return(t==="completed"||t==="done")&&Xn(a)>0?"blocked":(t==="completed"||t==="done")&&ad(a).length>0?"failed":t||"unknown"}function hs(a){return(Array.isArray(a?.active_session_ids)?a.active_session_ids:Array.isArray(a?.activeSessionIds)?a.activeSessionIds:[]).length}function dr(a){const t=fn(a);return t?.node_outputs||t?.nodeOutputs||{}}function Wr(a){return Object.entries(dr(a)).map(([t,n])=>({nodeId:t,value:n}))}function ur(a,t){const n=String(t||"").trim();return n&&dr(a)[n]||null}function rd(a,t){const n=fn(a),r=String(t||"").trim();return r?Number(n?.node_attempts?.[r]||n?.nodeAttempts?.[r]||0):0}function sd(a,t){const n=ur(a,t);return String(n?.content?.session_id||n?.content?.sessionId||"").trim()}function id(a,t,n){const r=new Set(Kr(a)),s=new Set(bi(a)),c=new Set(Lr(a)),d=String(t||"").trim();if(!d)return n.length?"pending":"runnable";if(r.has(d))return"done";const u=ur(a,d),p=String(u?.status||u?.content?.status||"").trim().toLowerCase();if(p==="done")return"done";if(p==="verify_failed"||p==="failed")return"failed";if(s.has(d)||p==="blocked")return"blocked";const N=String(u?.error||u?.content?.error||u?.content?.message||u?.content?.status_message||"").trim().toLowerCase();return N&&(N.includes("failed")||N.includes("error"))?"failed":(c.has(d),n.length?"pending":"runnable")}function od(a,t=""){const n=String(t||"").trim();if(n)return n;const r=Array.isArray(a)?a:[];return r.find(s=>s.state==="in_progress"||s.state==="assigned")?.id||r.find(s=>s.state==="runnable")?.id||""}function ld(a){const t=Lr(a),n=String(t[0]||"").trim();return n?n.startsWith("node-")?n:`node-${n}`:""}function cd(a,t=""){const n=Array.isArray(a?.automation_snapshot?.flow?.nodes)?a.automation_snapshot.flow.nodes:[];if(!n.length)return{currentTaskId:"",taskSource:"empty",tasks:[]};const r=new Set(Kr(a)),s=n.map(c=>{const d=String(c?.node_id||"").trim(),u=`node-${d}`,p=Array.isArray(c?.depends_on)?c.depends_on.map(k=>`node-${String(k||"").trim()}`).filter(Boolean):[],N=p.every(k=>r.has(k.replace(/^node-/,""))),E=id(a,d,N?[]:p),x=ur(a,d)||{},C=t===u&&String(a?.status||"").trim().toLowerCase()==="running"?"in_progress":E==="pending"&&N?"runnable":E,O=c?.metadata?.builder||{};return{id:u,title:String(c?.objective||d||"Workflow node"),description:c?.agent_id?`agent: ${c.agent_id}`:"",dependencies:p,state:C,retry_count:rd(a,d),error_message:String(x?.error||x?.content?.error||""),runtime_status:String(x?.status||x?.content?.status||""),runtime_detail:String(x?.summary||x?.content?.message||""),assigned_role:String(c?.agent_id||""),workflow_id:String(a?.automation_id||""),session_id:sd(a,d),projects_backlog_tasks:!!O?.project_backlog_tasks,backlog_task_id:String(O?.task_id||""),task_kind:String(O?.task_kind||""),repo_root:String(O?.repo_root||""),write_scope:String(O?.write_scope||""),acceptance_criteria:String(O?.acceptance_criteria||""),task_dependencies:String(O?.task_dependencies||""),verification_state:String(O?.verification_state||""),task_owner:String(O?.task_owner||""),verification_command:String(O?.verification_command||""),output_path:String(O?.output_path||"")}});return{currentTaskId:od(s,t),taskSource:"checkpoint",tasks:s}}function vi(a){const t=fn(a);return Array.isArray(t?.lifecycle_history)?t.lifecycle_history:Array.isArray(t?.lifecycleHistory)?t.lifecycleHistory:[]}function yi(a){const t=vi(a);return t.length&&[...t].sort((n,r)=>Number(r?.recorded_at_ms||r?.recordedAtMs||0)-Number(n?.recorded_at_ms||n?.recordedAtMs||0)).find(n=>String(n?.event||"").trim())||null}function zr(a){return String(a?.metadata?.node_id||a?.metadata?.nodeId||"").trim()}function wi(a){const t=zr(a);return t?t.startsWith("node-")?t:`node-${t}`:""}function dd(a,t,n=8){const r=String(t||"").trim();return r?vi(a).filter(s=>zr(s)===r).slice(-n).reverse():[]}function ud(a,t,n=8){return dd(a,t,n).map(r=>({...bd(r),raw:r}))}function md(a){const t=yi(a);return wi(t)}function pd(a){const t=Object.values(dr(a)).filter(Boolean);return t.length&&t[t.length-1]||null}function hd(a){const t=String(a?.summary||"").trim(),n=String(a?.status||a?.content?.status||"").trim(),r=String(a?.blocked_reason||a?.blockedReason||"").trim(),s=a?.content||{},c=String(s?.text||s?.raw_text||"").trim();return[t,n?`status: ${n}`:"",r,c].filter(Boolean).join(`
|
|
7
|
-
`).trim()}function
|
|
6
|
+
${U} attachment${U===1?"":"s"}`:"";M(X=>[...X,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",displayRole:"User",text:`${J}${L}`,markdown:!1}])},[]),bt=ft(async()=>{if(Le)return;const h=v.trim(),U=[...he],J=h||(U.length?"Please analyze the attached file(s).":"");if(J){try{const L=await t("/api/engine/setup/understand",{method:"POST",body:JSON.stringify({surface:"control_panel_chat",session_id:I||void 0,text:J,channel:null,trigger:{source:"direct_message",is_direct_message:!0,was_explicitly_mentioned:!1,is_reply_to_bot:!1},scope:{kind:"direct",id:I||"control-panel-chat"}})});if(L.decision!=="pass_through"){const X=yd(L);if(X){ze(X),j("");return}}}catch{}j(""),re(!0),Pt(J,U.length);try{let L=I;if(L||(L=await Ve()),!L)throw new Error("No active session.");const X=await Se();if(!X)throw new Error("No default provider/model configured. Set it in Settings before sending chat.");const ye=U.map(Ce=>({type:"file",mime:Ce.mime||As(Ce.name||Ce.path),filename:Ce.name||Ce.path||"attachment",url:Ce.url||Ce.path}));ye.push({type:"text",text:J});const Ue=async()=>{const Ce=await fetch(`/api/engine/session/${encodeURIComponent(L)}/run`,{method:"GET",credentials:"include"});if(!Ce.ok)return"";const we=await Ce.json().catch(()=>({}));return we?.active?.runID||we?.active?.runId||we?.active?.run_id||""},st=async()=>{const Ce=await Ue().catch(()=>"");Ce&&await fetch(`/api/engine/session/${encodeURIComponent(L)}/run/${encodeURIComponent(Ce)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent(L)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{});for(let we=0;we<50;we+=1){if(!await Ue().catch(()=>""))return!0;await new Promise(Qe=>window.setTimeout(Qe,200))}return!1},vt=async()=>fetch(`/api/engine/session/${encodeURIComponent(L)}/prompt_async?return=run`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({parts:ye,model:{providerID:X.providerID,modelID:X.modelID}})});let It=await vt(),et="";if(It.status===409){if(!await st())throw new Error("Session has a stuck active run. Cancel it and retry.");if(It=await vt(),It.ok){const we=await It.json().catch(()=>({}));et=we?.runID||we?.runId||we?.run_id||""}else{if(It.status===409)throw new Error("Session is still busy with another run. Retry in a moment.");{const we=await It.text().catch(()=>"");throw new Error(`prompt_async retry failed (${It.status}): ${we}`)}}}else if(It.ok){const Ce=await It.json().catch(()=>({}));et=Ce?.runID||Ce?.runId||Ce?.run_id||""}else{const Ce=await It.text().catch(()=>"");throw new Error(`prompt_async failed (${It.status}): ${Ce}`)}if(!et)throw new Error("No run ID returned from engine.");U.length&&ee([]),q(""),Pe(!0);const yt=new AbortController;A.current?.abort(),A.current=yt;let Lt=!1,Qt=!1,Ct="";const Ht=3e4,kt=18e4,Ge=async(Ce,we)=>{const ut=Date.now();for(;Date.now()-ut<we;){const Qe=await Ue().catch(()=>Ce);if(await dt(),!Qe||Qe!==Ce)return!0;await new Promise(qt=>window.setTimeout(qt,350))}return!1},da=()=>{_.current&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{Qt=!0,Ct="no-events-timeout",yt.abort("no-events-timeout")},Ht)};da(),z.current&&window.clearTimeout(z.current),z.current=window.setTimeout(()=>{Qt=!0,Ct="max-stream-window",yt.abort("max-stream-window")},kt);try{for await(const Ce of a.stream(L,et,{signal:yt.signal})){const we=Ce;if(hd(we.type)&&da(),we.type==="approval.requested"||we.type==="permission.request"||we.type==="permission.asked"){const Qe=er(we.properties||{});Qe&&Rr(Qe.sessionId,L)?(l(Qe),$()):T()}if(we.type==="approval.resolved"||we.type==="permission.resolved"||we.type==="permission.replied"){const Qe=er(we.properties||{});Qe?.id&&b(Qe.id),T()}String(we.type||"").toLowerCase().startsWith("pack.")&&Ke(we.type,we.properties||{});const ut=Tr(we);if(!(ut&&ut!==et)){if(we.type==="session.response"){const Qe=String(we.properties?.delta||"");if(!Qe)continue;Lt=!0,Pe(!1),q(qt=>`${qt}${Qe}`)}if(Ss.has(we.type)){const Qe=ln(we.properties)||"tool",qt=Cn(we.properties);ue(Qe,"started",`${qt||ut||et}:${Qe}:started`)}if(Is.has(we.type)){const Qe=ln(we.properties)||"tool",qt=Cn(we.properties),ia=String(we.properties?.status||we.properties?.state||"").toLowerCase(),ba=we.type==="tool_call.failed"||ia.includes("fail")||ia.includes("error")||!!we.properties?.error;ue(Qe,ba?"failed":"completed",`${qt||ut||et}:${Qe}:${ba?"failed":"completed"}`)}if(we.type==="message.part.updated"){const Qe=we.properties?.part||{},qt=String(Qe.type||"").trim().toLowerCase().replace(/_/g,"-"),ia=ln(Qe)||ln(we.properties),ba=Cn(Qe),Kt=Qe?.state,Gt=String((Kt&&typeof Kt=="object"?Kt.status:Kt)||Qe.status||"").trim().toLowerCase(),mt=!!Qe.error||!!(Kt&&typeof Kt=="object"&&Kt.error)||Gt.includes("fail")||Gt.includes("error")||Gt.includes("deny")||Gt.includes("reject")||Gt.includes("cancel"),ua=!!Qe.result||!!Qe.output||!!(Kt&&typeof Kt=="object"&&(Kt.output||Kt.result))||Gt.includes("done")||Gt.includes("complete")||Gt.includes("success");if(ia&&(qt==="tool"||qt==="tool-invocation")){const na=mt?"failed":ua?"completed":"started";ue(ia,na,`${ba||ut||et}:${ia}:${na}`)}ia&&qt==="tool-result"&&ue(ia,mt?"failed":"completed",`${ba||ut||et}:${ia}:${mt?"failed":"completed"}`)}if(id.has(we.type))throw new Error(String(we.properties?.error||"Run failed."));if((we.type==="session.updated"||we.type==="session.status")&&String(we.properties?.status||"").toLowerCase()==="idle"||sd.has(we.type))break}}}catch(Ce){const we=String(Ce?.message||Ce||"").toLowerCase();if(!(Qt||we.includes("abort")||we.includes("terminated")||we.includes("networkerror")))throw Ce}finally{_.current&&window.clearTimeout(_.current),z.current&&window.clearTimeout(z.current)}if(Qt){const Ce=await Ge(et,45e3);if(await dt(),!Ce)throw new Error("Run stream timed out and the run is still active. Check logs and retry.")}if(Lt||Pe(!0),await dt(),await new Promise(Ce=>window.setTimeout(Ce,180)),await dt(),await new Promise(Ce=>window.setTimeout(Ce,220)),await dt(),!Lt&&await Ue().catch(()=>"")===et)if(await Ge(et,3e4))await dt();else throw new Error(`Run ${et} is still active without a final response (${Ct||"stream-ended"}).`);q(""),Pe(!1),await be(),await d.invalidateQueries({queryKey:["chat"]}).catch(()=>{})}catch(L){const X=Va(L),ye=X.includes("no-events-timeout")||X.includes("max-stream-window")||X.includes("AbortError")||X.toLowerCase().includes("terminated")?"Run stream timed out before events were received. Check engine/provider logs and retry.":X;n("err",ye),await dt()}finally{O.current&&(re(!1),Pe(!1))}}},[t,Pt,$,a,Ve,v,d,Ke,ue,dt,T,be,b,Se,I,Le,n,he,l]);fe(()=>{be(),Xe();const h=async()=>{const J=await Ve().catch(()=>"");J&&C(J),ne(!1)};window.addEventListener("tcp:new-chat",h);const U=window.setInterval(()=>{be()},8e3);return()=>{window.removeEventListener("tcp:new-chat",h),window.clearInterval(U)}},[Ve,Xe,be]),fe(()=>{I&&(A.current?.abort(),ne(!1),S(),G(),T(),dt())},[dt,T,G,S,I]),fe(()=>{I||M([])},[I]),fe(()=>{!I&&P.length===0&&Ve().catch(()=>{})},[Ve,I,P.length]),fe(()=>{bd(lt),lt&&$()},[lt,$]),fe(()=>{const h=window.setInterval(()=>{I&&T()},2500);return()=>window.clearInterval(h)},[T,I]),fe(()=>{const h=es("/api/global/event",U=>{let J=null;try{J=JSON.parse(String(U.data||"{}"))}catch{return}const L=String(J?.type||"").trim();if(!L)return;const X=J?.properties||{},ye=er(X);if(ye&&Rr(ye.sessionId,I)&&((L==="approval.requested"||L==="permission.request"||L==="permission.asked")&&l(ye),(L==="approval.resolved"||L==="permission.resolved"||L==="permission.replied")&&b(ye.id)),L.toLowerCase().startsWith("pack.")&&Ke(L,X),Ss.has(L)){const Ue=ln(X)||"tool",st=Cn(X),vt=Tr(J,"global");ue(Ue,"started",`${st||vt}:${Ue}:started`)}if(Is.has(L)){const Ue=ln(X)||"tool",st=Cn(X),vt=Tr(J,"global"),It=String(X?.status||X?.state||"").toLowerCase(),et=L==="tool_call.failed"||It.includes("fail")||!!X?.error;ue(Ue,et?"failed":"completed",`${st||vt}:${Ue}:${et?"failed":"completed"}`)}},{withCredentials:!0});return()=>h()},[Ke,ue,b,I,l]);const te=he.length,Ne=!xe&&!H.length&&!ge&&!me;return e("div",{ref:p,className:"chat-layout chat-layout-fill min-w-0 min-h-0 h-full w-full flex-1",children:[e(Re.aside,{className:`chat-sessions-panel ${B?"open":""}`,initial:!1,animate:u?{x:B?0:"-104%"}:{x:B?0:"-104%",transition:{duration:.18,ease:"easeOut"}},children:[e("div",{className:"chat-sessions-header",children:[e("h3",{className:"chat-sessions-title",children:[e("i",{"data-lucide":"history"}),"Sessions"]}),e("div",{className:"flex items-center gap-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{Ve().catch(h=>n("err",Va(h))),ne(!1)},children:[e("i",{"data-lucide":"plus"}),"New"]}),e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{be()},children:e("i",{"data-lucide":"refresh-cw"})})]})]}),e("div",{className:"chat-session-list",children:[e(Mt,{children:P.map(h=>e(Re.div,{className:"chat-session-row",initial:u?!1:{opacity:0,y:6},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-6},children:[e("button",{type:"button",className:`chat-session-btn ${h.id===I?"active":""}`,title:h.id,onClick:()=>{C(h.id),ne(!1)},children:e("span",{className:"block truncate",children:h.title})}),e("button",{type:"button",className:"chat-session-del",title:"Delete session",onClick:()=>$t({id:h.id,title:h.title}),children:e("i",{"data-lucide":"trash-2"})})]},h.id))}),P.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No sessions yet."})]})]}),e(Mt,{children:B?e(Re.button,{type:"button",className:"chat-scrim open","aria-label":"Close sessions",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>ne(!1)}):null}),e("div",{className:"chat-workspace min-h-0 min-w-0",children:[e("section",{className:"chat-main-shell flex min-h-0 min-w-0 flex-col overflow-hidden",children:[e("header",{className:"chat-main-header shrink-0",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Sessions",onClick:()=>ne(h=>!h),children:e("i",{"data-lucide":"history"})}),e("div",{className:"chat-main-dot"}),e("h3",{className:"tcp-title chat-main-title",children:tt}),Fe.length?e("span",{className:"chat-main-tools",children:[Fe.length," tools"]}):null]}),We?e("div",{className:"mx-3 mb-2 rounded-xl border border-amber-500/30 bg-amber-500/8 p-3",children:[e("div",{className:"mb-2 flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"tcp-title text-sm",children:We.title}),e("div",{className:"tcp-subtle text-sm",children:We.body})]}),e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>ze(null),children:"Dismiss"})]}),We.clarifier?e("div",{className:"mb-2 flex flex-wrap gap-2",children:We.clarifier.options.map(h=>e("button",{type:"button",className:"tcp-btn tcp-btn-ghost",onClick:()=>ze({title:h.id==="provider_setup"?"Provider setup":h.id==="integration_setup"?"Tool connection":"Automation setup",body:h.id==="provider_setup"?"Open Settings to configure a provider.":h.id==="integration_setup"?"Open MCP to connect the tool you need.":"Open Automations to build the workflow.",cta:h.id==="provider_setup"?"Open Settings":h.id==="integration_setup"?"Open MCP":"Open Automations",actionType:h.id==="provider_setup"?"open_provider_setup":h.id==="integration_setup"?"open_mcp_setup":"open_automations",payload:We.payload}),children:h.label},h.id))}):null,e("button",{type:"button",className:"tcp-btn",onClick:()=>{We.actionType==="open_provider_setup"?c("settings"):We.actionType==="open_mcp_setup"?c("mcp"):We.actionType==="open_automations"&&(vd(We.payload),c("automations"))},children:We.cta})]}):null,e("div",{ref:x,className:`chat-messages mb-2 min-h-0 min-w-0 flex-1 overflow-auto p-3 ${Ne?"chat-messages-empty":"space-y-2"}`,children:[xe&&!H.length?e("p",{className:"chat-rail-empty",children:"Loading messages..."}):null,Ne?e("div",{className:"chat-empty-state",children:e("p",{className:"chat-rail-empty",children:"No messages yet. Send a prompt to start."})}):null,e(Mt,{initial:!1,children:H.map(h=>{const U=h.role==="assistant"||h.role==="system",J=U?"assistant":"user";return e(Re.article,{className:`chat-msg ${J}`,initial:u?!1:{opacity:0,y:4},animate:u?void 0:{opacity:1,y:0},exit:u?void 0:{opacity:0,y:-4},children:[e("div",{className:"chat-msg-role",children:U?e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:h.displayRole})]}):h.displayRole}),h.markdown?e("div",{className:"tcp-markdown tcp-markdown-ai",dangerouslySetInnerHTML:{__html:pn(h.text||"")}}):e("pre",{className:"chat-msg-pre",children:h.text})]},h.id)})}),ge||me?e("article",{className:"chat-msg assistant",children:[e("div",{className:"chat-msg-role",children:e("span",{className:"inline-flex items-center gap-2",children:[s.botAvatarUrl?e("img",{src:s.botAvatarUrl,alt:s.botName,className:"chat-avatar-ring h-5 w-5 rounded-full object-cover"}):null,e("span",{children:s.botName||"Assistant"})]})}),ge&&!me?e("div",{className:"tcp-thinking","aria-live":"polite",children:[e("span",{children:"Thinking"}),e("i",{}),e("i",{}),e("i",{})]}):null,me?e("pre",{className:"chat-msg-pre",children:me}):null]}):null]}),e("div",{className:"chat-composer shrink-0",children:[e("div",{className:`chat-attach-row mb-2 ${te?"":"hidden"}`,children:[e("span",{className:"tcp-subtle",children:[te," attached"]}),e("div",{className:"chat-files-line",children:he.map((h,U)=>e("span",{className:"chat-file-pill min-w-0",children:[e("span",{className:"chat-file-pill-name",title:h.path,children:h.path}),e("span",{className:"chat-file-pill-size",children:pd(h.size)}),e("button",{type:"button",className:"chat-file-pill-btn chat-file-pill-btn-danger",title:"Remove from list",onClick:()=>ee(J=>J.filter((L,X)=>X!==U)),children:e("i",{"data-lucide":"x"})})]},`${h.path}-${U}`))})]}),qe.length?e("div",{className:"mb-2 grid gap-1.5",children:qe.map(h=>{const U=Math.max(0,Math.min(100,Number(h.progress||0)));return e("div",{className:"chat-upload-card",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2 text-xs",children:[e("span",{className:"chat-upload-name truncate",children:h.name}),e("span",{className:h.error?"chat-upload-meta-error":"chat-upload-meta",children:h.error||`${U.toFixed(0)}%`})]}),e("div",{className:"chat-upload-bar",children:e("div",{className:"chat-upload-bar-fill",style:{width:`${U}%`}})})]},h.id)})}):null,e("div",{className:"chat-input-wrap",children:[e("input",{ref:E,type:"file",className:"hidden",multiple:!0,onChange:h=>{Ft(h.target.files),h.target.value=""}}),e("button",{type:"button",className:"chat-icon-btn chat-icon-btn-inner",title:"Attach files",onClick:()=>E.current?.click(),children:e("i",{"data-lucide":"paperclip"})}),e("textarea",{ref:N,rows:1,value:v,className:"tcp-input chat-input-with-clip chat-input-modern resize-none",placeholder:"Ask anything... (Enter to send, Shift+Enter newline)",onInput:h=>j(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),bt())}}),e("button",{type:"button",className:"chat-send-btn",title:"Send",disabled:Le,onClick:()=>{bt()},children:e("i",{"data-lucide":"send"})})]})]})]}),e("aside",{className:"chat-right-rail hidden min-h-0 flex-col gap-3 overflow-hidden xl:flex",children:[e("section",{className:"min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tools"}),e("span",{className:"chat-rail-count",children:Fe.length})]}),e("div",{className:"chat-tools-list",children:Fe.length?Fe.slice(0,32).map(h=>e("button",{type:"button",className:"chat-tool-pill",title:`Insert ${h}`,onClick:()=>{j(U=>U.trim()?`${U} ${h}`:h),N.current?.focus()},children:h},h)):e("p",{className:"chat-rail-empty",children:"No tools loaded."})})]}),e("section",{className:"min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Approvals"}),e("span",{className:"chat-rail-count",children:Ae.length})]}),e("div",{className:"mb-2 flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",disabled:!Ae.length||rt,onClick:async()=>{const h=Ae.map(J=>J.id).filter(Boolean);if(!h.length)return;for(const J of h)await R(J,"once",!0);await T();const U=h.filter(J=>Ae.some(L=>String(L.id||"").trim()===J)).length;U>0?n("warn",`${U} request${U===1?"":"s"} still pending (likely stale/expired).`):n("ok",`Approved ${h.length} pending request${h.length===1?"":"s"}.`)},children:"Approve all"}),e("label",{className:"chat-auto-approve-label",children:[e("input",{type:"checkbox",className:"chat-auto-approve-checkbox",checked:lt,onChange:h=>xt(h.target.checked)}),"Auto"]})]}),e("div",{className:"chat-tools-activity",children:Ae.length?Ae.slice(0,20).map(h=>{const U=oe.has(h.id),J=[h.permission,h.pattern].filter(Boolean).join(" ");return e("article",{className:"chat-pack-event-card",children:[e("div",{className:"chat-pack-event-title truncate",title:h.id,children:h.tool}),e("div",{className:"chat-pack-event-summary mt-0.5",children:J||h.id}),e("div",{className:"mt-1 flex gap-1",children:[e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:U,onClick:()=>{R(h.id,"once")},children:"Allow"}),e("button",{className:"tcp-btn h-6 px-1.5 text-[10px]",disabled:U,onClick:()=>{R(h.id,"always")},children:"Always"}),e("button",{className:"tcp-btn-danger h-6 px-1.5 text-[10px]",disabled:U,onClick:()=>{R(h.id,"deny")},children:"Deny"})]})]},h.id)}):e("p",{className:"chat-rail-empty",children:"No pending approvals."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Pack Events"}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:"chat-rail-count",children:He.length}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:()=>{G()},children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]})]}),e("div",{className:"chat-tools-activity",children:He.length?He.slice(0,20).map(h=>e(Re.article,{className:"chat-pack-event-card",initial:u?!1:{opacity:0,y:6},animate:u?void 0:{opacity:1,y:0},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"chat-pack-event-title truncate",title:h.type,children:h.type}),e("span",{className:"chat-pack-event-time",children:new Date(h.at).toLocaleTimeString()})]}),e("div",{className:"chat-pack-event-summary mt-0.5",children:h.summary}),h.error?e("div",{className:"chat-pack-event-error mt-1",children:h.error}):null,e("div",{className:"mt-1 flex flex-wrap gap-1",children:[e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:()=>c("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Packs"]}),h.path?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const U=await t("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:h.path,source:{kind:"control_panel_chat",event:"pack.detected"}})});n("ok",`Installed ${U?.installed?.name||"pack"} ${U?.installed?.version||""}`.trim())}catch(U){n("err",`Install failed: ${Va(U)}`)}},children:[e("i",{"data-lucide":"download"}),"Install path"]}):null,h.path&&h.attachmentId?e("button",{type:"button",className:"tcp-btn h-6 px-1.5 text-[10px]",onClick:async()=>{try{const U=await t("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:h.attachmentId,path:h.path,connector:h.connector||void 0,channel_id:h.channelId||void 0,sender_id:h.senderId||void 0})});n("ok",`Installed ${U?.installed?.name||"pack"} ${U?.installed?.version||""}`.trim())}catch(U){n("err",`Install failed: ${Va(U)}`)}},children:[e("i",{"data-lucide":"paperclip"}),"Install attach"]}):null]})]},`${h.id}-${h.at}`)):e("p",{className:"chat-rail-empty",children:"No pack events yet."})})]}),e("section",{className:"min-h-0 flex-1",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("p",{className:"chat-rail-label",children:"Tool Activity"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-[11px]",onClick:S,children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]}),e("div",{className:"chat-tools-activity",children:Te.length?Te.slice(0,24).map(h=>e("div",{className:`chat-tool-chip ${gd(h.status)}`,children:[h.tool,": ",h.status]},h.id)):e("p",{className:"chat-rail-empty",children:"No tool events yet."})})]})]})]}),e(Mt,{children:At?e(Re.div,{className:"tcp-confirm-overlay",initial:u?!1:{opacity:0},animate:u?void 0:{opacity:1},exit:u?void 0:{opacity:0},onClick:()=>$t(null),children:e(Re.div,{className:"tcp-confirm-dialog",initial:u?!1:{opacity:0,y:8,scale:.98},animate:u?void 0:{opacity:1,y:0,scale:1},exit:u?void 0:{opacity:0,y:6,scale:.98},onClick:h=>h.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Delete session"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:At.title})," and all its messages."]}),e("div",{className:"tcp-confirm-actions",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>$t(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{type:"button",className:"tcp-btn-danger",onClick:()=>{Ie(At.id).catch(h=>n("err",Va(h)))},children:[e("i",{"data-lucide":"trash-2"}),"Delete session"]})]})]})}):null})]})}function yn(a){return a?.checkpoint||{}}function zr(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function Ps(a){const t=a?.properties||{};return String(a?.run_id||a?.runId||a?.runID||t?.run_id||t?.runId||t?.runID||t?.run?.id||"").trim()}function Ta(a){return String(a?.type||a?.event_type||a?.event||"").trim()}function hn(a){const t=a?.properties||{},n=a?.timestamp_ms||a?.timestampMs||t?.timestamp_ms||t?.timestampMs||t?.firedAtMs||Date.now(),r=Number(n);return Number.isFinite(r)?r:Date.now()}function xr(a){const t=a?.properties||a||{};return String(t?.reason||t?.detail||t?.error?.message||t?.error||t?.message||t?.status||"").trim()}function Mi(a,t=""){return String(a?.properties?.sessionID||a?.sessionID||t||"").trim()}function ts(a,t,n){return(Array.isArray(a?.[t])?a[t]:Array.isArray(a?.[n])?a[n]:[]).map(s=>String(s||"").trim()).filter(Boolean)}function Ya(a){return Array.isArray(a)?a.map(t=>String(t||"").trim()).filter(Boolean):[]}function as(a){return ts(yn(a),"completed_nodes","completedNodes")}function qi(a){return String(a?.status||a?.content?.status||"").trim().toLowerCase()}function $i(a){const t=new Set(ts(yn(a),"blocked_nodes","blockedNodes"));for(const{nodeId:n,value:r}of rs(a))qi(r)==="blocked"&&t.add(n);return Array.from(t)}function xd(a){const t=new Set;for(const{nodeId:n,value:r}of rs(a)){const s=qi(r);(s==="verify_failed"||s==="failed")&&t.add(n)}return Array.from(t)}function ns(a){return ts(yn(a),"pending_nodes","pendingNodes")}function Ts(a){return as(a).length}function kd(a){return ns(a).length}function dr(a){return $i(a).length}function Wa(a){const t=String(a?.status||"").trim().toLowerCase();return(t==="completed"||t==="done")&&dr(a)>0?"blocked":(t==="completed"||t==="done")&&xd(a).length>0?"failed":t||"unknown"}function Rs(a){return(Array.isArray(a?.active_session_ids)?a.active_session_ids:Array.isArray(a?.activeSessionIds)?a.activeSessionIds:[]).length}function kr(a){const t=yn(a);return t?.node_outputs||t?.nodeOutputs||{}}function rs(a){return Object.entries(kr(a)).map(([t,n])=>({nodeId:t,value:n}))}function Nr(a,t){const n=String(t||"").trim();return n&&kr(a)[n]||null}function Nd(a,t){const n=yn(a),r=String(t||"").trim();return r?Number(n?.node_attempts?.[r]||n?.nodeAttempts?.[r]||0):0}function _d(a,t){const n=Nr(a,t);return String(n?.content?.session_id||n?.content?.sessionId||"").trim()}function Sd(a,t,n){const r=new Set(as(a)),s=new Set($i(a)),c=new Set(ns(a)),d=String(t||"").trim();if(!d)return n.length?"pending":"runnable";if(r.has(d))return"done";const u=Nr(a,d),p=String(u?.status||u?.content?.status||"").trim().toLowerCase();if(p==="done")return"done";if(p==="verify_failed"||p==="failed")return"failed";if(s.has(d)||p==="blocked")return"blocked";const N=String(u?.error||u?.content?.error||u?.content?.message||u?.content?.status_message||"").trim().toLowerCase();return N&&(N.includes("failed")||N.includes("error"))?"failed":(c.has(d),n.length?"pending":"runnable")}function Id(a,t=""){const n=String(t||"").trim();if(n)return n;const r=Array.isArray(a)?a:[];return r.find(s=>s.state==="in_progress"||s.state==="assigned")?.id||r.find(s=>s.state==="runnable")?.id||""}function Cd(a){const t=ns(a),n=String(t[0]||"").trim();return n?n.startsWith("node-")?n:`node-${n}`:""}function Ad(a,t=""){const n=Array.isArray(a?.automation_snapshot?.flow?.nodes)?a.automation_snapshot.flow.nodes:[];if(!n.length)return{currentTaskId:"",taskSource:"empty",tasks:[]};const r=new Set(as(a)),s=n.map(c=>{const d=String(c?.node_id||"").trim(),u=`node-${d}`,p=Array.isArray(c?.depends_on)?c.depends_on.map(_=>`node-${String(_||"").trim()}`).filter(Boolean):[],N=p.every(_=>r.has(_.replace(/^node-/,""))),E=Sd(a,d,N?[]:p),x=Nr(a,d)||{},A=t===u&&String(a?.status||"").trim().toLowerCase()==="running"?"in_progress":E==="pending"&&N?"runnable":E,O=c?.metadata?.builder||{};return{id:u,title:String(c?.objective||d||"Workflow node"),description:c?.agent_id?`agent: ${c.agent_id}`:"",dependencies:p,state:A,retry_count:Nd(a,d),error_message:String(x?.error||x?.content?.error||""),runtime_status:String(x?.status||x?.content?.status||""),runtime_detail:String(x?.summary||x?.content?.message||""),assigned_role:String(c?.agent_id||""),workflow_id:String(a?.automation_id||""),session_id:_d(a,d),projects_backlog_tasks:!!O?.project_backlog_tasks,backlog_task_id:String(O?.task_id||""),task_kind:String(O?.task_kind||""),repo_root:String(O?.repo_root||""),write_scope:String(O?.write_scope||""),acceptance_criteria:String(O?.acceptance_criteria||""),task_dependencies:String(O?.task_dependencies||""),verification_state:String(O?.verification_state||""),task_owner:String(O?.task_owner||""),verification_command:String(O?.verification_command||""),output_path:String(O?.output_path||"")}});return{currentTaskId:Id(s,t),taskSource:"checkpoint",tasks:s}}function Oi(a){const t=yn(a);return Array.isArray(t?.lifecycle_history)?t.lifecycle_history:Array.isArray(t?.lifecycleHistory)?t.lifecycleHistory:[]}function Ei(a){const t=Oi(a);return t.length&&[...t].sort((n,r)=>Number(r?.recorded_at_ms||r?.recordedAtMs||0)-Number(n?.recorded_at_ms||n?.recordedAtMs||0)).find(n=>String(n?.event||"").trim())||null}function ss(a){return String(a?.metadata?.node_id||a?.metadata?.nodeId||"").trim()}function Di(a){const t=ss(a);return t?t.startsWith("node-")?t:`node-${t}`:""}function Pd(a,t,n=8){const r=String(t||"").trim();return r?Oi(a).filter(s=>ss(s)===r).slice(-n).reverse():[]}function Td(a,t,n=8){return Pd(a,t,n).map(r=>({...Ed(r),raw:r}))}function Rd(a){const t=Ei(a);return Di(t)}function Md(a){const t=Object.values(kr(a)).filter(Boolean);return t.length&&t[t.length-1]||null}function qd(a){const t=String(a?.summary||"").trim(),n=String(a?.status||a?.content?.status||"").trim(),r=String(a?.blocked_reason||a?.blockedReason||"").trim(),s=a?.content||{},c=String(s?.text||s?.raw_text||"").trim();return[t,n?`status: ${n}`:"",r,c].filter(Boolean).join(`
|
|
7
|
+
`).trim()}function is(a){return a?.tool_telemetry||a?.toolTelemetry||null}function Kn(a){return a?.artifact_validation||a?.artifactValidation||null}function $d(a){const t=Kn(a);return Array.isArray(t?.artifact_candidates)?t.artifact_candidates:[]}function ji(a){const t=Kn(a);return{workflowClass:String(a?.workflow_class||a?.workflowClass||t?.execution_policy?.workflow_class||"").trim(),phase:String(a?.phase||a?.node_phase||"").trim(),failureKind:String(a?.failure_kind||a?.failureKind||"").trim()}}function Od(a){const t=Md(a),n=Ei(a),r=ji(t);return{latestOutput:t,latestEvent:n,phase:r.phase||String(n?.metadata?.phase||"").trim(),failureKind:r.failureKind||String(n?.metadata?.failure_kind||"").trim(),reason:String(n?.reason||t?.blocked_reason||"").trim(),status:String(a?.status||t?.status||"never_run").trim()}}function Ed(a){const t=a?.metadata||{};return{event:String(a?.event||"event").trim()||"event",recordedAtMs:Number(a?.recorded_at_ms||a?.recordedAtMs||0),nodeId:ss(a),taskId:Di(a),phase:String(a?.phase||t?.phase||"").trim(),failureKind:String(a?.failure_kind||a?.failureKind||t?.failure_kind||"").trim(),workflowClass:String(a?.workflow_class||a?.workflowClass||t?.workflow_class||"").trim(),reason:String(a?.reason||t?.reason||"").trim()||"No reason recorded",status:String(a?.status||t?.status||"").trim()}}function Dd(a,t){const n=(Array.isArray(a)?a:[]).map(s=>({id:`event:${String(s?.seq||"")}:${String(s?.event_type||s?.eventType||"")}`,family:"event",type:String(s?.event_type||s?.eventType||"context_event"),detail:String(s?.payload?.reason||s?.payload?.detail||s?.payload?.error||s?.payload?.status||s?.status||"").trim(),at:zr(s?.created_at_ms||s?.timestamp_ms||s?.timestampMs)||Number(s?.seq||0),raw:s})),r=(Array.isArray(t)?t:[]).map(s=>({id:`patch:${String(s?.seq||"")}:${String(s?.op||"")}`,family:"patch",type:String(s?.op||"blackboard_patch"),detail:String(s?.payload?.status||s?.payload?.task_id||s?.payload?.artifact_id||s?.payload?.title||"").trim(),at:zr(s?.created_at_ms||s?.timestamp_ms)||Number(s?.seq||0),raw:s}));return[...n,...r].sort((s,c)=>Number(c.at||0)-Number(s.at||0))}function jd(a,t=""){return(Array.isArray(a)?a:[]).map((n,r)=>({id:`persisted:${String(t||"")}:${r}`,family:"run_event",type:String(Ta(n)||"run.event"),detail:String(xr(n)||"").trim(),at:hn(n),raw:n})).sort((n,r)=>Number(r.at||0)-Number(n.at||0))}function Ud(a,t,n,r=""){const s=(Array.isArray(a)?a:[]).map((c,d)=>({id:`persisted:${String(r||"")}:${String(c?.seq||d)}:${String(Ta(c)||"")}`,source:"automations",at:hn(c),event:c}));return n?[...s,...(Array.isArray(t)?t:[]).map(c=>({id:`context:${String(c?.seq||"")}:${String(c?.event_type||"")}`,source:"context",at:zr(c?.created_at_ms||c?.timestamp_ms||c?.timestampMs)||Date.now(),event:c}))]:s}function Bd(a,t=""){return(Array.isArray(a)?a:[]).map(n=>{const r=Mi(n?.event,t),s=Ta(n?.event);return{id:`event:${n?.id||""}`,kind:"event",sessionId:r,at:Number(n?.at||0),variant:s==="session.error"?"error":s.startsWith("session.")?"system":"tool",label:s||"event",body:xr(n?.event),raw:n?.event,parts:[]}})}function Fd(a){const t=[],n=(r,s,c,d,u)=>{String(c||"").trim()&&(t.some(p=>p.key===r)||t.push({key:r,title:s,reason:String(c).trim(),source:d,at:u}))};for(const r of Array.isArray(a)?a:[]){const s=r?.event||r||{},c=String(Ta(s)||"").trim(),d=xr(s),u=Number(r?.at||hn(s)||0);(c==="permission.asked"||c==="approval.required"||c==="routine.approval_required")&&n(`event-${c}`,"Permission or approval required",d||c,"permission",u),c==="mcp.auth.required"&&n(`event-${c}`,"MCP auth required",d||"An MCP connector requires authorization.","mcp",u),(c==="session.error"||c==="run.failed"||c==="routine.run.failed")&&n(`event-${c}`,"Execution failure",d||c,"session",u),d.toLowerCase().includes("no further tool calls")&&n("tool-mode","Tool policy blocked progress",d,"policy",u),d.toLowerCase().includes("timed out")&&n(`timeout-${c||u}`,"Timeout",d,"session",u)}return t.sort((r,s)=>(s.at||0)-(r.at||0))}function Ld(a){return(Array.isArray(a)?a:[]).map(t=>({id:String(t?.id||"").trim(),source:String(t?.source||"").trim()||"event",at:Number(t?.at||0),label:Ta(t?.event)||"event",detail:xr(t?.event)||"No summary available.",raw:t?.event?.properties||t?.event||null,event:t?.event||null}))}function Kd(a,t){const n=is(t),r=Kn(t),s=ji(t),c=(()=>{const d=t?.approved;if(typeof d=="boolean")return d?"approved":"not approved";const u=String(n?.verification_outcome||"").trim().toLowerCase();if(u)return u;const p=String(t?.status||"").trim().toLowerCase();if(p)return p;const N=String(a?.state||"").trim().toLowerCase();return N==="done"?"completed":N==="blocked"?"blocked":N==="failed"?"failed":N||"unknown"})();return{telemetry:n,artifactValidation:r,touchedFiles:Ya(r?.touched_files),undeclaredFiles:Ya(r?.undeclared_files_created),researchReadPaths:Ya(r?.read_paths),discoveredRelevantPaths:Ya(r?.discovered_relevant_paths),reviewedPathsBackedByRead:Ya(r?.reviewed_paths_backed_by_read),unreviewedRelevantPaths:Ya(r?.unreviewed_relevant_paths),unmetResearchRequirements:Ya(r?.unmet_requirements),verificationOutcome:c,verificationPassed:typeof t?.approved=="boolean"?t.approved:["approved","completed","done"].includes(c)?!0:["blocked","failed","not approved"].includes(c)?!1:null,verificationResults:Array.isArray(n?.verification_results)?n.verification_results:[],failureDetail:String(t?.blocked_reason||t?.blockedReason||r?.semantic_block_reason||r?.rejected_artifact_reason||a?.error_message||"").trim(),workflowClass:s.workflowClass,phase:s.phase,failureKind:s.failureKind,artifactCandidates:$d(t)}}function Ui(a){const t=Array.isArray(a?.active_session_ids)?a.active_session_ids:Array.isArray(a?.activeSessionIds)?a.activeSessionIds:[],n=[String(a?.latest_session_id||"").trim(),String(a?.latestSessionId||"").trim()].filter(Boolean),r=Object.values(kr(a)).map(s=>{const c=s?.content||{};return String(c?.session_id||c?.sessionId||"").trim()}).filter(Boolean);return Array.from(new Set([...n,...t.map(s=>String(s||"").trim()).filter(Boolean),...r].filter(Boolean)))}async function Xt(a,t={}){const n=await fetch(a,{...t,credentials:"include",headers:{"content-type":"application/json",...t.headers||{}}});if(!n.ok){const s=await n.text().catch(()=>"");let c=s||`${a} failed (${n.status})`;try{const d=s?JSON.parse(s):null;d?.error&&(c=d.error)}catch{}throw new Error(c)}const r=await n.text();return r?JSON.parse(r):{}}function Bi(a=!0){return V({queryKey:["system","health"],queryFn:()=>Xt("/api/system/health"),enabled:a,refetchInterval:a?15e3:!1})}function Wd(a=!0){return V({queryKey:["swarm","status"],queryFn:()=>Xt("/api/swarm/status"),enabled:a,refetchInterval:a?5e3:!1})}const zd=`id: competitor-research-pipeline
|
|
8
8
|
order: 2
|
|
9
9
|
name: Competitor Research Pipeline
|
|
10
10
|
icon: radar
|
|
@@ -325,7 +325,7 @@ nodes:
|
|
|
325
325
|
verificationState: ""
|
|
326
326
|
taskOwner: ""
|
|
327
327
|
verificationCommand: ""
|
|
328
|
-
`,
|
|
328
|
+
`,Jd=`id: marketing-content-pipeline
|
|
329
329
|
order: 0
|
|
330
330
|
name: Marketing Content Pipeline
|
|
331
331
|
icon: megaphone
|
|
@@ -652,7 +652,7 @@ nodes:
|
|
|
652
652
|
verificationState: ""
|
|
653
653
|
taskOwner: ""
|
|
654
654
|
verificationCommand: ""
|
|
655
|
-
`,
|
|
655
|
+
`,Qd=`id: prd-to-launch-plan-team
|
|
656
656
|
order: 6
|
|
657
657
|
name: PRD to Launch Plan Team
|
|
658
658
|
icon: rocket
|
|
@@ -834,7 +834,7 @@ nodes:
|
|
|
834
834
|
verificationState: ""
|
|
835
835
|
taskOwner: ""
|
|
836
836
|
verificationCommand: ""
|
|
837
|
-
`,
|
|
837
|
+
`,Hd=`id: repo-coding-backlog
|
|
838
838
|
order: 1
|
|
839
839
|
name: Repo Coding Backlog
|
|
840
840
|
icon: code-2
|
|
@@ -1027,7 +1027,7 @@ nodes:
|
|
|
1027
1027
|
taskOwner: handoff
|
|
1028
1028
|
verificationCommand: ""
|
|
1029
1029
|
projectBacklogTasks: false
|
|
1030
|
-
`,
|
|
1030
|
+
`,Gd=`id: sales-prospecting-team
|
|
1031
1031
|
order: 5
|
|
1032
1032
|
name: Sales Prospecting Team
|
|
1033
1033
|
icon: target
|
|
@@ -1348,7 +1348,7 @@ nodes:
|
|
|
1348
1348
|
verificationState: ""
|
|
1349
1349
|
taskOwner: ""
|
|
1350
1350
|
verificationCommand: ""
|
|
1351
|
-
`,
|
|
1351
|
+
`,Vd=`id: support-triage-team
|
|
1352
1352
|
order: 4
|
|
1353
1353
|
name: Support Triage Team
|
|
1354
1354
|
icon: life-buoy
|
|
@@ -1528,7 +1528,7 @@ nodes:
|
|
|
1528
1528
|
verificationState: ""
|
|
1529
1529
|
taskOwner: ""
|
|
1530
1530
|
verificationCommand: ""
|
|
1531
|
-
`,
|
|
1531
|
+
`,Yd=`id: weekly-newsletter-builder
|
|
1532
1532
|
order: 3
|
|
1533
1533
|
name: Weekly Newsletter Builder
|
|
1534
1534
|
icon: mail
|
|
@@ -1853,11 +1853,11 @@ nodes:
|
|
|
1853
1853
|
verificationState: ""
|
|
1854
1854
|
taskOwner: ""
|
|
1855
1855
|
verificationCommand: ""
|
|
1856
|
-
`,
|
|
1856
|
+
`,Xd=Object.assign({"./templates/competitor-research-pipeline.yaml":zd,"./templates/marketing-content-pipeline.yaml":Jd,"./templates/prd-to-launch-plan-team.yaml":Qd,"./templates/repo-coding-backlog.yaml":Hd,"./templates/sales-prospecting-team.yaml":Gd,"./templates/support-triage-team.yaml":Vd,"./templates/weekly-newsletter-builder.yaml":Yd});function Zd(a,t){const n=wr.parse(a);if(!n||typeof n!="object")throw new Error("Invalid studio template at "+t+": expected a YAML object.");const r=n,s=String(r.id||"").trim(),c=String(r.name||"").trim(),d=String(r.icon||"").trim(),u=String(r.summary||"").trim(),p=String(r.description||"").trim(),N=Number(r.order),E=r.suggestedOutputs,x=r.agents,A=r.nodes;if(!s)throw new Error("Invalid studio template at "+t+": missing id.");if(!c)throw new Error("Invalid studio template at "+t+": missing name.");if(!d)throw new Error("Invalid studio template at "+t+": missing icon.");if(!u)throw new Error("Invalid studio template at "+t+": missing summary.");if(!p)throw new Error("Invalid studio template at "+t+": missing description.");if(Number.isNaN(N))throw new Error("Invalid studio template at "+t+": order must be a number.");if(!Array.isArray(E))throw new Error("Invalid studio template at "+t+": suggestedOutputs must be an array.");if(!Array.isArray(x))throw new Error("Invalid studio template at "+t+": agents must be an array.");if(!Array.isArray(A))throw new Error("Invalid studio template at "+t+": nodes must be an array.");return{id:s,name:c,icon:d,summary:u,description:p,order:N,suggestedOutputs:E,agents:x,nodes:A}}const Ba=Object.entries(Xd).map(([a,t])=>Zd(t,a)).sort((a,t)=>{const n=Number.isFinite(a.order)?Number(a.order):Number.MAX_SAFE_INTEGER,r=Number.isFinite(t.order)?Number(t.order):Number.MAX_SAFE_INTEGER;return n!==r?n-r:a.name.localeCompare(t.name,void 0,{sensitivity:"base"})});function ur(a,t=""){return{automationId:"",starterTemplateId:a.id,name:a.name,description:a.description,summary:a.summary,icon:a.icon,workspaceRoot:t,status:"draft",scheduleType:"manual",cronExpression:"",intervalSeconds:"3600",maxParallelAgents:"1",useSharedModel:!1,sharedModelProvider:"",sharedModelId:"",outputTargets:[...a.suggestedOutputs],agents:a.agents.map(n=>({...n,skills:[...n.skills],toolAllowlist:[...n.toolAllowlist],toolDenylist:[...n.toolDenylist],mcpAllowedServers:[...n.mcpAllowedServers],prompt:{...n.prompt}})),nodes:a.nodes.map(n=>({...n,dependsOn:[...n.dependsOn],inputRefs:n.inputRefs.map(r=>({...r}))}))}}function eu(a={}){return{role:"",mission:"",inputs:"",outputContract:"",guardrails:"",...a}}function Ms(a,t,n={}){return{agentId:a,displayName:t,role:"worker",avatarUrl:"",templateId:"",linkedTemplateId:"",skills:[],prompt:eu(),modelProvider:"",modelId:"",toolAllowlist:["read","write","glob"],toolDenylist:[],mcpAllowedServers:[],...n}}function tu(a,t,n,r=[],s=[],c={}){return{nodeId:a,title:t,agentId:n,objective:"",dependsOn:[...r],inputRefs:s.map(d=>({...d})),outputKind:"artifact",outputPath:"",taskKind:"",projectBacklogTasks:!1,backlogTaskId:"",repoRoot:"",writeScope:"",acceptanceCriteria:"",taskDependencies:"",verificationState:"",taskOwner:"",verificationCommand:"",...c}}const au=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],nu="tandem.automations.studioHandoff";function mr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function g(a){return String(a||"").trim()}function ru(a){const t=g(a).toLowerCase(),n=t.includes(".")&&t.split(".").pop()||"";return["rs","ts","tsx","js","jsx","py","go","java","kt","kts","c","cc","cpp","h","hpp","cs","rb","php","swift","scala","sh","bash","zsh"].includes(n)}function os(a){const t=g(a.taskKind).toLowerCase();return t==="code_change"||t==="repo_fix"||t==="implementation"||ru(a.outputPath)}function Fi(a){return!!a.projectBacklogTasks}function ls(a){const t=a.map(n=>g(n)).filter(Boolean);return t.includes("*")?["*"]:Array.from(new Set(t))}function qs(a,t){const n=ls(a);if(n.includes("*"))return["*"];const s=t.some(c=>os(c))?["read","glob","edit","apply_patch","write","bash"]:[];return Array.from(new Set([...n,...s]))}function su(a){const t=g(a);return t?t.length<=18?t:`${t.slice(0,8)}...${t.slice(-6)}`:""}function $s(a){const t=Number(a||0);if(!t)return"";try{return new Intl.DateTimeFormat(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(new Date(t))}catch{return""}}function An(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function Pn(a){return a.join(", ")}function Jr(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function tr(a,t){return Jr(a)||t}function Qr(a){const t=g(a);return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Os(a){try{sessionStorage.setItem(nu,JSON.stringify(a))}catch{}}function vr(a){return[["Role",a.role],["Mission",a.mission],["Inputs",a.inputs],["Output Contract",a.outputContract],["Guardrails",a.guardrails]].filter(([,n])=>g(n)).map(([n,r])=>`${n}:
|
|
1857
1857
|
${String(r).trim()}`).join(`
|
|
1858
1858
|
|
|
1859
|
-
`)}function
|
|
1860
|
-
`)}function Ci(a,t,n){const r=Oa.find(c=>c.id===a);return r&&Zn(r,n||"").agents.find(c=>c.agentId===t)||null}function $r(a,t){const n=[],r=[],s=a.nodes.map(d=>d.agentId).filter((d,u,p)=>!!d&&p.indexOf(d)===u&&!a.agents.some(N=>N.agentId===d)),c=a.agents.map(d=>{const u=g(d.linkedTemplateId||d.templateId);if(!u||t.has(u))return d;const p=Ci(a.starterTemplateId,d.agentId,a.workspaceRoot);return n.push(d.agentId),r.push(u),{...d,templateId:"",linkedTemplateId:"",prompt:ir(d.prompt)?d.prompt:p?.prompt||d.prompt,role:g(d.role)?d.role:p?.role||"worker",skills:d.skills.length?d.skills:p?.skills||[],toolAllowlist:Gr(d.toolAllowlist.length?d.toolAllowlist:p?.toolAllowlist||["read","write","glob"]),toolDenylist:d.toolDenylist.length?d.toolDenylist:p?.toolDenylist||[],mcpAllowedServers:d.mcpAllowedServers.length?d.mcpAllowedServers:p?.mcpAllowedServers||[],modelProvider:g(d.modelProvider)||p?.modelProvider||"",modelId:g(d.modelId)||p?.modelId||"",avatarUrl:g(d.avatarUrl)||p?.avatarUrl||"",displayName:g(d.displayName)||p?.displayName||d.agentId}});return!n.length&&!s.length?{draft:a,repairState:null}:{draft:{...a,agents:c},repairState:{repairedAgentIds:n,repairedTemplateIds:r,missingNodeAgentIds:s,reason:"load",requiresSave:n.length>0}}}function ks(a,t){const r=(Array.isArray(a?.agents)?a.agents:[]).map(s=>({agentId:g(s?.agent_id||s?.agentId),templateId:g(s?.template_id||s?.templateId)})).filter(s=>s.templateId&&!t.has(s.templateId));return{missingTemplateLinks:r,isBroken:r.length>0}}function Qd(a,t){const n=[],r=Mr(a.workspaceRoot);r&&n.push(r),g(a.name)||n.push("Workflow name is required."),a.agents.length||n.push("Add at least one agent."),a.nodes.length||n.push("Add at least one stage.");const s=a.nodes.map(d=>d.agentId).filter((d,u,p)=>!!d&&p.indexOf(d)===u&&!a.agents.some(N=>N.agentId===d));s.length&&n.push(`Stages reference missing agents: ${s.join(", ")}.`);const c=a.agents.map(d=>({agentId:d.agentId,templateId:g(d.linkedTemplateId||d.templateId)})).filter(d=>d.templateId&&!t.has(d.templateId));return{errors:n,missingNodeAgentIds:s,brokenAgentLinks:c}}function Gd(a,t,n){const r=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},s=r?.studio&&typeof r.studio=="object"?r.studio:{},c=s?.workflow&&typeof s.workflow=="object"?s.workflow:{},d=g(s?.template_id||s?.templateId),u=Array.isArray(s?.agent_drafts)?s.agent_drafts.map(ws):[],p=Array.isArray(s?.node_drafts)?s.node_drafts.map(xs):[],N=Array.isArray(a?.agents)?a.agents.map(k=>{const z=g(k?.template_id||k?.templateId),A=z?n.get(z):null,G=!A&&d?Ci(d,g(k?.agent_id||k?.agentId),g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t)):null;return ws({agentId:k?.agent_id||k?.agentId,displayName:k?.display_name||k?.displayName||G?.displayName||k?.agent_id||k?.agentId,role:A?.role||G?.role||"worker",templateId:z,linkedTemplateId:z,skills:Array.isArray(k?.skills)?k.skills:A?.skills||G?.skills||[],prompt:A?.systemPrompt?Hr(A.systemPrompt):G?.prompt,modelProvider:k?.model_policy?.default_model?.provider_id||k?.modelPolicy?.defaultModel?.providerId||G?.modelProvider||A?.modelProvider||"",modelId:k?.model_policy?.default_model?.model_id||k?.modelPolicy?.defaultModel?.modelId||G?.modelId||A?.modelId||"",toolAllowlist:k?.tool_policy?.allowlist||k?.toolPolicy?.allowlist||[],toolDenylist:k?.tool_policy?.denylist||k?.toolPolicy?.denylist||[],mcpAllowedServers:k?.mcp_policy?.allowed_servers||k?.mcpPolicy?.allowedServers||[]})}):[],E=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map(k=>xs({nodeId:k?.node_id||k?.nodeId,title:k?.metadata?.builder?.title||k?.metadata?.studio?.title||k?.objective||k?.node_id||k?.nodeId,agentId:k?.agent_id||k?.agentId,objective:k?.objective,dependsOn:k?.depends_on||k?.dependsOn||[],inputRefs:k?.input_refs||k?.inputRefs||[],outputKind:k?.output_contract?.kind||k?.outputContract?.kind||"artifact",metadata:k?.metadata})):[],x={automationId:g(a?.automation_id||a?.automationId||a?.id),starterTemplateId:d,name:g(a?.name||"Workflow"),description:g(a?.description),summary:g(s?.summary),icon:g(s?.icon),workspaceRoot:g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t),status:g(a?.status||c?.status||"draft")||"draft",scheduleType:g(a?.schedule?.type||c?.schedule_type||"manual")||"manual",cronExpression:g(a?.schedule?.cron_expression||a?.schedule?.cronExpression||c?.cron_expression),intervalSeconds:String(a?.schedule?.interval_seconds||a?.schedule?.intervalSeconds||c?.interval_seconds||3600),maxParallelAgents:String(a?.execution?.max_parallel_agents||a?.execution?.maxParallelAgents||c?.max_parallel_agents||1),useSharedModel:!1,sharedModelProvider:"",sharedModelId:"",outputTargets:Array.isArray(a?.output_targets||a?.outputTargets)?(a.output_targets||a.outputTargets).map(k=>g(k)).filter(Boolean):Array.isArray(c?.output_targets)?c.output_targets.map(k=>g(k)).filter(Boolean):[],agents:u.length?u:N,nodes:p.length?p:E},C=Si(x.agents);return x.useSharedModel=C.useSharedModel,x.sharedModelProvider=C.provider,x.sharedModelId=C.model,$r(x,n)}function Hd(a,t){const n={templateID:t,display_name:g(a.displayName)||t,avatar_url:g(a.avatarUrl)||void 0,role:g(a.role)||"worker",system_prompt:ir(a.prompt)||void 0,skills:a.skills.map(r=>({id:r,skill_id:r,name:r})),default_budget:{},capabilities:{}};return g(a.modelProvider)&&g(a.modelId)&&(n.default_model={provider_id:g(a.modelProvider),model_id:g(a.modelId)}),n}function Vd(a,t,n){const r=Ii(t);return{version:2,template_id:g(a.starterTemplateId),workflow_structure_version:2,summary:g(a.summary),icon:g(a.icon),created_from:"studio",last_saved_at_ms:Date.now(),workflow:{status:g(a.status)||"draft",schedule_type:g(a.scheduleType)||"manual",cron_expression:g(a.cronExpression),interval_seconds:Math.max(60,Number.parseInt(String(a.intervalSeconds||"3600"),10)||3600),output_targets:a.outputTargets,max_parallel_agents:Math.max(1,Number.parseInt(String(a.maxParallelAgents||"1"),10)||1)},repair_state:n?{status:n.repairedAgentIds.length||n.missingNodeAgentIds.length?"repaired":"clean",reason:n.reason,requires_save:n.requiresSave}:{status:"clean",reason:"",requires_save:!1},repaired_missing_templates:n?.repairedTemplateIds||[],repaired_agent_ids:n?.repairedAgentIds||[],agent_drafts:a.agents,node_drafts:t,node_layout:Object.fromEntries(Array.from(r.entries()))}}function Yd(a){const t=new Map,n=new Set;for(const r of a){const s=Ln(r.nodeId||r.title,"stage");let c=s,d=2;for(;n.has(c);)c=`${s}-${d}`,d+=1;n.add(c),t.set(r.nodeId,c)}return a.map(r=>{const s=t.get(r.nodeId)||Ln(r.nodeId||r.title,"stage"),c=r.dependsOn.map(u=>t.get(u)||Ln(u,u)).filter(Boolean),d=Mn(c,r.inputRefs.map(u=>({fromStepId:t.get(u.fromStepId)||Ln(u.fromStepId,u.fromStepId),alias:u.alias})));return{...r,nodeId:s,dependsOn:c,inputRefs:d}})}async function Xd(a,t,n=4){for(let r=0;r<n;r+=1){const s=await a.automationsV2.list().catch(()=>({automations:[]}));if(!er(s,"automations").some(u=>g(u?.automation_id||u?.automationId||u?.id)===t))return;await new Promise(u=>window.setTimeout(u,250*(r+1)))}throw new Error("Delete did not persist on the engine. The workflow is still present after verification.")}function Zd({client:a,api:t,toast:n,navigate:r}){const s=na(),c=Ni(!0),d=Y({queryKey:["studio","automations"],queryFn:()=>a.automationsV2.list().catch(()=>({automations:[]})),refetchInterval:15e3}),u=Y({queryKey:["studio","templates"],queryFn:()=>a.agentTeams.listTemplates().catch(()=>({templates:[]})),refetchInterval:1e4}),p=Y({queryKey:["studio","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),N=Y({queryKey:["studio","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),E=Y({queryKey:["studio","mcp"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:15e3}),x=g(c.data?.workspaceRoot||c.data?.workspace_root),C=K(()=>er(u.data,"templates").map(zd).filter(o=>o.templateId),[u.data]),O=K(()=>new Map(C.map(o=>[o.templateId,o])),[C]),k=K(()=>(Array.isArray(p.data?.all)?p.data.all:[]).map(f=>({id:g(f?.id),models:Object.keys(f?.models||{})})).filter(f=>!!f.id).sort((f,R)=>f.id.localeCompare(R.id)),[p.data]),z=K(()=>Kd(k,N.data),[k,N.data]),A=K(()=>er(d.data,"automations").filter(o=>{const f=o?.metadata?.studio;return!!f&&(Number(f?.version||0)>0||g(f?.created_from)==="studio")}),[d.data]),G=K(()=>A.map(o=>g(o?.automation_id||o?.automationId||o?.id)).filter(Boolean),[A]),B=Y({queryKey:["studio","workflow-runs",G],enabled:!!a?.automationsV2?.listRuns&&G.length>0,queryFn:async()=>({runs:(await Promise.all(G.map(async f=>{const R=await a.automationsV2.listRuns(f,6).catch(()=>({runs:[]}));return Array.isArray(R?.runs)?R.runs:[]}))).flat()}),refetchInterval:12e3}),ae=K(()=>{const o=er(B.data,"runs"),f=new Map;return o.forEach(R=>{const P=g(R?.automation_id||R?.automationId);if(!P)return;const $=f.get(P),Xe=Number($?.updated_at_ms||$?.updatedAtMs||$?.created_at_ms||$?.createdAtMs||0),et=Number(R?.updated_at_ms||R?.updatedAtMs||R?.created_at_ms||R?.createdAtMs||0);(!$||et>=Xe)&&f.set(P,R)}),f},[B.data]),S=K(()=>Wd(E.data),[E.data]),[I,H]=w(()=>Zn(Oa[0],"")),[q,ye]=w(()=>Oa[0]?.nodes?.[0]?.nodeId||""),[y,v]=w(()=>Oa[0]?.agents?.[0]?.agentId||""),[U,ue]=w(""),[ee,Oe]=w(!1),[Ee,We]=w(!1),[ne,ce]=w(!0),[M,me]=w(!0),[Re,qe]=w(!1),[se,Ue]=w(""),[Me,ze]=w(""),[X,Ve]=w(null),[re,Ce]=w(null);fe(()=>{x&&H(o=>g(o.workspaceRoot)?o:{...o,workspaceRoot:x})},[x]),fe(()=>{!z.provider||!z.model||H(o=>{const f=Sn(o.agents,z);return f.some((P,$)=>P.modelProvider!==o.agents[$]?.modelProvider||P.modelId!==o.agents[$]?.modelId)?{...o,agents:f}:o})},[z]),fe(()=>{I.useSharedModel&&(!g(I.sharedModelProvider)||!g(I.sharedModelId)||H(o=>{if(!o.useSharedModel)return o;const f=ys(o.agents,o.sharedModelProvider,o.sharedModelId);return f.some((P,$)=>P.modelProvider!==o.agents[$]?.modelProvider||P.modelId!==o.agents[$]?.modelId)?{...o,agents:f}:o}))},[I.useSharedModel,I.sharedModelProvider,I.sharedModelId]),fe(()=>{new Set(I.nodes.map(f=>f.nodeId)).has(q)||ye(I.nodes[0]?.nodeId||"")},[I.nodes,q]),fe(()=>{new Set(I.agents.map(f=>f.agentId)).has(y)||v(I.agents[0]?.agentId||"")},[I.agents,y]),fe(()=>{try{wa()}catch{}},[I,q,U,ne,M,A.length,C.length,Re,Me]);const gt=Y({queryKey:["studio","workspace-browser",se],enabled:Re&&!!se,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(se)}`,{method:"GET"}),refetchInterval:Re?15e3:!1}),ie=I.nodes.find(o=>o.nodeId===q)||I.nodes[0]||null,L=I.agents.find(o=>o.agentId===(y||ie?.agentId))||I.agents.find(o=>o.agentId===ie?.agentId)||I.agents[0]||null,st=Mr(I.workspaceRoot),pt=Array.isArray(gt.data?.directories)?gt.data.directories:[],lt=g(gt.data?.parent),Ct=g(gt.data?.dir||se||""),De=K(()=>{const o=g(Me).toLowerCase();return o?pt.filter(f=>g(f?.name||f?.path).toLowerCase().includes(o)):pt},[Me,pt]),$t=K(()=>Ii(I.nodes),[I.nodes]),yt=K(()=>{const o=new Map;for(const f of I.nodes){const R=Number($t.get(f.nodeId)||0);o.has(R)||o.set(R,[]),o.get(R)?.push(f)}return Array.from(o.entries()).sort((f,R)=>f[0]-R[0])},[I.nodes,$t]),Ut=o=>{const f=Oa.find(P=>P.id===o)||Oa[0],R=Zn(f,I.workspaceRoot||x);H({...R,agents:Sn(R.agents,z)}),ye(R.nodes[0]?.nodeId||""),v(R.agents[0]?.agentId||""),Oe(!1),Ce(null)},Je=o=>H(f=>({...f,...o})),Ge=(o,f)=>H(R=>({...R,nodes:R.nodes.map(P=>P.nodeId===o?{...P,...f,inputRefs:f.dependsOn||f.inputRefs?Mn(f.dependsOn?[...f.dependsOn]:P.dependsOn,f.inputRefs?[...f.inputRefs]:P.inputRefs):P.inputRefs}:P)})),nt=(o,f)=>H(R=>({...R,agents:R.agents.map(P=>P.agentId===o?{...P,...f}:P)})),ve=()=>{const o=`agent-${I.agents.length+1}`,f=I.agents.some(R=>R.agentId===o)?`agent-${Date.now().toString().slice(-5)}`:o;H(R=>({...R,agents:[...R.agents,Sn([gs(f,`Agent ${R.agents.length+1}`)],z)[0]]})),v(f)},_e=()=>{const o=I.nodes.length+1,f=`stage-${o}`,R=L?.agentId||I.agents[0]?.agentId||"",P=Ed(f,`Stage ${o}`,R,ie?[ie.nodeId]:[],ie?[{fromStepId:ie.nodeId,alias:ie.nodeId.replace(/-/g,"_")}]:[],{objective:"Describe what this stage should produce."});H($=>({...$,nodes:[...$.nodes,P]})),ye(f),R&&v(R)},Ye=()=>{ie&&H(o=>({...o,nodes:o.nodes.filter(f=>f.nodeId!==ie.nodeId).map(f=>{const R=f.dependsOn.filter(P=>P!==ie.nodeId);return{...f,dependsOn:R,inputRefs:Mn(R,f.inputRefs.filter(P=>P.fromStepId!==ie.nodeId))}})}))},le=()=>{if(!L)return;if(I.nodes.some(f=>f.agentId===L.agentId)){n("warn","Reassign or remove the stages using this agent first.");return}H(f=>({...f,agents:f.agents.filter(R=>R.agentId!==L.agentId)})),v("")},it=()=>{if(!L||!U)return;const o=O.get(U);o&&(nt(L.agentId,{displayName:o.displayName||L.displayName,avatarUrl:o.avatarUrl||L.avatarUrl,role:o.role||L.role,linkedTemplateId:o.templateId,templateId:o.templateId,prompt:o.systemPrompt?Hr(o.systemPrompt):L.prompt,modelProvider:o.modelProvider||L.modelProvider,modelId:o.modelId||L.modelId,skills:o.skills.length?o.skills:L.skills}),Ce(f=>f&&{...f,repairedAgentIds:f.repairedAgentIds.filter(R=>R!==L.agentId),repairedTemplateIds:f.repairedTemplateIds.filter(R=>R!==o.templateId)}),n("ok",`Loaded template ${o.templateId}.`))},_=o=>{const f=Gd(o,x,O),R={...f.draft,agents:Sn(f.draft.agents,z)};H(R),ye(R.nodes[0]?.nodeId||""),v(R.agents[0]?.agentId||""),Oe(f.draft.agents.some(P=>!!g(P.linkedTemplateId||P.templateId))),Ce(f.repairState?{...f.repairState,reason:"load",requiresSave:!0}:null),f.repairState?.repairedAgentIds.length&&n("warn",`Repaired missing template links for: ${f.repairState.repairedAgentIds.join(", ")}. Save the workflow before running it.`),r("studio")},J=async o=>{const f=g(o?.automation_id||o?.automationId||o?.id);if(ks(o,O).isBroken){_(o),n("warn","This workflow references missing agent templates. It was repaired in Studio. Save it before running.");return}const P=await a.automationsV2.runNow(f),$=g(P?.run?.run_id||P?.run?.runId);await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]}),s.invalidateQueries({queryKey:["automations","runs"]}),s.invalidateQueries({queryKey:["automations","v2","runs"]})]),n("ok",$?`Workflow run started: ${$}. Opening Automations.`:"Workflow run started. Opening Automations."),vs({tab:"running",runId:$,automationId:f,openTaskInspector:!0}),r("automations")},be=xe({mutationFn:async()=>{const o=ee?I:$r(I,O).draft;let f={...o,agents:Sn(o.agents,z)};f.useSharedModel&&g(f.sharedModelProvider)&&g(f.sharedModelId)&&(f={...f,agents:ys(f.agents,f.sharedModelProvider,f.sharedModelId)});const R=Mr(f.workspaceRoot);if(R)throw new Error(R);if(!g(f.name))throw new Error("Workflow name is required.");if(!f.agents.length)throw new Error("Add at least one agent.");if(!f.nodes.length)throw new Error("Add at least one stage.");const P=Qd(f,O);if(P.errors.length)throw new Error(P.errors[0]);const $=f.agents.filter(te=>!g(te.modelProvider)||!g(te.modelId)).map(te=>te.displayName||te.agentId);if($.length)throw new Error(`Model selection is required. Set a default provider/model in Settings or choose one for: ${$.join(", ")}.`);const Xe=qr(f.name)||"studio-workflow",et=new Map;if(ee)for(const te of f.agents){const Se=g(te.linkedTemplateId)||g(te.templateId)||`${Xe}--${qr(te.agentId)||"agent"}`;et.set(te.agentId,Se),O.has(Se)?await a.agentTeams.updateTemplate(Se,{display_name:g(te.displayName)||Se,avatar_url:g(te.avatarUrl)||void 0,role:g(te.role)||"worker",system_prompt:ir(te.prompt)||void 0,default_model:g(te.modelProvider)&&g(te.modelId)?{provider_id:g(te.modelProvider),model_id:g(te.modelId)}:void 0,skills:te.skills.map(h=>({id:h,skill_id:h,name:h}))}):await a.agentTeams.createTemplate({template:Hd(te,Se)})}const bt=Yd(f.nodes),Ot={name:g(f.name),description:g(f.description)||void 0,status:f.status,schedule:Ld(f),workspace_root:g(f.workspaceRoot),execution:{max_parallel_agents:Math.max(1,Number.parseInt(String(f.maxParallelAgents||"1"),10)||1)},output_targets:f.outputTargets.map(te=>g(te)).filter(Boolean),agents:f.agents.map(te=>({agent_id:g(te.agentId),template_id:ee&&(et.get(te.agentId)||g(te.linkedTemplateId))||void 0,display_name:g(te.displayName)||g(te.agentId),avatar_url:g(te.avatarUrl)||void 0,model_policy:Fd(te),skills:te.skills.map(Se=>g(Se)).filter(Boolean),tool_policy:{allowlist:fs(te.toolAllowlist,bt.filter(Se=>Se.agentId===te.agentId)),denylist:te.toolDenylist.map(Se=>g(Se)).filter(Boolean)},mcp_policy:{allowed_servers:te.mcpAllowedServers.map(Se=>g(Se)).filter(Boolean),allowed_tools:[]}})),flow:{nodes:bt.map(te=>{const Se=f.agents.find(Pe=>Pe.agentId===te.agentId),h=g(te.outputPath),j=Qr(te),Q=g(te.stageKind),W=Q==="research_finalize",V=!!Q&&!h,ge=te.inputRefs.some(Pe=>g(Pe.alias)==="external_research"),Be=fs(Se?.toolAllowlist||[],bt.filter(Pe=>Pe.agentId===te.agentId)),ht=!!Se?.toolAllowlist?.includes("websearch")&&!W,ct=g(te.outputKind)==="brief",kt=V&&Q==="research_discover",tt=V&&(Q==="research_discover"||Q==="research_local_sources"),Nt=V&&Q==="research_external_sources"&&ht,Bt=h?[Be.includes("read")&&!W?"read":null,Be.includes("websearch")&&!W?"websearch":null].filter(Pe=>!!Pe).filter((Pe,ha,Ne)=>Ne.indexOf(Pe)===ha):V?[tt?"read":null,Nt?"websearch":null].filter(Pe=>!!Pe):[],Jt=h?[!W&&(Bt.includes("read")||ct)?"local_source_reads":null,!W&&ht?"external_sources":null].filter(Pe=>!!Pe):V?[tt?"local_source_reads":null,Nt?"external_sources":null].filter(Pe=>!!Pe):[],vt=ct?["files_reviewed","files_not_reviewed","citations",ht||ge?"web_sources_reviewed":null].filter(Pe=>!!Pe):[],dt=h?[W?null:"workspace_inspection",!W&&(Bt.includes("read")||ct)?"concrete_reads":null,!W&&ht?"successful_web_research":null].filter(Pe=>!!Pe):V?[kt?"workspace_inspection":null,tt?"concrete_reads":null,Nt?"successful_web_research":null].filter(Pe=>!!Pe):[],Ie=[...Jt,...vt,...dt];return{node_id:g(te.nodeId),agent_id:g(te.agentId),objective:g(te.objective)||g(te.title),depends_on:te.dependsOn.map(Pe=>g(Pe)).filter(Boolean),input_refs:Mn(te.dependsOn,te.inputRefs).map(Pe=>({from_step_id:g(Pe.fromStepId),alias:g(Pe.alias)||g(Pe.fromStepId).replace(/-/g,"_")})),stage_kind:Q?"workstream":void 0,output_contract:{kind:g(te.outputKind)||"artifact",enforcement:h?{required_tools:Bt,required_evidence:Jt,required_sections:vt,prewrite_gates:dt,retry_on_missing:Ie,terminal_on:Ie.length?["tool_unavailable","repair_budget_exhausted"]:[],repair_budget:Ie.length?5:void 0,session_text_recovery:Ie.length||ct?"require_prewrite_satisfied":"allow"}:void 0,summary_guidance:h?j?`Apply the scoped repository changes, update \`${h}\` in the workspace, and use patch/edit/write tools before completing this stage.`:`Create or update \`${h}\` in the workspace and use the write tool before completing this stage.`:V?"Return a structured handoff in the final response instead of writing workspace files.":void 0},metadata:{studio:{output_path:h||void 0,research_stage:Q||void 0},builder:{title:g(te.title)||g(te.nodeId),role:g(Se?.role)||"worker",output_path:h||void 0,research_stage:Q||void 0,write_required:!!h,required_tools:Bt,web_research_expected:ht,task_kind:g(te.taskKind)||void 0,project_backlog_tasks:_i(te)||void 0,task_id:g(te.backlogTaskId)||void 0,repo_root:g(te.repoRoot)||void 0,write_scope:g(te.writeScope)||void 0,acceptance_criteria:g(te.acceptanceCriteria)||void 0,task_dependencies:g(te.taskDependencies)||void 0,verification_state:g(te.verificationState)||void 0,task_owner:g(te.taskOwner)||void 0,verification_command:g(te.verificationCommand)||void 0,prompt:Jd(te,Se||gs(g(te.agentId),g(te.agentId)))}}}})},metadata:{workspace_root:g(I.workspaceRoot),studio:Vd({...f,agents:f.agents.map(te=>({...te,templateId:ee?et.get(te.agentId)||g(te.linkedTemplateId)||g(te.templateId):"",linkedTemplateId:ee?et.get(te.agentId)||g(te.linkedTemplateId)||g(te.templateId):""}))},bt,ee?null:re||$r(f,O).repairState)}},Ae=I.automationId?await a.automationsV2.update(I.automationId,Ot):await a.automationsV2.create(Ot),xt=g(Ae?.automation?.automation_id||Ae?.automation?.automationId);let At="";if(Ee&&xt){const te=await a.automationsV2.runNow(xt);At=g(te?.run?.run_id||te?.run?.runId)}return{response:Ae,automationId:xt,linkedTemplateIds:et,workingDraft:f,startedRunId:At}},onSuccess:async({response:o,automationId:f,linkedTemplateIds:R,workingDraft:P,startedRunId:$})=>{n("ok",Ee?"Studio workflow saved and run started.":"Studio workflow saved."),await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]}),s.invalidateQueries({queryKey:["studio","templates"]}),s.invalidateQueries({queryKey:["teams"]})]),H(Xe=>({...Xe,...P,automationId:f||g(o?.automation?.automation_id||o?.automation?.automationId),agents:P.agents.map(et=>({...et,templateId:ee?R.get(et.agentId)||et.templateId:"",linkedTemplateId:ee?R.get(et.agentId)||et.linkedTemplateId:""}))})),Ce(Xe=>Xe?{...Xe,requiresSave:!1,reason:"save"}:null),Ee&&(vs({tab:"running",runId:$,automationId:f||g(o?.automation?.automation_id||o?.automation?.automationId),openTaskInspector:!0}),r("automations"))},onError:o=>n("err",o instanceof Error?o.message:String(o))}),je=xe({mutationFn:async o=>(await a.automationsV2.delete(o),await Xd(a,o),o),onSuccess:async o=>{if(I.automationId===o){const f=Zn(Oa[0],x||"");H(f),ye(f.nodes[0]?.nodeId||""),v(f.agents[0]?.agentId||"")}await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]})]),n("ok","Studio workflow deleted.")},onError:o=>n("err",o instanceof Error?o.message:String(o))});return e("div",{className:"grid gap-4",children:e(Wt,{title:"Studio",subtitle:"Template-first multi-agent workflow builder with reusable role prompts.",actions:e("div",{className:"flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:()=>Ut(I.starterTemplateId||Oa[0].id),children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset From Template"]}),e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:ve,children:[e("i",{"data-lucide":"user-plus"}),"Add Agent"]}),e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:_e,children:[e("i",{"data-lucide":"plus"}),"Add Stage"]}),e("button",{className:"tcp-btn-primary inline-flex items-center gap-2",disabled:be.isPending,onClick:()=>be.mutate(),children:[e("i",{"data-lucide":be.isPending?"loader-circle":"save"}),be.isPending?"Saving...":"Save Workflow"]})]}),children:e("div",{className:"grid gap-4 xl:grid-cols-[320px_minmax(0,1fr)_360px] xl:items-start",children:[e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:e(Wt,{title:"Studio Library",subtitle:"Templates and saved workflows in one place.",children:e("div",{className:"grid gap-4",children:[e("section",{className:"grid gap-2",children:[e("button",{type:"button",className:"flex w-full items-center gap-2 text-left","aria-expanded":ne,onClick:()=>ce(o=>!o),children:[e("i",{"data-lucide":ne?"chevron-down":"chevron-right",className:"text-slate-400"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Starter Templates"}),e("div",{className:"text-xs text-slate-400",children:"Begin with a proven workflow shape."})]})]}),e(Mt,{initial:!1,children:ne?e($e.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.16,ease:"easeOut"},className:"grid gap-2 overflow-hidden pl-5",children:Oa.map(o=>e("button",{className:`tcp-list-item text-left ${I.starterTemplateId===o.id?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>Ut(o.id),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:o.name}),e("span",{className:"tcp-badge-info",children:o.icon})]}),e("div",{className:"mt-1 text-sm text-slate-300",children:o.summary})]},o.id))}):null})]}),e("section",{className:"grid gap-2 border-t border-slate-800/80 pt-3",children:[e("button",{type:"button",className:"flex w-full items-center gap-2 text-left","aria-expanded":M,onClick:()=>me(o=>!o),children:[e("i",{"data-lucide":M?"chevron-down":"chevron-right",className:"text-slate-400"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Saved Studio Workflows"}),e("div",{className:"text-xs text-slate-400",children:"Reopen workflows created from Studio metadata."})]})]}),e(Mt,{initial:!1,children:M?e($e.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.16,ease:"easeOut"},className:"grid gap-2 overflow-hidden pl-5",children:A.length?[...A].sort((o,f)=>{const R=Number(o?.updated_at_ms||o?.updatedAtMs||o?.created_at_ms||o?.createdAtMs||0);return Number(f?.updated_at_ms||f?.updatedAtMs||f?.created_at_ms||f?.createdAtMs||0)-R}).slice(0,12).map(o=>{const f=g(o?.automation_id||o?.automationId||o?.id),R=ae.get(f)||null,P=fd(R),$=g(P.status),Xe=g(P.failureKind),et=g(P.phase),bt=bs(R?.updated_at_ms||R?.updatedAtMs||R?.created_at_ms||R?.createdAtMs),Ot=o?.metadata?.studio||{},Ae=ks(o,O),xt=g(Ot?.template_id||Ot?.templateId||Ot?.starter_template_id||Ot?.starterTemplateId),At=bs(o?.updated_at_ms||o?.updatedAtMs||o?.created_at_ms||o?.createdAtMs),te=je.isPending&&je.variables===f;return e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:g(o?.name)||f}),e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[Ae.isBroken?e("span",{className:"tcp-badge-warn",children:"broken links"}):null,e("span",{className:"tcp-badge-info",children:g(o?.status)||"draft"})]})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:g(Ot?.summary)||"Studio workflow"}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-slate-500",children:[xt?e("span",{className:"tcp-badge-info",children:["template: ",xt]}):null,e("span",{className:"tcp-badge-muted",children:["id: ",Bd(f)]}),At?e("span",{className:"tcp-badge-muted",children:["updated: ",At]}):null]}),R?e("div",{className:"mt-2 rounded-lg border border-slate-700/50 bg-slate-950/20 p-2",children:[e("div",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:"Latest Run Stability"}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px]",children:[e("span",{className:"tcp-badge-info",children:["status: ",$]}),et?e("span",{className:"tcp-badge-muted",children:["phase: ",et]}):null,Xe?e("span",{className:"tcp-badge-warn",children:["failure: ",Xe]}):null,bt?e("span",{className:"tcp-badge-muted",children:["run: ",bt]}):null]}),g(P.reason)?e("div",{className:"mt-2 text-xs text-slate-300",children:g(P.reason)}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>{_(o)},children:[e("i",{"data-lucide":"folder-open"}),"Open"]}),e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:async()=>{try{await J(o)}catch(Se){n("err",Se instanceof Error?Se.message:String(Se))}},children:[e("i",{"data-lucide":"play"}),Ae.isBroken?"Repair & Open":"Run Now"]}),e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs text-rose-200",disabled:te,onClick:()=>{Ve({automationId:f,title:g(o?.name)||f})},children:[e("i",{"data-lucide":"trash-2"}),te?"Deleting...":"Delete"]})]})]},f)}):e(Le,{text:"No Studio-created workflows yet."})}):null})]})]})})}),e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:[re?.requiresSave&&(re?.repairedAgentIds.length||re?.missingNodeAgentIds.length)?e(Wt,{title:"Repair Applied",subtitle:"Studio repaired runtime dependencies so this workflow can be saved and run locally.",actions:e("button",{className:"tcp-btn-primary inline-flex items-center gap-2",onClick:()=>be.mutate(),disabled:be.isPending,children:[e("i",{"data-lucide":be.isPending?"loader-circle":"save"}),be.isPending?"Saving...":"Save Repaired Workflow"]}),children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[re.repairedAgentIds.length?e("div",{children:["Repaired missing template links for: ",re.repairedAgentIds.join(", ")]}):null,re.missingNodeAgentIds.length?e("div",{children:["Stages still reference missing agents:"," ",re.missingNodeAgentIds.join(", ")]}):null,e("div",{className:"text-xs text-slate-400",children:"Save this workflow to persist the repaired local-first configuration."})]})}):null,e(Wt,{title:"Workflow Settings",subtitle:"Name, schedule, workspace, and save behavior.",children:e("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.3fr)_minmax(18rem,0.95fr)]",children:[e("div",{className:"grid content-start gap-3",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Name"}),e("input",{className:"tcp-input text-sm",value:I.name,onInput:o=>Je({name:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Description"}),e("textarea",{className:"tcp-input min-h-[88px] text-sm",value:I.description,onInput:o=>Je({description:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Workspace Root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:()=>{const o=g(I.workspaceRoot||x||"/");Ue(o||"/"),ze(""),qe(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:`tcp-input text-sm ${st?"border-red-500/60 text-red-100":""}`,value:I.workspaceRoot,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:()=>Je({workspaceRoot:""}),disabled:!I.workspaceRoot,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),st?e("span",{className:"text-xs text-red-300",children:st}):null]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Targets"}),e("input",{className:"tcp-input text-sm",value:_n(I.outputTargets),onInput:o=>Je({outputTargets:Nn(o.target.value)}),placeholder:"content-brief.md, approved-post.md"})]})]}),e("div",{className:"grid content-start gap-3",children:[e("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Status"}),e("select",{className:"tcp-input text-sm",value:I.status,onInput:o=>Je({status:o.target.value}),children:[e("option",{value:"draft",children:"draft"}),e("option",{value:"active",children:"active"}),e("option",{value:"paused",children:"paused"})]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Max Parallel Agents"}),e("input",{className:"tcp-input text-sm",value:I.maxParallelAgents,onInput:o=>Je({maxParallelAgents:o.target.value})})]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Schedule"}),e("select",{className:"tcp-input text-sm",value:I.scheduleType,onInput:o=>Je({scheduleType:o.target.value}),children:[e("option",{value:"manual",children:"manual"}),e("option",{value:"cron",children:"cron"}),e("option",{value:"interval",children:"interval"})]})]}),I.scheduleType==="cron"?e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Cron Expression"}),e("input",{className:"tcp-input text-sm",value:I.cronExpression,onInput:o=>Je({cronExpression:o.target.value}),placeholder:"0 9 * * 1"})]}):null,I.scheduleType==="interval"?e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Interval Seconds"}),e("input",{className:"tcp-input text-sm",value:I.intervalSeconds,onInput:o=>Je({intervalSeconds:o.target.value})})]}):null,e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:ee,onInput:o=>Oe(o.target.checked)}),"Save agent prompts as reusable templates"]}),e("div",{className:"text-xs text-slate-400",children:"Off: this workflow runs from Studio-local prompts only. On: Studio also creates shared Agent Team templates and links the workflow to them at runtime."}),e("div",{className:"text-xs text-slate-500",children:["Default model fallback:"," ",z.provider&&z.model?`${z.provider}/${z.model}`:"No provider default configured in Settings."]}),e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:I.useSharedModel,onInput:o=>{const f=o.target.checked,R=Si(I.agents);Je({useSharedModel:f,sharedModelProvider:f?g(I.sharedModelProvider)||R.provider||z.provider:I.sharedModelProvider,sharedModelId:f?g(I.sharedModelId)||R.model||z.model:I.sharedModelId})}}),"Use one model for all agents in this workflow"]}),I.useSharedModel?e(aa,{children:[e("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Shared Model Provider"}),e("select",{className:"tcp-input text-sm",value:I.sharedModelProvider,onInput:o=>{const f=o.target.value,R=on(k,f);Je({sharedModelProvider:f,sharedModelId:R.includes(I.sharedModelId)?I.sharedModelId:R[0]||I.sharedModelId})},children:[e("option",{value:"",children:"Select provider..."}),k.map(o=>e("option",{value:o.id,children:o.id},o.id))]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Shared Model"}),on(k,I.sharedModelProvider).length?e("select",{className:"tcp-input text-sm",value:I.sharedModelId,onInput:o=>Je({sharedModelId:o.target.value}),children:on(k,I.sharedModelProvider).map(o=>e("option",{value:o,children:o},o))}):e("input",{className:"tcp-input text-sm",value:I.sharedModelId,onInput:o=>Je({sharedModelId:o.target.value}),placeholder:"provider-specific model id"})]})]}),e("div",{className:"rounded-lg border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-xs text-amber-100",children:"Shared model mode applies the same provider/model to every agent on save and while editing."})]}):null,e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:Ee,onInput:o=>We(o.target.checked)}),"Run workflow immediately after save"]}),re&&!re.requiresSave&&re.repairedAgentIds.length?e("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-500/8 px-3 py-2 text-xs text-emerald-100",children:"Repaired template links were saved successfully. This workflow is now using local Studio prompts and can run normally."}):null]})]})}),Re?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:()=>{qe(!1),ze("")}}),e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",Ct||se||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:()=>{lt&&Ue(lt)},disabled:!lt,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:()=>{Ct&&(Je({workspaceRoot:Ct}),qe(!1),ze(""),n("ok",`Workspace selected: ${Ct}`))},disabled:!Ct,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>{qe(!1),ze("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:Me,onInput:o=>ze(o.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:De.length?De.map(o=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>Ue(String(o?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(o?.name||o?.path||"")})]})},String(o?.path||o?.name))):e(Le,{text:g(Me)?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null,X?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close delete workflow dialog",onClick:()=>Ve(null)}),e("div",{className:"tcp-confirm-dialog w-[min(34rem,96vw)]",children:[e("h3",{className:"tcp-confirm-title",children:"Delete Studio workflow"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:X.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:()=>Ve(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger inline-flex items-center gap-2",disabled:je.isPending,onClick:()=>je.mutate(X.automationId,{onSettled:()=>Ve(null)}),children:[e("i",{"data-lucide":"trash-2"}),je.isPending?"Deleting...":"Delete workflow"]})]})]})]}):null,e(Wt,{title:"Workflow Map",subtitle:"Select a stage to edit its objective, dependencies, and bound agent.",children:yt.length?e("div",{className:"grid gap-3 xl:grid-cols-4 xl:items-start",children:yt.map(([o,f])=>e("div",{className:"grid content-start gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:["Column ",o+1]}),f.map(R=>{const P=I.agents.find(Xe=>Xe.agentId===R.agentId),$=R.nodeId===q;return e("button",{className:`tcp-list-item flex flex-col text-left ${$?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{ye(R.nodeId),v(R.agentId)},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:R.title}),e("span",{className:"tcp-badge-info",children:R.outputKind||"artifact"})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:P?.displayName||R.agentId||"Unassigned agent"}),e("div",{className:"mt-2 text-sm text-slate-300",children:R.objective}),R.outputPath?e("div",{className:"mt-2 text-xs text-emerald-200",children:["output: ",R.outputPath]}):null,e("div",{className:"mt-auto flex flex-wrap gap-1 pt-3",children:R.dependsOn.length?R.dependsOn.map(Xe=>e("span",{className:"tcp-badge-warn",children:["<-"," ",Xe]},`${R.nodeId}-${Xe}`)):e("span",{className:"tcp-badge-info",children:"start"})})]},R.nodeId)})]},o))}):e(Le,{text:"No stages yet. Add one to start shaping the workflow."})}),e(Wt,{title:"Agent Directory",subtitle:"All agents currently participating in this workflow.",children:e("div",{className:"grid gap-2 md:grid-cols-2",children:I.agents.map(o=>{const f=L?.agentId===o.agentId;return e("button",{className:`tcp-list-item text-left ${f?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{v(o.agentId);const R=I.nodes.find(P=>P.agentId===o.agentId);R&&ye(R.nodeId)},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:o.displayName||o.agentId}),e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e("span",{className:"tcp-badge-info",children:o.role}),re?.repairedAgentIds.includes(o.agentId)?e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):g(o.linkedTemplateId||o.templateId)?O.has(g(o.linkedTemplateId||o.templateId))?e("span",{className:"tcp-badge-info",children:"linked"}):e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):e("span",{className:"tcp-badge-muted",children:"local"})]})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:o.agentId}),o.linkedTemplateId?e("div",{className:"mt-2 text-xs text-emerald-200",children:["linked template: ",o.linkedTemplateId]}):null]},o.agentId)})})})]}),e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:[e(Wt,{title:ie?`Stage: ${ie.title}`:"Stage",subtitle:"Edit stage behavior, dependencies, and handoff aliases.",actions:e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:Ye,disabled:!ie,children:[e("i",{"data-lucide":"trash-2"}),"Remove Stage"]}),children:ie?e("div",{className:"grid gap-3",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Title"}),e("input",{className:"tcp-input text-sm",value:ie.title,onInput:o=>{Ge(ie.nodeId,{title:o.target.value})}})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Bound Agent"}),e("select",{className:"tcp-input text-sm",value:ie.agentId,onInput:o=>{const f=o.target.value;Ge(ie.nodeId,{agentId:f}),v(f)},children:I.agents.map(o=>e("option",{value:o.agentId,children:o.displayName||o.agentId},o.agentId))})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[110px] text-sm",value:ie.objective,onInput:o=>Ge(ie.nodeId,{objective:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Kind"}),e("input",{className:"tcp-input text-sm",value:ie.outputKind,onInput:o=>Ge(ie.nodeId,{outputKind:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Required Output File"}),e("input",{className:"tcp-input text-sm",placeholder:"marketing-brief.md",value:ie.outputPath,onInput:o=>Ge(ie.nodeId,{outputPath:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Task Kind"}),e("input",{className:"tcp-input text-sm",placeholder:"code_change",value:ie.taskKind||"",onInput:o=>Ge(ie.nodeId,{taskKind:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Project Backlog Tasks"}),e("input",{type:"checkbox",checked:!!ie.projectBacklogTasks,onChange:o=>Ge(ie.nodeId,{projectBacklogTasks:o.target.checked})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Backlog Task ID"}),e("input",{className:"tcp-input text-sm",placeholder:"BACKLOG-123",value:ie.backlogTaskId||"",onInput:o=>Ge(ie.nodeId,{backlogTaskId:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Repo Root"}),e("input",{className:"tcp-input text-sm",placeholder:".",value:ie.repoRoot||"",onInput:o=>Ge(ie.nodeId,{repoRoot:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Write Scope"}),e("input",{className:"tcp-input text-sm",placeholder:"src/api, tests/api, Cargo.toml",value:ie.writeScope||"",onInput:o=>Ge(ie.nodeId,{writeScope:o.target.value})})]}),e("label",{className:"grid gap-1 sm:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Acceptance Criteria"}),e("input",{className:"tcp-input text-sm",placeholder:"Describe what must be true for this coding task to count as done.",value:ie.acceptanceCriteria||"",onInput:o=>Ge(ie.nodeId,{acceptanceCriteria:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Backlog Dependencies"}),e("input",{className:"tcp-input text-sm",placeholder:"BACKLOG-101, BACKLOG-102",value:ie.taskDependencies||"",onInput:o=>Ge(ie.nodeId,{taskDependencies:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Verification State"}),e("input",{className:"tcp-input text-sm",placeholder:"pending",value:ie.verificationState||"",onInput:o=>Ge(ie.nodeId,{verificationState:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Task Owner / Claimer"}),e("input",{className:"tcp-input text-sm",placeholder:"implementer",value:ie.taskOwner||"",onInput:o=>Ge(ie.nodeId,{taskOwner:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Verification Command"}),e("input",{className:"tcp-input text-sm",placeholder:"cargo test -p tandem-server",value:ie.verificationCommand||"",onInput:o=>Ge(ie.nodeId,{verificationCommand:o.target.value})})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs text-slate-400",children:"Dependencies"}),e("div",{className:"flex flex-wrap gap-2",children:I.nodes.filter(o=>o.nodeId!==ie.nodeId).map(o=>{const f=ie.dependsOn.includes(o.nodeId);return e("button",{className:f?"tcp-btn-primary inline-flex h-7 items-center gap-2 px-2 text-xs":"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>{const R=f?ie.dependsOn.filter(P=>P!==o.nodeId):[...ie.dependsOn,o.nodeId];Ge(ie.nodeId,{dependsOn:R})},children:[e("i",{"data-lucide":f?"check":"plus"}),o.title]},`${ie.nodeId}-${o.nodeId}`)})})]}),ie.inputRefs.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs text-slate-400",children:"Input Aliases"}),ie.inputRefs.map(o=>e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500",children:o.fromStepId}),e("input",{className:"tcp-input text-sm",value:o.alias,onInput:f=>Ge(ie.nodeId,{inputRefs:ie.inputRefs.map(R=>R.fromStepId===o.fromStepId?{...R,alias:f.target.value}:R)})})]},`${ie.nodeId}-${o.fromStepId}`))]}):null]}):e(Le,{text:"Select a stage to edit it."})}),e(Wt,{title:L?`Agent: ${L.displayName||L.agentId}`:"Agent",subtitle:"Role prompt, policies, reusable template link, and model settings.",actions:e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:le,disabled:!L,children:[e("i",{"data-lucide":"trash-2"}),"Remove Agent"]}),children:L?e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Display Name"}),e("input",{className:"tcp-input text-sm",value:L.displayName,onInput:o=>nt(L.agentId,{displayName:o.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Role"}),e("select",{className:"tcp-input text-sm",value:L.role,onInput:o=>nt(L.agentId,{role:o.target.value}),children:Dd.map(o=>e("option",{value:o,children:o},o))})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Skills"}),e("input",{className:"tcp-input text-sm",value:_n(L.skills),onInput:o=>nt(L.agentId,{skills:Nn(o.target.value)}),placeholder:"copywriting, websearch, qa"})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Template Link"}),L.linkedTemplateId?e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>nt(L.agentId,{linkedTemplateId:"",templateId:""}),children:[e("i",{"data-lucide":"unlink"}),"Detach"]}):null]}),e("div",{className:"grid gap-2 md:grid-cols-[minmax(0,1fr)_auto]",children:[e("select",{className:"tcp-input text-sm",value:U,onInput:o=>ue(o.target.value),children:[e("option",{value:"",children:"Select an existing agent template..."}),C.map(o=>e("option",{value:o.templateId,children:o.displayName||o.templateId},o.templateId))]}),e("button",{className:"tcp-btn inline-flex h-10 items-center gap-2 px-3 text-sm",disabled:!U,onClick:it,children:[e("i",{"data-lucide":"download"}),"Load Template"]})]}),e("div",{className:"mt-2 text-xs text-slate-400",children:re?.repairedAgentIds.includes(L.agentId)?"This agent had a missing shared template link. Studio repaired it into a workflow-local prompt.":L.linkedTemplateId?O.has(L.linkedTemplateId)?`Linked template: ${L.linkedTemplateId}`:`Missing template link repaired locally: ${L.linkedTemplateId}`:"This agent is currently workflow-local unless you save reusable templates."}),e("div",{className:"mt-1 text-xs text-slate-500",children:"Local means Studio stores the prompt in workflow metadata. Linked means runtime depends on a shared Agent Team template."})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Model Provider"}),e("select",{className:"tcp-input text-sm",value:L.modelProvider,disabled:I.useSharedModel,onInput:o=>nt(L.agentId,(()=>{const f=o.target.value,R=on(k,f);return{modelProvider:f,modelId:R.includes(L.modelId)?L.modelId:R[0]||L.modelId}})()),children:[e("option",{value:"",children:"Select provider..."}),k.map(o=>e("option",{value:o.id,children:o.id},o.id))]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Model ID"}),on(k,L.modelProvider).length?e("select",{className:"tcp-input text-sm",value:L.modelId,disabled:I.useSharedModel,onInput:o=>nt(L.agentId,{modelId:o.target.value}),children:on(k,L.modelProvider).map(o=>e("option",{value:o,children:o},o))}):e("input",{className:"tcp-input text-sm",value:L.modelId,disabled:I.useSharedModel,onInput:o=>nt(L.agentId,{modelId:o.target.value}),placeholder:"provider-specific model id"})]}),I.useSharedModel?e("div",{className:"text-xs text-amber-200 md:col-span-2",children:"Per-agent model controls are locked because this workflow is using one shared model for all agents."}):null,e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Tool Allowlist"}),e("input",{className:"tcp-input text-sm",value:_n(L.toolAllowlist),onInput:o=>nt(L.agentId,{toolAllowlist:Nn(o.target.value)})})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Tool Denylist"}),e("input",{className:"tcp-input text-sm",value:_n(L.toolDenylist),onInput:o=>nt(L.agentId,{toolDenylist:Nn(o.target.value)})})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Allowed MCP Servers"}),e("input",{className:"tcp-input text-sm",value:_n(L.mcpAllowedServers),onInput:o=>nt(L.agentId,{mcpAllowedServers:Nn(o.target.value)}),placeholder:S.join(", ")||"No MCP servers detected"})]})]}),e("div",{className:"grid gap-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Role Prompt"}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Role"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:L.prompt.role,onInput:o=>nt(L.agentId,{prompt:{...L.prompt,role:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Mission"}),e("textarea",{className:"tcp-input min-h-[92px] text-sm",value:L.prompt.mission,onInput:o=>nt(L.agentId,{prompt:{...L.prompt,mission:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Inputs"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:L.prompt.inputs,onInput:o=>nt(L.agentId,{prompt:{...L.prompt,inputs:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Contract"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:L.prompt.outputContract,onInput:o=>nt(L.agentId,{prompt:{...L.prompt,outputContract:o.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Guardrails"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:L.prompt.guardrails,onInput:o=>nt(L.agentId,{prompt:{...L.prompt,guardrails:o.target.value}})})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 text-xs uppercase tracking-wide text-slate-500",children:"Composed System Prompt"}),e("pre",{className:"whitespace-pre-wrap break-words text-xs text-slate-200",children:ir(L.prompt)||"Prompt preview will appear here."})]})]}):e(Le,{text:"Select or add an agent to edit it."})})]})]})})})}const eu=`defaults:
|
|
1859
|
+
`)}function iu(a){if(!(!g(a.modelProvider)||!g(a.modelId)))return{default_model:{provider_id:g(a.modelProvider),model_id:g(a.modelId)}}}function ou(a,t){const r=g(t?.default)||a[0]?.id||"";if(!r)return{provider:"",model:""};const s=a.find(d=>d.id===r)?.models||[],c=g(t?.providers?.[r]?.default_model||s[0]);return{provider:r,model:c}}function cn(a,t){return a.find(n=>n.id===t)?.models||[]}function Tn(a,t){return!t.provider||!t.model?a:a.map(n=>g(n.modelProvider)&&g(n.modelId)?n:{...n,modelProvider:g(n.modelProvider)||t.provider,modelId:g(n.modelId)||t.model})}function Li(a){const t=a.map(s=>({provider:g(s.modelProvider),model:g(s.modelId)})).filter(s=>s.provider&&s.model);if(!t.length)return{useSharedModel:!1,provider:"",model:""};const n=t[0],r=t.every(s=>s.provider===n.provider&&s.model===n.model);return{useSharedModel:r,provider:r?n.provider:"",model:r?n.model:""}}function Es(a,t,n){const r=g(t),s=g(n);return!r||!s?a:a.map(c=>({...c,modelProvider:r,modelId:s}))}function lu(a){const t={type:"run_once"};return a.scheduleType==="cron"&&g(a.cronExpression)?{type:"cron",cron_expression:g(a.cronExpression),timezone:"UTC",misfire_policy:t}:a.scheduleType==="interval"?{type:"interval",interval_seconds:Math.max(60,Number.parseInt(String(a.intervalSeconds||"3600"),10)||3600),timezone:"UTC",misfire_policy:t}:{type:"manual",timezone:"UTC",misfire_policy:t}}function cu(a){return Array.isArray(a?.servers)?a.servers.map(t=>g(t?.name)).filter(Boolean).sort((t,n)=>t.localeCompare(n)):Object.keys(a||{}).map(t=>g(t)).filter(Boolean).sort((t,n)=>t.localeCompare(n))}function du(a){const t=a?.default_model||a?.defaultModel||{},r=(Array.isArray(a?.skills)?a.skills:[]).map(s=>g(typeof s=="string"?s:s?.skill_id||s?.skillId||s?.id||s?.name)).filter(Boolean);return{templateId:g(a?.template_id||a?.templateID||a?.id),displayName:g(a?.display_name||a?.displayName||a?.name),avatarUrl:g(a?.avatar_url||a?.avatarUrl),role:g(a?.role||"worker")||"worker",systemPrompt:g(a?.system_prompt||a?.systemPrompt),modelProvider:g(t?.provider_id||t?.providerId),modelId:g(t?.model_id||t?.modelId),skills:r}}function cs(a){return{role:"",mission:g(a),inputs:"",outputContract:"",guardrails:""}}function jn(a,t){return a.map(r=>t.find(c=>c.fromStepId===r)||{fromStepId:r,alias:r.replace(/-/g,"_")})}function Ki(a){const t=new Map(a.map(s=>[s.nodeId,s])),n=new Map,r=(s,c=new Set)=>{if(n.has(s))return Number(n.get(s)||0);if(c.has(s))return 0;const d=t.get(s);if(!d||!d.dependsOn.length)return n.set(s,0),0;const u=new Set(c);u.add(s);const p=Math.max(...d.dependsOn.map(N=>r(N,u)))+1;return n.set(s,p),p};for(const s of a)r(s.nodeId);return n}function Ds(a){return{agentId:g(a?.agentId||a?.agent_id||a?.id),displayName:g(a?.displayName||a?.display_name||a?.name),role:g(a?.role||"worker")||"worker",avatarUrl:g(a?.avatarUrl||a?.avatar_url),templateId:g(a?.templateId||a?.template_id),linkedTemplateId:g(a?.linkedTemplateId||a?.linked_template_id||a?.templateId||a?.template_id),skills:Array.isArray(a?.skills)?a.skills.map(t=>g(t)).filter(Boolean):[],prompt:a?.prompt&&typeof a.prompt=="object"?{role:g(a.prompt.role),mission:g(a.prompt.mission),inputs:g(a.prompt.inputs),outputContract:g(a.prompt.outputContract||a.prompt.output_contract),guardrails:g(a.prompt.guardrails)}:cs(g(a?.systemPrompt||a?.system_prompt)),modelProvider:g(a?.modelProvider||a?.model_provider),modelId:g(a?.modelId||a?.model_id),toolAllowlist:ls(Array.isArray(a?.toolAllowlist||a?.tool_allowlist)?(a.toolAllowlist||a.tool_allowlist).map(t=>g(t)).filter(Boolean):Array.isArray(a?.tool_policy?.allowlist)?a.tool_policy.allowlist.map(t=>g(t)).filter(Boolean):[]),toolDenylist:Array.isArray(a?.toolDenylist||a?.tool_denylist)?(a.toolDenylist||a.tool_denylist).map(t=>g(t)).filter(Boolean):Array.isArray(a?.tool_policy?.denylist)?a.tool_policy.denylist.map(t=>g(t)).filter(Boolean):[],mcpAllowedServers:Array.isArray(a?.mcpAllowedServers||a?.mcp_allowed_servers)?(a.mcpAllowedServers||a.mcp_allowed_servers).map(t=>g(t)).filter(Boolean):Array.isArray(a?.mcp_policy?.allowed_servers)?a.mcp_policy.allowed_servers.map(t=>g(t)).filter(Boolean):[]}}function js(a){const t=Array.isArray(a?.dependsOn||a?.depends_on)?(a.dependsOn||a.depends_on).map(s=>g(s)).filter(Boolean):[],n=Array.isArray(a?.inputRefs||a?.input_refs)?a.inputRefs||a.input_refs:[],r=a?.metadata?.builder&&typeof a.metadata.builder=="object"?a.metadata.builder:{};return{nodeId:g(a?.nodeId||a?.node_id||a?.id),title:g(a?.title||a?.objective||a?.nodeId||a?.node_id),agentId:g(a?.agentId||a?.agent_id),objective:g(a?.objective),dependsOn:t,inputRefs:jn(t,n.map(s=>({fromStepId:g(s?.fromStepId||s?.from_step_id),alias:g(s?.alias)}))),stageKind:g(a?.stageKind||a?.stage_kind||r?.research_stage||a?.metadata?.studio?.research_stage),outputKind:g(a?.outputKind||a?.output_kind||a?.output_contract?.kind||"artifact"),outputPath:g(a?.outputPath||a?.output_path||r?.output_path||a?.metadata?.studio?.output_path),taskKind:g(a?.taskKind||a?.task_kind||r?.task_kind),projectBacklogTasks:!!(a?.projectBacklogTasks||a?.project_backlog_tasks||r?.project_backlog_tasks),backlogTaskId:g(a?.backlogTaskId||a?.backlog_task_id||r?.task_id),repoRoot:g(a?.repoRoot||a?.repo_root||r?.repo_root),writeScope:g(a?.writeScope||a?.write_scope||r?.write_scope),acceptanceCriteria:g(a?.acceptanceCriteria||a?.acceptance_criteria||r?.acceptance_criteria),taskDependencies:g(a?.taskDependencies||a?.task_dependencies||r?.task_dependencies),verificationState:g(a?.verificationState||a?.verification_state||r?.verification_state),taskOwner:g(a?.taskOwner||a?.task_owner||r?.task_owner),verificationCommand:g(a?.verificationCommand||a?.verification_command||r?.verification_command)}}function uu(a,t){const n=os(a),r=t.toolAllowlist.includes("glob"),s=t.toolAllowlist.includes("read"),c=t.toolAllowlist.includes("edit")||n,d=t.toolAllowlist.includes("apply_patch")||n,u=t.toolAllowlist.includes("bash");return[g(a.objective),g(t.prompt.mission),g(t.prompt.inputs),g(t.prompt.outputContract),g(t.prompt.guardrails),g(a.taskKind)?`Task kind: ${g(a.taskKind)}.`:"",Fi(a)?"Project backlog tasks for this run. Include a fenced `json` block containing either an array of tasks or an object with `backlog_tasks`, where each task includes `task_id`, `title`, `description`, `repo_root`, `write_scope`, `acceptance_criteria`, `task_dependencies`, `verification_state`, `task_owner`, and `verification_command` when known.":"",g(a.backlogTaskId)?`Backlog task id: ${g(a.backlogTaskId)}.`:"",g(a.repoRoot)?`Repository root for this task: ${g(a.repoRoot)}.`:"",g(a.writeScope)?`Declared write scope: ${g(a.writeScope)}.`:"",g(a.acceptanceCriteria)?`Acceptance criteria: ${g(a.acceptanceCriteria)}.`:"",g(a.taskDependencies)?`Backlog task dependencies: ${g(a.taskDependencies)}.`:"",g(a.verificationState)?`Expected verification state progression: ${g(a.verificationState)}.`:"",g(a.taskOwner)?`Preferred task owner or claimer: ${g(a.taskOwner)}.`:"",g(a.verificationCommand)?`Expected verification command or rule: ${g(a.verificationCommand)}.`:"","Execution rules:",r||s?`- Inspect the workspace before writing using ${[r?"`glob`":"",s?"`read`":""].filter(Boolean).join(" and ")}.`:"",r?"- Use `glob` to enumerate directories or discover candidate file paths.":"",s?"- Use `read` only for concrete file paths you have already identified.":"","- Use workspace-relative paths like `README.md` or `subdir/file.md`. Do not use a `/workspace/...` prefix.",t.toolAllowlist.includes("websearch")?"- Use `websearch` to gather current external evidence before finalizing the file.":"",a.stageKind==="research_discover"?"- After `glob` discovery, perform at least one concrete `read` on a prioritized source index or representative workspace file before completing this stage.":"",a.stageKind&&!g(a.outputPath)?"- Do not write final workspace artifacts in this stage. Return a structured handoff in your final response instead.":"",n&&d?"- Prefer `apply_patch` for multi-line source edits when a git-backed patch tool is available.":"",n&&c?"- Prefer `edit` for existing-file source changes; use `write` only for new files or when patch/edit cannot express the change.":g(a.outputPath)?`- Create or update \`${g(a.outputPath)}\` in the workspace with the \`write\` tool.`:"- If this stage creates a file, use the `write` tool rather than a prose-only response.",n&&u?"- Use `bash` for repo-appropriate build, test, or lint commands after editing, and report the exact commands run.":"",n?"- Do not replace an existing source file with a status note, placeholder, or preservation summary.":"",a.stageKind&&!g(a.outputPath)?"- Do not claim success unless the required structured handoff was actually returned in the final response.":g(a.outputPath)?`- Do not claim success unless \`${g(a.outputPath)}\` was actually written.`:"- Do not claim success unless the required artifact was actually created."].filter(Boolean).join(`
|
|
1860
|
+
`)}function Wi(a,t,n){const r=Ba.find(c=>c.id===a);return r&&ur(r,n||"").agents.find(c=>c.agentId===t)||null}function Hr(a,t){const n=[],r=[],s=a.nodes.map(d=>d.agentId).filter((d,u,p)=>!!d&&p.indexOf(d)===u&&!a.agents.some(N=>N.agentId===d)),c=a.agents.map(d=>{const u=g(d.linkedTemplateId||d.templateId);if(!u||t.has(u))return d;const p=Wi(a.starterTemplateId,d.agentId,a.workspaceRoot);return n.push(d.agentId),r.push(u),{...d,templateId:"",linkedTemplateId:"",prompt:vr(d.prompt)?d.prompt:p?.prompt||d.prompt,role:g(d.role)?d.role:p?.role||"worker",skills:d.skills.length?d.skills:p?.skills||[],toolAllowlist:ls(d.toolAllowlist.length?d.toolAllowlist:p?.toolAllowlist||["read","write","glob"]),toolDenylist:d.toolDenylist.length?d.toolDenylist:p?.toolDenylist||[],mcpAllowedServers:d.mcpAllowedServers.length?d.mcpAllowedServers:p?.mcpAllowedServers||[],modelProvider:g(d.modelProvider)||p?.modelProvider||"",modelId:g(d.modelId)||p?.modelId||"",avatarUrl:g(d.avatarUrl)||p?.avatarUrl||"",displayName:g(d.displayName)||p?.displayName||d.agentId}});return!n.length&&!s.length?{draft:a,repairState:null}:{draft:{...a,agents:c},repairState:{repairedAgentIds:n,repairedTemplateIds:r,missingNodeAgentIds:s,reason:"load",requiresSave:n.length>0}}}function Us(a,t){const r=(Array.isArray(a?.agents)?a.agents:[]).map(s=>({agentId:g(s?.agent_id||s?.agentId),templateId:g(s?.template_id||s?.templateId)})).filter(s=>s.templateId&&!t.has(s.templateId));return{missingTemplateLinks:r,isBroken:r.length>0}}function mu(a,t){const n=[],r=Qr(a.workspaceRoot);r&&n.push(r),g(a.name)||n.push("Workflow name is required."),a.agents.length||n.push("Add at least one agent."),a.nodes.length||n.push("Add at least one stage.");const s=a.nodes.map(d=>d.agentId).filter((d,u,p)=>!!d&&p.indexOf(d)===u&&!a.agents.some(N=>N.agentId===d));s.length&&n.push(`Stages reference missing agents: ${s.join(", ")}.`);const c=a.agents.map(d=>({agentId:d.agentId,templateId:g(d.linkedTemplateId||d.templateId)})).filter(d=>d.templateId&&!t.has(d.templateId));return{errors:n,missingNodeAgentIds:s,brokenAgentLinks:c}}function pu(a,t,n){const r=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},s=r?.studio&&typeof r.studio=="object"?r.studio:{},c=s?.workflow&&typeof s.workflow=="object"?s.workflow:{},d=g(s?.template_id||s?.templateId),u=Array.isArray(s?.agent_drafts)?s.agent_drafts.map(Ds):[],p=Array.isArray(s?.node_drafts)?s.node_drafts.map(js):[],N=Array.isArray(a?.agents)?a.agents.map(_=>{const z=g(_?.template_id||_?.templateId),P=z?n.get(z):null,Q=!P&&d?Wi(d,g(_?.agent_id||_?.agentId),g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t)):null;return Ds({agentId:_?.agent_id||_?.agentId,displayName:_?.display_name||_?.displayName||Q?.displayName||_?.agent_id||_?.agentId,role:P?.role||Q?.role||"worker",templateId:z,linkedTemplateId:z,skills:Array.isArray(_?.skills)?_.skills:P?.skills||Q?.skills||[],prompt:P?.systemPrompt?cs(P.systemPrompt):Q?.prompt,modelProvider:_?.model_policy?.default_model?.provider_id||_?.modelPolicy?.defaultModel?.providerId||Q?.modelProvider||P?.modelProvider||"",modelId:_?.model_policy?.default_model?.model_id||_?.modelPolicy?.defaultModel?.modelId||Q?.modelId||P?.modelId||"",toolAllowlist:_?.tool_policy?.allowlist||_?.toolPolicy?.allowlist||[],toolDenylist:_?.tool_policy?.denylist||_?.toolPolicy?.denylist||[],mcpAllowedServers:_?.mcp_policy?.allowed_servers||_?.mcpPolicy?.allowedServers||[]})}):[],E=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map(_=>js({nodeId:_?.node_id||_?.nodeId,title:_?.metadata?.builder?.title||_?.metadata?.studio?.title||_?.objective||_?.node_id||_?.nodeId,agentId:_?.agent_id||_?.agentId,objective:_?.objective,dependsOn:_?.depends_on||_?.dependsOn||[],inputRefs:_?.input_refs||_?.inputRefs||[],outputKind:_?.output_contract?.kind||_?.outputContract?.kind||"artifact",metadata:_?.metadata})):[],x={automationId:g(a?.automation_id||a?.automationId||a?.id),starterTemplateId:d,name:g(a?.name||"Workflow"),description:g(a?.description),summary:g(s?.summary),icon:g(s?.icon),workspaceRoot:g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t),status:g(a?.status||c?.status||"draft")||"draft",scheduleType:g(a?.schedule?.type||c?.schedule_type||"manual")||"manual",cronExpression:g(a?.schedule?.cron_expression||a?.schedule?.cronExpression||c?.cron_expression),intervalSeconds:String(a?.schedule?.interval_seconds||a?.schedule?.intervalSeconds||c?.interval_seconds||3600),maxParallelAgents:String(a?.execution?.max_parallel_agents||a?.execution?.maxParallelAgents||c?.max_parallel_agents||1),useSharedModel:!1,sharedModelProvider:"",sharedModelId:"",outputTargets:Array.isArray(a?.output_targets||a?.outputTargets)?(a.output_targets||a.outputTargets).map(_=>g(_)).filter(Boolean):Array.isArray(c?.output_targets)?c.output_targets.map(_=>g(_)).filter(Boolean):[],agents:u.length?u:N,nodes:p.length?p:E},A=Li(x.agents);return x.useSharedModel=A.useSharedModel,x.sharedModelProvider=A.provider,x.sharedModelId=A.model,Hr(x,n)}function hu(a,t){const n={templateID:t,display_name:g(a.displayName)||t,avatar_url:g(a.avatarUrl)||void 0,role:g(a.role)||"worker",system_prompt:vr(a.prompt)||void 0,skills:a.skills.map(r=>({id:r,skill_id:r,name:r})),default_budget:{},capabilities:{}};return g(a.modelProvider)&&g(a.modelId)&&(n.default_model={provider_id:g(a.modelProvider),model_id:g(a.modelId)}),n}function gu(a,t,n){const r=Ki(t);return{version:2,template_id:g(a.starterTemplateId),workflow_structure_version:2,summary:g(a.summary),icon:g(a.icon),created_from:"studio",last_saved_at_ms:Date.now(),workflow:{status:g(a.status)||"draft",schedule_type:g(a.scheduleType)||"manual",cron_expression:g(a.cronExpression),interval_seconds:Math.max(60,Number.parseInt(String(a.intervalSeconds||"3600"),10)||3600),output_targets:a.outputTargets,max_parallel_agents:Math.max(1,Number.parseInt(String(a.maxParallelAgents||"1"),10)||1)},repair_state:n?{status:n.repairedAgentIds.length||n.missingNodeAgentIds.length?"repaired":"clean",reason:n.reason,requires_save:n.requiresSave}:{status:"clean",reason:"",requires_save:!1},repaired_missing_templates:n?.repairedTemplateIds||[],repaired_agent_ids:n?.repairedAgentIds||[],agent_drafts:a.agents,node_drafts:t,node_layout:Object.fromEntries(Array.from(r.entries()))}}function fu(a){const t=new Map,n=new Set;for(const r of a){const s=tr(r.nodeId||r.title,"stage");let c=s,d=2;for(;n.has(c);)c=`${s}-${d}`,d+=1;n.add(c),t.set(r.nodeId,c)}return a.map(r=>{const s=t.get(r.nodeId)||tr(r.nodeId||r.title,"stage"),c=r.dependsOn.map(u=>t.get(u)||tr(u,u)).filter(Boolean),d=jn(c,r.inputRefs.map(u=>({fromStepId:t.get(u.fromStepId)||tr(u.fromStepId,u.fromStepId),alias:u.alias})));return{...r,nodeId:s,dependsOn:c,inputRefs:d}})}async function bu(a,t,n=4){for(let r=0;r<n;r+=1){const s=await a.automationsV2.list().catch(()=>({automations:[]}));if(!mr(s,"automations").some(u=>g(u?.automation_id||u?.automationId||u?.id)===t))return;await new Promise(u=>window.setTimeout(u,250*(r+1)))}throw new Error("Delete did not persist on the engine. The workflow is still present after verification.")}function vu({client:a,api:t,toast:n,navigate:r}){const s=ca(),c=Bi(!0),d=V({queryKey:["studio","automations"],queryFn:()=>a.automationsV2.list().catch(()=>({automations:[]})),refetchInterval:15e3}),u=V({queryKey:["studio","templates"],queryFn:()=>a.agentTeams.listTemplates().catch(()=>({templates:[]})),refetchInterval:1e4}),p=V({queryKey:["studio","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),N=V({queryKey:["studio","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),E=V({queryKey:["studio","mcp"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:15e3}),x=g(c.data?.workspaceRoot||c.data?.workspace_root),A=F(()=>mr(u.data,"templates").map(du).filter(l=>l.templateId),[u.data]),O=F(()=>new Map(A.map(l=>[l.templateId,l])),[A]),_=F(()=>(Array.isArray(p.data?.all)?p.data.all:[]).map(b=>({id:g(b?.id),models:Object.keys(b?.models||{})})).filter(b=>!!b.id).sort((b,T)=>b.id.localeCompare(T.id)),[p.data]),z=F(()=>ou(_,N.data),[_,N.data]),P=F(()=>mr(d.data,"automations").filter(l=>{const b=l?.metadata?.studio;return!!b&&(Number(b?.version||0)>0||g(b?.created_from)==="studio")}),[d.data]),Q=F(()=>P.map(l=>g(l?.automation_id||l?.automationId||l?.id)).filter(Boolean),[P]),B=V({queryKey:["studio","workflow-runs",Q],enabled:!!a?.automationsV2?.listRuns&&Q.length>0,queryFn:async()=>({runs:(await Promise.all(Q.map(async b=>{const T=await a.automationsV2.listRuns(b,6).catch(()=>({runs:[]}));return Array.isArray(T?.runs)?T.runs:[]}))).flat()}),refetchInterval:12e3}),ne=F(()=>{const l=mr(B.data,"runs"),b=new Map;return l.forEach(T=>{const R=g(T?.automation_id||T?.automationId);if(!R)return;const $=b.get(R),Ye=Number($?.updated_at_ms||$?.updatedAtMs||$?.created_at_ms||$?.createdAtMs||0),Xe=Number(T?.updated_at_ms||T?.updatedAtMs||T?.created_at_ms||T?.createdAtMs||0);(!$||Xe>=Ye)&&b.set(R,T)}),b},[B.data]),I=F(()=>cu(E.data),[E.data]),[C,H]=w(()=>ur(Ba[0],"")),[M,xe]=w(()=>Ba[0]?.nodes?.[0]?.nodeId||""),[y,v]=w(()=>Ba[0]?.agents?.[0]?.agentId||""),[j,he]=w(""),[ee,qe]=w(!1),[$e,Le]=w(!1),[re,me]=w(!0),[q,ge]=w(!0),[Pe,Te]=w(!1),[se,Oe]=w(""),[Me,He]=w(""),[Y,Ze]=w(null),[ae,Ae]=w(null);fe(()=>{x&&H(l=>g(l.workspaceRoot)?l:{...l,workspaceRoot:x})},[x]),fe(()=>{!z.provider||!z.model||H(l=>{const b=Tn(l.agents,z);return b.some((R,$)=>R.modelProvider!==l.agents[$]?.modelProvider||R.modelId!==l.agents[$]?.modelId)?{...l,agents:b}:l})},[z]),fe(()=>{C.useSharedModel&&(!g(C.sharedModelProvider)||!g(C.sharedModelId)||H(l=>{if(!l.useSharedModel)return l;const b=Es(l.agents,l.sharedModelProvider,l.sharedModelId);return b.some((R,$)=>R.modelProvider!==l.agents[$]?.modelProvider||R.modelId!==l.agents[$]?.modelId)?{...l,agents:b}:l}))},[C.useSharedModel,C.sharedModelProvider,C.sharedModelId]),fe(()=>{new Set(C.nodes.map(b=>b.nodeId)).has(M)||xe(C.nodes[0]?.nodeId||"")},[C.nodes,M]),fe(()=>{new Set(C.agents.map(b=>b.agentId)).has(y)||v(C.agents[0]?.agentId||"")},[C.agents,y]),fe(()=>{try{xa()}catch{}},[C,M,j,re,q,P.length,A.length,Pe,Me]);const St=V({queryKey:["studio","workspace-browser",se],enabled:Pe&&!!se,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(se)}`,{method:"GET"}),refetchInterval:Pe?15e3:!1}),oe=C.nodes.find(l=>l.nodeId===M)||C.nodes[0]||null,W=C.agents.find(l=>l.agentId===(y||oe?.agentId))||C.agents.find(l=>l.agentId===oe?.agentId)||C.agents[0]||null,lt=Qr(C.workspaceRoot),xt=Array.isArray(St.data?.directories)?St.data.directories:[],rt=g(St.data?.parent),Et=g(St.data?.dir||se||""),Fe=F(()=>{const l=g(Me).toLowerCase();return l?xt.filter(b=>g(b?.name||b?.path).toLowerCase().includes(l)):xt},[Me,xt]),Bt=F(()=>Ki(C.nodes),[C.nodes]),At=F(()=>{const l=new Map;for(const b of C.nodes){const T=Number(Bt.get(b.nodeId)||0);l.has(T)||l.set(T,[]),l.get(T)?.push(b)}return Array.from(l.entries()).sort((b,T)=>b[0]-T[0])},[C.nodes,Bt]),$t=l=>{const b=Ba.find(R=>R.id===l)||Ba[0],T=ur(b,C.workspaceRoot||x);H({...T,agents:Tn(T.agents,z)}),xe(T.nodes[0]?.nodeId||""),v(T.agents[0]?.agentId||""),qe(!1),Ae(null)},We=l=>H(b=>({...b,...l})),ze=(l,b)=>H(T=>({...T,nodes:T.nodes.map(R=>R.nodeId===l?{...R,...b,inputRefs:b.dependsOn||b.inputRefs?jn(b.dependsOn?[...b.dependsOn]:R.dependsOn,b.inputRefs?[...b.inputRefs]:R.inputRefs):R.inputRefs}:R)})),tt=(l,b)=>H(T=>({...T,agents:T.agents.map(R=>R.agentId===l?{...R,...b}:R)})),be=()=>{const l=`agent-${C.agents.length+1}`,b=C.agents.some(T=>T.agentId===l)?`agent-${Date.now().toString().slice(-5)}`:l;H(T=>({...T,agents:[...T.agents,Tn([Ms(b,`Agent ${T.agents.length+1}`)],z)[0]]})),v(b)},Se=()=>{const l=C.nodes.length+1,b=`stage-${l}`,T=W?.agentId||C.agents[0]?.agentId||"",R=tu(b,`Stage ${l}`,T,oe?[oe.nodeId]:[],oe?[{fromStepId:oe.nodeId,alias:oe.nodeId.replace(/-/g,"_")}]:[],{objective:"Describe what this stage should produce."});H($=>({...$,nodes:[...$.nodes,R]})),xe(b),T&&v(T)},Ve=()=>{oe&&H(l=>({...l,nodes:l.nodes.filter(b=>b.nodeId!==oe.nodeId).map(b=>{const T=b.dependsOn.filter(R=>R!==oe.nodeId);return{...b,dependsOn:T,inputRefs:jn(T,b.inputRefs.filter(R=>R.fromStepId!==oe.nodeId))}})}))},ce=()=>{if(!W)return;if(C.nodes.some(b=>b.agentId===W.agentId)){n("warn","Reassign or remove the stages using this agent first.");return}H(b=>({...b,agents:b.agents.filter(T=>T.agentId!==W.agentId)})),v("")},dt=()=>{if(!W||!j)return;const l=O.get(j);l&&(tt(W.agentId,{displayName:l.displayName||W.displayName,avatarUrl:l.avatarUrl||W.avatarUrl,role:l.role||W.role,linkedTemplateId:l.templateId,templateId:l.templateId,prompt:l.systemPrompt?cs(l.systemPrompt):W.prompt,modelProvider:l.modelProvider||W.modelProvider,modelId:l.modelId||W.modelId,skills:l.skills.length?l.skills:W.skills}),Ae(b=>b&&{...b,repairedAgentIds:b.repairedAgentIds.filter(T=>T!==W.agentId),repairedTemplateIds:b.repairedTemplateIds.filter(T=>T!==l.templateId)}),n("ok",`Loaded template ${l.templateId}.`))},S=l=>{const b=pu(l,x,O),T={...b.draft,agents:Tn(b.draft.agents,z)};H(T),xe(T.nodes[0]?.nodeId||""),v(T.agents[0]?.agentId||""),qe(b.draft.agents.some(R=>!!g(R.linkedTemplateId||R.templateId))),Ae(b.repairState?{...b.repairState,reason:"load",requiresSave:!0}:null),b.repairState?.repairedAgentIds.length&&n("warn",`Repaired missing template links for: ${b.repairState.repairedAgentIds.join(", ")}. Save the workflow before running it.`),r("studio")},G=async l=>{const b=g(l?.automation_id||l?.automationId||l?.id);if(Us(l,O).isBroken){S(l),n("warn","This workflow references missing agent templates. It was repaired in Studio. Save it before running.");return}const R=await a.automationsV2.runNow(b),$=g(R?.run?.run_id||R?.run?.runId);await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]}),s.invalidateQueries({queryKey:["automations","runs"]}),s.invalidateQueries({queryKey:["automations","v2","runs"]})]),n("ok",$?`Workflow run started: ${$}. Opening Automations.`:"Workflow run started. Opening Automations."),Os({tab:"running",runId:$,automationId:b,openTaskInspector:!0}),r("automations")},ue=ke({mutationFn:async()=>{const l=ee?C:Hr(C,O).draft;let b={...l,agents:Tn(l.agents,z)};b.useSharedModel&&g(b.sharedModelProvider)&&g(b.sharedModelId)&&(b={...b,agents:Es(b.agents,b.sharedModelProvider,b.sharedModelId)});const T=Qr(b.workspaceRoot);if(T)throw new Error(T);if(!g(b.name))throw new Error("Workflow name is required.");if(!b.agents.length)throw new Error("Add at least one agent.");if(!b.nodes.length)throw new Error("Add at least one stage.");const R=mu(b,O);if(R.errors.length)throw new Error(R.errors[0]);const $=b.agents.filter(te=>!g(te.modelProvider)||!g(te.modelId)).map(te=>te.displayName||te.agentId);if($.length)throw new Error(`Model selection is required. Set a default provider/model in Settings or choose one for: ${$.join(", ")}.`);const Ye=Jr(b.name)||"studio-workflow",Xe=new Map;if(ee)for(const te of b.agents){const Ne=g(te.linkedTemplateId)||g(te.templateId)||`${Ye}--${Jr(te.agentId)||"agent"}`;Xe.set(te.agentId,Ne),O.has(Ne)?await a.agentTeams.updateTemplate(Ne,{display_name:g(te.displayName)||Ne,avatar_url:g(te.avatarUrl)||void 0,role:g(te.role)||"worker",system_prompt:vr(te.prompt)||void 0,default_model:g(te.modelProvider)&&g(te.modelId)?{provider_id:g(te.modelProvider),model_id:g(te.modelId)}:void 0,skills:te.skills.map(h=>({id:h,skill_id:h,name:h}))}):await a.agentTeams.createTemplate({template:hu(te,Ne)})}const Ot=fu(b.nodes),Ft={name:g(b.name),description:g(b.description)||void 0,status:b.status,schedule:lu(b),workspace_root:g(b.workspaceRoot),execution:{max_parallel_agents:Math.max(1,Number.parseInt(String(b.maxParallelAgents||"1"),10)||1)},output_targets:b.outputTargets.map(te=>g(te)).filter(Boolean),agents:b.agents.map(te=>({agent_id:g(te.agentId),template_id:ee&&(Xe.get(te.agentId)||g(te.linkedTemplateId))||void 0,display_name:g(te.displayName)||g(te.agentId),avatar_url:g(te.avatarUrl)||void 0,model_policy:iu(te),skills:te.skills.map(Ne=>g(Ne)).filter(Boolean),tool_policy:{allowlist:qs(te.toolAllowlist,Ot.filter(Ne=>Ne.agentId===te.agentId)),denylist:te.toolDenylist.map(Ne=>g(Ne)).filter(Boolean)},mcp_policy:{allowed_servers:te.mcpAllowedServers.map(Ne=>g(Ne)).filter(Boolean),allowed_tools:[]}})),flow:{nodes:Ot.map(te=>{const Ne=b.agents.find(Ge=>Ge.agentId===te.agentId),h=g(te.outputPath),U=os(te),J=g(te.stageKind),L=J==="research_finalize",X=!!J&&!h,ye=te.inputRefs.some(Ge=>g(Ge.alias)==="external_research"),Ue=qs(Ne?.toolAllowlist||[],Ot.filter(Ge=>Ge.agentId===te.agentId)),st=!!Ne?.toolAllowlist?.includes("websearch")&&!L,vt=g(te.outputKind)==="brief",It=X&&J==="research_discover",et=X&&(J==="research_discover"||J==="research_local_sources"),yt=X&&J==="research_external_sources"&&st,Lt=h?[Ue.includes("read")&&!L?"read":null,Ue.includes("websearch")&&!L?"websearch":null].filter(Ge=>!!Ge).filter((Ge,da,Ce)=>Ce.indexOf(Ge)===da):X?[et?"read":null,yt?"websearch":null].filter(Ge=>!!Ge):[],Qt=h?[!L&&(Lt.includes("read")||vt)?"local_source_reads":null,!L&&st?"external_sources":null].filter(Ge=>!!Ge):X?[et?"local_source_reads":null,yt?"external_sources":null].filter(Ge=>!!Ge):[],Ct=vt?["files_reviewed","files_not_reviewed","citations",st||ye?"web_sources_reviewed":null].filter(Ge=>!!Ge):[],Ht=h?[L?null:"workspace_inspection",!L&&(Lt.includes("read")||vt)?"concrete_reads":null,!L&&st?"successful_web_research":null].filter(Ge=>!!Ge):X?[It?"workspace_inspection":null,et?"concrete_reads":null,yt?"successful_web_research":null].filter(Ge=>!!Ge):[],kt=[...Qt,...Ct,...Ht];return{node_id:g(te.nodeId),agent_id:g(te.agentId),objective:g(te.objective)||g(te.title),depends_on:te.dependsOn.map(Ge=>g(Ge)).filter(Boolean),input_refs:jn(te.dependsOn,te.inputRefs).map(Ge=>({from_step_id:g(Ge.fromStepId),alias:g(Ge.alias)||g(Ge.fromStepId).replace(/-/g,"_")})),stage_kind:J?"workstream":void 0,output_contract:{kind:g(te.outputKind)||"artifact",enforcement:h?{required_tools:Lt,required_evidence:Qt,required_sections:Ct,prewrite_gates:Ht,retry_on_missing:kt,terminal_on:kt.length?["tool_unavailable","repair_budget_exhausted"]:[],repair_budget:kt.length?5:void 0,session_text_recovery:kt.length||vt?"require_prewrite_satisfied":"allow"}:void 0,summary_guidance:h?U?`Apply the scoped repository changes, update \`${h}\` in the workspace, and use patch/edit/write tools before completing this stage.`:`Create or update \`${h}\` in the workspace and use the write tool before completing this stage.`:X?"Return a structured handoff in the final response instead of writing workspace files.":void 0},metadata:{studio:{output_path:h||void 0,research_stage:J||void 0},builder:{title:g(te.title)||g(te.nodeId),role:g(Ne?.role)||"worker",output_path:h||void 0,research_stage:J||void 0,write_required:!!h,required_tools:Lt,web_research_expected:st,task_kind:g(te.taskKind)||void 0,project_backlog_tasks:Fi(te)||void 0,task_id:g(te.backlogTaskId)||void 0,repo_root:g(te.repoRoot)||void 0,write_scope:g(te.writeScope)||void 0,acceptance_criteria:g(te.acceptanceCriteria)||void 0,task_dependencies:g(te.taskDependencies)||void 0,verification_state:g(te.verificationState)||void 0,task_owner:g(te.taskOwner)||void 0,verification_command:g(te.verificationCommand)||void 0,prompt:uu(te,Ne||Ms(g(te.agentId),g(te.agentId)))}}}})},metadata:{workspace_root:g(C.workspaceRoot),studio:gu({...b,agents:b.agents.map(te=>({...te,templateId:ee?Xe.get(te.agentId)||g(te.linkedTemplateId)||g(te.templateId):"",linkedTemplateId:ee?Xe.get(te.agentId)||g(te.linkedTemplateId)||g(te.templateId):""}))},Ot,ee?null:ae||Hr(b,O).repairState)}},Ie=C.automationId?await a.automationsV2.update(C.automationId,Ft):await a.automationsV2.create(Ft),Pt=g(Ie?.automation?.automation_id||Ie?.automation?.automationId);let bt="";if($e&&Pt){const te=await a.automationsV2.runNow(Pt);bt=g(te?.run?.run_id||te?.run?.runId)}return{response:Ie,automationId:Pt,linkedTemplateIds:Xe,workingDraft:b,startedRunId:bt}},onSuccess:async({response:l,automationId:b,linkedTemplateIds:T,workingDraft:R,startedRunId:$})=>{n("ok",$e?"Studio workflow saved and run started.":"Studio workflow saved."),await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]}),s.invalidateQueries({queryKey:["studio","templates"]}),s.invalidateQueries({queryKey:["teams"]})]),H(Ye=>({...Ye,...R,automationId:b||g(l?.automation?.automation_id||l?.automation?.automationId),agents:R.agents.map(Xe=>({...Xe,templateId:ee?T.get(Xe.agentId)||Xe.templateId:"",linkedTemplateId:ee?T.get(Xe.agentId)||Xe.linkedTemplateId:""}))})),Ae(Ye=>Ye?{...Ye,requiresSave:!1,reason:"save"}:null),$e&&(Os({tab:"running",runId:$,automationId:b||g(l?.automation?.automation_id||l?.automation?.automationId),openTaskInspector:!0}),r("automations"))},onError:l=>n("err",l instanceof Error?l.message:String(l))}),Ke=ke({mutationFn:async l=>(await a.automationsV2.delete(l),await bu(a,l),l),onSuccess:async l=>{if(C.automationId===l){const b=ur(Ba[0],x||"");H(b),xe(b.nodes[0]?.nodeId||""),v(b.agents[0]?.agentId||"")}await Promise.all([s.invalidateQueries({queryKey:["studio","automations"]}),s.invalidateQueries({queryKey:["automations"]})]),n("ok","Studio workflow deleted.")},onError:l=>n("err",l instanceof Error?l.message:String(l))});return e("div",{className:"grid gap-4",children:e(Yt,{title:"Studio",subtitle:"Template-first multi-agent workflow builder with reusable role prompts.",actions:e("div",{className:"flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:()=>$t(C.starterTemplateId||Ba[0].id),children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset From Template"]}),e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:be,children:[e("i",{"data-lucide":"user-plus"}),"Add Agent"]}),e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:Se,children:[e("i",{"data-lucide":"plus"}),"Add Stage"]}),e("button",{className:"tcp-btn-primary inline-flex items-center gap-2",disabled:ue.isPending,onClick:()=>ue.mutate(),children:[e("i",{"data-lucide":ue.isPending?"loader-circle":"save"}),ue.isPending?"Saving...":"Save Workflow"]})]}),children:e("div",{className:"grid gap-4 xl:grid-cols-[320px_minmax(0,1fr)_360px] xl:items-start",children:[e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:e(Yt,{title:"Studio Library",subtitle:"Templates and saved workflows in one place.",children:e("div",{className:"grid gap-4",children:[e("section",{className:"grid gap-2",children:[e("button",{type:"button",className:"flex w-full items-center gap-2 text-left","aria-expanded":re,onClick:()=>me(l=>!l),children:[e("i",{"data-lucide":re?"chevron-down":"chevron-right",className:"text-slate-400"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Starter Templates"}),e("div",{className:"text-xs text-slate-400",children:"Begin with a proven workflow shape."})]})]}),e(Mt,{initial:!1,children:re?e(Re.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.16,ease:"easeOut"},className:"grid gap-2 overflow-hidden pl-5",children:Ba.map(l=>e("button",{className:`tcp-list-item text-left ${C.starterTemplateId===l.id?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>$t(l.id),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:l.name}),e("span",{className:"tcp-badge-info",children:l.icon})]}),e("div",{className:"mt-1 text-sm text-slate-300",children:l.summary})]},l.id))}):null})]}),e("section",{className:"grid gap-2 border-t border-slate-800/80 pt-3",children:[e("button",{type:"button",className:"flex w-full items-center gap-2 text-left","aria-expanded":q,onClick:()=>ge(l=>!l),children:[e("i",{"data-lucide":q?"chevron-down":"chevron-right",className:"text-slate-400"}),e("div",{className:"min-w-0",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Saved Studio Workflows"}),e("div",{className:"text-xs text-slate-400",children:"Reopen workflows created from Studio metadata."})]})]}),e(Mt,{initial:!1,children:q?e(Re.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.16,ease:"easeOut"},className:"grid gap-2 overflow-hidden pl-5",children:P.length?[...P].sort((l,b)=>{const T=Number(l?.updated_at_ms||l?.updatedAtMs||l?.created_at_ms||l?.createdAtMs||0);return Number(b?.updated_at_ms||b?.updatedAtMs||b?.created_at_ms||b?.createdAtMs||0)-T}).slice(0,12).map(l=>{const b=g(l?.automation_id||l?.automationId||l?.id),T=ne.get(b)||null,R=Od(T),$=g(R.status),Ye=g(R.failureKind),Xe=g(R.phase),Ot=$s(T?.updated_at_ms||T?.updatedAtMs||T?.created_at_ms||T?.createdAtMs),Ft=l?.metadata?.studio||{},Ie=Us(l,O),Pt=g(Ft?.template_id||Ft?.templateId||Ft?.starter_template_id||Ft?.starterTemplateId),bt=$s(l?.updated_at_ms||l?.updatedAtMs||l?.created_at_ms||l?.createdAtMs),te=Ke.isPending&&Ke.variables===b;return e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:g(l?.name)||b}),e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[Ie.isBroken?e("span",{className:"tcp-badge-warn",children:"broken links"}):null,e("span",{className:"tcp-badge-info",children:g(l?.status)||"draft"})]})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:g(Ft?.summary)||"Studio workflow"}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-slate-500",children:[Pt?e("span",{className:"tcp-badge-info",children:["template: ",Pt]}):null,e("span",{className:"tcp-badge-muted",children:["id: ",su(b)]}),bt?e("span",{className:"tcp-badge-muted",children:["updated: ",bt]}):null]}),T?e("div",{className:"mt-2 rounded-lg border border-slate-700/50 bg-slate-950/20 p-2",children:[e("div",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:"Latest Run Stability"}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px]",children:[e("span",{className:"tcp-badge-info",children:["status: ",$]}),Xe?e("span",{className:"tcp-badge-muted",children:["phase: ",Xe]}):null,Ye?e("span",{className:"tcp-badge-warn",children:["failure: ",Ye]}):null,Ot?e("span",{className:"tcp-badge-muted",children:["run: ",Ot]}):null]}),g(R.reason)?e("div",{className:"mt-2 text-xs text-slate-300",children:g(R.reason)}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>{S(l)},children:[e("i",{"data-lucide":"folder-open"}),"Open"]}),e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:async()=>{try{await G(l)}catch(Ne){n("err",Ne instanceof Error?Ne.message:String(Ne))}},children:[e("i",{"data-lucide":"play"}),Ie.isBroken?"Repair & Open":"Run Now"]}),e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs text-rose-200",disabled:te,onClick:()=>{Ze({automationId:b,title:g(l?.name)||b})},children:[e("i",{"data-lucide":"trash-2"}),te?"Deleting...":"Delete"]})]})]},b)}):e(je,{text:"No Studio-created workflows yet."})}):null})]})]})})}),e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:[ae?.requiresSave&&(ae?.repairedAgentIds.length||ae?.missingNodeAgentIds.length)?e(Yt,{title:"Repair Applied",subtitle:"Studio repaired runtime dependencies so this workflow can be saved and run locally.",actions:e("button",{className:"tcp-btn-primary inline-flex items-center gap-2",onClick:()=>ue.mutate(),disabled:ue.isPending,children:[e("i",{"data-lucide":ue.isPending?"loader-circle":"save"}),ue.isPending?"Saving...":"Save Repaired Workflow"]}),children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[ae.repairedAgentIds.length?e("div",{children:["Repaired missing template links for: ",ae.repairedAgentIds.join(", ")]}):null,ae.missingNodeAgentIds.length?e("div",{children:["Stages still reference missing agents:"," ",ae.missingNodeAgentIds.join(", ")]}):null,e("div",{className:"text-xs text-slate-400",children:"Save this workflow to persist the repaired local-first configuration."})]})}):null,e(Yt,{title:"Workflow Settings",subtitle:"Name, schedule, workspace, and save behavior.",children:e("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.3fr)_minmax(18rem,0.95fr)]",children:[e("div",{className:"grid content-start gap-3",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Name"}),e("input",{className:"tcp-input text-sm",value:C.name,onInput:l=>We({name:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Description"}),e("textarea",{className:"tcp-input min-h-[88px] text-sm",value:C.description,onInput:l=>We({description:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Workspace Root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:()=>{const l=g(C.workspaceRoot||x||"/");Oe(l||"/"),He(""),Te(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:`tcp-input text-sm ${lt?"border-red-500/60 text-red-100":""}`,value:C.workspaceRoot,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:()=>We({workspaceRoot:""}),disabled:!C.workspaceRoot,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),lt?e("span",{className:"text-xs text-red-300",children:lt}):null]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Targets"}),e("input",{className:"tcp-input text-sm",value:Pn(C.outputTargets),onInput:l=>We({outputTargets:An(l.target.value)}),placeholder:"content-brief.md, approved-post.md"})]})]}),e("div",{className:"grid content-start gap-3",children:[e("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Status"}),e("select",{className:"tcp-input text-sm",value:C.status,onInput:l=>We({status:l.target.value}),children:[e("option",{value:"draft",children:"draft"}),e("option",{value:"active",children:"active"}),e("option",{value:"paused",children:"paused"})]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Max Parallel Agents"}),e("input",{className:"tcp-input text-sm",value:C.maxParallelAgents,onInput:l=>We({maxParallelAgents:l.target.value})})]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Schedule"}),e("select",{className:"tcp-input text-sm",value:C.scheduleType,onInput:l=>We({scheduleType:l.target.value}),children:[e("option",{value:"manual",children:"manual"}),e("option",{value:"cron",children:"cron"}),e("option",{value:"interval",children:"interval"})]})]}),C.scheduleType==="cron"?e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Cron Expression"}),e("input",{className:"tcp-input text-sm",value:C.cronExpression,onInput:l=>We({cronExpression:l.target.value}),placeholder:"0 9 * * 1"})]}):null,C.scheduleType==="interval"?e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Interval Seconds"}),e("input",{className:"tcp-input text-sm",value:C.intervalSeconds,onInput:l=>We({intervalSeconds:l.target.value})})]}):null,e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:ee,onInput:l=>qe(l.target.checked)}),"Save agent prompts as reusable templates"]}),e("div",{className:"text-xs text-slate-400",children:"Off: this workflow runs from Studio-local prompts only. On: Studio also creates shared Agent Team templates and links the workflow to them at runtime."}),e("div",{className:"text-xs text-slate-500",children:["Default model fallback:"," ",z.provider&&z.model?`${z.provider}/${z.model}`:"No provider default configured in Settings."]}),e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:C.useSharedModel,onInput:l=>{const b=l.target.checked,T=Li(C.agents);We({useSharedModel:b,sharedModelProvider:b?g(C.sharedModelProvider)||T.provider||z.provider:C.sharedModelProvider,sharedModelId:b?g(C.sharedModelId)||T.model||z.model:C.sharedModelId})}}),"Use one model for all agents in this workflow"]}),C.useSharedModel?e(la,{children:[e("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-1 2xl:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Shared Model Provider"}),e("select",{className:"tcp-input text-sm",value:C.sharedModelProvider,onInput:l=>{const b=l.target.value,T=cn(_,b);We({sharedModelProvider:b,sharedModelId:T.includes(C.sharedModelId)?C.sharedModelId:T[0]||C.sharedModelId})},children:[e("option",{value:"",children:"Select provider..."}),_.map(l=>e("option",{value:l.id,children:l.id},l.id))]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Shared Model"}),cn(_,C.sharedModelProvider).length?e("select",{className:"tcp-input text-sm",value:C.sharedModelId,onInput:l=>We({sharedModelId:l.target.value}),children:cn(_,C.sharedModelProvider).map(l=>e("option",{value:l,children:l},l))}):e("input",{className:"tcp-input text-sm",value:C.sharedModelId,onInput:l=>We({sharedModelId:l.target.value}),placeholder:"provider-specific model id"})]})]}),e("div",{className:"rounded-lg border border-amber-500/20 bg-amber-500/8 px-3 py-2 text-xs text-amber-100",children:"Shared model mode applies the same provider/model to every agent on save and while editing."})]}):null,e("label",{className:"flex items-center gap-2 text-sm text-slate-300",children:[e("input",{type:"checkbox",checked:$e,onInput:l=>Le(l.target.checked)}),"Run workflow immediately after save"]}),ae&&!ae.requiresSave&&ae.repairedAgentIds.length?e("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-500/8 px-3 py-2 text-xs text-emerald-100",children:"Repaired template links were saved successfully. This workflow is now using local Studio prompts and can run normally."}):null]})]})}),Pe?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:()=>{Te(!1),He("")}}),e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",Et||se||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:()=>{rt&&Oe(rt)},disabled:!rt,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:()=>{Et&&(We({workspaceRoot:Et}),Te(!1),He(""),n("ok",`Workspace selected: ${Et}`))},disabled:!Et,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>{Te(!1),He("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:Me,onInput:l=>He(l.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:Fe.length?Fe.map(l=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>Oe(String(l?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(l?.name||l?.path||"")})]})},String(l?.path||l?.name))):e(je,{text:g(Me)?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null,Y?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close delete workflow dialog",onClick:()=>Ze(null)}),e("div",{className:"tcp-confirm-dialog w-[min(34rem,96vw)]",children:[e("h3",{className:"tcp-confirm-title",children:"Delete Studio workflow"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:Y.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn inline-flex items-center gap-2",onClick:()=>Ze(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger inline-flex items-center gap-2",disabled:Ke.isPending,onClick:()=>Ke.mutate(Y.automationId,{onSettled:()=>Ze(null)}),children:[e("i",{"data-lucide":"trash-2"}),Ke.isPending?"Deleting...":"Delete workflow"]})]})]})]}):null,e(Yt,{title:"Workflow Map",subtitle:"Select a stage to edit its objective, dependencies, and bound agent.",children:At.length?e("div",{className:"grid gap-3 xl:grid-cols-4 xl:items-start",children:At.map(([l,b])=>e("div",{className:"grid content-start gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:["Column ",l+1]}),b.map(T=>{const R=C.agents.find(Ye=>Ye.agentId===T.agentId),$=T.nodeId===M;return e("button",{className:`tcp-list-item flex flex-col text-left ${$?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{xe(T.nodeId),v(T.agentId)},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:T.title}),e("span",{className:"tcp-badge-info",children:T.outputKind||"artifact"})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:R?.displayName||T.agentId||"Unassigned agent"}),e("div",{className:"mt-2 text-sm text-slate-300",children:T.objective}),T.outputPath?e("div",{className:"mt-2 text-xs text-emerald-200",children:["output: ",T.outputPath]}):null,e("div",{className:"mt-auto flex flex-wrap gap-1 pt-3",children:T.dependsOn.length?T.dependsOn.map(Ye=>e("span",{className:"tcp-badge-warn",children:["<-"," ",Ye]},`${T.nodeId}-${Ye}`)):e("span",{className:"tcp-badge-info",children:"start"})})]},T.nodeId)})]},l))}):e(je,{text:"No stages yet. Add one to start shaping the workflow."})}),e(Yt,{title:"Agent Directory",subtitle:"All agents currently participating in this workflow.",children:e("div",{className:"grid gap-2 md:grid-cols-2",children:C.agents.map(l=>{const b=W?.agentId===l.agentId;return e("button",{className:`tcp-list-item text-left ${b?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{v(l.agentId);const T=C.nodes.find(R=>R.agentId===l.agentId);T&&xe(T.nodeId)},children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:l.displayName||l.agentId}),e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e("span",{className:"tcp-badge-info",children:l.role}),ae?.repairedAgentIds.includes(l.agentId)?e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):g(l.linkedTemplateId||l.templateId)?O.has(g(l.linkedTemplateId||l.templateId))?e("span",{className:"tcp-badge-info",children:"linked"}):e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):e("span",{className:"tcp-badge-muted",children:"local"})]})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:l.agentId}),l.linkedTemplateId?e("div",{className:"mt-2 text-xs text-emerald-200",children:["linked template: ",l.linkedTemplateId]}):null]},l.agentId)})})})]}),e("div",{className:"grid auto-rows-max content-start self-start gap-4",children:[e(Yt,{title:oe?`Stage: ${oe.title}`:"Stage",subtitle:"Edit stage behavior, dependencies, and handoff aliases.",actions:e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:Ve,disabled:!oe,children:[e("i",{"data-lucide":"trash-2"}),"Remove Stage"]}),children:oe?e("div",{className:"grid gap-3",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Title"}),e("input",{className:"tcp-input text-sm",value:oe.title,onInput:l=>{ze(oe.nodeId,{title:l.target.value})}})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Bound Agent"}),e("select",{className:"tcp-input text-sm",value:oe.agentId,onInput:l=>{const b=l.target.value;ze(oe.nodeId,{agentId:b}),v(b)},children:C.agents.map(l=>e("option",{value:l.agentId,children:l.displayName||l.agentId},l.agentId))})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[110px] text-sm",value:oe.objective,onInput:l=>ze(oe.nodeId,{objective:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Kind"}),e("input",{className:"tcp-input text-sm",value:oe.outputKind,onInput:l=>ze(oe.nodeId,{outputKind:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Required Output File"}),e("input",{className:"tcp-input text-sm",placeholder:"marketing-brief.md",value:oe.outputPath,onInput:l=>ze(oe.nodeId,{outputPath:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Task Kind"}),e("input",{className:"tcp-input text-sm",placeholder:"code_change",value:oe.taskKind||"",onInput:l=>ze(oe.nodeId,{taskKind:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Project Backlog Tasks"}),e("input",{type:"checkbox",checked:!!oe.projectBacklogTasks,onChange:l=>ze(oe.nodeId,{projectBacklogTasks:l.target.checked})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Backlog Task ID"}),e("input",{className:"tcp-input text-sm",placeholder:"BACKLOG-123",value:oe.backlogTaskId||"",onInput:l=>ze(oe.nodeId,{backlogTaskId:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Repo Root"}),e("input",{className:"tcp-input text-sm",placeholder:".",value:oe.repoRoot||"",onInput:l=>ze(oe.nodeId,{repoRoot:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Write Scope"}),e("input",{className:"tcp-input text-sm",placeholder:"src/api, tests/api, Cargo.toml",value:oe.writeScope||"",onInput:l=>ze(oe.nodeId,{writeScope:l.target.value})})]}),e("label",{className:"grid gap-1 sm:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Acceptance Criteria"}),e("input",{className:"tcp-input text-sm",placeholder:"Describe what must be true for this coding task to count as done.",value:oe.acceptanceCriteria||"",onInput:l=>ze(oe.nodeId,{acceptanceCriteria:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Backlog Dependencies"}),e("input",{className:"tcp-input text-sm",placeholder:"BACKLOG-101, BACKLOG-102",value:oe.taskDependencies||"",onInput:l=>ze(oe.nodeId,{taskDependencies:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Verification State"}),e("input",{className:"tcp-input text-sm",placeholder:"pending",value:oe.verificationState||"",onInput:l=>ze(oe.nodeId,{verificationState:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Task Owner / Claimer"}),e("input",{className:"tcp-input text-sm",placeholder:"implementer",value:oe.taskOwner||"",onInput:l=>ze(oe.nodeId,{taskOwner:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Verification Command"}),e("input",{className:"tcp-input text-sm",placeholder:"cargo test -p tandem-server",value:oe.verificationCommand||"",onInput:l=>ze(oe.nodeId,{verificationCommand:l.target.value})})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs text-slate-400",children:"Dependencies"}),e("div",{className:"flex flex-wrap gap-2",children:C.nodes.filter(l=>l.nodeId!==oe.nodeId).map(l=>{const b=oe.dependsOn.includes(l.nodeId);return e("button",{className:b?"tcp-btn-primary inline-flex h-7 items-center gap-2 px-2 text-xs":"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>{const T=b?oe.dependsOn.filter(R=>R!==l.nodeId):[...oe.dependsOn,l.nodeId];ze(oe.nodeId,{dependsOn:T})},children:[e("i",{"data-lucide":b?"check":"plus"}),l.title]},`${oe.nodeId}-${l.nodeId}`)})})]}),oe.inputRefs.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs text-slate-400",children:"Input Aliases"}),oe.inputRefs.map(l=>e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500",children:l.fromStepId}),e("input",{className:"tcp-input text-sm",value:l.alias,onInput:b=>ze(oe.nodeId,{inputRefs:oe.inputRefs.map(T=>T.fromStepId===l.fromStepId?{...T,alias:b.target.value}:T)})})]},`${oe.nodeId}-${l.fromStepId}`))]}):null]}):e(je,{text:"Select a stage to edit it."})}),e(Yt,{title:W?`Agent: ${W.displayName||W.agentId}`:"Agent",subtitle:"Role prompt, policies, reusable template link, and model settings.",actions:e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:ce,disabled:!W,children:[e("i",{"data-lucide":"trash-2"}),"Remove Agent"]}),children:W?e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Display Name"}),e("input",{className:"tcp-input text-sm",value:W.displayName,onInput:l=>tt(W.agentId,{displayName:l.target.value})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Role"}),e("select",{className:"tcp-input text-sm",value:W.role,onInput:l=>tt(W.agentId,{role:l.target.value}),children:au.map(l=>e("option",{value:l,children:l},l))})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Skills"}),e("input",{className:"tcp-input text-sm",value:Pn(W.skills),onInput:l=>tt(W.agentId,{skills:An(l.target.value)}),placeholder:"copywriting, websearch, qa"})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Template Link"}),W.linkedTemplateId?e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>tt(W.agentId,{linkedTemplateId:"",templateId:""}),children:[e("i",{"data-lucide":"unlink"}),"Detach"]}):null]}),e("div",{className:"grid gap-2 md:grid-cols-[minmax(0,1fr)_auto]",children:[e("select",{className:"tcp-input text-sm",value:j,onInput:l=>he(l.target.value),children:[e("option",{value:"",children:"Select an existing agent template..."}),A.map(l=>e("option",{value:l.templateId,children:l.displayName||l.templateId},l.templateId))]}),e("button",{className:"tcp-btn inline-flex h-10 items-center gap-2 px-3 text-sm",disabled:!j,onClick:dt,children:[e("i",{"data-lucide":"download"}),"Load Template"]})]}),e("div",{className:"mt-2 text-xs text-slate-400",children:ae?.repairedAgentIds.includes(W.agentId)?"This agent had a missing shared template link. Studio repaired it into a workflow-local prompt.":W.linkedTemplateId?O.has(W.linkedTemplateId)?`Linked template: ${W.linkedTemplateId}`:`Missing template link repaired locally: ${W.linkedTemplateId}`:"This agent is currently workflow-local unless you save reusable templates."}),e("div",{className:"mt-1 text-xs text-slate-500",children:"Local means Studio stores the prompt in workflow metadata. Linked means runtime depends on a shared Agent Team template."})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Model Provider"}),e("select",{className:"tcp-input text-sm",value:W.modelProvider,disabled:C.useSharedModel,onInput:l=>tt(W.agentId,(()=>{const b=l.target.value,T=cn(_,b);return{modelProvider:b,modelId:T.includes(W.modelId)?W.modelId:T[0]||W.modelId}})()),children:[e("option",{value:"",children:"Select provider..."}),_.map(l=>e("option",{value:l.id,children:l.id},l.id))]})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Model ID"}),cn(_,W.modelProvider).length?e("select",{className:"tcp-input text-sm",value:W.modelId,disabled:C.useSharedModel,onInput:l=>tt(W.agentId,{modelId:l.target.value}),children:cn(_,W.modelProvider).map(l=>e("option",{value:l,children:l},l))}):e("input",{className:"tcp-input text-sm",value:W.modelId,disabled:C.useSharedModel,onInput:l=>tt(W.agentId,{modelId:l.target.value}),placeholder:"provider-specific model id"})]}),C.useSharedModel?e("div",{className:"text-xs text-amber-200 md:col-span-2",children:"Per-agent model controls are locked because this workflow is using one shared model for all agents."}):null,e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Tool Allowlist"}),e("input",{className:"tcp-input text-sm",value:Pn(W.toolAllowlist),onInput:l=>tt(W.agentId,{toolAllowlist:An(l.target.value)})})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Tool Denylist"}),e("input",{className:"tcp-input text-sm",value:Pn(W.toolDenylist),onInput:l=>tt(W.agentId,{toolDenylist:An(l.target.value)})})]}),e("label",{className:"grid gap-1 md:col-span-2",children:[e("span",{className:"text-xs text-slate-400",children:"Allowed MCP Servers"}),e("input",{className:"tcp-input text-sm",value:Pn(W.mcpAllowedServers),onInput:l=>tt(W.agentId,{mcpAllowedServers:An(l.target.value)}),placeholder:I.join(", ")||"No MCP servers detected"})]})]}),e("div",{className:"grid gap-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Role Prompt"}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Role"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:W.prompt.role,onInput:l=>tt(W.agentId,{prompt:{...W.prompt,role:l.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Mission"}),e("textarea",{className:"tcp-input min-h-[92px] text-sm",value:W.prompt.mission,onInput:l=>tt(W.agentId,{prompt:{...W.prompt,mission:l.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Inputs"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:W.prompt.inputs,onInput:l=>tt(W.agentId,{prompt:{...W.prompt,inputs:l.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Output Contract"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:W.prompt.outputContract,onInput:l=>tt(W.agentId,{prompt:{...W.prompt,outputContract:l.target.value}})})]}),e("label",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-400",children:"Guardrails"}),e("textarea",{className:"tcp-input min-h-[72px] text-sm",value:W.prompt.guardrails,onInput:l=>tt(W.agentId,{prompt:{...W.prompt,guardrails:l.target.value}})})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 text-xs uppercase tracking-wide text-slate-500",children:"Composed System Prompt"}),e("pre",{className:"whitespace-pre-wrap break-words text-xs text-slate-200",children:vr(W.prompt)||"Prompt preview will appear here."})]})]}):e(je,{text:"Select or add an agent to edit it."})})]})]})})})}const yu=`defaults:
|
|
1861
1861
|
schedulePreset: Every morning
|
|
1862
1862
|
mode: team
|
|
1863
1863
|
maxAgents: "4"
|
|
@@ -1914,7 +1914,7 @@ executionModes:
|
|
|
1914
1914
|
icon: "🐝"
|
|
1915
1915
|
desc: A swarm of AIs work in parallel on sub-tasks
|
|
1916
1916
|
bestFor: Large-scale parallel work
|
|
1917
|
-
`;function Ai(a){const t=String(a||"").trim().toLowerCase();return t==="assigned"?"assigned":t==="validated"?"validated":t==="in_progress"||t==="running"?"in_progress":t==="done"||t==="completed"?"done":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"failed":t==="blocked"?"blocked":t==="runnable"||t==="ready"?"runnable":t==="created"?"created":"pending"}function tu(a){const t={};for(const n of Array.isArray(a)?a:[]){const r=String(n?.step_id||n?.payload?.task_id||"").trim();if(!r)continue;const s=n?.payload&&typeof n.payload=="object"?n.payload:{},c=t[r]||{assignedRole:"",errorMessage:"",runtimeDetail:"",runtimeStatus:"",sessionId:""};t[r]={assignedRole:String(s?.assigned_agent||s?.agent_id||c.assignedRole||""),errorMessage:String(s?.error||c.errorMessage||""),runtimeDetail:String(s?.why_next_step||c.runtimeDetail||""),runtimeStatus:String(s?.step_status||c.runtimeStatus||""),sessionId:String(s?.session_id||c.sessionId||"")}}return t}function au(a,t){const n=Ai(a?.status),r=a?.payload&&typeof a.payload=="object"?a.payload:{},s=Number(a?.lease_expires_at_ms||0)||0,c=Number(a?.next_retry_at_ms||0)||0,d=Date.now();return{id:String(a?.id||""),title:String(r?.title||a?.task_type||a?.id||"Untitled task"),description:String(r?.description||r?.objective||""),dependencies:Array.isArray(a?.depends_on_task_ids)?a.depends_on_task_ids.map(u=>String(u||"")).filter(Boolean):[],state:n,retry_count:Number(a?.attempt||a?.retry_count||0),error_message:n==="failed"||n==="blocked"?String(a?.last_error||t?.errorMessage||""):"",runtime_status:String(t?.runtimeStatus||""),runtime_detail:String(t?.runtimeDetail||""),assigned_role:String(a?.assigned_agent||a?.lease_owner||t?.assignedRole||""),workflow_id:String(a?.workflow_id||""),session_id:String(t?.sessionId||""),task_kind:String(r?.task_kind||""),backlog_task_id:String(r?.backlog_task_id||r?.task_id||""),repo_root:String(r?.repo_root||""),write_scope:String(r?.write_scope||""),acceptance_criteria:String(r?.acceptance_criteria||""),task_dependencies:Array.isArray(r?.task_dependencies)?r.task_dependencies.join(", "):String(r?.task_dependencies||""),verification_state:String(r?.verification_state||""),task_owner:String(r?.task_owner||r?.owner||""),verification_command:String(r?.verification_command||""),output_path:String(r?.output_path||""),parent_task_id:String(a?.parent_task_id||""),task_type:String(a?.task_type||""),projects_backlog_tasks:!!r?.projects_backlog_tasks,lease_owner:String(a?.lease_owner||""),lease_expires_at_ms:s||void 0,next_retry_at_ms:c||void 0,max_attempts:Number(a?.max_attempts||0)||void 0,is_stale:n==="in_progress"&&s>0&&s<=d}}function nu(a,t){const n=Ai(a?.stepStatus||a?.status);return{id:String(a?.taskId||a?.step_id||""),title:String(a?.title||a?.step_id||"Untitled step"),description:String(a?.description||""),dependencies:Array.isArray(a?.dependsOn)?a.dependsOn.map(r=>String(r||"")).filter(Boolean):[],state:n,retry_count:Number(a?.retry_count||0),error_message:n==="failed"||n==="blocked"?String(a?.error_message||t?.errorMessage||""):"",runtime_status:String(a?.runtime_status||t?.runtimeStatus||""),runtime_detail:String(a?.runtime_detail||t?.runtimeDetail||""),assigned_role:String(a?.assignedAgent||t?.assignedRole||""),workflow_id:String(a?.workflowId||""),session_id:String(a?.sessionId||a?.session_id||t?.sessionId||"")}}function Pi(a){const t=tu(a?.events),n=Array.isArray(a?.run?.tasks)?a.run.tasks:[],r=n.length?n:Array.isArray(a?.blackboard?.tasks)?a.blackboard.tasks:[],s=Array.isArray(a?.tasks)?a.tasks:[],c=r.map(x=>au(x,t[String(x?.id||"").trim()])).filter(x=>x.id),d=s.map(x=>nu(x,t[String(x?.taskId||x?.step_id||"").trim()])).filter(x=>x.id),u=new Map;for(const x of c)u.set(x.id,x);for(const x of d){if(!u.has(x.id)){u.set(x.id,x);continue}const C=u.get(x.id);C&&u.set(x.id,{...C,session_id:C.session_id||x.session_id,runtime_status:C.runtime_status||x.runtime_status,runtime_detail:C.runtime_detail||x.runtime_detail,assigned_role:C.assigned_role||x.assigned_role,error_message:C.error_message||x.error_message})}const p=[...u.values()],N=String(a?.run?.current_step_id||"").trim()||p.find(x=>x.state==="in_progress"||x.state==="assigned")?.id||"",E=c.length?d.length?"hybrid":(n.length,"blackboard"):d.length?"context_steps":"empty";return{currentTaskId:N,taskSource:E,tasks:p}}const ru={created:"Created",pending:"Pending",runnable:"Runnable",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"};function su(a){return a==="done"||a==="validated"?"tcp-badge-ok":a==="failed"?"tcp-badge-err":a==="blocked"?"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200":a==="in_progress"||a==="runnable"||a==="assigned"?"tcp-badge-warn":"tcp-badge-info"}function iu(a,t,n){return n?"border-cyan-400/70 bg-cyan-950/20":a==="blocked"?"border-emerald-500/35 bg-emerald-950/18":t?"border-emerald-400/70 bg-emerald-950/14":"border-slate-700/60 bg-slate-900/20"}function ou(a){return a==="in_progress"||a==="assigned"?e("i",{"data-lucide":"loader-circle",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null}function Ns({task:a,isCurrent:t,isSelected:n,workflowSummary:r,onTaskSelect:s,onRetryTask:c}){const[d,u]=w(!1),p=a.state==="failed"||a.state==="blocked"?String(a.error_message||"").trim():"";return e("div",{className:`cursor-pointer rounded-lg border p-2 ${iu(a.state,t,!!n)}`,onClick:()=>s?.(a),children:[e("div",{className:"mb-1 flex items-start justify-between gap-2",children:[e("div",{className:"line-clamp-6 text-xs font-medium leading-snug",title:a.title,children:a.title}),e("span",{className:`${su(a.state)} inline-flex shrink-0 items-center gap-1`,children:[ou(a.state),e("span",{children:ru[a.state]})]})]}),a.description?e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:a.description}):null,a.assigned_role||a.gate?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[a.assigned_role?e("span",{className:"rounded border border-cyan-600/50 bg-cyan-950/30 px-1.5 py-0.5",children:["role: ",a.assigned_role]}):null,a.gate?e("span",{className:"rounded border border-emerald-600/50 bg-emerald-950/30 px-1.5 py-0.5 text-emerald-200",children:["gate: ",a.gate]}):null]}):null,r&&r.runs>0?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[e("span",{className:"rounded border border-indigo-600/50 bg-indigo-950/30 px-1.5 py-0.5",children:["workflow runs: ",r.runs]}),r.failed>0?e("span",{className:"rounded border border-rose-600/50 bg-rose-950/30 px-1.5 py-0.5 text-rose-200",children:["workflow failed: ",r.failed]}):null]}):null,p?e("div",{className:`mt-1 text-xs ${a.state==="blocked"?"text-emerald-200/90":"text-rose-300"}`,children:[e("div",{className:d?"whitespace-pre-wrap break-words":"line-clamp-2",children:p}),p.length>130?e("button",{className:"tcp-btn mt-1 h-6 px-2 text-[11px]",onClick:()=>u(N=>!N),children:d?"Less":"More"}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-1",children:[a.dependencies.slice(0,2).map(N=>e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["<-"," ",N]},N)),a.dependencies.length>2?e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["+",a.dependencies.length-2," more"]}):null]}),e("div",{className:"mt-2 tcp-subtle text-[10px]",children:"Details"}),a.state==="failed"&&c?e("button",{className:"tcp-btn mt-2 h-7 px-2 text-xs",onClick:N=>{N.stopPropagation(),c(a)},children:"Retry Task"}):null]})}function Ti({tasks:a,currentTaskId:t,selectedTaskId:n,workflowSummaryByTaskId:r,onTaskSelect:s,onRetryTask:c}){const[d,u]=w("runnable"),p=qt(null),N=qt({}),E=K(()=>{const A={created:[],pending:[],runnable:[],assigned:[],in_progress:[],blocked:[],done:[],failed:[],validated:[]};for(const S of a)A[S.state].push(S);const G=new Set([...A.done,...A.validated].map(S=>S.id)),B=[...A.runnable],ae=[];for(const S of[...A.created,...A.pending])S.dependencies.length===0||S.dependencies.every(H=>G.has(H))?B.push(S):ae.push(S);return{runnable:B,waiting:ae,assigned:A.assigned,in_progress:A.in_progress,blocked:A.blocked,done:[...A.done,...A.validated],failed:A.failed}},[a]),x=[{key:"runnable",label:"Ready",tasks:E.runnable},{key:"waiting",label:"Waiting on deps",tasks:E.waiting},{key:"assigned",label:"Assigned",tasks:E.assigned},{key:"in_progress",label:"In Progress",tasks:E.in_progress},{key:"blocked",label:"Blocked",tasks:E.blocked},{key:"done",label:"Done",tasks:E.done},{key:"failed",label:"Failed",tasks:E.failed}],C=K(()=>{const A=x.find(G=>G.tasks.some(B=>B.id===t));return A?A.key:x.find(G=>G.tasks.length>0)?.key||"runnable"},[x,t]),O=C;fe(()=>{u(A=>x.some(G=>G.key===A)?A:C)},[x,C]);const k=A=>{const G=N.current[A];G&&G.scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"})},z=()=>{O&&k(O)};return a.length?e(aa,{children:[e("div",{className:"grid gap-3 xl:hidden",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:t?e("button",{type:"button",className:"rounded-full border border-emerald-400/60 bg-emerald-400/10 px-3 py-1.5 text-[11px] font-medium text-emerald-200",onClick:()=>u(O),children:"Jump to active task"}):null}),e("div",{className:"flex gap-2 overflow-x-auto pb-1",children:x.map(A=>{const G=A.key===d;return e("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[11px] font-medium ${G?"border-emerald-400/60 bg-emerald-400/10 text-emerald-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>u(A.key),children:[A.label," (",A.tasks.length,")"]},A.key)})}),x.filter(A=>A.key===d).map(A=>e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-2",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:A.label}),e("div",{className:"tcp-subtle text-xs",children:A.tasks.length})]}),e("div",{className:"grid gap-2",children:[A.tasks.map(G=>e(Ns,{task:G,isCurrent:G.id===t,isSelected:G.id===n,workflowSummary:r?.[G.id],onTaskSelect:s,onRetryTask:c},G.id)),A.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},A.key))]}),e("div",{className:"hidden gap-3 xl:grid",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[t?e("button",{type:"button",className:"rounded-full border border-emerald-400/60 bg-emerald-400/10 px-3 py-1.5 text-[11px] font-medium text-emerald-200",onClick:z,children:"Jump to active task"}):null,e("div",{className:"flex flex-wrap gap-2",children:x.map(A=>{const G=A.key===O;return e("button",{type:"button",className:`rounded-full border px-3 py-1.5 text-[11px] font-medium ${G?"border-emerald-400/60 bg-emerald-400/10 text-emerald-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>k(A.key),children:[A.label," (",A.tasks.length,")"]},`desktop-tab-${A.key}`)})})]}),e("div",{ref:p,className:"overflow-x-auto pb-2",children:e("div",{className:"flex min-w-max gap-3",children:x.map(A=>e("div",{ref:G=>{N.current[A.key]=G},className:`min-h-[16rem] w-[320px] shrink-0 rounded-xl border p-2 ${A.key===O?"border-emerald-400/60 bg-emerald-400/5":"border-slate-700/60 bg-slate-900/20"}`,children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:A.label}),e("div",{className:"tcp-subtle text-xs",children:A.tasks.length})]}),e("div",{className:"grid gap-2",children:[A.tasks.map(G=>e(Ns,{task:G,isCurrent:G.id===t,isSelected:G.id===n,workflowSummary:r?.[G.id],onTaskSelect:s,onRetryTask:c},G.id)),A.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},A.key))})})]})]}):e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-4",children:"No tasks yet."})}function en(a,t,n={}){fe(()=>{if(!(!n.enabled||!a))return Br(a,t,{withCredentials:n.withCredentials})},[t,n.enabled,n.withCredentials,a])}const lu=`id: agentic-design
|
|
1917
|
+
`;function zi(a){const t=String(a||"").trim().toLowerCase();return t==="assigned"?"assigned":t==="validated"?"validated":t==="in_progress"||t==="running"?"in_progress":t==="done"||t==="completed"?"done":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"failed":t==="blocked"?"blocked":t==="runnable"||t==="ready"?"runnable":t==="created"?"created":"pending"}function wu(a){const t={};for(const n of Array.isArray(a)?a:[]){const r=String(n?.step_id||n?.payload?.task_id||"").trim();if(!r)continue;const s=n?.payload&&typeof n.payload=="object"?n.payload:{},c=t[r]||{assignedRole:"",errorMessage:"",runtimeDetail:"",runtimeStatus:"",sessionId:""};t[r]={assignedRole:String(s?.assigned_agent||s?.agent_id||c.assignedRole||""),errorMessage:String(s?.error||c.errorMessage||""),runtimeDetail:String(s?.why_next_step||c.runtimeDetail||""),runtimeStatus:String(s?.step_status||c.runtimeStatus||""),sessionId:String(s?.session_id||c.sessionId||"")}}return t}function xu(a,t){const n=zi(a?.status),r=a?.payload&&typeof a.payload=="object"?a.payload:{},s=Number(a?.lease_expires_at_ms||0)||0,c=Number(a?.next_retry_at_ms||0)||0,d=Date.now();return{id:String(a?.id||""),title:String(r?.title||a?.task_type||a?.id||"Untitled task"),description:String(r?.description||r?.objective||""),dependencies:Array.isArray(a?.depends_on_task_ids)?a.depends_on_task_ids.map(u=>String(u||"")).filter(Boolean):[],state:n,retry_count:Number(a?.attempt||a?.retry_count||0),error_message:n==="failed"||n==="blocked"?String(a?.last_error||t?.errorMessage||""):"",runtime_status:String(t?.runtimeStatus||""),runtime_detail:String(t?.runtimeDetail||""),assigned_role:String(a?.assigned_agent||a?.lease_owner||t?.assignedRole||""),workflow_id:String(a?.workflow_id||""),session_id:String(t?.sessionId||""),task_kind:String(r?.task_kind||""),backlog_task_id:String(r?.backlog_task_id||r?.task_id||""),repo_root:String(r?.repo_root||""),write_scope:String(r?.write_scope||""),acceptance_criteria:String(r?.acceptance_criteria||""),task_dependencies:Array.isArray(r?.task_dependencies)?r.task_dependencies.join(", "):String(r?.task_dependencies||""),verification_state:String(r?.verification_state||""),task_owner:String(r?.task_owner||r?.owner||""),verification_command:String(r?.verification_command||""),output_path:String(r?.output_path||""),parent_task_id:String(a?.parent_task_id||""),task_type:String(a?.task_type||""),projects_backlog_tasks:!!r?.projects_backlog_tasks,lease_owner:String(a?.lease_owner||""),lease_expires_at_ms:s||void 0,next_retry_at_ms:c||void 0,max_attempts:Number(a?.max_attempts||0)||void 0,is_stale:n==="in_progress"&&s>0&&s<=d}}function ku(a,t){const n=zi(a?.stepStatus||a?.status);return{id:String(a?.taskId||a?.step_id||""),title:String(a?.title||a?.step_id||"Untitled step"),description:String(a?.description||""),dependencies:Array.isArray(a?.dependsOn)?a.dependsOn.map(r=>String(r||"")).filter(Boolean):[],state:n,retry_count:Number(a?.retry_count||0),error_message:n==="failed"||n==="blocked"?String(a?.error_message||t?.errorMessage||""):"",runtime_status:String(a?.runtime_status||t?.runtimeStatus||""),runtime_detail:String(a?.runtime_detail||t?.runtimeDetail||""),assigned_role:String(a?.assignedAgent||t?.assignedRole||""),workflow_id:String(a?.workflowId||""),session_id:String(a?.sessionId||a?.session_id||t?.sessionId||"")}}function Ji(a){const t=wu(a?.events),n=Array.isArray(a?.run?.tasks)?a.run.tasks:[],r=n.length?n:Array.isArray(a?.blackboard?.tasks)?a.blackboard.tasks:[],s=Array.isArray(a?.tasks)?a.tasks:[],c=r.map(x=>xu(x,t[String(x?.id||"").trim()])).filter(x=>x.id),d=s.map(x=>ku(x,t[String(x?.taskId||x?.step_id||"").trim()])).filter(x=>x.id),u=new Map;for(const x of c)u.set(x.id,x);for(const x of d){if(!u.has(x.id)){u.set(x.id,x);continue}const A=u.get(x.id);A&&u.set(x.id,{...A,session_id:A.session_id||x.session_id,runtime_status:A.runtime_status||x.runtime_status,runtime_detail:A.runtime_detail||x.runtime_detail,assigned_role:A.assigned_role||x.assigned_role,error_message:A.error_message||x.error_message})}const p=[...u.values()],N=String(a?.run?.current_step_id||"").trim()||p.find(x=>x.state==="in_progress"||x.state==="assigned")?.id||"",E=c.length?d.length?"hybrid":(n.length,"blackboard"):d.length?"context_steps":"empty";return{currentTaskId:N,taskSource:E,tasks:p}}const Nu={created:"Created",pending:"Pending",runnable:"Runnable",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"};function _u(a){return a==="done"||a==="validated"?"tcp-badge-ok":a==="failed"?"tcp-badge-err":a==="blocked"?"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200":a==="in_progress"||a==="runnable"||a==="assigned"?"tcp-badge-warn":"tcp-badge-info"}function Su(a,t,n){return n?"border-cyan-400/70 bg-cyan-950/20":a==="blocked"?"border-emerald-500/35 bg-emerald-950/18":t?"border-emerald-400/70 bg-emerald-950/14":"border-slate-700/60 bg-slate-900/20"}function Iu(a){return a==="in_progress"||a==="assigned"?e("i",{"data-lucide":"loader-circle",className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null}function Bs({task:a,isCurrent:t,isSelected:n,workflowSummary:r,onTaskSelect:s,onRetryTask:c}){const[d,u]=w(!1),p=a.state==="failed"||a.state==="blocked"?String(a.error_message||"").trim():"";return e("div",{className:`cursor-pointer rounded-lg border p-2 ${Su(a.state,t,!!n)}`,onClick:()=>s?.(a),children:[e("div",{className:"mb-1 flex items-start justify-between gap-2",children:[e("div",{className:"line-clamp-6 text-xs font-medium leading-snug",title:a.title,children:a.title}),e("span",{className:`${_u(a.state)} inline-flex shrink-0 items-center gap-1`,children:[Iu(a.state),e("span",{children:Nu[a.state]})]})]}),a.description?e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:a.description}):null,a.assigned_role||a.gate?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[a.assigned_role?e("span",{className:"rounded border border-cyan-600/50 bg-cyan-950/30 px-1.5 py-0.5",children:["role: ",a.assigned_role]}):null,a.gate?e("span",{className:"rounded border border-emerald-600/50 bg-emerald-950/30 px-1.5 py-0.5 text-emerald-200",children:["gate: ",a.gate]}):null]}):null,r&&r.runs>0?e("div",{className:"mt-1 flex flex-wrap gap-1 text-[10px] text-slate-300",children:[e("span",{className:"rounded border border-indigo-600/50 bg-indigo-950/30 px-1.5 py-0.5",children:["workflow runs: ",r.runs]}),r.failed>0?e("span",{className:"rounded border border-rose-600/50 bg-rose-950/30 px-1.5 py-0.5 text-rose-200",children:["workflow failed: ",r.failed]}):null]}):null,p?e("div",{className:`mt-1 text-xs ${a.state==="blocked"?"text-emerald-200/90":"text-rose-300"}`,children:[e("div",{className:d?"whitespace-pre-wrap break-words":"line-clamp-2",children:p}),p.length>130?e("button",{className:"tcp-btn mt-1 h-6 px-2 text-[11px]",onClick:()=>u(N=>!N),children:d?"Less":"More"}):null]}):null,e("div",{className:"mt-2 flex flex-wrap gap-1",children:[a.dependencies.slice(0,2).map(N=>e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["<-"," ",N]},N)),a.dependencies.length>2?e("span",{className:"rounded border border-slate-700/60 px-1.5 py-0.5 text-[10px] text-slate-300",children:["+",a.dependencies.length-2," more"]}):null]}),e("div",{className:"mt-2 tcp-subtle text-[10px]",children:"Details"}),a.state==="failed"&&c?e("button",{className:"tcp-btn mt-2 h-7 px-2 text-xs",onClick:N=>{N.stopPropagation(),c(a)},children:"Retry Task"}):null]})}function Qi({tasks:a,currentTaskId:t,selectedTaskId:n,workflowSummaryByTaskId:r,onTaskSelect:s,onRetryTask:c}){const[d,u]=w("runnable"),p=Rt(null),N=Rt({}),E=F(()=>{const P={created:[],pending:[],runnable:[],assigned:[],in_progress:[],blocked:[],done:[],failed:[],validated:[]};for(const I of a)P[I.state].push(I);const Q=new Set([...P.done,...P.validated].map(I=>I.id)),B=[...P.runnable],ne=[];for(const I of[...P.created,...P.pending])I.dependencies.length===0||I.dependencies.every(H=>Q.has(H))?B.push(I):ne.push(I);return{runnable:B,waiting:ne,assigned:P.assigned,in_progress:P.in_progress,blocked:P.blocked,done:[...P.done,...P.validated],failed:P.failed}},[a]),x=[{key:"runnable",label:"Ready",tasks:E.runnable},{key:"waiting",label:"Waiting on deps",tasks:E.waiting},{key:"assigned",label:"Assigned",tasks:E.assigned},{key:"in_progress",label:"In Progress",tasks:E.in_progress},{key:"blocked",label:"Blocked",tasks:E.blocked},{key:"done",label:"Done",tasks:E.done},{key:"failed",label:"Failed",tasks:E.failed}],A=F(()=>{const P=x.find(Q=>Q.tasks.some(B=>B.id===t));return P?P.key:x.find(Q=>Q.tasks.length>0)?.key||"runnable"},[x,t]),O=A;fe(()=>{u(P=>x.some(Q=>Q.key===P)?P:A)},[x,A]);const _=P=>{const Q=N.current[P];Q&&Q.scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"})},z=()=>{O&&_(O)};return a.length?e(la,{children:[e("div",{className:"grid gap-3 xl:hidden",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:t?e("button",{type:"button",className:"rounded-full border border-emerald-400/60 bg-emerald-400/10 px-3 py-1.5 text-[11px] font-medium text-emerald-200",onClick:()=>u(O),children:"Jump to active task"}):null}),e("div",{className:"flex gap-2 overflow-x-auto pb-1",children:x.map(P=>{const Q=P.key===d;return e("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[11px] font-medium ${Q?"border-emerald-400/60 bg-emerald-400/10 text-emerald-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>u(P.key),children:[P.label," (",P.tasks.length,")"]},P.key)})}),x.filter(P=>P.key===d).map(P=>e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-2",children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:P.label}),e("div",{className:"tcp-subtle text-xs",children:P.tasks.length})]}),e("div",{className:"grid gap-2",children:[P.tasks.map(Q=>e(Bs,{task:Q,isCurrent:Q.id===t,isSelected:Q.id===n,workflowSummary:r?.[Q.id],onTaskSelect:s,onRetryTask:c},Q.id)),P.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},P.key))]}),e("div",{className:"hidden gap-3 xl:grid",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[t?e("button",{type:"button",className:"rounded-full border border-emerald-400/60 bg-emerald-400/10 px-3 py-1.5 text-[11px] font-medium text-emerald-200",onClick:z,children:"Jump to active task"}):null,e("div",{className:"flex flex-wrap gap-2",children:x.map(P=>{const Q=P.key===O;return e("button",{type:"button",className:`rounded-full border px-3 py-1.5 text-[11px] font-medium ${Q?"border-emerald-400/60 bg-emerald-400/10 text-emerald-200":"border-slate-700/60 bg-slate-900/20 text-slate-300"}`,onClick:()=>_(P.key),children:[P.label," (",P.tasks.length,")"]},`desktop-tab-${P.key}`)})})]}),e("div",{ref:p,className:"overflow-x-auto pb-2",children:e("div",{className:"flex min-w-max gap-3",children:x.map(P=>e("div",{ref:Q=>{N.current[P.key]=Q},className:`min-h-[16rem] w-[320px] shrink-0 rounded-xl border p-2 ${P.key===O?"border-emerald-400/60 bg-emerald-400/5":"border-slate-700/60 bg-slate-900/20"}`,children:[e("div",{className:"mb-2 flex items-center justify-between",children:[e("div",{className:"text-xs font-semibold",children:P.label}),e("div",{className:"tcp-subtle text-xs",children:P.tasks.length})]}),e("div",{className:"grid gap-2",children:[P.tasks.map(Q=>e(Bs,{task:Q,isCurrent:Q.id===t,isSelected:Q.id===n,workflowSummary:r?.[Q.id],onTaskSelect:s,onRetryTask:c},Q.id)),P.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},P.key))})})]})]}):e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-4",children:"No tasks yet."})}function en(a,t,n={}){fe(()=>{if(!(!n.enabled||!a))return es(a,t,{withCredentials:n.withCredentials})},[t,n.enabled,n.withCredentials,a])}const Cu=`id: agentic-design
|
|
1918
1918
|
label: Agentic Design
|
|
1919
1919
|
description: Design a multi-agent workflow with explicit orchestration, gates, and operator controls.
|
|
1920
1920
|
blueprint:
|
|
@@ -2026,7 +2026,7 @@ blueprint:
|
|
|
2026
2026
|
- governance-design
|
|
2027
2027
|
instructions: Use rework if the design lacks control boundaries, clear outputs, or repairability.
|
|
2028
2028
|
metadata: null
|
|
2029
|
-
`,
|
|
2029
|
+
`,Au=`id: ai-opportunity
|
|
2030
2030
|
label: AI Opportunities
|
|
2031
2031
|
description: Map workflow pain points to realistic AI, copilot, and agentic opportunities.
|
|
2032
2032
|
blueprint:
|
|
@@ -2129,7 +2129,7 @@ blueprint:
|
|
|
2129
2129
|
tool_allowlist_override: []
|
|
2130
2130
|
mcp_servers_override: []
|
|
2131
2131
|
metadata: null
|
|
2132
|
-
`,
|
|
2132
|
+
`,Pu=`id: automation-rollout
|
|
2133
2133
|
label: Rollout
|
|
2134
2134
|
description: Plan rollout, enablement, controls, and measurement for an automation initiative.
|
|
2135
2135
|
blueprint:
|
|
@@ -2233,7 +2233,7 @@ blueprint:
|
|
|
2233
2233
|
- launch-plan
|
|
2234
2234
|
instructions: Use rework if the rollout plan lacks readiness criteria, operator enablement, or fallback handling.
|
|
2235
2235
|
metadata: null
|
|
2236
|
-
`,
|
|
2236
|
+
`,Tu=`id: workflow-audit
|
|
2237
2237
|
label: Workflow Audit
|
|
2238
2238
|
description: Audit an existing workflow and design a safer, observable automation model.
|
|
2239
2239
|
blueprint:
|
|
@@ -2345,7 +2345,7 @@ blueprint:
|
|
|
2345
2345
|
- automation-design
|
|
2346
2346
|
instructions: Approve only when the automation design is safe, observable, and realistically deployable.
|
|
2347
2347
|
metadata: null
|
|
2348
|
-
`,mu={"ai-opportunity":"sparkles","workflow-audit":"workflow","agentic-design":"bot","automation-rollout":"arrow-up-circle"},pu=Object.assign({"../presets/mission-builder/agentic-design.yaml":lu,"../presets/mission-builder/ai-opportunity.yaml":cu,"../presets/mission-builder/automation-rollout.yaml":du,"../presets/mission-builder/workflow-audit.yaml":uu});function hu(a){return Array.isArray(a?.servers)?a.servers.map(t=>{const n=String(t?.name||"").trim();return n?{name:n,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(Boolean):a&&typeof a=="object"?Object.entries(a).map(([t,n])=>{const r=String(t||"").trim();return r?{name:r,connected:!!n?.connected,enabled:n?.enabled!==!1}:null}).filter(Boolean):[]}function Ma(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function vr(a){const t=String(a.provider||"").trim(),n=String(a.model||"").trim();return!t||!n?null:{default_model:{provider_id:t,model_id:n}}}function yr(a){const t=a?.default_model||a?.defaultModel||{};return{provider:String(t?.provider_id||t?.providerId||"").trim(),model:String(t?.model_id||t?.modelId||"").trim()}}function _s(a,t,n){const r={type:"run_once"};return a==="cron"?{type:"cron",cron_expression:String(n||"").trim(),timezone:"UTC",misfire_policy:r}:a==="interval"?{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(t||"3600"),10)||3600),timezone:"UTC",misfire_policy:r}:{type:"manual",timezone:"UTC",misfire_policy:r}}function Za(a){return{mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,title:"",goal:"",success_criteria:[],shared_context:"",workspace_root:a,orchestrator_template_id:"",phases:[{phase_id:"phase_1",title:"Phase 1",description:"",execution_mode:"soft"}],milestones:[],team:{allowed_template_ids:[],default_model_policy:null,allowed_mcp_servers:[],max_parallel_agents:4,mission_budget:{},orchestrator_only_tool_calls:!1},workstreams:[{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:"Workstream 1",objective:"",role:"worker",prompt:"",priority:1,phase_id:"phase_1",lane:"lane_1",milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}],review_stages:[],metadata:null}}function gu(a,t){const n=lr.parse(a);if(!n||typeof n!="object")throw new Error(`Invalid mission preset at ${t}: expected a YAML object.`);const r=n,s=String(r.id||"").trim(),c=String(r.label||"").trim(),d=String(r.description||"").trim(),u=r.blueprint;if(!s)throw new Error(`Invalid mission preset at ${t}: missing id.`);if(!c)throw new Error(`Invalid mission preset at ${t}: missing label.`);if(!d)throw new Error(`Invalid mission preset at ${t}: missing description.`);if(!u||typeof u!="object")throw new Error(`Invalid mission preset at ${t}: missing blueprint.`);return{id:s,label:c,description:d,blueprint:u}}const Ss=Object.entries(pu).map(([a,t])=>gu(t,a)).sort((a,t)=>a.label.localeCompare(t.label,void 0,{sensitivity:"base"}));function Ri(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function fu(a){const t=[];String(a.title||"").trim()||t.push("Mission title is required."),String(a.goal||"").trim()||t.push("Mission goal is required.");const n=Ri(a.workspace_root);return n&&t.push(n),(!Array.isArray(a.workstreams)||a.workstreams.length===0)&&t.push("At least one workstream is required."),t}function bu(a,t){const n=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},r=n.mission_blueprint||n.missionBlueprint||n.mission_blueprint_v1;if(!r||typeof r!="object")return null;const s=r;return{...Za(t),...s,workspace_root:String(s.workspace_root||t||"").trim(),phases:Array.isArray(s.phases)&&s.phases.length?s.phases:Za(t).phases,milestones:Array.isArray(s.milestones)?s.milestones:[],workstreams:Array.isArray(s.workstreams)?s.workstreams:[],review_stages:Array.isArray(s.review_stages)?s.review_stages:[]}}function $a({title:a,subtitle:t,icon:n,children:r}){return e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-3",children:[e("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-100",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:a})]}),t?e("div",{className:"tcp-subtle mt-1 text-xs",children:t}):null]}),e("div",{className:"grid gap-3",children:r})]})}function ft({label:a,value:t,onInput:n,placeholder:r,type:s="text"}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("input",{type:s,value:t,placeholder:r,onInput:c=>n(c.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function In({label:a,value:t,onInput:n,placeholder:r,rows:s=5}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("textarea",{rows:s,value:t,placeholder:r,onInput:c=>n(c.target.value),className:"min-h-[108px] w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function vu({active:a,label:t,icon:n,onClick:r}){return e("button",{className:`tcp-btn h-8 px-3 text-xs ${a?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:r,type:"button",children:e("span",{className:"inline-flex items-center gap-2",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:t})]})})}function Vt({children:a}){return e("div",{className:"tcp-subtle -mt-1 text-xs",children:a})}function yu({text:a}){return e("div",{className:"tcp-subtle rounded-lg border border-slate-800 bg-slate-950/50 p-3 text-xs",children:a})}function wu({value:a,error:t,open:n,browseDir:r,search:s,parentDir:c,currentDir:d,directories:u,onOpen:p,onClose:N,onClear:E,onSearchChange:x,onBrowseParent:C,onBrowseDirectory:O,onSelectDirectory:k}){const z=String(s||"").trim().toLowerCase();return e(aa,{children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Workspace root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:p,children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:`tcp-input text-sm ${t?"border-red-500/70 text-red-100":""}`,value:a,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:E,disabled:!a,children:[e("i",{"data-lucide":"x"}),"Clear"]})]})]}),n?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:N}),e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",d||r||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:C,disabled:!c,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:k,disabled:!d,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:N,children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:s,onInput:A=>x(A.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:u.length?u.map(A=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>O(String(A?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(A?.name||A?.path||"")})]})},String(A?.path||A?.name))):e(yu,{text:z?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null]})}function wr({providerLabel:a,modelLabel:t,draft:n,providers:r,onChange:s,inheritLabel:c="Inherit team default"}){const d=r.find(u=>u.id===n.provider)?.models||[];return e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"cpu"}),e("span",{children:a})]}),e("select",{value:n.provider,onInput:u=>{const p=u.target.value,N=r.find(E=>E.id===p)?.models||[];s({provider:p,model:N[0]||""})},className:"tcp-select h-10 w-full",children:[e("option",{value:"",children:c}),r.map(u=>e("option",{value:u.id,children:[u.id,u.configured===!1?" (not configured)":""]},u.id))]})]}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"sparkles"}),e("span",{children:t})]}),e("select",{value:n.model,onInput:u=>s({...n,model:u.target.value}),className:"tcp-select h-10 w-full",disabled:!n.provider,children:[e("option",{value:"",children:n.provider?"Select a model":c}),d.map(u=>e("option",{value:u,children:u},u))]})]})]})}function xu({client:a,api:t,toast:n,defaultProvider:r,defaultModel:s,editingAutomation:c=null,onShowAutomations:d,onShowRuns:u,onClearEditing:p}){const N=na(),E=qt(null),[x,C]=w("mission"),[O,k]=w("manual"),[z,A]=w("3600"),[G,B]=w(""),[ae,S]=w(!0),[I,H]=w(""),[q,ye]=w(""),[y,v]=w(null),[U,ue]=w(""),[ee,Oe]=w(Za("")),[Ee,We]=w({provider:r,model:s}),[ne,ce]=w({}),[M,me]=w({}),[Re,qe]=w(!1),[se,Ue]=w(!1),[Me,ze]=w(""),[X,Ve]=w(""),re=Y({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),Ce=Y({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),gt=Y({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),ie=Y({queryKey:["tool","ids"],queryFn:()=>a.listToolIds().catch(()=>[]),refetchInterval:3e4}),L=Y({queryKey:["agent-team","templates"],queryFn:async()=>{const o=await a.agentTeams.listTemplates().catch(()=>({templates:[]}));return Array.isArray(o?.templates)?o.templates:[]},refetchInterval:3e4}),st=Y({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),pt=Y({queryKey:["advanced-mission-builder","workspace-browser",Me],enabled:se&&!!Me,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(Me)}`,{method:"GET"})});fe(()=>{const o=String(st.data?.workspaceRoot||st.data?.workspace_root||"").trim();o&&(ue(o),Oe(f=>f.workspace_root?f:{...Za(o),workspace_root:o}))},[st.data]),fe(()=>{const o=U||String(st.data?.workspaceRoot||st.data?.workspace_root||"").trim();if(!c){Oe(Za(o)),v(null),H(""),S(!0),k("manual"),A("3600"),B(""),We({provider:r,model:s}),ce({}),me({});return}const f=bu(c,o);if(!f)return;Oe(f),We(yr(f.team.default_model_policy));const R={};for(const et of f.workstreams)R[et.workstream_id]=yr(et.model_override);ce(R);const P={};for(const et of f.review_stages)P[et.stage_id]=yr(et.model_override);me(P);const $=c?.schedule||{},Xe=String($?.type||"").trim().toLowerCase();Xe==="cron"?(k("cron"),B(String($?.cron_expression||"").trim())):Xe==="interval"?(k("interval"),A(String($?.interval_seconds||3600))):(k("manual"),B(""),A("3600")),S(!1),v(null),H("")},[c?.automation_id,U,r,s,st.data]);const lt=K(()=>{const o=Array.isArray(re.data?.all)?re.data.all:[],f=Ce.data?.providers||{},R=o.map(P=>({id:String(P?.id||"").trim(),models:Object.keys(P?.models||{}),configured:!!f[String(P?.id||"").trim()]})).filter(P=>P.id).sort((P,$)=>P.id.localeCompare($.id));return r&&!R.some(P=>P.id===r)&&R.unshift({id:r,models:s?[s]:[],configured:!0}),R},[s,r,re.data,Ce.data]),Ct=K(()=>hu(gt.data),[gt.data]),De=K(()=>(Array.isArray(ie.data)?ie.data:[]).map(o=>String(o||"").trim()).filter(Boolean).sort(),[ie.data]),$t=K(()=>(Array.isArray(L.data)?L.data:[]).map(o=>({template_id:String(o?.template_id||o?.templateId||"").trim(),role:String(o?.role||"").trim()})).filter(o=>o.template_id),[L.data]),yt=Array.isArray(pt.data?.directories)?pt.data.directories:[],Ut=String(pt.data?.parent||"").trim(),Je=String(pt.data?.dir||Me||"").trim(),Ge=K(()=>{const o=String(X||"").trim().toLowerCase();return o?yt.filter(f=>String(f?.name||f?.path||"").trim().toLowerCase().includes(o)):yt},[X,yt]),nt=Ri(ee.workspace_root||U);fe(()=>{try{E.current?wa(E.current):wa()}catch{}},[x,Re,y,q,ee,Ee,ne,M]);const ve=K(()=>({...ee,workspace_root:ee.workspace_root||U,team:{...ee.team,default_model_policy:vr(Ee)},workstreams:ee.workstreams.map(o=>({...o,model_override:vr(ne[o.workstream_id]||{provider:"",model:""})})),review_stages:ee.review_stages.map(o=>({...o,model_override:vr(M[o.stage_id]||{provider:"",model:""})}))}),[ee,U,Ee,ne,M]),_e=K(()=>fu(ve),[ve]),Ye=K(()=>[...ve.workstreams.map(o=>o.workstream_id),...ve.review_stages.map(o=>o.stage_id)],[ve]);function le(o){Oe(f=>({...f,...o})),v(null)}function it(){Oe(o=>({...o,workstreams:[...o.workstreams,{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:`Workstream ${o.workstreams.length+1}`,objective:"",role:"worker",prompt:"",priority:o.workstreams.length+1,phase_id:o.phases[0]?.phase_id||"",lane:`lane_${o.workstreams.length+1}`,milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}]})),v(null)}function _(){Oe(o=>({...o,review_stages:[...o.review_stages,{stage_id:`review_${crypto.randomUUID().slice(0,8)}`,stage_kind:"approval",title:`Gate ${o.review_stages.length+1}`,target_ids:[],role:"reviewer",prompt:"",checklist:[],priority:o.review_stages.length+1,phase_id:o.phases[0]?.phase_id||"",lane:"review",milestone:"",tool_allowlist_override:[],mcp_servers_override:[],gate:{required:!0,decisions:["approve","rework","cancel"],rework_targets:[],instructions:""}}]})),v(null)}function J(o){const f=Ss.find(P=>P.id===o);if(!f)return;const R={...Za(ee.workspace_root||U),...f.blueprint,mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,workspace_root:ee.workspace_root||U};Oe(R),v(null),H(""),C("mission"),We({provider:r,model:s}),ce({}),me({}),n("info",`Loaded ${f.label}. Review the prompts and adapt them to your mission.`)}async function be(){if(_e.length){const o=_e.join(" ");H(o),n("err",o),C("mission");return}ye("preview"),H("");try{const o=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:ve,schedule:_s(O,z,G)})});v(o),C("compile")}catch(o){const f=o instanceof Error?o.message:String(o||""),R=f==="mission blueprint validation failed"&&_e.length?_e.join(" "):f;H(R),n("err",R)}finally{ye("")}}async function je(){if(_e.length){const o=_e.join(" ");H(o),n("err",o),C("mission");return}ye("apply"),H("");try{const o=_s(O,z,G);if(c?.automation_id){const P=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:ve,schedule:o})});await a.automationsV2.update(c.automation_id,{name:P?.automation?.name,description:P?.automation?.description||null,schedule:P?.automation?.schedule,agents:P?.automation?.agents,flow:P?.automation?.flow,execution:P?.automation?.execution,workspace_root:P?.automation?.workspace_root,metadata:P?.automation?.metadata}),await Promise.all([N.invalidateQueries({queryKey:["automations"]}),N.invalidateQueries({queryKey:["automations","v2","list"]})]),n("ok","Advanced mission updated."),p?.(),d();return}const f=await t("/api/engine/mission-builder/apply",{method:"POST",body:JSON.stringify({blueprint:ve,creator_id:"control-panel",schedule:o})});await Promise.all([N.invalidateQueries({queryKey:["automations"]}),N.invalidateQueries({queryKey:["automations","v2","list"]})]);const R=String(f?.automation?.automation_id||"").trim();ae&&R?(await a.automationsV2.runNow(R),n("ok","Advanced mission created and started."),u()):(n("ok","Advanced mission created."),d()),Oe(Za(U)),v(null),S(!0)}catch(o){const f=o instanceof Error?o.message:String(o||""),R=f==="mission blueprint validation failed"&&_e.length?_e.join(" "):f;H(R),n("err",R)}finally{ye("")}}return e("div",{ref:E,className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-3",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Mission Builder"}),e("div",{className:"tcp-subtle text-xs",children:"Build one coordinated swarm mission with shared context, per-lane roles, explicit handoffs, and a compiled preview before launch."}),e("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>qe(!0),children:[e("i",{"data-lucide":"book-open"}),"How this works"]}),e("span",{className:"tcp-subtle text-xs",children:"Start from example:"}),Ss.map(o=>e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>J(o.id),children:[e("i",{"data-lucide":mu[o.id]||"sparkles"}),o.label]},o.id))]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[["mission","clipboard-list"],["team","users"],["workstreams","workflow"],["review","shield-check"],["compile","binary"]].map(([o,f])=>e(vu,{active:x===o,label:o==="workstreams"?"workstreams":o,icon:f,onClick:()=>C(o)},o))})]}),I?e("div",{className:"rounded-xl border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-200",children:I}):null,c?e("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:["Editing advanced mission:"," ",e("strong",{children:String(c?.name||c?.automation_id||"")})]}):null,Re?e("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-slate-950/80 p-4 backdrop-blur-sm",children:e("div",{className:"max-h-[90vh] w-full max-w-4xl overflow-y-auto rounded-2xl border border-slate-700 bg-slate-950 p-5 shadow-2xl",children:[e("div",{className:"mb-4 flex items-start justify-between gap-4",children:[e("div",{children:[e("div",{className:"text-lg font-semibold text-slate-100",children:"How the Advanced Swarm Builder Works"}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Think of this as a mission compiler: one shared goal, many scoped workstreams, explicit handoffs, and optional review gates."})]}),e("button",{className:"tcp-btn h-9 px-3 text-sm",onClick:()=>qe(!1),children:"Close"})]}),e("div",{className:"grid gap-4 lg:grid-cols-2",children:[e($a,{title:"What goes where",subtitle:"Use the right field for the right level of instruction.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"Mission goal:"})," the one shared outcome for the whole operation."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Success criteria:"})," concrete checks for whether the mission is done well."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Shared context:"})," facts, constraints, tone, audience, deadlines, approved sources."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream objective:"})," the local assignment for that lane."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream prompt:"})," the operating instructions for how that lane should work."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Output contract:"})," the artifact that downstream work expects to receive."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Review / gate prompt:"})," what a reviewer or approver must check before promotion."]})]})}),e($a,{title:"How to get good results",subtitle:"The builder works best when each stage is explicit.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:"Keep the mission goal outcome-based, not a long checklist."}),e("div",{children:"Make success criteria measurable."}),e("div",{children:"Give each workstream one clear responsibility."}),e("div",{children:"Use dependencies only for real handoffs."}),e("div",{children:"Define outputs as concrete artifacts, not vague intentions."}),e("div",{children:"Use review gates for quality and promotion, not for every step."}),e("div",{children:"Prefer prompts that say what evidence, format, and audience the step should target."})]})}),e($a,{title:"Prompt pattern",subtitle:"A reliable starting scaffold for most workstreams.",children:e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3 text-xs text-slate-300",children:[e("div",{children:e("strong",{className:"text-slate-100",children:"Mission goal"})}),e("div",{className:"mt-1",children:"Produce a coordinated launch plan for Product X for the next 30 days."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Shared context"})}),e("div",{className:"mt-1",children:"Audience is SMB owners. Tone is clear and practical. Use approved workspace and MCP sources only. Avoid speculative claims."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream objective"})}),e("div",{className:"mt-1",children:"Analyze the target workflow and identify the 3 highest-value AI opportunities for a near-term pilot."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream prompt"})}),e("div",{className:"mt-1",children:"Act as an AI workflow strategist. Map the current process, identify repeated manual work, decision bottlenecks, and coordination pain, then recommend realistic AI patterns with evidence and operational caveats."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Output contract"})}),e("div",{className:"mt-1",children:"A markdown memo with sections: workflow summary, AI opportunities, feasibility constraints, risks, and recommended pilots."})]})}),e($a,{title:"Starter examples",subtitle:"Use these when you do not want to begin from a blank blueprint.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"AI Opportunities:"})," workflow analysis and capability mapping feeding a ranked pilot brief."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workflow Audit:"})," current-state mapping and failure analysis feeding an automation design review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Agentic Design:"})," role design and flow design feeding governance and safety review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Rollout:"})," process readiness and platform readiness feeding a launch plan and approval gate."]})]})})]})]})}):null,x==="mission"?e($a,{title:"Mission",subtitle:"Global brief, success criteria, and schedule.",icon:"clipboard-list",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(ft,{label:"Mission title",value:ee.title,onInput:o=>le({title:o})}),e(ft,{label:"Mission ID",value:ee.mission_id,onInput:o=>le({mission_id:o})})]}),e(Vt,{children:"Use a short title a human operator would recognize later in the automation list."}),e(wu,{value:ee.workspace_root,error:nt,open:se,browseDir:Me,search:X,parentDir:Ut,currentDir:Je,directories:Ge,onOpen:()=>{const o=String(ee.workspace_root||U||"/").trim();ze(o||"/"),Ve(""),Ue(!0)},onClose:()=>{Ue(!1),Ve("")},onClear:()=>le({workspace_root:""}),onSearchChange:Ve,onBrowseParent:()=>{Ut&&ze(Ut)},onBrowseDirectory:o=>ze(o),onSelectDirectory:()=>{Je&&(le({workspace_root:Je}),Ue(!1),Ve(""),n("ok",`Workspace selected: ${Je}`))}}),e(Vt,{children:"This is the shared working directory the mission can use for files and artifacts."}),nt?e("div",{className:"text-xs text-red-300",children:nt}):null,e(In,{label:"Mission goal",value:ee.goal,onInput:o=>le({goal:o}),placeholder:"Describe the shared objective all participants are working toward."}),e(Vt,{children:"Write the one shared outcome for the whole swarm, not a list of steps."}),e(In,{label:"Shared context",value:ee.shared_context||"",onInput:o=>le({shared_context:o}),placeholder:"Shared constraints, references, context, and operator guidance."}),e(Vt,{children:"Put the facts every lane should inherit here: audience, constraints, tone, deadlines, approved sources, and things to avoid."}),e(ft,{label:"Success criteria",value:ee.success_criteria.join(", "),onInput:o=>le({success_criteria:Ma(o)}),placeholder:"comma-separated"}),e(Vt,{children:"These should be measurable checks like “brief includes 5 competitors” or “plan contains owner, timeline, and risks”."}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Schedule"}),e("select",{value:O,onInput:o=>k(o.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"manual",children:"Manual"}),e("option",{value:"interval",children:"Interval"}),e("option",{value:"cron",children:"Cron"})]})]}),O==="interval"?e(ft,{label:"Interval seconds",value:z,onInput:A}):null,O==="cron"?e(ft,{label:"Cron expression",value:G,onInput:B}):null]})]}):null,x==="team"?e($a,{title:"Team",subtitle:"Templates, default model, concurrency, and mission limits.",icon:"users",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Orchestrator template"}),e("select",{value:ee.orchestrator_template_id||"",onInput:o=>le({orchestrator_template_id:o.target.value}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"",children:"None"}),$t.map(o=>e("option",{value:o.template_id,children:[o.template_id," (",o.role||"role",")"]},o.template_id))]})]}),e(ft,{label:"Allowed templates",value:(ee.team.allowed_template_ids||[]).join(", "),onInput:o=>le({team:{...ee.team,allowed_template_ids:Ma(o)}}),placeholder:"comma-separated"})]}),e(Vt,{children:"The orchestrator keeps the mission coherent. Allowed templates restrict which reusable agent profiles lanes are permitted to use."}),e(wr,{providerLabel:"Default model provider",modelLabel:"Default model",draft:Ee,providers:lt,inheritLabel:"No team default",onChange:We}),e("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-4",children:[e(ft,{label:"Max parallel agents",value:String(ee.team.max_parallel_agents||4),onInput:o=>le({team:{...ee.team,max_parallel_agents:Math.max(1,Number.parseInt(String(o||"4"),10)||4)}}),type:"number"}),e(ft,{label:"Token ceiling",value:String(ee.team.mission_budget?.max_total_tokens||""),onInput:o=>le({team:{...ee.team,mission_budget:{...ee.team.mission_budget||{},max_total_tokens:o?Number(o):void 0}}}),type:"number"}),e(ft,{label:"Cost ceiling USD",value:String(ee.team.mission_budget?.max_total_cost_usd||""),onInput:o=>le({team:{...ee.team,mission_budget:{...ee.team.mission_budget||{},max_total_cost_usd:o?Number(o):void 0}}}),type:"number"}),e(ft,{label:"Tool-call ceiling",value:String(ee.team.mission_budget?.max_total_tool_calls||""),onInput:o=>le({team:{...ee.team,mission_budget:{...ee.team.mission_budget||{},max_total_tool_calls:o?Number(o):void 0}}}),type:"number"})]}),e(ft,{label:"Allowed MCP servers",value:(ee.team.allowed_mcp_servers||[]).join(", "),onInput:o=>le({team:{...ee.team,allowed_mcp_servers:Ma(o)}}),placeholder:Ct.map(o=>o.name).join(", ")}),e(Vt,{children:"Team defaults apply everywhere unless a workstream or review stage overrides its own tool or MCP scope."})]}):null,x==="workstreams"?e($a,{title:"Workstreams",subtitle:"Scoped sub-objectives, dependencies, tools, MCP, and output contracts.",icon:"workflow",children:[e(Vt,{children:"A workstream is one scoped lane of work. Give it one responsibility, one artifact to produce, and only the dependencies it truly needs."}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:it,children:[e("i",{"data-lucide":"plus"}),"Add workstream"]})}),ve.workstreams.map((o,f)=>{const R=ne[o.workstream_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:o.title||`Workstream ${f+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>le({workstreams:ve.workstreams.filter(P=>P.workstream_id!==o.workstream_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(ft,{label:"Title",value:o.title,onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,title:P}:$)})}),e(ft,{label:"Role",value:o.role,onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,role:P}:$)})})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(ft,{label:"Phase",value:o.phase_id||"",onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,phase_id:P}:$)})}),e(ft,{label:"Lane",value:o.lane||"",onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,lane:P}:$)})}),e(ft,{label:"Priority",value:String(o.priority||0),onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,priority:Number(P)||0}:$)}),type:"number"})]}),e(Vt,{children:"`Phase` says when this lane belongs in the mission. `Lane` groups related work. `Priority` decides ordering among runnable work in the same open phase."}),e(In,{label:"Objective",value:o.objective,onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,objective:P}:$)}),rows:3}),e(Vt,{children:"Objective is the local assignment. Keep it crisp: what this lane must accomplish."}),e(In,{label:"Prompt",value:o.prompt,onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,prompt:P}:$)}),rows:5}),e(Vt,{children:"Prompt is how the lane should operate: role, evidence standard, audience, format, and what good work looks like."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(ft,{label:"Depends on",value:o.depends_on.join(", "),onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,depends_on:Ma(P)}:$)}),placeholder:"comma-separated stage ids"}),e(ft,{label:"Output contract kind",value:o.output_contract.kind,onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,output_contract:{...$.output_contract,kind:P}}:$)})})]}),e(Vt,{children:"`Depends on` should list upstream stage IDs that must finish first. `Output contract kind` names the artifact downstream lanes expect."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(ft,{label:"Tool allowlist override",value:(o.tool_allowlist_override||[]).join(", "),onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,tool_allowlist_override:Ma(P)}:$)}),placeholder:De.join(", ")}),e(ft,{label:"MCP servers override",value:(o.mcp_servers_override||[]).join(", "),onInput:P=>le({workstreams:ve.workstreams.map($=>$.workstream_id===o.workstream_id?{...$,mcp_servers_override:Ma(P)}:$)}),placeholder:Ct.map(P=>P.name).join(", ")})]}),e(Vt,{children:"Leave tool and MCP overrides empty to inherit team defaults. Override only when this lane needs a narrower or different scope."}),e(wr,{providerLabel:"Model provider",modelLabel:"Model",draft:R,providers:lt,onChange:P=>ce($=>({...$,[o.workstream_id]:P}))})]},o.workstream_id)})]}):null,x==="review"?e($a,{title:"Review & Gates",subtitle:"Reviewer, tester, and approval stages.",icon:"shield-check",children:[e(Vt,{children:"Use review stages to check quality or readiness before later work is promoted. Approval stages are the right place for human checkpoints."}),e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:_,children:[e("i",{"data-lucide":"plus"}),"Add review stage"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>le({phases:[...ve.phases,{phase_id:`phase_${ve.phases.length+1}`,title:`Phase ${ve.phases.length+1}`,description:"",execution_mode:"soft"}]}),children:[e("i",{"data-lucide":"copy-plus"}),"Add phase"]})]}),e("div",{className:"grid gap-2",children:ve.phases.map((o,f)=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:e("div",{className:"grid gap-3 md:grid-cols-4",children:[e(ft,{label:"Phase ID",value:o.phase_id,onInput:R=>le({phases:ve.phases.map((P,$)=>$===f?{...P,phase_id:R}:P)})}),e(ft,{label:"Title",value:o.title,onInput:R=>le({phases:ve.phases.map((P,$)=>$===f?{...P,title:R}:P)})}),e(ft,{label:"Description",value:o.description||"",onInput:R=>le({phases:ve.phases.map((P,$)=>$===f?{...P,description:R}:P)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Execution mode"}),e("select",{value:o.execution_mode||"soft",onInput:R=>le({phases:ve.phases.map((P,$)=>$===f?{...P,execution_mode:R.target.value}:P)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"soft",children:"soft"}),e("option",{value:"barrier",children:"barrier"})]})]})]})},o.phase_id))}),e(Vt,{children:"`soft` phases prefer the current open phase first. `barrier` phases hold later phases closed until earlier required work is complete."}),ve.review_stages.map((o,f)=>{const R=M[o.stage_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:o.title||`Review stage ${f+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>le({review_stages:ve.review_stages.filter(P=>P.stage_id!==o.stage_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(ft,{label:"Title",value:o.title,onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,title:P}:$)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Stage kind"}),e("select",{value:o.stage_kind,onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,stage_kind:P.target.value}:$)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"review",children:"review"}),e("option",{value:"test",children:"test"}),e("option",{value:"approval",children:"approval"})]})]})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(ft,{label:"Targets",value:o.target_ids.join(", "),onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,target_ids:Ma(P)}:$)}),placeholder:Ye.join(", ")}),e(ft,{label:"Phase",value:o.phase_id||"",onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,phase_id:P}:$)})}),e(ft,{label:"Lane",value:o.lane||"",onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,lane:P}:$)})})]}),e(Vt,{children:"Targets are the stages this review or gate is checking. Put the review in the phase where that checkpoint should happen."}),e(In,{label:"Prompt",value:o.prompt,onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,prompt:P}:$)}),rows:4}),e(Vt,{children:"Use the prompt to define what must be checked and what should trigger approve, rework, or fail."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(ft,{label:"Checklist",value:(o.checklist||[]).join(", "),onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,checklist:Ma(P)}:$)}),placeholder:"comma-separated"}),e(ft,{label:"MCP servers override",value:(o.mcp_servers_override||[]).join(", "),onInput:P=>le({review_stages:ve.review_stages.map($=>$.stage_id===o.stage_id?{...$,mcp_servers_override:Ma(P)}:$)}),placeholder:Ct.map(P=>P.name).join(", ")})]}),e(Vt,{children:"Checklist items should be concrete pass/fail checks, not broad wishes."}),e(wr,{providerLabel:"Model provider",modelLabel:"Model",draft:R,providers:lt,onChange:P=>me($=>({...$,[o.stage_id]:P}))})]},o.stage_id)})]}):null,x==="compile"?e($a,{title:"Compile & Run",subtitle:"Validate the mission graph before launch.",icon:"binary",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",disabled:q==="preview",onClick:()=>{be()},children:[e("i",{"data-lucide":"refresh-cw"}),q==="preview"?"Compiling...":"Compile preview"]}),e("button",{className:"tcp-btn-primary h-8 px-3 text-xs",disabled:q==="apply",onClick:()=>{je()},children:[e("i",{"data-lucide":c?"save":"arrow-up-circle"}),q==="apply"?"Saving...":c?"Save automation":ae?"Create and run":"Create draft"]}),c?null:e("label",{className:"ml-2 inline-flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:ae,onChange:o=>S(o.target.checked)}),"Run immediately after create"]}),c&&p?e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>p(),children:"Cancel edit"}):null]}),y?e(aa,{children:[e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Validation"}),Array.isArray(y?.validation)&&y.validation.length?e("div",{className:"grid gap-2",children:y.validation.map((o,f)=>e("div",{className:`rounded-lg border px-3 py-2 text-xs ${String(o?.severity||"").toLowerCase()==="warning"?"border-amber-500/40 bg-amber-500/10 text-amber-200":"border-slate-700 bg-slate-950/60 text-slate-200"}`,children:[e("div",{className:"font-medium",children:String(o?.code||o?.severity||"validation")}),e("div",{className:"mt-1",children:String(o?.message||"")})]},`${o?.code||"message"}-${f}`))}):e("div",{className:"tcp-subtle text-xs",children:"No validation warnings."})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Compiled automation"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:[e("div",{children:["name: ",String(y?.automation?.name||"—")]}),e("div",{children:["nodes:"," ",Array.isArray(y?.automation?.flow?.nodes)?y.automation.flow.nodes.length:0]}),e("div",{children:["agents:"," ",Array.isArray(y?.automation?.agents)?y.automation.agents.length:0]}),e("div",{children:["max parallel:"," ",String(y?.automation?.execution?.max_parallel_agents??"—")]})]})]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Node preview"}),e("div",{className:"grid gap-2",children:(Array.isArray(y?.node_previews)?y.node_previews:[]).map(o=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/70 p-3 text-xs text-slate-300",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-slate-100",children:String(o?.title||o?.node_id||"node")}),e("span",{className:"tcp-subtle",children:String(o?.node_id||"")}),e("span",{className:"tcp-subtle",children:["phase: ",String(o?.phase_id||"—")]}),e("span",{className:"tcp-subtle",children:["lane: ",String(o?.lane||"—")]}),e("span",{className:"tcp-subtle",children:["priority: ",String(o?.priority??"—")]})]}),e("div",{className:"mt-1",children:["depends on:"," ",Array.isArray(o?.depends_on)&&o.depends_on.length?o.depends_on.join(", "):"none"]}),e("div",{className:"mt-1",children:["tools:"," ",Array.isArray(o?.tool_allowlist)&&o.tool_allowlist.length?o.tool_allowlist.join(", "):"default"]}),e("div",{className:"mt-1",children:["MCP:"," ",Array.isArray(o?.mcp_servers)&&o.mcp_servers.length?o.mcp_servers.join(", "):"default"]})]},String(o?.node_id||"")))})]})]}):e("div",{className:"tcp-subtle text-xs",children:"Compile the mission to inspect validation, compiled nodes, and execution shape."})]}):null]})}const ku=`kind: extract_format
|
|
2348
|
+
`,Ru={"ai-opportunity":"sparkles","workflow-audit":"workflow","agentic-design":"bot","automation-rollout":"arrow-up-circle"},Mu=Object.assign({"../presets/mission-builder/agentic-design.yaml":Cu,"../presets/mission-builder/ai-opportunity.yaml":Au,"../presets/mission-builder/automation-rollout.yaml":Pu,"../presets/mission-builder/workflow-audit.yaml":Tu});function qu(a){return Array.isArray(a?.servers)?a.servers.map(t=>{const n=String(t?.name||"").trim();return n?{name:n,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(Boolean):a&&typeof a=="object"?Object.entries(a).map(([t,n])=>{const r=String(t||"").trim();return r?{name:r,connected:!!n?.connected,enabled:n?.enabled!==!1}:null}).filter(Boolean):[]}function ja(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function Mr(a){const t=String(a.provider||"").trim(),n=String(a.model||"").trim();return!t||!n?null:{default_model:{provider_id:t,model_id:n}}}function qr(a){const t=a?.default_model||a?.defaultModel||{};return{provider:String(t?.provider_id||t?.providerId||"").trim(),model:String(t?.model_id||t?.modelId||"").trim()}}function Fs(a,t,n){const r={type:"run_once"};return a==="cron"?{type:"cron",cron_expression:String(n||"").trim(),timezone:"UTC",misfire_policy:r}:a==="interval"?{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(t||"3600"),10)||3600),timezone:"UTC",misfire_policy:r}:{type:"manual",timezone:"UTC",misfire_policy:r}}function Za(a){return{mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,title:"",goal:"",success_criteria:[],shared_context:"",workspace_root:a,orchestrator_template_id:"",phases:[{phase_id:"phase_1",title:"Phase 1",description:"",execution_mode:"soft"}],milestones:[],team:{allowed_template_ids:[],default_model_policy:null,allowed_mcp_servers:[],max_parallel_agents:4,mission_budget:{},orchestrator_only_tool_calls:!1},workstreams:[{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:"Workstream 1",objective:"",role:"worker",prompt:"",priority:1,phase_id:"phase_1",lane:"lane_1",milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}],review_stages:[],metadata:null}}function $u(a,t){const n=wr.parse(a);if(!n||typeof n!="object")throw new Error(`Invalid mission preset at ${t}: expected a YAML object.`);const r=n,s=String(r.id||"").trim(),c=String(r.label||"").trim(),d=String(r.description||"").trim(),u=r.blueprint;if(!s)throw new Error(`Invalid mission preset at ${t}: missing id.`);if(!c)throw new Error(`Invalid mission preset at ${t}: missing label.`);if(!d)throw new Error(`Invalid mission preset at ${t}: missing description.`);if(!u||typeof u!="object")throw new Error(`Invalid mission preset at ${t}: missing blueprint.`);return{id:s,label:c,description:d,blueprint:u}}const Ls=Object.entries(Mu).map(([a,t])=>$u(t,a)).sort((a,t)=>a.label.localeCompare(t.label,void 0,{sensitivity:"base"}));function Hi(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Ou(a){const t=[];String(a.title||"").trim()||t.push("Mission title is required."),String(a.goal||"").trim()||t.push("Mission goal is required.");const n=Hi(a.workspace_root);return n&&t.push(n),(!Array.isArray(a.workstreams)||a.workstreams.length===0)&&t.push("At least one workstream is required."),t}function Eu(a,t){const n=a?.metadata&&typeof a.metadata=="object"?a.metadata:{},r=n.mission_blueprint||n.missionBlueprint||n.mission_blueprint_v1;if(!r||typeof r!="object")return null;const s=r;return{...Za(t),...s,workspace_root:String(s.workspace_root||t||"").trim(),phases:Array.isArray(s.phases)&&s.phases.length?s.phases:Za(t).phases,milestones:Array.isArray(s.milestones)?s.milestones:[],workstreams:Array.isArray(s.workstreams)?s.workstreams:[],review_stages:Array.isArray(s.review_stages)?s.review_stages:[]}}function Ua({title:a,subtitle:t,icon:n,children:r}){return e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-3",children:[e("div",{className:"flex items-center gap-2 text-sm font-semibold text-slate-100",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:a})]}),t?e("div",{className:"tcp-subtle mt-1 text-xs",children:t}):null]}),e("div",{className:"grid gap-3",children:r})]})}function wt({label:a,value:t,onInput:n,placeholder:r,type:s="text"}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("input",{type:s,value:t,placeholder:r,onInput:c=>n(c.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function Rn({label:a,value:t,onInput:n,placeholder:r,rows:s=5}){return e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:a}),e("textarea",{rows:s,value:t,placeholder:r,onInput:c=>n(c.target.value),className:"min-h-[108px] w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 py-2 text-sm text-slate-100 outline-none focus:border-amber-400"})]})}function Du({active:a,label:t,icon:n,onClick:r}){return e("button",{className:`tcp-btn h-8 px-3 text-xs ${a?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:r,type:"button",children:e("span",{className:"inline-flex items-center gap-2",children:[n?e("i",{"data-lucide":n}):null,e("span",{children:t})]})})}function ta({children:a}){return e("div",{className:"tcp-subtle -mt-1 text-xs",children:a})}function ju({text:a}){return e("div",{className:"tcp-subtle rounded-lg border border-slate-800 bg-slate-950/50 p-3 text-xs",children:a})}function Uu({value:a,error:t,open:n,browseDir:r,search:s,parentDir:c,currentDir:d,directories:u,onOpen:p,onClose:N,onClear:E,onSearchChange:x,onBrowseParent:A,onBrowseDirectory:O,onSelectDirectory:_}){const z=String(s||"").trim().toLowerCase();return e(la,{children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Workspace root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:p,children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:`tcp-input text-sm ${t?"border-red-500/70 text-red-100":""}`,value:a,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn h-10 px-3",type:"button",onClick:E,disabled:!a,children:[e("i",{"data-lucide":"x"}),"Clear"]})]})]}),n?e("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:N}),e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",d||r||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:A,disabled:!c,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:_,disabled:!d,children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",type:"button",onClick:N,children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:s,onInput:P=>x(P.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:u.length?u.map(P=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>O(String(P?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(P?.name||P?.path||"")})]})},String(P?.path||P?.name))):e(ju,{text:z?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null]})}function $r({providerLabel:a,modelLabel:t,draft:n,providers:r,onChange:s,inheritLabel:c="Inherit team default"}){const d=r.find(u=>u.id===n.provider)?.models||[];return e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"cpu"}),e("span",{children:a})]}),e("select",{value:n.provider,onInput:u=>{const p=u.target.value,N=r.find(E=>E.id===p)?.models||[];s({provider:p,model:N[0]||""})},className:"tcp-select h-10 w-full",children:[e("option",{value:"",children:c}),r.map(u=>e("option",{value:u.id,children:[u.id,u.configured===!1?" (not configured)":""]},u.id))]})]}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 flex items-center gap-2 font-medium text-slate-200",children:[e("i",{"data-lucide":"sparkles"}),e("span",{children:t})]}),e("select",{value:n.model,onInput:u=>s({...n,model:u.target.value}),className:"tcp-select h-10 w-full",disabled:!n.provider,children:[e("option",{value:"",children:n.provider?"Select a model":c}),d.map(u=>e("option",{value:u,children:u},u))]})]})]})}function Bu({client:a,api:t,toast:n,defaultProvider:r,defaultModel:s,editingAutomation:c=null,onShowAutomations:d,onShowRuns:u,onClearEditing:p}){const N=ca(),E=Rt(null),[x,A]=w("mission"),[O,_]=w("manual"),[z,P]=w("3600"),[Q,B]=w(""),[ne,I]=w(!0),[C,H]=w(""),[M,xe]=w(""),[y,v]=w(null),[j,he]=w(""),[ee,qe]=w(Za("")),[$e,Le]=w({provider:r,model:s}),[re,me]=w({}),[q,ge]=w({}),[Pe,Te]=w(!1),[se,Oe]=w(!1),[Me,He]=w(""),[Y,Ze]=w(""),ae=V({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),Ae=V({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),St=V({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),oe=V({queryKey:["tool","ids"],queryFn:()=>a.listToolIds().catch(()=>[]),refetchInterval:3e4}),W=V({queryKey:["agent-team","templates"],queryFn:async()=>{const l=await a.agentTeams.listTemplates().catch(()=>({templates:[]}));return Array.isArray(l?.templates)?l.templates:[]},refetchInterval:3e4}),lt=V({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),xt=V({queryKey:["advanced-mission-builder","workspace-browser",Me],enabled:se&&!!Me,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(Me)}`,{method:"GET"})});fe(()=>{const l=String(lt.data?.workspaceRoot||lt.data?.workspace_root||"").trim();l&&(he(l),qe(b=>b.workspace_root?b:{...Za(l),workspace_root:l}))},[lt.data]),fe(()=>{const l=j||String(lt.data?.workspaceRoot||lt.data?.workspace_root||"").trim();if(!c){qe(Za(l)),v(null),H(""),I(!0),_("manual"),P("3600"),B(""),Le({provider:r,model:s}),me({}),ge({});return}const b=Eu(c,l);if(!b)return;qe(b),Le(qr(b.team.default_model_policy));const T={};for(const Xe of b.workstreams)T[Xe.workstream_id]=qr(Xe.model_override);me(T);const R={};for(const Xe of b.review_stages)R[Xe.stage_id]=qr(Xe.model_override);ge(R);const $=c?.schedule||{},Ye=String($?.type||"").trim().toLowerCase();Ye==="cron"?(_("cron"),B(String($?.cron_expression||"").trim())):Ye==="interval"?(_("interval"),P(String($?.interval_seconds||3600))):(_("manual"),B(""),P("3600")),I(!1),v(null),H("")},[c?.automation_id,j,r,s,lt.data]);const rt=F(()=>{const l=Array.isArray(ae.data?.all)?ae.data.all:[],b=Ae.data?.providers||{},T=l.map(R=>({id:String(R?.id||"").trim(),models:Object.keys(R?.models||{}),configured:!!b[String(R?.id||"").trim()]})).filter(R=>R.id).sort((R,$)=>R.id.localeCompare($.id));return r&&!T.some(R=>R.id===r)&&T.unshift({id:r,models:s?[s]:[],configured:!0}),T},[s,r,ae.data,Ae.data]),Et=F(()=>qu(St.data),[St.data]),Fe=F(()=>(Array.isArray(oe.data)?oe.data:[]).map(l=>String(l||"").trim()).filter(Boolean).sort(),[oe.data]),Bt=F(()=>(Array.isArray(W.data)?W.data:[]).map(l=>({template_id:String(l?.template_id||l?.templateId||"").trim(),role:String(l?.role||"").trim()})).filter(l=>l.template_id),[W.data]),At=Array.isArray(xt.data?.directories)?xt.data.directories:[],$t=String(xt.data?.parent||"").trim(),We=String(xt.data?.dir||Me||"").trim(),ze=F(()=>{const l=String(Y||"").trim().toLowerCase();return l?At.filter(b=>String(b?.name||b?.path||"").trim().toLowerCase().includes(l)):At},[Y,At]),tt=Hi(ee.workspace_root||j);fe(()=>{try{E.current?xa(E.current):xa()}catch{}},[x,Pe,y,M,ee,$e,re,q]);const be=F(()=>({...ee,workspace_root:ee.workspace_root||j,team:{...ee.team,default_model_policy:Mr($e)},workstreams:ee.workstreams.map(l=>({...l,model_override:Mr(re[l.workstream_id]||{provider:"",model:""})})),review_stages:ee.review_stages.map(l=>({...l,model_override:Mr(q[l.stage_id]||{provider:"",model:""})}))}),[ee,j,$e,re,q]),Se=F(()=>Ou(be),[be]),Ve=F(()=>[...be.workstreams.map(l=>l.workstream_id),...be.review_stages.map(l=>l.stage_id)],[be]);function ce(l){qe(b=>({...b,...l})),v(null)}function dt(){qe(l=>({...l,workstreams:[...l.workstreams,{workstream_id:`workstream_${crypto.randomUUID().slice(0,8)}`,title:`Workstream ${l.workstreams.length+1}`,objective:"",role:"worker",prompt:"",priority:l.workstreams.length+1,phase_id:l.phases[0]?.phase_id||"",lane:`lane_${l.workstreams.length+1}`,milestone:"",depends_on:[],input_refs:[],tool_allowlist_override:[],mcp_servers_override:[],output_contract:{kind:"report_markdown",summary_guidance:""}}]})),v(null)}function S(){qe(l=>({...l,review_stages:[...l.review_stages,{stage_id:`review_${crypto.randomUUID().slice(0,8)}`,stage_kind:"approval",title:`Gate ${l.review_stages.length+1}`,target_ids:[],role:"reviewer",prompt:"",checklist:[],priority:l.review_stages.length+1,phase_id:l.phases[0]?.phase_id||"",lane:"review",milestone:"",tool_allowlist_override:[],mcp_servers_override:[],gate:{required:!0,decisions:["approve","rework","cancel"],rework_targets:[],instructions:""}}]})),v(null)}function G(l){const b=Ls.find(R=>R.id===l);if(!b)return;const T={...Za(ee.workspace_root||j),...b.blueprint,mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,workspace_root:ee.workspace_root||j};qe(T),v(null),H(""),A("mission"),Le({provider:r,model:s}),me({}),ge({}),n("info",`Loaded ${b.label}. Review the prompts and adapt them to your mission.`)}async function ue(){if(Se.length){const l=Se.join(" ");H(l),n("err",l),A("mission");return}xe("preview"),H("");try{const l=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:be,schedule:Fs(O,z,Q)})});v(l),A("compile")}catch(l){const b=l instanceof Error?l.message:String(l||""),T=b==="mission blueprint validation failed"&&Se.length?Se.join(" "):b;H(T),n("err",T)}finally{xe("")}}async function Ke(){if(Se.length){const l=Se.join(" ");H(l),n("err",l),A("mission");return}xe("apply"),H("");try{const l=Fs(O,z,Q);if(c?.automation_id){const R=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:be,schedule:l})});await a.automationsV2.update(c.automation_id,{name:R?.automation?.name,description:R?.automation?.description||null,schedule:R?.automation?.schedule,agents:R?.automation?.agents,flow:R?.automation?.flow,execution:R?.automation?.execution,workspace_root:R?.automation?.workspace_root,metadata:R?.automation?.metadata}),await Promise.all([N.invalidateQueries({queryKey:["automations"]}),N.invalidateQueries({queryKey:["automations","v2","list"]})]),n("ok","Advanced mission updated."),p?.(),d();return}const b=await t("/api/engine/mission-builder/apply",{method:"POST",body:JSON.stringify({blueprint:be,creator_id:"control-panel",schedule:l})});await Promise.all([N.invalidateQueries({queryKey:["automations"]}),N.invalidateQueries({queryKey:["automations","v2","list"]})]);const T=String(b?.automation?.automation_id||"").trim();ne&&T?(await a.automationsV2.runNow(T),n("ok","Advanced mission created and started."),u()):(n("ok","Advanced mission created."),d()),qe(Za(j)),v(null),I(!0)}catch(l){const b=l instanceof Error?l.message:String(l||""),T=b==="mission blueprint validation failed"&&Se.length?Se.join(" "):b;H(T),n("err",T)}finally{xe("")}}return e("div",{ref:E,className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-3",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Mission Builder"}),e("div",{className:"tcp-subtle text-xs",children:"Build one coordinated swarm mission with shared context, per-lane roles, explicit handoffs, and a compiled preview before launch."}),e("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>Te(!0),children:[e("i",{"data-lucide":"book-open"}),"How this works"]}),e("span",{className:"tcp-subtle text-xs",children:"Start from example:"}),Ls.map(l=>e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>G(l.id),children:[e("i",{"data-lucide":Ru[l.id]||"sparkles"}),l.label]},l.id))]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[["mission","clipboard-list"],["team","users"],["workstreams","workflow"],["review","shield-check"],["compile","binary"]].map(([l,b])=>e(Du,{active:x===l,label:l==="workstreams"?"workstreams":l,icon:b,onClick:()=>A(l)},l))})]}),C?e("div",{className:"rounded-xl border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-200",children:C}):null,c?e("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:["Editing advanced mission:"," ",e("strong",{children:String(c?.name||c?.automation_id||"")})]}):null,Pe?e("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-slate-950/80 p-4 backdrop-blur-sm",children:e("div",{className:"max-h-[90vh] w-full max-w-4xl overflow-y-auto rounded-2xl border border-slate-700 bg-slate-950 p-5 shadow-2xl",children:[e("div",{className:"mb-4 flex items-start justify-between gap-4",children:[e("div",{children:[e("div",{className:"text-lg font-semibold text-slate-100",children:"How the Advanced Swarm Builder Works"}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Think of this as a mission compiler: one shared goal, many scoped workstreams, explicit handoffs, and optional review gates."})]}),e("button",{className:"tcp-btn h-9 px-3 text-sm",onClick:()=>Te(!1),children:"Close"})]}),e("div",{className:"grid gap-4 lg:grid-cols-2",children:[e(Ua,{title:"What goes where",subtitle:"Use the right field for the right level of instruction.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"Mission goal:"})," the one shared outcome for the whole operation."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Success criteria:"})," concrete checks for whether the mission is done well."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Shared context:"})," facts, constraints, tone, audience, deadlines, approved sources."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream objective:"})," the local assignment for that lane."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workstream prompt:"})," the operating instructions for how that lane should work."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Output contract:"})," the artifact that downstream work expects to receive."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Review / gate prompt:"})," what a reviewer or approver must check before promotion."]})]})}),e(Ua,{title:"How to get good results",subtitle:"The builder works best when each stage is explicit.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:"Keep the mission goal outcome-based, not a long checklist."}),e("div",{children:"Make success criteria measurable."}),e("div",{children:"Give each workstream one clear responsibility."}),e("div",{children:"Use dependencies only for real handoffs."}),e("div",{children:"Define outputs as concrete artifacts, not vague intentions."}),e("div",{children:"Use review gates for quality and promotion, not for every step."}),e("div",{children:"Prefer prompts that say what evidence, format, and audience the step should target."})]})}),e(Ua,{title:"Prompt pattern",subtitle:"A reliable starting scaffold for most workstreams.",children:e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3 text-xs text-slate-300",children:[e("div",{children:e("strong",{className:"text-slate-100",children:"Mission goal"})}),e("div",{className:"mt-1",children:"Produce a coordinated launch plan for Product X for the next 30 days."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Shared context"})}),e("div",{className:"mt-1",children:"Audience is SMB owners. Tone is clear and practical. Use approved workspace and MCP sources only. Avoid speculative claims."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream objective"})}),e("div",{className:"mt-1",children:"Analyze the target workflow and identify the 3 highest-value AI opportunities for a near-term pilot."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Workstream prompt"})}),e("div",{className:"mt-1",children:"Act as an AI workflow strategist. Map the current process, identify repeated manual work, decision bottlenecks, and coordination pain, then recommend realistic AI patterns with evidence and operational caveats."}),e("div",{className:"mt-3",children:e("strong",{className:"text-slate-100",children:"Output contract"})}),e("div",{className:"mt-1",children:"A markdown memo with sections: workflow summary, AI opportunities, feasibility constraints, risks, and recommended pilots."})]})}),e(Ua,{title:"Starter examples",subtitle:"Use these when you do not want to begin from a blank blueprint.",children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[e("div",{children:[e("strong",{className:"text-slate-100",children:"AI Opportunities:"})," workflow analysis and capability mapping feeding a ranked pilot brief."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Workflow Audit:"})," current-state mapping and failure analysis feeding an automation design review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Agentic Design:"})," role design and flow design feeding governance and safety review."]}),e("div",{children:[e("strong",{className:"text-slate-100",children:"Rollout:"})," process readiness and platform readiness feeding a launch plan and approval gate."]})]})})]})]})}):null,x==="mission"?e(Ua,{title:"Mission",subtitle:"Global brief, success criteria, and schedule.",icon:"clipboard-list",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(wt,{label:"Mission title",value:ee.title,onInput:l=>ce({title:l})}),e(wt,{label:"Mission ID",value:ee.mission_id,onInput:l=>ce({mission_id:l})})]}),e(ta,{children:"Use a short title a human operator would recognize later in the automation list."}),e(Uu,{value:ee.workspace_root,error:tt,open:se,browseDir:Me,search:Y,parentDir:$t,currentDir:We,directories:ze,onOpen:()=>{const l=String(ee.workspace_root||j||"/").trim();He(l||"/"),Ze(""),Oe(!0)},onClose:()=>{Oe(!1),Ze("")},onClear:()=>ce({workspace_root:""}),onSearchChange:Ze,onBrowseParent:()=>{$t&&He($t)},onBrowseDirectory:l=>He(l),onSelectDirectory:()=>{We&&(ce({workspace_root:We}),Oe(!1),Ze(""),n("ok",`Workspace selected: ${We}`))}}),e(ta,{children:"This is the shared working directory the mission can use for files and artifacts."}),tt?e("div",{className:"text-xs text-red-300",children:tt}):null,e(Rn,{label:"Mission goal",value:ee.goal,onInput:l=>ce({goal:l}),placeholder:"Describe the shared objective all participants are working toward."}),e(ta,{children:"Write the one shared outcome for the whole swarm, not a list of steps."}),e(Rn,{label:"Shared context",value:ee.shared_context||"",onInput:l=>ce({shared_context:l}),placeholder:"Shared constraints, references, context, and operator guidance."}),e(ta,{children:"Put the facts every lane should inherit here: audience, constraints, tone, deadlines, approved sources, and things to avoid."}),e(wt,{label:"Success criteria",value:ee.success_criteria.join(", "),onInput:l=>ce({success_criteria:ja(l)}),placeholder:"comma-separated"}),e(ta,{children:"These should be measurable checks like “brief includes 5 competitors” or “plan contains owner, timeline, and risks”."}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Schedule"}),e("select",{value:O,onInput:l=>_(l.target.value),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"manual",children:"Manual"}),e("option",{value:"interval",children:"Interval"}),e("option",{value:"cron",children:"Cron"})]})]}),O==="interval"?e(wt,{label:"Interval seconds",value:z,onInput:P}):null,O==="cron"?e(wt,{label:"Cron expression",value:Q,onInput:B}):null]})]}):null,x==="team"?e(Ua,{title:"Team",subtitle:"Templates, default model, concurrency, and mission limits.",icon:"users",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Orchestrator template"}),e("select",{value:ee.orchestrator_template_id||"",onInput:l=>ce({orchestrator_template_id:l.target.value}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"",children:"None"}),Bt.map(l=>e("option",{value:l.template_id,children:[l.template_id," (",l.role||"role",")"]},l.template_id))]})]}),e(wt,{label:"Allowed templates",value:(ee.team.allowed_template_ids||[]).join(", "),onInput:l=>ce({team:{...ee.team,allowed_template_ids:ja(l)}}),placeholder:"comma-separated"})]}),e(ta,{children:"The orchestrator keeps the mission coherent. Allowed templates restrict which reusable agent profiles lanes are permitted to use."}),e($r,{providerLabel:"Default model provider",modelLabel:"Default model",draft:$e,providers:rt,inheritLabel:"No team default",onChange:Le}),e("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-4",children:[e(wt,{label:"Max parallel agents",value:String(ee.team.max_parallel_agents||4),onInput:l=>ce({team:{...ee.team,max_parallel_agents:Math.max(1,Number.parseInt(String(l||"4"),10)||4)}}),type:"number"}),e(wt,{label:"Token ceiling",value:String(ee.team.mission_budget?.max_total_tokens||""),onInput:l=>ce({team:{...ee.team,mission_budget:{...ee.team.mission_budget||{},max_total_tokens:l?Number(l):void 0}}}),type:"number"}),e(wt,{label:"Cost ceiling USD",value:String(ee.team.mission_budget?.max_total_cost_usd||""),onInput:l=>ce({team:{...ee.team,mission_budget:{...ee.team.mission_budget||{},max_total_cost_usd:l?Number(l):void 0}}}),type:"number"}),e(wt,{label:"Tool-call ceiling",value:String(ee.team.mission_budget?.max_total_tool_calls||""),onInput:l=>ce({team:{...ee.team,mission_budget:{...ee.team.mission_budget||{},max_total_tool_calls:l?Number(l):void 0}}}),type:"number"})]}),e(wt,{label:"Allowed MCP servers",value:(ee.team.allowed_mcp_servers||[]).join(", "),onInput:l=>ce({team:{...ee.team,allowed_mcp_servers:ja(l)}}),placeholder:Et.map(l=>l.name).join(", ")}),e(ta,{children:"Team defaults apply everywhere unless a workstream or review stage overrides its own tool or MCP scope."})]}):null,x==="workstreams"?e(Ua,{title:"Workstreams",subtitle:"Scoped sub-objectives, dependencies, tools, MCP, and output contracts.",icon:"workflow",children:[e(ta,{children:"A workstream is one scoped lane of work. Give it one responsibility, one artifact to produce, and only the dependencies it truly needs."}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:dt,children:[e("i",{"data-lucide":"plus"}),"Add workstream"]})}),be.workstreams.map((l,b)=>{const T=re[l.workstream_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:l.title||`Workstream ${b+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>ce({workstreams:be.workstreams.filter(R=>R.workstream_id!==l.workstream_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(wt,{label:"Title",value:l.title,onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,title:R}:$)})}),e(wt,{label:"Role",value:l.role,onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,role:R}:$)})})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(wt,{label:"Phase",value:l.phase_id||"",onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,phase_id:R}:$)})}),e(wt,{label:"Lane",value:l.lane||"",onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,lane:R}:$)})}),e(wt,{label:"Priority",value:String(l.priority||0),onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,priority:Number(R)||0}:$)}),type:"number"})]}),e(ta,{children:"`Phase` says when this lane belongs in the mission. `Lane` groups related work. `Priority` decides ordering among runnable work in the same open phase."}),e(Rn,{label:"Objective",value:l.objective,onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,objective:R}:$)}),rows:3}),e(ta,{children:"Objective is the local assignment. Keep it crisp: what this lane must accomplish."}),e(Rn,{label:"Prompt",value:l.prompt,onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,prompt:R}:$)}),rows:5}),e(ta,{children:"Prompt is how the lane should operate: role, evidence standard, audience, format, and what good work looks like."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(wt,{label:"Depends on",value:l.depends_on.join(", "),onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,depends_on:ja(R)}:$)}),placeholder:"comma-separated stage ids"}),e(wt,{label:"Output contract kind",value:l.output_contract.kind,onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,output_contract:{...$.output_contract,kind:R}}:$)})})]}),e(ta,{children:"`Depends on` should list upstream stage IDs that must finish first. `Output contract kind` names the artifact downstream lanes expect."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(wt,{label:"Tool allowlist override",value:(l.tool_allowlist_override||[]).join(", "),onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,tool_allowlist_override:ja(R)}:$)}),placeholder:Fe.join(", ")}),e(wt,{label:"MCP servers override",value:(l.mcp_servers_override||[]).join(", "),onInput:R=>ce({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,mcp_servers_override:ja(R)}:$)}),placeholder:Et.map(R=>R.name).join(", ")})]}),e(ta,{children:"Leave tool and MCP overrides empty to inherit team defaults. Override only when this lane needs a narrower or different scope."}),e($r,{providerLabel:"Model provider",modelLabel:"Model",draft:T,providers:rt,onChange:R=>me($=>({...$,[l.workstream_id]:R}))})]},l.workstream_id)})]}):null,x==="review"?e(Ua,{title:"Review & Gates",subtitle:"Reviewer, tester, and approval stages.",icon:"shield-check",children:[e(ta,{children:"Use review stages to check quality or readiness before later work is promoted. Approval stages are the right place for human checkpoints."}),e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:S,children:[e("i",{"data-lucide":"plus"}),"Add review stage"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>ce({phases:[...be.phases,{phase_id:`phase_${be.phases.length+1}`,title:`Phase ${be.phases.length+1}`,description:"",execution_mode:"soft"}]}),children:[e("i",{"data-lucide":"copy-plus"}),"Add phase"]})]}),e("div",{className:"grid gap-2",children:be.phases.map((l,b)=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:e("div",{className:"grid gap-3 md:grid-cols-4",children:[e(wt,{label:"Phase ID",value:l.phase_id,onInput:T=>ce({phases:be.phases.map((R,$)=>$===b?{...R,phase_id:T}:R)})}),e(wt,{label:"Title",value:l.title,onInput:T=>ce({phases:be.phases.map((R,$)=>$===b?{...R,title:T}:R)})}),e(wt,{label:"Description",value:l.description||"",onInput:T=>ce({phases:be.phases.map((R,$)=>$===b?{...R,description:T}:R)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Execution mode"}),e("select",{value:l.execution_mode||"soft",onInput:T=>ce({phases:be.phases.map((R,$)=>$===b?{...R,execution_mode:T.target.value}:R)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"soft",children:"soft"}),e("option",{value:"barrier",children:"barrier"})]})]})]})},l.phase_id))}),e(ta,{children:"`soft` phases prefer the current open phase first. `barrier` phases hold later phases closed until earlier required work is complete."}),be.review_stages.map((l,b)=>{const T=q[l.stage_id]||{provider:"",model:""};return e("div",{className:"rounded-xl border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:l.title||`Review stage ${b+1}`}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>ce({review_stages:be.review_stages.filter(R=>R.stage_id!==l.stage_id)}),children:"Remove"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(wt,{label:"Title",value:l.title,onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,title:R}:$)})}),e("label",{className:"block text-sm",children:[e("div",{className:"mb-1 font-medium text-slate-200",children:"Stage kind"}),e("select",{value:l.stage_kind,onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,stage_kind:R.target.value}:$)}),className:"h-10 w-full rounded-lg border border-slate-700 bg-slate-950/80 px-3 text-sm text-slate-100 outline-none focus:border-amber-400",children:[e("option",{value:"review",children:"review"}),e("option",{value:"test",children:"test"}),e("option",{value:"approval",children:"approval"})]})]})]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e(wt,{label:"Targets",value:l.target_ids.join(", "),onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,target_ids:ja(R)}:$)}),placeholder:Ve.join(", ")}),e(wt,{label:"Phase",value:l.phase_id||"",onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,phase_id:R}:$)})}),e(wt,{label:"Lane",value:l.lane||"",onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,lane:R}:$)})})]}),e(ta,{children:"Targets are the stages this review or gate is checking. Put the review in the phase where that checkpoint should happen."}),e(Rn,{label:"Prompt",value:l.prompt,onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,prompt:R}:$)}),rows:4}),e(ta,{children:"Use the prompt to define what must be checked and what should trigger approve, rework, or fail."}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e(wt,{label:"Checklist",value:(l.checklist||[]).join(", "),onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,checklist:ja(R)}:$)}),placeholder:"comma-separated"}),e(wt,{label:"MCP servers override",value:(l.mcp_servers_override||[]).join(", "),onInput:R=>ce({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,mcp_servers_override:ja(R)}:$)}),placeholder:Et.map(R=>R.name).join(", ")})]}),e(ta,{children:"Checklist items should be concrete pass/fail checks, not broad wishes."}),e($r,{providerLabel:"Model provider",modelLabel:"Model",draft:T,providers:rt,onChange:R=>ge($=>({...$,[l.stage_id]:R}))})]},l.stage_id)})]}):null,x==="compile"?e(Ua,{title:"Compile & Run",subtitle:"Validate the mission graph before launch.",icon:"binary",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",disabled:M==="preview",onClick:()=>{ue()},children:[e("i",{"data-lucide":"refresh-cw"}),M==="preview"?"Compiling...":"Compile preview"]}),e("button",{className:"tcp-btn-primary h-8 px-3 text-xs",disabled:M==="apply",onClick:()=>{Ke()},children:[e("i",{"data-lucide":c?"save":"arrow-up-circle"}),M==="apply"?"Saving...":c?"Save automation":ne?"Create and run":"Create draft"]}),c?null:e("label",{className:"ml-2 inline-flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:ne,onChange:l=>I(l.target.checked)}),"Run immediately after create"]}),c&&p?e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>p(),children:"Cancel edit"}):null]}),y?e(la,{children:[e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Validation"}),Array.isArray(y?.validation)&&y.validation.length?e("div",{className:"grid gap-2",children:y.validation.map((l,b)=>e("div",{className:`rounded-lg border px-3 py-2 text-xs ${String(l?.severity||"").toLowerCase()==="warning"?"border-amber-500/40 bg-amber-500/10 text-amber-200":"border-slate-700 bg-slate-950/60 text-slate-200"}`,children:[e("div",{className:"font-medium",children:String(l?.code||l?.severity||"validation")}),e("div",{className:"mt-1",children:String(l?.message||"")})]},`${l?.code||"message"}-${b}`))}):e("div",{className:"tcp-subtle text-xs",children:"No validation warnings."})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Compiled automation"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:[e("div",{children:["name: ",String(y?.automation?.name||"—")]}),e("div",{children:["nodes:"," ",Array.isArray(y?.automation?.flow?.nodes)?y.automation.flow.nodes.length:0]}),e("div",{children:["agents:"," ",Array.isArray(y?.automation?.agents)?y.automation.agents.length:0]}),e("div",{children:["max parallel:"," ",String(y?.automation?.execution?.max_parallel_agents??"—")]})]})]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-900/70 p-3",children:[e("div",{className:"mb-2 text-sm font-semibold text-slate-100",children:"Node preview"}),e("div",{className:"grid gap-2",children:(Array.isArray(y?.node_previews)?y.node_previews:[]).map(l=>e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/70 p-3 text-xs text-slate-300",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-slate-100",children:String(l?.title||l?.node_id||"node")}),e("span",{className:"tcp-subtle",children:String(l?.node_id||"")}),e("span",{className:"tcp-subtle",children:["phase: ",String(l?.phase_id||"—")]}),e("span",{className:"tcp-subtle",children:["lane: ",String(l?.lane||"—")]}),e("span",{className:"tcp-subtle",children:["priority: ",String(l?.priority??"—")]})]}),e("div",{className:"mt-1",children:["depends on:"," ",Array.isArray(l?.depends_on)&&l.depends_on.length?l.depends_on.join(", "):"none"]}),e("div",{className:"mt-1",children:["tools:"," ",Array.isArray(l?.tool_allowlist)&&l.tool_allowlist.length?l.tool_allowlist.join(", "):"default"]}),e("div",{className:"mt-1",children:["MCP:"," ",Array.isArray(l?.mcp_servers)&&l.mcp_servers.length?l.mcp_servers.join(", "):"default"]})]},String(l?.node_id||"")))})]})]}):e("div",{className:"tcp-subtle text-xs",children:"Compile the mission to inspect validation, compiled nodes, and execution shape."})]}):null]})}const Fu=`kind: extract_format
|
|
2349
2349
|
description: Two-node validator-backed workflow for cheap optimization smoke tests.
|
|
2350
2350
|
status: draft
|
|
2351
2351
|
schedule:
|
|
@@ -2392,7 +2392,7 @@ flow:
|
|
|
2392
2392
|
retry_policy:
|
|
2393
2393
|
max_attempts: 1
|
|
2394
2394
|
timeout_ms: 60000
|
|
2395
|
-
`,
|
|
2395
|
+
`,Lu=`kind: summary
|
|
2396
2396
|
description: Single-node validator-backed workflow for cheap optimization smoke tests.
|
|
2397
2397
|
status: draft
|
|
2398
2398
|
schedule:
|
|
@@ -2428,33 +2428,33 @@ flow:
|
|
|
2428
2428
|
retry_policy:
|
|
2429
2429
|
max_attempts: 1
|
|
2430
2430
|
timeout_ms: 60000
|
|
2431
|
-
`;function xr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Is(a){const t=String(a||"").trim().toLowerCase();return t==="running"?"tcp-badge-warn":t.includes("paused")?"tcp-badge-info":t==="completed"?"tcp-badge-ok":t==="failed"?"tcp-badge-err":t.includes("approval")?"tcp-badge-warn":"tcp-badge-info"}function Wn(a){const t=Number(a);return Number.isFinite(t)?t.toFixed(3):"n/a"}const _u=Object.assign({"./smoke-workflows/extract-format.yaml":ku,"./smoke-workflows/summary.yaml":Nu}),Su=Object.entries(_u).map(([a,t])=>{const n=lr.parse(t);if(!n||typeof n!="object")throw new Error("Invalid smoke workflow template at "+a+": expected a YAML object.");const r=n,s=String(r.kind||"").trim();if(s!=="summary"&&s!=="extract_format")throw new Error("Invalid smoke workflow template at "+a+": missing kind.");return{kind:s,payload:r}}).sort((a,t)=>a.kind.localeCompare(t.kind));function Iu(a,t){const n=Su.find(d=>d.kind===a);if(!n)throw new Error("Unknown smoke workflow kind: "+a);const r=structuredClone(n.payload),{kind:s,...c}=r;return c.workspace_root=String(t||"").trim(),c}function Cu({client:a,toast:t}){const n=na(),[r,s]=w(""),[c,d]=w({name:"",sourceWorkflowId:"",smokeWorkspaceRoot:"",objectiveRef:"objective.md",evalRef:"eval.yaml",mutationPolicyRef:"mutation_policy.yaml",scopeRef:"scope.yaml",budgetRef:"budget.yaml",modelProvider:"",modelId:"",startImmediately:!0}),u=Y({queryKey:["optimizations","workflows","automations-v2"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]})}),p=Y({queryKey:["optimizations","list"],queryFn:()=>a?.optimizations?.list?.().catch(()=>({optimizations:[]}))??Promise.resolve({optimizations:[]})}),N=Y({queryKey:["optimizations","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),E=Y({queryKey:["optimizations","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),x=Y({queryKey:["optimizations","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),C=K(()=>xr(p.data,"optimizations"),[p.data]),O=K(()=>{const v=Array.isArray(E.data?.all)?E.data.all:[],U=x.data?.providers||{};return v.map(ue=>({id:String(ue?.id||"").trim(),models:Object.keys(ue?.models||{}).sort(),configured:!!U[String(ue?.id||"").trim()]})).filter(ue=>ue.id).sort((ue,ee)=>ue.id.localeCompare(ee.id))},[E.data,x.data]),k=K(()=>{const v=O.find(U=>U.id===String(c.modelProvider||"").trim());return Array.isArray(v?.models)?v.models:[]},[c.modelProvider,O]);fe(()=>{const v=String(N.data?.workspaceRoot||N.data?.workspace_root||"").trim();v&&d(U=>String(U.smokeWorkspaceRoot||"").trim()?U:{...U,smokeWorkspaceRoot:`${v}/docs/internal/optimization-smoke-pack`})},[N.data]);const z=r||String(C[0]?.optimization_id||"").trim(),A=Y({queryKey:["optimizations","detail",z],enabled:!!z,queryFn:()=>a.optimizations.get(z)}),G=Y({queryKey:["optimizations","experiments",z],enabled:!!z,queryFn:()=>a.optimizations.listExperiments(z)}),B=xe({mutationFn:async()=>{const v=String(c.sourceWorkflowId||"").trim();if(!v)throw new Error("Source workflow is required.");const U={name:String(c.name||"").trim()||void 0,source_workflow_id:v,artifacts:{objective_ref:String(c.objectiveRef||"").trim(),eval_ref:String(c.evalRef||"").trim(),mutation_policy_ref:String(c.mutationPolicyRef||"").trim(),scope_ref:String(c.scopeRef||"").trim(),budget_ref:String(c.budgetRef||"").trim()},execution_override:String(c.modelProvider||"").trim()&&String(c.modelId||"").trim()?{provider_id:String(c.modelProvider||"").trim(),model_id:String(c.modelId||"").trim()}:void 0},ue=await a.optimizations.create(U);if(c.startImmediately){const ee=String(ue?.optimization?.optimization_id||"").trim();ee&&await a.optimizations.action(ee,{action:"start"})}return ue},onSuccess:async v=>{const U=String(v?.optimization?.optimization_id||"").trim();t("ok","Optimization campaign created."),U&&s(U),await n.invalidateQueries({queryKey:["optimizations"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),ae=xe({mutationFn:async v=>{const U=String(c.smokeWorkspaceRoot||"").trim();if(!U)throw new Error("Smoke workflow workspace root is required.");if(!a?.automationsV2?.create)throw new Error("Workflow creation client is unavailable.");const ue=Iu(v,U);return a.automationsV2.create(ue)},onSuccess:async(v,U)=>{const ue=String(v?.automation?.automation_id||v?.automation?.automationId||"").trim();d(ee=>({...ee,sourceWorkflowId:ue||ee.sourceWorkflowId,name:ue&&!String(ee.name||"").trim()?`Optimize ${String(v?.automation?.name||ue).trim()}`:ee.name})),t("ok",U==="summary"?"Smoke summary workflow created and selected.":"Smoke extract-format workflow created and selected."),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),S=xe({mutationFn:async({optimizationId:v,action:U,experimentId:ue})=>a.optimizations.action(v,{action:U,experiment_id:ue}),onSuccess:async()=>{t("ok","Optimization action applied."),await n.invalidateQueries({queryKey:["optimizations"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),I=xe({mutationFn:async({optimizationId:v,experimentId:U})=>a.optimizations.applyWinner(v,U),onSuccess:async()=>{t("ok","Approved winner applied to the live workflow."),await n.invalidateQueries({queryKey:["optimizations"]}),await n.invalidateQueries({queryKey:["optimizations","detail",z]}),await n.invalidateQueries({queryKey:["optimizations","experiments",z]}),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),H=xr(u.data,"automations").map(v=>({id:String(v?.automation_id||v?.automationId||v?.id||"").trim(),name:String(v?.name||v?.automation_id||"Workflow").trim()})),q=A.data?.optimization||null,ye=xr(G.data,"experiments"),y=q?.baseline_metrics||null;return e("div",{className:"grid gap-4 lg:grid-cols-[minmax(320px,380px),minmax(0,1fr)]",children:[e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"mb-1 text-sm font-semibold text-slate-100",children:"New Optimization Campaign"}),e("div",{className:"tcp-subtle text-xs",children:"Create a shadow-eval workflow optimization campaign from an existing automation."}),e("div",{className:"mt-1 text-xs text-slate-500",children:["Inspired by"," ",e("a",{className:"text-amber-300 hover:text-amber-200",href:"https://github.com/karpathy/autoresearch",target:"_blank",rel:"noreferrer",children:"karpathy/autoresearch"}),"."]}),e("div",{className:"mt-3 grid gap-3",children:[e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Name"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.name,onChange:v=>d(U=>({...U,name:v.target.value})),placeholder:"Optimize research brief workflow"})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Source workflow"}),e("select",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.sourceWorkflowId,onChange:v=>d(U=>({...U,sourceWorkflowId:v.target.value})),children:[e("option",{value:"",children:"Select a workflow"}),H.map(v=>e("option",{value:v.id,children:v.name},v.id))]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:[e("div",{className:"text-xs font-medium text-slate-200",children:"Need a cheap target first?"}),e("div",{className:"mt-1 text-[11px] text-slate-500",children:"Create a tiny validator-backed workflow in the smoke-pack workspace, then use it as the optimization source."}),e("label",{className:"mt-3 grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Smoke workspace root"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.smokeWorkspaceRoot,onChange:v=>d(U=>({...U,smokeWorkspaceRoot:v.target.value})),placeholder:"/abs/path/to/docs/internal/optimization-smoke-pack"})]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>ae.mutate("summary"),disabled:ae.isPending,children:"Create Smoke Summary"}),e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>ae.mutate("extract_format"),disabled:ae.isPending,children:"Create Extract + Format"})]})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Model provider"}),e("select",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.modelProvider,onChange:v=>d(U=>({...U,modelProvider:v.target.value,modelId:v.target.value&&U.modelProvider!==v.target.value?"":U.modelId})),children:[e("option",{value:"",children:"Use workflow/default model"}),O.map(v=>e("option",{value:v.id,children:[v.id,v.configured?"":" (catalog only)"]},v.id))]})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Model id"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.modelId,onChange:v=>d(U=>({...U,modelId:v.target.value})),placeholder:c.modelProvider?"Pick a cheaper model for this campaign":"Optional",list:"optimization-model-ids"}),e("datalist",{id:"optimization-model-ids",children:k.map(v=>e("option",{value:v},v))}),e("span",{className:"tcp-subtle text-[11px]",children:"Fixed for the whole campaign. Leave blank to use the workflow's existing model settings."})]}),[["Objective ref","objectiveRef"],["Eval ref","evalRef"],["Mutation policy ref","mutationPolicyRef"],["Scope ref","scopeRef"],["Budget ref","budgetRef"]].map(([v,U])=>e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:v}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c[U],onChange:ue=>d(ee=>({...ee,[U]:ue.target.value}))})]},U)),e("label",{className:"flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:c.startImmediately,onChange:v=>d(U=>({...U,startImmediately:v.target.checked}))}),"Start immediately after create"]}),e("button",{className:"tcp-btn h-10 px-3 text-sm",onClick:()=>B.mutate(),disabled:B.isPending,children:B.isPending?"Creating...":"Create Campaign"})]})]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Campaigns"}),e("span",{className:"tcp-badge-info",children:C.length})]}),e("div",{className:"grid gap-2",children:C.length?C.map(v=>{const U=String(v?.optimization_id||"").trim();return e("button",{type:"button",className:`rounded-xl border px-3 py-3 text-left transition ${z===U?"border-amber-400/60 bg-amber-400/10":"border-slate-700/50 bg-slate-950/40 hover:border-slate-600"}`,onClick:()=>s(U),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium text-slate-100",children:String(v?.name||U||"Optimization")}),e("span",{className:Is(v?.status),children:String(v?.status||"draft")})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:["workflow:"," ",String(v?.source_workflow_name||v?.source_workflow_id||"unknown")]})]},U)}):e(Le,{text:"No optimization campaigns yet."})})]})]}),e("div",{className:"grid gap-4",children:q?e(aa,{children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"text-lg font-semibold text-slate-100",children:String(q?.name||q?.optimization_id||"Optimization")}),e("div",{className:"mt-1 text-sm text-slate-400",children:["Source workflow:"," ",String(q?.source_workflow_name||q?.source_workflow_id||"unknown")]}),e("div",{className:"mt-1 text-xs text-slate-500",children:["baseline: ",String(q?.baseline_snapshot_hash||"").slice(0,12)]}),q?.execution_override?e("div",{className:"mt-1 text-xs text-slate-500",children:["model: ",String(q.execution_override.provider_id||"").trim(),"/",String(q.execution_override.model_id||"").trim()]}):null]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({optimizationId:z,action:"start"}),disabled:S.isPending,children:"Start"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({optimizationId:z,action:"pause"}),disabled:S.isPending,children:"Pause"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({optimizationId:z,action:"resume"}),disabled:S.isPending,children:"Resume"})]})]}),e("div",{className:"mt-4 grid gap-3 md:grid-cols-4",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Status"}),e("div",{className:"mt-1 text-sm text-slate-100",children:String(q?.status||"draft")})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Pass Rate"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?Wn(y.artifact_validator_pass_rate):"n/a"})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Unmet Reqs"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?Wn(y.unmet_requirement_count):"n/a"})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Blocked Rate"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?Wn(y.blocked_node_rate):"n/a"})]})]}),q?.last_pause_reason?e("div",{className:"mt-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:String(q.last_pause_reason)}):null]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Experiments"}),e("span",{className:"tcp-badge-info",children:ye.length})]}),ye.length?e("div",{className:"overflow-x-auto",children:e("table",{className:"min-w-full text-left text-sm",children:[e("thead",{className:"text-xs uppercase tracking-[0.22em] text-slate-500",children:e("tr",{children:[e("th",{className:"px-2 py-2",children:"Experiment"}),e("th",{className:"px-2 py-2",children:"Status"}),e("th",{className:"px-2 py-2",children:"Mutation"}),e("th",{className:"px-2 py-2",children:"Pass"}),e("th",{className:"px-2 py-2",children:"Recommendation"}),e("th",{className:"px-2 py-2",children:"Action"})]})}),e("tbody",{children:ye.map(v=>{const U=String(v?.experiment_id||"").trim(),ue=v?.phase1_metrics||{};return e("tr",{className:"border-t border-slate-800",children:[e("td",{className:"px-2 py-3 text-slate-200",children:U||"unknown"}),e("td",{className:"px-2 py-3",children:e("span",{className:Is(v?.status),children:String(v?.status||"draft")})}),e("td",{className:"px-2 py-3 text-slate-300",children:String(v?.mutation_summary||"pending")}),e("td",{className:"px-2 py-3 text-slate-300",children:ue?Wn(ue.artifact_validator_pass_rate):"n/a"}),e("td",{className:"px-2 py-3 text-slate-300",children:String(v?.promotion_recommendation||"n/a")}),e("td",{className:"px-2 py-3",children:e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>S.mutate({optimizationId:z,action:"approve_winner",experimentId:U}),disabled:!U||S.isPending,children:"Approve"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>S.mutate({optimizationId:z,action:"reject_winner",experimentId:U}),disabled:!U||S.isPending,children:"Reject"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>I.mutate({optimizationId:z,experimentId:U}),disabled:!U||I.isPending||String(v?.status||"").trim().toLowerCase()!=="promotion_approved",children:"Apply"})]})})]},U)})})]})}):e(Le,{text:"No experiments recorded for this campaign yet."})]})]}):e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-6",children:e(Le,{text:"Select or create an optimization campaign to inspect it."})})})]})}const Au=Object.assign({"./automation-wizard.yaml":eu});function Pu(a){const t=lr.parse(a);if(!t||typeof t!="object")throw new Error("Invalid automation wizard config: expected a YAML object.");const n=t,r=n.defaults||{},s=n.steps,c=n.schedulePresets,d=n.executionModes,u=n.goalExamples;if(!Array.isArray(s)||!s.length)throw new Error("Invalid automation wizard config: steps must be a non-empty array.");if(!Array.isArray(c)||!c.length)throw new Error("Invalid automation wizard config: schedulePresets must be a non-empty array.");if(!Array.isArray(d)||!d.length)throw new Error("Invalid automation wizard config: executionModes must be a non-empty array.");if(!Array.isArray(u)||!u.length)throw new Error("Invalid automation wizard config: goalExamples must be a non-empty array.");return{defaults:{schedulePreset:String(r.schedulePreset||"").trim()||"Every morning",mode:r.mode==="single"||r.mode==="team"||r.mode==="swarm"?r.mode:"team",maxAgents:String(r.maxAgents||"").trim()||"4"},steps:s.map(p=>String(p||"").trim()).filter(Boolean),schedulePresets:c.map(p=>({label:String(p?.label||"").trim(),desc:String(p?.desc||"").trim(),icon:String(p?.icon||"").trim(),cron:String(p?.cron||"").trim(),intervalSeconds:p?.intervalSeconds===void 0||p?.intervalSeconds===null?void 0:Number(p.intervalSeconds)})),executionModes:d.map(p=>({id:p?.id==="single"||p?.id==="team"||p?.id==="swarm"?p.id:"team",label:String(p?.label||"").trim(),icon:String(p?.icon||"").trim(),desc:String(p?.desc||"").trim(),bestFor:String(p?.bestFor||"").trim()})),goalExamples:u.map(p=>String(p||"").trim()).filter(Boolean)}}const ma=Pu(Object.values(Au)[0]||""),Cs="tandem.automations.plannerSeed",As="tandem.automations.studioHandoff";function Ps(a,t,n=""){return{goal:"",workspaceRoot:n,schedulePreset:ma.defaults.schedulePreset,cron:"",mode:ma.defaults.mode,maxAgents:ma.defaults.maxAgents,routedSkill:"",routingConfidence:"",modelProvider:String(a||""),modelId:String(t||""),plannerModelProvider:"",plannerModelId:"",roleModelsJson:"",toolAccessMode:"all",customToolsText:"",selectedMcpServers:[],exportPackDraft:!1,advancedMode:!1,customSkillName:"",customSkillDescription:"",customWorkflowKind:"pack_builder_recipe"}}function Ea(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function qi(a){return Array.isArray(a?.servers)?a.servers.map(t=>{const n=String(t?.name||"").trim();return n?{name:n,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):a&&typeof a=="object"?Object.entries(a).map(([t,n])=>{const r=String(t||"").trim();if(!r)return null;const s=n&&typeof n=="object"?n:{};return{name:r,connected:!!s.connected,enabled:s.enabled!==!1}}).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):[]}function Tu(a){const t=String(a.cron||"").trim();if(t)return{cron:{expression:t}};const n=ma.schedulePresets.find(r=>r.label===a.schedulePreset);return n?.intervalSeconds?{interval_seconds:{seconds:n.intervalSeconds}}:n?.cron?{cron:{expression:n.cron}}:{type:"manual"}}function Ru(a){const t=String(a?.cron?.expression||a?.cron_expression||"").trim();if(t)return t;const n=Number(a?.interval_seconds?.seconds);return Number.isFinite(n)&&n>0?n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`:"manual"}function Mi(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function Pn(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function tr(a,t){const n=String(a||"").trim(),r=String(t||"").trim();return!n&&!r?"":n?r?"":"Planner model is required when a planner provider is set.":"Planner model provider is required when a planner model is set."}function kr(a,t){const n=String(a||"").trim(),r=String(t||"").trim();return!n&&!r?"":n?r?"":"Model is required when a provider is set.":"Model provider is required when a model is set."}function qu(a){let t;const n=String(a.roleModelsJson||"").trim();if(n)try{const u=JSON.parse(n);u&&typeof u=="object"&&!Array.isArray(u)&&(t=u)}catch{t=void 0}const r=String(a.plannerModelProvider||"").trim(),s=String(a.plannerModelId||"").trim();r&&s&&(t={...t||{}},t.planner={provider_id:r,model_id:s});const c=a.mode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxAgents||"4"),10)||4)):1,d={execution_mode:a.mode,max_parallel_agents:c};return String(a.modelProvider||"").trim()&&(d.model_provider=String(a.modelProvider).trim()),String(a.modelId||"").trim()&&(d.model_id=String(a.modelId).trim()),t&&Object.keys(t).length&&(d.role_models=t),d}function Mu(a){const t=String(a||"").trim();if(!t)return"";try{const n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?"Role model overrides must be a JSON object.":""}catch{return"Role model overrides must be valid JSON."}}function $i(a){const t=String(a?.type||"").trim().toLowerCase(),n=String(a?.cron?.expression||a?.cron_expression||a?.cron||"").trim(),r=Number(a?.interval_seconds?.seconds||a?.interval_seconds||a?.intervalSeconds||3600),s=Number.isFinite(r)&&r>0?Math.round(r):3600;return{scheduleKind:t==="manual"?"manual":n?"cron":"interval",cronExpression:n,intervalSeconds:s}}function $u(a){let t="",n=!1;for(const r of String(a||"").trim())/^[a-z0-9]$/i.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="_",n=!0);return t.replace(/^_+|_+$/g,"")||"mcp"}function Un(a){const t=new Set,n=[];for(const r of a){const s=String(r||"").trim();!s||t.has(s)||(t.add(s),n.push(s))}return n}function zn(a,t){const n=new Set,r=[];for(const s of[t,...a]){const c=String(s||"").trim();!c||n.has(c)||(n.add(c),r.push(c))}return r}function Vr(a){return Un(String(a||"").split(/[\n,]/g).map(t=>String(t||"").trim()).filter(Boolean))}function Ou(a){return Un(a).join(`
|
|
2432
|
-
`)}function
|
|
2431
|
+
`;function Or(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Ks(a){const t=String(a||"").trim().toLowerCase();return t==="running"?"tcp-badge-warn":t.includes("paused")?"tcp-badge-info":t==="completed"?"tcp-badge-ok":t==="failed"?"tcp-badge-err":t.includes("approval")?"tcp-badge-warn":"tcp-badge-info"}function ar(a){const t=Number(a);return Number.isFinite(t)?t.toFixed(3):"n/a"}const Ku=Object.assign({"./smoke-workflows/extract-format.yaml":Fu,"./smoke-workflows/summary.yaml":Lu}),Wu=Object.entries(Ku).map(([a,t])=>{const n=wr.parse(t);if(!n||typeof n!="object")throw new Error("Invalid smoke workflow template at "+a+": expected a YAML object.");const r=n,s=String(r.kind||"").trim();if(s!=="summary"&&s!=="extract_format")throw new Error("Invalid smoke workflow template at "+a+": missing kind.");return{kind:s,payload:r}}).sort((a,t)=>a.kind.localeCompare(t.kind));function zu(a,t){const n=Wu.find(d=>d.kind===a);if(!n)throw new Error("Unknown smoke workflow kind: "+a);const r=structuredClone(n.payload),{kind:s,...c}=r;return c.workspace_root=String(t||"").trim(),c}function Ju({client:a,toast:t}){const n=ca(),[r,s]=w(""),[c,d]=w({name:"",sourceWorkflowId:"",smokeWorkspaceRoot:"",objectiveRef:"objective.md",evalRef:"eval.yaml",mutationPolicyRef:"mutation_policy.yaml",scopeRef:"scope.yaml",budgetRef:"budget.yaml",modelProvider:"",modelId:"",startImmediately:!0}),u=V({queryKey:["optimizations","workflows","automations-v2"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]})}),p=V({queryKey:["optimizations","list"],queryFn:()=>a?.optimizations?.list?.().catch(()=>({optimizations:[]}))??Promise.resolve({optimizations:[]})}),N=V({queryKey:["optimizations","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),E=V({queryKey:["optimizations","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),x=V({queryKey:["optimizations","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),A=F(()=>Or(p.data,"optimizations"),[p.data]),O=F(()=>{const v=Array.isArray(E.data?.all)?E.data.all:[],j=x.data?.providers||{};return v.map(he=>({id:String(he?.id||"").trim(),models:Object.keys(he?.models||{}).sort(),configured:!!j[String(he?.id||"").trim()]})).filter(he=>he.id).sort((he,ee)=>he.id.localeCompare(ee.id))},[E.data,x.data]),_=F(()=>{const v=O.find(j=>j.id===String(c.modelProvider||"").trim());return Array.isArray(v?.models)?v.models:[]},[c.modelProvider,O]);fe(()=>{const v=String(N.data?.workspaceRoot||N.data?.workspace_root||"").trim();v&&d(j=>String(j.smokeWorkspaceRoot||"").trim()?j:{...j,smokeWorkspaceRoot:`${v}/docs/internal/optimization-smoke-pack`})},[N.data]);const z=r||String(A[0]?.optimization_id||"").trim(),P=V({queryKey:["optimizations","detail",z],enabled:!!z,queryFn:()=>a.optimizations.get(z)}),Q=V({queryKey:["optimizations","experiments",z],enabled:!!z,queryFn:()=>a.optimizations.listExperiments(z)}),B=ke({mutationFn:async()=>{const v=String(c.sourceWorkflowId||"").trim();if(!v)throw new Error("Source workflow is required.");const j={name:String(c.name||"").trim()||void 0,source_workflow_id:v,artifacts:{objective_ref:String(c.objectiveRef||"").trim(),eval_ref:String(c.evalRef||"").trim(),mutation_policy_ref:String(c.mutationPolicyRef||"").trim(),scope_ref:String(c.scopeRef||"").trim(),budget_ref:String(c.budgetRef||"").trim()},execution_override:String(c.modelProvider||"").trim()&&String(c.modelId||"").trim()?{provider_id:String(c.modelProvider||"").trim(),model_id:String(c.modelId||"").trim()}:void 0},he=await a.optimizations.create(j);if(c.startImmediately){const ee=String(he?.optimization?.optimization_id||"").trim();ee&&await a.optimizations.action(ee,{action:"start"})}return he},onSuccess:async v=>{const j=String(v?.optimization?.optimization_id||"").trim();t("ok","Optimization campaign created."),j&&s(j),await n.invalidateQueries({queryKey:["optimizations"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),ne=ke({mutationFn:async v=>{const j=String(c.smokeWorkspaceRoot||"").trim();if(!j)throw new Error("Smoke workflow workspace root is required.");if(!a?.automationsV2?.create)throw new Error("Workflow creation client is unavailable.");const he=zu(v,j);return a.automationsV2.create(he)},onSuccess:async(v,j)=>{const he=String(v?.automation?.automation_id||v?.automation?.automationId||"").trim();d(ee=>({...ee,sourceWorkflowId:he||ee.sourceWorkflowId,name:he&&!String(ee.name||"").trim()?`Optimize ${String(v?.automation?.name||he).trim()}`:ee.name})),t("ok",j==="summary"?"Smoke summary workflow created and selected.":"Smoke extract-format workflow created and selected."),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),I=ke({mutationFn:async({optimizationId:v,action:j,experimentId:he})=>a.optimizations.action(v,{action:j,experiment_id:he}),onSuccess:async()=>{t("ok","Optimization action applied."),await n.invalidateQueries({queryKey:["optimizations"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),C=ke({mutationFn:async({optimizationId:v,experimentId:j})=>a.optimizations.applyWinner(v,j),onSuccess:async()=>{t("ok","Approved winner applied to the live workflow."),await n.invalidateQueries({queryKey:["optimizations"]}),await n.invalidateQueries({queryKey:["optimizations","detail",z]}),await n.invalidateQueries({queryKey:["optimizations","experiments",z]}),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),H=Or(u.data,"automations").map(v=>({id:String(v?.automation_id||v?.automationId||v?.id||"").trim(),name:String(v?.name||v?.automation_id||"Workflow").trim()})),M=P.data?.optimization||null,xe=Or(Q.data,"experiments"),y=M?.baseline_metrics||null;return e("div",{className:"grid gap-4 lg:grid-cols-[minmax(320px,380px),minmax(0,1fr)]",children:[e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"mb-1 text-sm font-semibold text-slate-100",children:"New Optimization Campaign"}),e("div",{className:"tcp-subtle text-xs",children:"Create a shadow-eval workflow optimization campaign from an existing automation."}),e("div",{className:"mt-1 text-xs text-slate-500",children:["Inspired by"," ",e("a",{className:"text-amber-300 hover:text-amber-200",href:"https://github.com/karpathy/autoresearch",target:"_blank",rel:"noreferrer",children:"karpathy/autoresearch"}),"."]}),e("div",{className:"mt-3 grid gap-3",children:[e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Name"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.name,onChange:v=>d(j=>({...j,name:v.target.value})),placeholder:"Optimize research brief workflow"})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Source workflow"}),e("select",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.sourceWorkflowId,onChange:v=>d(j=>({...j,sourceWorkflowId:v.target.value})),children:[e("option",{value:"",children:"Select a workflow"}),H.map(v=>e("option",{value:v.id,children:v.name},v.id))]})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:[e("div",{className:"text-xs font-medium text-slate-200",children:"Need a cheap target first?"}),e("div",{className:"mt-1 text-[11px] text-slate-500",children:"Create a tiny validator-backed workflow in the smoke-pack workspace, then use it as the optimization source."}),e("label",{className:"mt-3 grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Smoke workspace root"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.smokeWorkspaceRoot,onChange:v=>d(j=>({...j,smokeWorkspaceRoot:v.target.value})),placeholder:"/abs/path/to/docs/internal/optimization-smoke-pack"})]}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>ne.mutate("summary"),disabled:ne.isPending,children:"Create Smoke Summary"}),e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>ne.mutate("extract_format"),disabled:ne.isPending,children:"Create Extract + Format"})]})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Model provider"}),e("select",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.modelProvider,onChange:v=>d(j=>({...j,modelProvider:v.target.value,modelId:v.target.value&&j.modelProvider!==v.target.value?"":j.modelId})),children:[e("option",{value:"",children:"Use workflow/default model"}),O.map(v=>e("option",{value:v.id,children:[v.id,v.configured?"":" (catalog only)"]},v.id))]})]}),e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:"Model id"}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c.modelId,onChange:v=>d(j=>({...j,modelId:v.target.value})),placeholder:c.modelProvider?"Pick a cheaper model for this campaign":"Optional",list:"optimization-model-ids"}),e("datalist",{id:"optimization-model-ids",children:_.map(v=>e("option",{value:v},v))}),e("span",{className:"tcp-subtle text-[11px]",children:"Fixed for the whole campaign. Leave blank to use the workflow's existing model settings."})]}),[["Objective ref","objectiveRef"],["Eval ref","evalRef"],["Mutation policy ref","mutationPolicyRef"],["Scope ref","scopeRef"],["Budget ref","budgetRef"]].map(([v,j])=>e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:v}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c[j],onChange:he=>d(ee=>({...ee,[j]:he.target.value}))})]},j)),e("label",{className:"flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:c.startImmediately,onChange:v=>d(j=>({...j,startImmediately:v.target.checked}))}),"Start immediately after create"]}),e("button",{className:"tcp-btn h-10 px-3 text-sm",onClick:()=>B.mutate(),disabled:B.isPending,children:B.isPending?"Creating...":"Create Campaign"})]})]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Campaigns"}),e("span",{className:"tcp-badge-info",children:A.length})]}),e("div",{className:"grid gap-2",children:A.length?A.map(v=>{const j=String(v?.optimization_id||"").trim();return e("button",{type:"button",className:`rounded-xl border px-3 py-3 text-left transition ${z===j?"border-amber-400/60 bg-amber-400/10":"border-slate-700/50 bg-slate-950/40 hover:border-slate-600"}`,onClick:()=>s(j),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium text-slate-100",children:String(v?.name||j||"Optimization")}),e("span",{className:Ks(v?.status),children:String(v?.status||"draft")})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:["workflow:"," ",String(v?.source_workflow_name||v?.source_workflow_id||"unknown")]})]},j)}):e(je,{text:"No optimization campaigns yet."})})]})]}),e("div",{className:"grid gap-4",children:M?e(la,{children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"text-lg font-semibold text-slate-100",children:String(M?.name||M?.optimization_id||"Optimization")}),e("div",{className:"mt-1 text-sm text-slate-400",children:["Source workflow:"," ",String(M?.source_workflow_name||M?.source_workflow_id||"unknown")]}),e("div",{className:"mt-1 text-xs text-slate-500",children:["baseline: ",String(M?.baseline_snapshot_hash||"").slice(0,12)]}),M?.execution_override?e("div",{className:"mt-1 text-xs text-slate-500",children:["model: ",String(M.execution_override.provider_id||"").trim(),"/",String(M.execution_override.model_id||"").trim()]}):null]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>I.mutate({optimizationId:z,action:"start"}),disabled:I.isPending,children:"Start"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>I.mutate({optimizationId:z,action:"pause"}),disabled:I.isPending,children:"Pause"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>I.mutate({optimizationId:z,action:"resume"}),disabled:I.isPending,children:"Resume"})]})]}),e("div",{className:"mt-4 grid gap-3 md:grid-cols-4",children:[e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Status"}),e("div",{className:"mt-1 text-sm text-slate-100",children:String(M?.status||"draft")})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Pass Rate"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?ar(y.artifact_validator_pass_rate):"n/a"})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Unmet Reqs"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?ar(y.unmet_requirement_count):"n/a"})]}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/60 p-3",children:[e("div",{className:"text-[11px] uppercase tracking-[0.22em] text-slate-500",children:"Blocked Rate"}),e("div",{className:"mt-1 text-sm text-slate-100",children:y?ar(y.blocked_node_rate):"n/a"})]})]}),M?.last_pause_reason?e("div",{className:"mt-3 rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 text-sm text-amber-200",children:String(M.last_pause_reason)}):null]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-4",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"text-sm font-semibold text-slate-100",children:"Experiments"}),e("span",{className:"tcp-badge-info",children:xe.length})]}),xe.length?e("div",{className:"overflow-x-auto",children:e("table",{className:"min-w-full text-left text-sm",children:[e("thead",{className:"text-xs uppercase tracking-[0.22em] text-slate-500",children:e("tr",{children:[e("th",{className:"px-2 py-2",children:"Experiment"}),e("th",{className:"px-2 py-2",children:"Status"}),e("th",{className:"px-2 py-2",children:"Mutation"}),e("th",{className:"px-2 py-2",children:"Pass"}),e("th",{className:"px-2 py-2",children:"Recommendation"}),e("th",{className:"px-2 py-2",children:"Action"})]})}),e("tbody",{children:xe.map(v=>{const j=String(v?.experiment_id||"").trim(),he=v?.phase1_metrics||{};return e("tr",{className:"border-t border-slate-800",children:[e("td",{className:"px-2 py-3 text-slate-200",children:j||"unknown"}),e("td",{className:"px-2 py-3",children:e("span",{className:Ks(v?.status),children:String(v?.status||"draft")})}),e("td",{className:"px-2 py-3 text-slate-300",children:String(v?.mutation_summary||"pending")}),e("td",{className:"px-2 py-3 text-slate-300",children:he?ar(he.artifact_validator_pass_rate):"n/a"}),e("td",{className:"px-2 py-3 text-slate-300",children:String(v?.promotion_recommendation||"n/a")}),e("td",{className:"px-2 py-3",children:e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>I.mutate({optimizationId:z,action:"approve_winner",experimentId:j}),disabled:!j||I.isPending,children:"Approve"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>I.mutate({optimizationId:z,action:"reject_winner",experimentId:j}),disabled:!j||I.isPending,children:"Reject"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>C.mutate({optimizationId:z,experimentId:j}),disabled:!j||C.isPending||String(v?.status||"").trim().toLowerCase()!=="promotion_approved",children:"Apply"})]})})]},j)})})]})}):e(je,{text:"No experiments recorded for this campaign yet."})]})]}):e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-6",children:e(je,{text:"Select or create an optimization campaign to inspect it."})})})]})}const Qu=Object.assign({"./automation-wizard.yaml":yu});function Hu(a){const t=wr.parse(a);if(!t||typeof t!="object")throw new Error("Invalid automation wizard config: expected a YAML object.");const n=t,r=n.defaults||{},s=n.steps,c=n.schedulePresets,d=n.executionModes,u=n.goalExamples;if(!Array.isArray(s)||!s.length)throw new Error("Invalid automation wizard config: steps must be a non-empty array.");if(!Array.isArray(c)||!c.length)throw new Error("Invalid automation wizard config: schedulePresets must be a non-empty array.");if(!Array.isArray(d)||!d.length)throw new Error("Invalid automation wizard config: executionModes must be a non-empty array.");if(!Array.isArray(u)||!u.length)throw new Error("Invalid automation wizard config: goalExamples must be a non-empty array.");return{defaults:{schedulePreset:String(r.schedulePreset||"").trim()||"Every morning",mode:r.mode==="single"||r.mode==="team"||r.mode==="swarm"?r.mode:"team",maxAgents:String(r.maxAgents||"").trim()||"4"},steps:s.map(p=>String(p||"").trim()).filter(Boolean),schedulePresets:c.map(p=>({label:String(p?.label||"").trim(),desc:String(p?.desc||"").trim(),icon:String(p?.icon||"").trim(),cron:String(p?.cron||"").trim(),intervalSeconds:p?.intervalSeconds===void 0||p?.intervalSeconds===null?void 0:Number(p.intervalSeconds)})),executionModes:d.map(p=>({id:p?.id==="single"||p?.id==="team"||p?.id==="swarm"?p.id:"team",label:String(p?.label||"").trim(),icon:String(p?.icon||"").trim(),desc:String(p?.desc||"").trim(),bestFor:String(p?.bestFor||"").trim()})),goalExamples:u.map(p=>String(p||"").trim()).filter(Boolean)}}const ga=Hu(Object.values(Qu)[0]||""),Ws="tandem.automations.plannerSeed",zs="tandem.automations.studioHandoff";function Js(a,t,n=""){return{goal:"",workspaceRoot:n,schedulePreset:ga.defaults.schedulePreset,cron:"",mode:ga.defaults.mode,maxAgents:ga.defaults.maxAgents,routedSkill:"",routingConfidence:"",modelProvider:String(a||""),modelId:String(t||""),plannerModelProvider:"",plannerModelId:"",roleModelsJson:"",toolAccessMode:"all",customToolsText:"",selectedMcpServers:[],exportPackDraft:!1,advancedMode:!1,customSkillName:"",customSkillDescription:"",customWorkflowKind:"pack_builder_recipe"}}function Fa(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Gi(a){return Array.isArray(a?.servers)?a.servers.map(t=>{const n=String(t?.name||"").trim();return n?{name:n,connected:!!t?.connected,enabled:t?.enabled!==!1}:null}).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):a&&typeof a=="object"?Object.entries(a).map(([t,n])=>{const r=String(t||"").trim();if(!r)return null;const s=n&&typeof n=="object"?n:{};return{name:r,connected:!!s.connected,enabled:s.enabled!==!1}}).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):[]}function Gu(a){const t=String(a.cron||"").trim();if(t)return{cron:{expression:t}};const n=ga.schedulePresets.find(r=>r.label===a.schedulePreset);return n?.intervalSeconds?{interval_seconds:{seconds:n.intervalSeconds}}:n?.cron?{cron:{expression:n.cron}}:{type:"manual"}}function Vu(a){const t=String(a?.cron?.expression||a?.cron_expression||"").trim();if(t)return t;const n=Number(a?.interval_seconds?.seconds);return Number.isFinite(n)&&n>0?n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`:"manual"}function Vi(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function $n(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function pr(a,t){const n=String(a||"").trim(),r=String(t||"").trim();return!n&&!r?"":n?r?"":"Planner model is required when a planner provider is set.":"Planner model provider is required when a planner model is set."}function Er(a,t){const n=String(a||"").trim(),r=String(t||"").trim();return!n&&!r?"":n?r?"":"Model is required when a provider is set.":"Model provider is required when a model is set."}function Yu(a){let t;const n=String(a.roleModelsJson||"").trim();if(n)try{const u=JSON.parse(n);u&&typeof u=="object"&&!Array.isArray(u)&&(t=u)}catch{t=void 0}const r=String(a.plannerModelProvider||"").trim(),s=String(a.plannerModelId||"").trim();r&&s&&(t={...t||{}},t.planner={provider_id:r,model_id:s});const c=a.mode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxAgents||"4"),10)||4)):1,d={execution_mode:a.mode,max_parallel_agents:c};return String(a.modelProvider||"").trim()&&(d.model_provider=String(a.modelProvider).trim()),String(a.modelId||"").trim()&&(d.model_id=String(a.modelId).trim()),t&&Object.keys(t).length&&(d.role_models=t),d}function Xu(a){const t=String(a||"").trim();if(!t)return"";try{const n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?"Role model overrides must be a JSON object.":""}catch{return"Role model overrides must be valid JSON."}}function Yi(a){const t=String(a?.type||"").trim().toLowerCase(),n=String(a?.cron?.expression||a?.cron_expression||a?.cron||"").trim(),r=Number(a?.interval_seconds?.seconds||a?.interval_seconds||a?.intervalSeconds||3600),s=Number.isFinite(r)&&r>0?Math.round(r):3600;return{scheduleKind:t==="manual"?"manual":n?"cron":"interval",cronExpression:n,intervalSeconds:s}}function Zu(a){let t="",n=!1;for(const r of String(a||"").trim())/^[a-z0-9]$/i.test(r)?(t+=r.toLowerCase(),n=!1):n||(t+="_",n=!0);return t.replace(/^_+|_+$/g,"")||"mcp"}function Wn(a){const t=new Set,n=[];for(const r of a){const s=String(r||"").trim();!s||t.has(s)||(t.add(s),n.push(s))}return n}function nr(a,t){const n=new Set,r=[];for(const s of[t,...a]){const c=String(s||"").trim();!c||n.has(c)||(n.add(c),r.push(c))}return r}function ds(a){return Wn(String(a||"").split(/[\n,]/g).map(t=>String(t||"").trim()).filter(Boolean))}function em(a){return Wn(a).join(`
|
|
2432
|
+
`)}function tm(a,t,n){return t==="all"?["*"]:Wn([...ds(n),...a.map(r=>`mcp.${Zu(r)}.*`)])}function am(a){const t=a?.metadata?.operator_preferences||a?.metadata?.operatorPreferences;if(t&&typeof t=="object")return t;const n=Array.isArray(a?.agents)?a.agents[0]:null,r=n?.model_policy?.default_model||n?.modelPolicy?.defaultModel||null,s=n?.model_policy?.role_models||n?.modelPolicy?.roleModels||null,c={};return(r?.provider_id||r?.providerId)&&(c.model_provider=r.provider_id||r.providerId),(r?.model_id||r?.modelId)&&(c.model_id=r.model_id||r.modelId),s&&typeof s=="object"&&(c.role_models=s),(a?.execution?.max_parallel_agents||a?.execution?.maxParallelAgents)&&(c.max_parallel_agents=a.execution.max_parallel_agents||a.execution.maxParallelAgents),c}function nm(a){const t=Wn((Array.isArray(a?.agents)?a.agents.flatMap(r=>Array.isArray(r?.tool_policy?.allowlist)?r.tool_policy.allowlist:[]):[]).map(r=>String(r||"").trim()).filter(Boolean));if(!t.length||t.includes("*"))return{toolAccessMode:"all",customToolsText:""};const n=t.filter(r=>!r.startsWith("mcp."));return{toolAccessMode:"custom",customToolsText:em(n)}}function rm(a){const t=String(a?.automation_id||a?.automationId||a?.id||"").trim();if(!t)return null;const n=Yi(a?.schedule),r=am(a),s=r?.role_models?.planner||r?.roleModels?.planner||{},c=Number(r?.max_parallel_agents??r?.maxParallelAgents??a?.execution?.max_parallel_agents??a?.execution?.maxParallelAgents??1),d=String(r?.execution_mode||r?.executionMode||"").trim(),u=Array.isArray(a?.metadata?.allowed_mcp_servers)?a.metadata.allowed_mcp_servers:Array.isArray(a?.agents?.[0]?.mcp_policy?.allowed_servers)?a.agents[0].mcp_policy.allowed_servers:[],p=nm(a),N=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map((E,x)=>({nodeId:String(E?.node_id||E?.nodeId||E?.id||`node-${x}`).trim(),title:String(E?.title||E?.name||E?.objective||E?.node_id||E?.id||"Workflow step").trim(),objective:String(E?.objective||"").trim(),agentId:String(E?.agent_id||E?.agentId||"").trim()})):[];return{automationId:t,name:String(a?.name||t).trim(),description:String(a?.description||"").trim(),scheduleKind:n.scheduleKind,cronExpression:n.cronExpression,intervalSeconds:String(n.intervalSeconds),workspaceRoot:String(a?.workspace_root||a?.workspaceRoot||a?.metadata?.workspace_root||"").trim(),executionMode:d==="single"||d==="swarm"||d==="team"?d:c>1?"swarm":"team",maxParallelAgents:String(Number.isFinite(c)&&c>0?Math.round(c):1),modelProvider:String(r?.model_provider||r?.modelProvider||"").trim(),modelId:String(r?.model_id||r?.modelId||"").trim(),plannerModelProvider:String(s?.provider_id||s?.providerId||"").trim(),plannerModelId:String(s?.model_id||s?.modelId||"").trim(),toolAccessMode:p.toolAccessMode,customToolsText:p.customToolsText,selectedMcpServers:u.map(E=>String(E||"").trim()).filter(Boolean),nodes:N}}function sm(a){const t=a?.metadata&&typeof a.metadata=="object"?a.metadata:{};return String(t.builder_kind||t.builderKind||a?.builder_kind||"").trim().toLowerCase()==="mission_blueprint"?!0:!!(t.mission_blueprint||t.missionBlueprint||t.mission_blueprint_v1||t.mission)}function im(a){const t={type:"run_once"};return a.scheduleKind==="manual"?{type:"manual",timezone:"UTC",misfire_policy:t}:a.scheduleKind==="cron"?{type:"cron",cron_expression:String(a.cronExpression||"").trim(),timezone:"UTC",misfire_policy:t}:{type:"interval",interval_seconds:Math.max(1,Number.parseInt(String(a.intervalSeconds||"3600"),10)||3600),timezone:"UTC",misfire_policy:t}}function om(a){return String(a?.metadata?.feature||"").trim()==="agent_standup"}function lm(a){const t={execution_mode:a.executionMode,max_parallel_agents:a.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(a.maxParallelAgents||"4"),10)||4)):1},n=String(a.modelProvider||"").trim(),r=String(a.modelId||"").trim();n&&(t.model_provider=n),r&&(t.model_id=r);const s=String(a.plannerModelProvider||"").trim(),c=String(a.plannerModelId||"").trim();return s&&c&&(t.role_models={planner:{provider_id:s,model_id:c}}),t.tool_access_mode=a.toolAccessMode,a.toolAccessMode==="custom"&&(t.tool_allowlist=ds(a.customToolsText)),t}function cm(a){const t={};return a.model_provider&&a.model_id&&(t.default_model={provider_id:a.model_provider,model_id:a.model_id}),a.role_models&&typeof a.role_models=="object"&&(t.role_models=a.role_models),Object.keys(t).length?t:null}function La(a){const t=String(a||"").trim().toLowerCase();return["queued","running","in_progress","executing","pending_approval","awaiting_approval"].includes(t)}function Qs(a){const t=Number(a?.started_at_ms||a?.fired_at_ms||a?.created_at_ms||0);if(!Number.isFinite(t)||t<=0)return"time unavailable";const n=Date.now()-t,r=Math.max(0,Math.floor(n/1e3));return r<60?`${r}s`:r<3600?`${Math.floor(r/60)}m`:`${Math.floor(r/3600)}h`}function dm(a,t){const n=[],r=Wa(a);return(r==="pending_approval"||r==="awaiting_approval")&&n.push("Run is waiting for approval before external actions."),r==="blocked_policy"&&n.push("Run was blocked by policy. Check tool allowlist and integration permissions."),(r==="failed"||r==="error")&&n.push("Run failed. Inspect detail/error fields for root cause."),(r==="completed"||r==="done")&&!t.length&&n.push("Run completed but produced no artifacts. Verify output target and tool actions."),a?.requires_approval===!0&&n.push("Automation policy requires human approval. Disable it for fully automated runs."),n}function yr(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?Date.now():t<1e12?t*1e3:t}function Xi(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function Hs(a){const t=Xi(a);return t?new Date(t).toLocaleTimeString():"time unavailable"}function hr(a,t=28){const n=String(a||"").trim();if(!n)return"";if(n.length<=t)return n;const r=Math.max(8,Math.floor((t-1)/2)),s=Math.max(6,t-r-1);return`${n.slice(0,r)}…${n.slice(-s)}`}function Un(a,t=88){const n=String(a||"").replace(/\s+/g," ").trim();return n?n.length>t?`${n.slice(0,t-1).trimEnd()}…`:n:""}function Xa(a){return String(a?.mission_snapshot?.objective||a?.mission?.objective||a?.objective||a?.name||"").replace(/\s+/g," ").trim()}function Dr(a){const t=String(a?.name||"").trim();if(t)return t;const n=Xa(a);if(n)return Un(n,96);const r=String(a?.automation_id||a?.routine_id||"").trim();return r||"Run"}function Ka(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"":new Date(yr(t)).toLocaleString()}function rr(a){const t=new Set,n=[];for(const r of a){const s=String(r||"").trim();!s||t.has(s)||(t.add(s),n.push(s))}return n}function um(a){const t=String(a||"").trim();return t?t.includes("/")||t.includes("\\")?!0:/\.[a-z0-9]{1,8}$/i.test(t):!1}function Bn(a,t="",n=0){if(n>4||a==null)return[];if(typeof a=="string"){const r=a.trim();return r?/(path|file|artifact)/i.test(t)||um(r)?[r]:[]:[]}return Array.isArray(a)?a.flatMap(r=>Bn(r,t,n+1)):typeof a=="object"?Object.entries(a).flatMap(([r,s])=>Bn(s,r,n+1)):[]}function us(a){return(Array.isArray(a?.parts)?a.parts:[]).map(r=>{const s=String(r?.type||"").trim();if(s==="text"||s==="reasoning")return String(r?.text||"").trim();if(s==="tool"){const c=String(r?.tool||"tool").trim(),d=String(r?.error||"").trim(),u=r?.result?aa(r.result):"";return[`tool: ${c}`,d?`error: ${d}`:"",u].filter(Boolean).join(`
|
|
2433
2433
|
`)}return String(r?.text||"").trim()}).filter(Boolean).join(`
|
|
2434
2434
|
|
|
2435
|
-
`).trim()}function
|
|
2436
|
-
`),c.nodeId)}if(!d)continue;const N=d.toLowerCase();(N.includes("could not complete")||N.includes("invalid attachment")||N.includes("timed out")||N.includes("blocked")||N.includes("no email delivery tool")||N.includes("auth was not approved"))&&s(`node-output-${c.nodeId}`,`Node issue: ${c.nodeId}`,$n(d,360),c.nodeId,Number(c.value?.created_at_ms||c.value?.createdAtMs||0))}return kd([...t,...n]).forEach(c=>{s(c.key,c.title,c.reason,c.source,c.at)}),r.sort((c,d)=>(d.at||0)-(c.at||0))}function em({value:a,onChange:t,routedSkill:n,routingConfidence:r,validationBadge:s,generatedSkill:c,advancedMode:d,customSkillName:u,customSkillDescription:p,customWorkflowKind:N,onToggleAdvancedMode:E,onChangeCustomSkillName:x,onChangeCustomSkillDescription:C,onChangeCustomWorkflowKind:O,showArtifactPreview:k,onToggleArtifactPreview:z,artifactPreviewKey:A,onSelectArtifactPreviewKey:G,onGenerateSkill:B,onInstallGeneratedSkill:ae,isGeneratingSkill:S,isInstallingSkill:I,installStatus:H,topMatches:q,isMatching:ye}){const y=Object.keys(c?.artifacts||{});return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Describe what you want the AI to do — in plain English. No technical knowledge needed."}),e("textarea",{className:"tcp-input min-h-[120px] text-base",placeholder:`e.g. "${ma.goalExamples[0]}"`,value:a,onInput:v=>t(v.target.value),autoFocus:!0}),e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500",children:"Need inspiration? Try one of these:"}),e("div",{className:"flex flex-wrap gap-2",children:ma.goalExamples.slice(1).map(v=>e("button",{className:"tcp-btn truncate text-left text-xs",style:{maxWidth:"280px"},onClick:()=>t(v),children:v},v))})]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Reusable Flows"}),e("span",{className:"text-slate-500",children:ye?"Analyzing…":"Ready"})]}),n?e("p",{className:"mt-1",children:["Reusable flow match: ",e("strong",{children:n})," ",r?`(${r})`:"",s?e("span",{className:`ml-2 ${s==="validated"?"tcp-badge-ok":"tcp-badge-warn"}`,children:s==="validated"?"Validated":"Not validated"}):null]}):e("p",{className:"mt-1 text-slate-400",children:"No reusable flow selected. Tandem will create and run a workflow plan in the engine."}),q.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:q.slice(0,3).map((v,U)=>e("span",{className:"tcp-badge-info",children:[String(v?.skill_name||"unknown")," ",typeof v?.confidence=="number"?`${Math.round(v.confidence*100)}%`:""]},`${String(v?.skill_name||"match")}-${U}`))}):null]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Optional: Reusable Skill Export"}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:E,children:d?"Hide Export Options":"Show Export Options"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:B,disabled:!a.trim()||S,children:S?"Generating…":"Generate Reusable Skill Draft"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:ae,disabled:!c?.artifacts||I,children:I?"Installing…":"Save Reusable Skill"})]})]}),e("p",{className:"mt-1 text-slate-400",children:"This is a secondary prompt-based export path. It does not power the default automation flow, and it does not automatically track planner-chat revisions to the workflow plan."}),e("div",{className:"mt-2 rounded-lg border border-slate-800/70 bg-slate-950/30 px-3 py-2 text-xs text-slate-400",children:"Recommended flow: review and finalize the workflow plan first, then generate or regenerate the reusable skill draft if you want a reusable export from the current prompt."}),d?e("div",{className:"mt-2 grid gap-2",children:[e("input",{className:"tcp-input text-xs",placeholder:"skill-name",value:u,onInput:v=>x(v.target.value)}),e("input",{className:"tcp-input text-xs",placeholder:"Short skill description",value:p,onInput:v=>C(v.target.value)}),e("select",{className:"tcp-input text-xs",value:N,onInput:v=>O(v.target.value),children:[e("option",{value:"pack_builder_recipe",children:"pack_builder_recipe"}),e("option",{value:"automation_v2_dag",children:"automation_v2_dag"})]})]}):null,c?e("div",{className:"mt-2 grid gap-1",children:[e("p",{children:["Optional scaffold status:"," ",e("strong",{children:String(c?.status||"generated")})]}),e("p",{className:"text-amber-200",children:"This draft was generated from the prompt and export options. If you revise the workflow plan later in review, regenerate this draft before saving it."}),e("p",{children:["Suggested skill:"," ",e("strong",{children:String(c?.router?.skill_name||"new optional skill")})]}),e("p",{className:"text-slate-400",children:["Artifacts:"," ",y.join(", ")||"SKILL.md, workflow.yaml, automation.example.yaml"]}),e("div",{className:"mt-1 flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:z,children:k?"Hide Raw":"Show Raw"}),k?e("select",{className:"tcp-input h-7 text-xs",value:A,onInput:v=>G(v.target.value),children:Object.keys(c?.artifacts||{}).map(v=>e("option",{value:v,children:v},v))}):null]}),k?e("textarea",{className:"tcp-input min-h-[140px] font-mono text-[11px]",readOnly:!0,value:String(c?.artifacts?.[A]||"")}):null]}):e("p",{className:"mt-1 text-slate-400",children:"Generate a reusable skill draft from this prompt if you want to save it for later reuse."}),H?e("p",{className:"mt-2 text-slate-300",children:H}):null]})]})}function tm({selected:a,onSelect:t,customCron:n,onCustomCron:r}){return e("div",{className:"grid gap-3",children:[e("p",{className:"text-sm text-slate-400",children:"When should this automation run?"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:ma.schedulePresets.map(s=>e("button",{onClick:()=>t(s),className:`tcp-list-item flex flex-col items-start gap-1 text-left transition-all ${a===s.label?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("div",{className:"flex items-center gap-2 font-medium",children:[e("span",{children:s.icon}),e("span",{children:s.label})]}),e("span",{className:"tcp-subtle text-xs",children:s.desc}),s.cron?e("code",{className:"rounded bg-slate-800/60 px-1.5 py-0.5 text-xs text-slate-400",children:s.cron}):null]},s.label))}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-500",children:"Custom cron expression (advanced)"}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"e.g. 30 8 * * 1-5 (8:30am weekdays)",value:n,onInput:s=>r(s.target.value)})]})]})}function am({selected:a,onSelect:t,maxAgents:n,onMaxAgents:r,workspaceRoot:s,onWorkspaceRootChange:c,providerOptions:d,providerId:u,modelId:p,plannerProviderId:N,plannerModelId:E,onProviderChange:x,onModelChange:C,onPlannerProviderChange:O,onPlannerModelChange:k,roleModelsJson:z,onRoleModelsChange:A,roleModelsError:G,toolAccessMode:B,customToolsText:ae,onToolAccessModeChange:S,onCustomToolsTextChange:I,mcpServers:H,selectedMcpServers:q,onToggleMcpServer:ye,onOpenMcpSettings:y,workspaceRootError:v,plannerModelError:U,workspaceBrowserOpen:ue,workspaceBrowserDir:ee,workspaceBrowserSearch:Oe,onWorkspaceBrowserSearchChange:Ee,onOpenWorkspaceBrowser:We,onCloseWorkspaceBrowser:ne,onBrowseWorkspaceParent:ce,onBrowseWorkspaceDirectory:M,onSelectWorkspaceDirectory:me,workspaceBrowserParentDir:Re,workspaceCurrentBrowseDir:qe,filteredWorkspaceDirectories:se}){const Ue=d.find(X=>X.id===u)?.models||[],Me=d.find(X=>X.id===N)?.models||[],ze=String(Oe||"").trim().toLowerCase();return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"How should the AI handle this task? (You can always change this later.)"}),e("div",{className:"grid gap-3",children:ma.executionModes.map(X=>e("button",{onClick:()=>t(X.id),className:`tcp-list-item flex items-start gap-4 text-left transition-all ${a===X.id?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("span",{className:"mt-0.5 text-2xl",children:X.icon}),e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-semibold",children:X.label}),X.id==="team"?e("span",{className:"rounded-full bg-amber-500/20 px-2 py-0.5 text-xs text-amber-300",children:"Recommended"}):null]}),e("span",{className:"text-sm text-slate-300",children:X.desc}),e("span",{className:"tcp-subtle text-xs",children:["Best for: ",X.bestFor]})]}),e("div",{className:"ml-auto mt-1 h-4 w-4 shrink-0 rounded-full border-2 border-slate-600 transition-all data-[checked]:border-amber-400 data-[checked]:bg-amber-400/30","data-checked":a===X.id?!0:void 0})]},X.id))}),a==="swarm"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Max parallel agents"}),e("input",{type:"number",min:"2",max:"16",className:"tcp-input w-24",value:n,onInput:X=>r(X.target.value)})]}):null,e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Execution Directory"}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn",type:"button",onClick:We,children:"Browse"}),e("input",{className:`tcp-input text-sm ${v?"border-red-500/70 text-red-100":""}`,value:s,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>c(""),disabled:!s,children:"Clear"})]}),e("div",{className:"text-xs text-slate-500",children:"Tandem will run this automation from this workspace directory."}),v?e("div",{className:"text-xs text-red-300",children:v}):null]})]}),e(Mt,{children:ue?e($e.div,{className:"fixed inset-0 z-50 flex items-center justify-center p-4",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:ne}),e($e.div,{className:"tcp-confirm-dialog max-w-2xl",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",qe||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:ce,disabled:!Re,children:"Up"}),e("button",{className:"tcp-btn-primary",type:"button",onClick:me,disabled:!qe,children:"Select This Folder"}),e("button",{className:"tcp-btn",type:"button",onClick:ne,children:"Close"})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:Oe,onInput:X=>Ee(X.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:se.length?se.map(X=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>M(String(X?.path||"")),children:String(X?.name||X?.path||"")},String(X?.path||X?.name))):e(Le,{text:ze?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Provider"}),e("select",{className:"tcp-input text-sm",value:u,onInput:X=>x(X.target.value),children:[e("option",{value:"",children:"Use workspace default"}),d.map(X=>e("option",{value:X.id,children:X.id},X.id))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("input",{className:"tcp-input text-sm",value:p,list:u?`models-${u}`:void 0,onInput:X=>C(X.target.value),placeholder:"Use workspace default model"}),u?e("datalist",{id:`models-${u}`,children:Ue.map(X=>e("option",{value:X},X))}):null]})]}),e("div",{className:"grid gap-2 rounded-lg border border-slate-800/70 bg-slate-950/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Planner fallback model"}),e("div",{className:"text-xs text-slate-400",children:"Optional. Use this only if you want planning chat to try broader engine-side revisions beyond the built-in deterministic edits."}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner provider"}),e("select",{className:"tcp-input text-sm",value:N,onInput:X=>O(X.target.value),children:[e("option",{value:"",children:"Disabled"}),d.map(X=>e("option",{value:X.id,children:X.id},`planner-${X.id}`))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("input",{className:"tcp-input text-sm",value:E,list:N?`planner-models-${N}`:void 0,onInput:X=>k(X.target.value),placeholder:"Disabled unless provider and model are set"}),N?e("datalist",{id:`planner-models-${N}`,children:Me.map(X=>e("option",{value:X},X))}):null]})]}),U?e("div",{className:"text-xs text-red-300",children:U}):null]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Role model overrides (advanced JSON)"}),e("textarea",{className:`tcp-input min-h-[72px] font-mono text-xs ${G?"border-red-500/70 text-red-100":""}`,value:z,onInput:X=>A(X.target.value),placeholder:'{"planner":{"provider_id":"openai","model_id":"gpt-5"},"worker":{"provider_id":"anthropic","model_id":"claude-sonnet-4"}}'}),G?e("div",{className:"text-xs text-red-300",children:G}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${B==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>S("all"),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access. Use this for autonomous coding and file operations."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${B==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>S("custom"),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still come from the selected servers below."})]})]}),B==="custom"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Allowed built-in tools"}),e("textarea",{className:"tcp-input min-h-[96px] font-mono text-xs",value:ae,onInput:X=>I(X.target.value),placeholder:`read
|
|
2435
|
+
`).trim()}function mm(a){const t=String(a?.info?.role||"").trim().toLowerCase();if(t==="user")return"user";if(t==="assistant")return"assistant";const n=us(a).toLowerCase();return n.includes("engine_error")||n.includes("error")?"error":"system"}function pm(a){return Array.isArray(a?.parts)?a.parts:[]}function hm(a){return yr(a?.info?.time?.created||a?.info?.created_at_ms||a?.created_at_ms||0)}function gm(a,t){return String(a?.info?.id||a?.id||`message-${t}`).trim()||`message-${t}`}function Mn(a){const t=String(a||"").trim();return t?`session ${hr(t,18)}`:"session"}function Zi(a){const t=String(a||"").trim();return t?t.startsWith("node-")?t:`node-${t}`:""}function Gs(a){const t=String(a||"").trim();if(!t)return"";for(const n of[/node id:\s*([a-z0-9._-]+)/i,/step[_\s]id:\s*([a-z0-9._-]+)/i,/task[_\s]id:\s*(?:node-)?([a-z0-9._-]+)/i]){const r=t.match(n);if(r?.[1])return Zi(r[1])}return""}function fm(a,t){const n=String(t||"").trim();if(!n)return[];const r=new Set([n]);let s=!0;for(;s;){s=!1;for(const c of Array.isArray(a)?a:[]){const d=String(c?.id||"").trim();if(!d||r.has(d))continue;(Array.isArray(c?.dependencies)?c.dependencies.map(p=>String(p||"").trim()).filter(Boolean):[]).some(p=>r.has(p))&&(r.add(d),s=!0)}}return Array.from(r)}function bm(a,t,n){const r=String(a?.status||"").trim().toLowerCase();if(!["running","pausing","paused"].includes(r))return"";const s=Rd(a);if(s)return s;for(let c=n.length-1;c>=0;c-=1){const d=n[c]?.event?.properties||n[c]?.event||{},u=Zi(String(d?.task_id||d?.step_id||d?.node_id||"").trim());if(u)return u;const p=Gs(String(d?.message||d?.detail||d?.reason||""));if(p)return p}for(let c=t.length-1;c>=0;c-=1){const d=Gs(us(t[c]?.message));if(d)return d}return Cd(a)}function eo(a){const t=String(a?.detail||"").trim();return t?t.includes("BASH_COMMAND_MISSING")?"This workflow failed because the agent called the `bash` tool without providing a shell command. The tool was available, but the request payload was missing its required `command` field.":t.includes("WEBFETCH_URL_MISSING")?"This workflow failed because a web fetch tool call was made without a URL.":t.includes("No such file or directory")?"This workflow failed because the agent tried to read a path that does not exist from the configured workspace root.":t:""}function vm(a,t,n){const r=[],s=(c,d,u,p,N)=>{u.trim()&&(r.some(E=>E.key===c)||r.push({key:c,title:d,reason:u,source:p,at:N}))};if((a?.requires_approval===!0||String(a?.status||"").trim()==="pending_approval")&&s("approval-required","Approval required",String(a?.approval_reason||"Manual approval required before external side effects.").trim(),"policy"),String(a?.denial_reason||"").trim()&&s("denied","Run denied",String(a.denial_reason).trim(),"run"),String(a?.paused_reason||"").trim()&&s("paused","Run paused",String(a.paused_reason).trim(),"run"),String(a?.detail||"").trim()){const c=String(a.detail).trim();(c.toLowerCase().includes("tool")||c.toLowerCase().includes("bash_command_missing")||c.toLowerCase().includes("command_missing")||c.toLowerCase().includes("permission")||c.toLowerCase().includes("approval")||c.toLowerCase().includes("mcp")||c.toLowerCase().includes("auth")||c.toLowerCase().includes("failed after"))&&s("detail","Failure reason",eo(a),"run")}Ui(a).length||s("missing-session","No linked session transcript","This run does not expose a linked session transcript, so only telemetry/history are available.","run");for(const c of rs(a)){const d=qd(c.value),u=is(c.value),p=Kn(c.value);if(String(c?.value?.status||"").trim().toLowerCase()==="blocked"){const E=Array.isArray(u?.executed_tools)?u.executed_tools.join(", "):"",x=Array.isArray(u?.requested_tools)?u.requested_tools.join(", "):"";s(`node-status-${c.nodeId}`,`Node blocked: ${c.nodeId}`,[String(c?.value?.blocked_reason||c?.value?.blockedReason||"").trim(),x?`offered tools: ${x}`:"",E?`executed tools: ${E}`:"",String(p?.semantic_block_reason||"").trim()?`research validation: ${String(p?.semantic_block_reason||"").trim()}`:"",String(p?.rejected_artifact_reason||"").trim()?`artifact validation: ${String(p?.rejected_artifact_reason||"").trim()}`:"",Array.isArray(p?.unmet_requirements)&&p.unmet_requirements.length?`unmet requirements: ${p.unmet_requirements.join(", ")}`:"",Array.isArray(p?.undeclared_files_created)&&p.undeclared_files_created.length?`undeclared files created: ${p.undeclared_files_created.join(", ")}`:"",p?.auto_cleaned?"artifact cleanup was applied":"",u&&!u?.web_research_used?"web research was not used":"",u&&!u?.workspace_inspection_used?"workspace inspection was not used":""].filter(Boolean).join(`
|
|
2436
|
+
`),c.nodeId)}if(!d)continue;const N=d.toLowerCase();(N.includes("could not complete")||N.includes("invalid attachment")||N.includes("timed out")||N.includes("blocked")||N.includes("no email delivery tool")||N.includes("auth was not approved"))&&s(`node-output-${c.nodeId}`,`Node issue: ${c.nodeId}`,Un(d,360),c.nodeId,Number(c.value?.created_at_ms||c.value?.createdAtMs||0))}return Fd([...t,...n]).forEach(c=>{s(c.key,c.title,c.reason,c.source,c.at)}),r.sort((c,d)=>(d.at||0)-(c.at||0))}function ym({value:a,onChange:t,routedSkill:n,routingConfidence:r,validationBadge:s,generatedSkill:c,advancedMode:d,customSkillName:u,customSkillDescription:p,customWorkflowKind:N,onToggleAdvancedMode:E,onChangeCustomSkillName:x,onChangeCustomSkillDescription:A,onChangeCustomWorkflowKind:O,showArtifactPreview:_,onToggleArtifactPreview:z,artifactPreviewKey:P,onSelectArtifactPreviewKey:Q,onGenerateSkill:B,onInstallGeneratedSkill:ne,isGeneratingSkill:I,isInstallingSkill:C,installStatus:H,topMatches:M,isMatching:xe}){const y=Object.keys(c?.artifacts||{});return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Describe what you want the AI to do — in plain English. No technical knowledge needed."}),e("textarea",{className:"tcp-input min-h-[120px] text-base",placeholder:`e.g. "${ga.goalExamples[0]}"`,value:a,onInput:v=>t(v.target.value),autoFocus:!0}),e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500",children:"Need inspiration? Try one of these:"}),e("div",{className:"flex flex-wrap gap-2",children:ga.goalExamples.slice(1).map(v=>e("button",{className:"tcp-btn truncate text-left text-xs",style:{maxWidth:"280px"},onClick:()=>t(v),children:v},v))})]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Reusable Flows"}),e("span",{className:"text-slate-500",children:xe?"Analyzing…":"Ready"})]}),n?e("p",{className:"mt-1",children:["Reusable flow match: ",e("strong",{children:n})," ",r?`(${r})`:"",s?e("span",{className:`ml-2 ${s==="validated"?"tcp-badge-ok":"tcp-badge-warn"}`,children:s==="validated"?"Validated":"Not validated"}):null]}):e("p",{className:"mt-1 text-slate-400",children:"No reusable flow selected. Tandem will create and run a workflow plan in the engine."}),M.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:M.slice(0,3).map((v,j)=>e("span",{className:"tcp-badge-info",children:[String(v?.skill_name||"unknown")," ",typeof v?.confidence=="number"?`${Math.round(v.confidence*100)}%`:""]},`${String(v?.skill_name||"match")}-${j}`))}):null]}),e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-900/30 p-3 text-xs text-slate-300",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"uppercase tracking-wide text-slate-500",children:"Optional: Reusable Skill Export"}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:E,children:d?"Hide Export Options":"Show Export Options"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:B,disabled:!a.trim()||I,children:I?"Generating…":"Generate Reusable Skill Draft"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:ne,disabled:!c?.artifacts||C,children:C?"Installing…":"Save Reusable Skill"})]})]}),e("p",{className:"mt-1 text-slate-400",children:"This is a secondary prompt-based export path. It does not power the default automation flow, and it does not automatically track planner-chat revisions to the workflow plan."}),e("div",{className:"mt-2 rounded-lg border border-slate-800/70 bg-slate-950/30 px-3 py-2 text-xs text-slate-400",children:"Recommended flow: review and finalize the workflow plan first, then generate or regenerate the reusable skill draft if you want a reusable export from the current prompt."}),d?e("div",{className:"mt-2 grid gap-2",children:[e("input",{className:"tcp-input text-xs",placeholder:"skill-name",value:u,onInput:v=>x(v.target.value)}),e("input",{className:"tcp-input text-xs",placeholder:"Short skill description",value:p,onInput:v=>A(v.target.value)}),e("select",{className:"tcp-input text-xs",value:N,onInput:v=>O(v.target.value),children:[e("option",{value:"pack_builder_recipe",children:"pack_builder_recipe"}),e("option",{value:"automation_v2_dag",children:"automation_v2_dag"})]})]}):null,c?e("div",{className:"mt-2 grid gap-1",children:[e("p",{children:["Optional scaffold status:"," ",e("strong",{children:String(c?.status||"generated")})]}),e("p",{className:"text-amber-200",children:"This draft was generated from the prompt and export options. If you revise the workflow plan later in review, regenerate this draft before saving it."}),e("p",{children:["Suggested skill:"," ",e("strong",{children:String(c?.router?.skill_name||"new optional skill")})]}),e("p",{className:"text-slate-400",children:["Artifacts:"," ",y.join(", ")||"SKILL.md, workflow.yaml, automation.example.yaml"]}),e("div",{className:"mt-1 flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:z,children:_?"Hide Raw":"Show Raw"}),_?e("select",{className:"tcp-input h-7 text-xs",value:P,onInput:v=>Q(v.target.value),children:Object.keys(c?.artifacts||{}).map(v=>e("option",{value:v,children:v},v))}):null]}),_?e("textarea",{className:"tcp-input min-h-[140px] font-mono text-[11px]",readOnly:!0,value:String(c?.artifacts?.[P]||"")}):null]}):e("p",{className:"mt-1 text-slate-400",children:"Generate a reusable skill draft from this prompt if you want to save it for later reuse."}),H?e("p",{className:"mt-2 text-slate-300",children:H}):null]})]})}function wm({selected:a,onSelect:t,customCron:n,onCustomCron:r}){return e("div",{className:"grid gap-3",children:[e("p",{className:"text-sm text-slate-400",children:"When should this automation run?"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:ga.schedulePresets.map(s=>e("button",{onClick:()=>t(s),className:`tcp-list-item flex flex-col items-start gap-1 text-left transition-all ${a===s.label?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("div",{className:"flex items-center gap-2 font-medium",children:[e("span",{children:s.icon}),e("span",{children:s.label})]}),e("span",{className:"tcp-subtle text-xs",children:s.desc}),s.cron?e("code",{className:"rounded bg-slate-800/60 px-1.5 py-0.5 text-xs text-slate-400",children:s.cron}):null]},s.label))}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-500",children:"Custom cron expression (advanced)"}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"e.g. 30 8 * * 1-5 (8:30am weekdays)",value:n,onInput:s=>r(s.target.value)})]})]})}function xm({selected:a,onSelect:t,maxAgents:n,onMaxAgents:r,workspaceRoot:s,onWorkspaceRootChange:c,providerOptions:d,providerId:u,modelId:p,plannerProviderId:N,plannerModelId:E,onProviderChange:x,onModelChange:A,onPlannerProviderChange:O,onPlannerModelChange:_,roleModelsJson:z,onRoleModelsChange:P,roleModelsError:Q,toolAccessMode:B,customToolsText:ne,onToolAccessModeChange:I,onCustomToolsTextChange:C,mcpServers:H,selectedMcpServers:M,onToggleMcpServer:xe,onOpenMcpSettings:y,workspaceRootError:v,plannerModelError:j,workspaceBrowserOpen:he,workspaceBrowserDir:ee,workspaceBrowserSearch:qe,onWorkspaceBrowserSearchChange:$e,onOpenWorkspaceBrowser:Le,onCloseWorkspaceBrowser:re,onBrowseWorkspaceParent:me,onBrowseWorkspaceDirectory:q,onSelectWorkspaceDirectory:ge,workspaceBrowserParentDir:Pe,workspaceCurrentBrowseDir:Te,filteredWorkspaceDirectories:se}){const Oe=d.find(Y=>Y.id===u)?.models||[],Me=d.find(Y=>Y.id===N)?.models||[],He=String(qe||"").trim().toLowerCase();return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"How should the AI handle this task? (You can always change this later.)"}),e("div",{className:"grid gap-3",children:ga.executionModes.map(Y=>e("button",{onClick:()=>t(Y.id),className:`tcp-list-item flex items-start gap-4 text-left transition-all ${a===Y.id?"border-amber-400/60 bg-amber-400/10":""}`,children:[e("span",{className:"mt-0.5 text-2xl",children:Y.icon}),e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{className:"font-semibold",children:Y.label}),Y.id==="team"?e("span",{className:"rounded-full bg-amber-500/20 px-2 py-0.5 text-xs text-amber-300",children:"Recommended"}):null]}),e("span",{className:"text-sm text-slate-300",children:Y.desc}),e("span",{className:"tcp-subtle text-xs",children:["Best for: ",Y.bestFor]})]}),e("div",{className:"ml-auto mt-1 h-4 w-4 shrink-0 rounded-full border-2 border-slate-600 transition-all data-[checked]:border-amber-400 data-[checked]:bg-amber-400/30","data-checked":a===Y.id?!0:void 0})]},Y.id))}),a==="swarm"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Max parallel agents"}),e("input",{type:"number",min:"2",max:"16",className:"tcp-input w-24",value:n,onInput:Y=>r(Y.target.value)})]}):null,e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Execution Directory"}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn",type:"button",onClick:Le,children:"Browse"}),e("input",{className:`tcp-input text-sm ${v?"border-red-500/70 text-red-100":""}`,value:s,readOnly:!0,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>c(""),disabled:!s,children:"Clear"})]}),e("div",{className:"text-xs text-slate-500",children:"Tandem will run this automation from this workspace directory."}),v?e("div",{className:"text-xs text-red-300",children:v}):null]})]}),e(Mt,{children:he?e(Re.div,{className:"fixed inset-0 z-50 flex items-center justify-center p-4",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close workspace directory dialog",onClick:re}),e(Re.div,{className:"tcp-confirm-dialog max-w-2xl",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",Te||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:me,disabled:!Pe,children:"Up"}),e("button",{className:"tcp-btn-primary",type:"button",onClick:ge,disabled:!Te,children:"Select This Folder"}),e("button",{className:"tcp-btn",type:"button",onClick:re,children:"Close"})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:qe,onInput:Y=>$e(Y.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:se.length?se.map(Y=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>q(String(Y?.path||"")),children:String(Y?.name||Y?.path||"")},String(Y?.path||Y?.name))):e(je,{text:He?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Provider"}),e("select",{className:"tcp-input text-sm",value:u,onInput:Y=>x(Y.target.value),children:[e("option",{value:"",children:"Use workspace default"}),d.map(Y=>e("option",{value:Y.id,children:Y.id},Y.id))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("input",{className:"tcp-input text-sm",value:p,list:u?`models-${u}`:void 0,onInput:Y=>A(Y.target.value),placeholder:"Use workspace default model"}),u?e("datalist",{id:`models-${u}`,children:Oe.map(Y=>e("option",{value:Y},Y))}):null]})]}),e("div",{className:"grid gap-2 rounded-lg border border-slate-800/70 bg-slate-950/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Planner fallback model"}),e("div",{className:"text-xs text-slate-400",children:"Optional. Use this only if you want planning chat to try broader engine-side revisions beyond the built-in deterministic edits."}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner provider"}),e("select",{className:"tcp-input text-sm",value:N,onInput:Y=>O(Y.target.value),children:[e("option",{value:"",children:"Disabled"}),d.map(Y=>e("option",{value:Y.id,children:Y.id},`planner-${Y.id}`))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("input",{className:"tcp-input text-sm",value:E,list:N?`planner-models-${N}`:void 0,onInput:Y=>_(Y.target.value),placeholder:"Disabled unless provider and model are set"}),N?e("datalist",{id:`planner-models-${N}`,children:Me.map(Y=>e("option",{value:Y},Y))}):null]})]}),j?e("div",{className:"text-xs text-red-300",children:j}):null]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Role model overrides (advanced JSON)"}),e("textarea",{className:`tcp-input min-h-[72px] font-mono text-xs ${Q?"border-red-500/70 text-red-100":""}`,value:z,onInput:Y=>P(Y.target.value),placeholder:'{"planner":{"provider_id":"openai","model_id":"gpt-5"},"worker":{"provider_id":"anthropic","model_id":"claude-sonnet-4"}}'}),Q?e("div",{className:"text-xs text-red-300",children:Q}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${B==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>I("all"),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access. Use this for autonomous coding and file operations."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${B==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>I("custom"),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still come from the selected servers below."})]})]}),B==="custom"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Allowed built-in tools"}),e("textarea",{className:"tcp-input min-h-[96px] font-mono text-xs",value:ne,onInput:Y=>C(Y.target.value),placeholder:`read
|
|
2437
2437
|
write
|
|
2438
2438
|
edit
|
|
2439
2439
|
bash
|
|
2440
2440
|
ls
|
|
2441
2441
|
glob
|
|
2442
|
-
websearch`}),e("div",{className:"text-xs text-slate-500",children:"Enter one tool per line or comma-separated. Example: `read`, `write`, `edit`, `bash`, `ls`, `glob`, `websearch`."})]}):e("div",{className:"text-xs text-slate-500",children:"All built-in tools are allowed. MCP tools are additionally controlled by the server selection below."})]}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"MCP Servers"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:y,children:"Add MCP Server"})]}),H.length?e("div",{className:"flex flex-wrap gap-2",children:H.map(X=>{const Ve=q.includes(X.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${Ve?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>ye(X.name),children:[X.name," ",X.connected?"• connected":"• disconnected"]},X.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet. Add one to allow external tools in this automation."})]})]})}function nm({wizard:a,onToggleExportPackDraft:t,onSubmit:n,isPending:r,planPreview:s,isPreviewing:c,planningConversation:d,planningChangeSummary:u,onSendPlanningMessage:p,isSendingPlanningMessage:N,onResetPlanningChat:E,isResettingPlanningChat:x,plannerError:C,plannerDiagnostics:O,generatedSkill:k,installStatus:z}){const[A,G]=w(""),[B,ae]=w(!1),[S,I]=w(!1),[H,q]=w({}),ye=a.cron?a.cron:ma.schedulePresets.find(re=>re.label===a.schedulePreset)?.intervalSeconds?`Every ${ma.schedulePresets.find(re=>re.label===a.schedulePreset).intervalSeconds/3600}h`:a.schedulePreset||"Manual",y=s&&typeof s=="object"?s.operator_preferences||s.operatorPreferences||{}:{},v=String(y?.execution_mode||a.mode||"team").trim(),U=ma.executionModes.find(re=>re.id===v),ue=Number(y?.max_parallel_agents??y?.maxParallelAgents??(v==="swarm"?a.maxAgents:1)),ee=!!s,Oe=String(ee?y?.model_provider||y?.modelProvider||"":a.modelProvider||"").trim(),Ee=String(ee?y?.model_id||y?.modelId||"":a.modelId||"").trim(),We=y&&typeof y=="object"&&(y?.role_models?.planner||y?.roleModels?.planner),ne=String(ee?We?.provider_id||We?.providerId||"":a.plannerModelProvider||"").trim(),ce=String(ee?We?.model_id||We?.modelId||"":a.plannerModelId||"").trim(),M=!!(ne&&ce||Oe&&Ee),me=String(s?.workspace_root||s?.workspaceRoot||a.workspaceRoot||"").trim(),Re=Array.isArray(s?.allowed_mcp_servers||s?.allowedMcpServers)?s?.allowed_mcp_servers||s?.allowedMcpServers||[]:a.selectedMcpServers,qe=String(ee?y?.tool_access_mode||y?.toolAccessMode||"all":a.toolAccessMode||"all").trim(),se=ee?Un((y?.tool_allowlist||y?.toolAllowlist||[]).map(re=>String(re||"").trim())):Vr(a.customToolsText),Ue=s?.schedule?Mi(s.schedule):ye,Me=String(s?.title||"").trim(),ze=String(O?.fallback_reason||O?.fallbackReason||"").trim(),X=String(O?.detail||"").trim(),Ve=re=>q(Ce=>({...Ce,[re]:!Ce[re]}));return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Review your automation before deploying."}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/40 p-4 grid gap-3",children:[Me?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Plan Title"}),e("span",{className:"text-sm font-semibold text-slate-100",children:Me})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Goal"}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>ae(re=>!re),children:[e("span",{className:"text-sm text-slate-100 italic",children:B?"Hide goal":"View goal"}),e("span",{className:"tcp-subtle text-xs",children:B?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${B?"":"max-h-28 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:dn(a.goal||"")}})})]})]}),e("div",{className:"grid grid-cols-2 gap-3",children:[e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Schedule"}),e("span",{className:"text-sm font-medium text-slate-200",children:Ue})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Execution Mode"}),e("span",{className:"text-sm font-medium text-slate-200",children:[U?.icon," ",U?.label||v,Number.isFinite(ue)&&ue>1?` · ${ue} agents`:""]})]})]}),ee||Oe||Ee?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Model Override"}),e("span",{className:"text-sm font-medium text-slate-200",children:Oe||Ee?`${Oe||"default provider"} / ${Ee||"default model"}`:"Workspace default"})]}):null,ee||ne||ce?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Planner Model"}),e("span",{className:"text-sm font-medium text-slate-200",children:ne||ce?`${ne||"default provider"} / ${ce||"default model"}`:Oe||Ee?`Using model override: ${Oe||"default provider"} / ${Ee||"default model"}`:"Workspace default"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Broader Planner Revisions"}),e("span",{className:"text-sm font-medium text-slate-200",children:M?"Enabled. Tandem will use the planner model if set, otherwise it falls back to the selected model override.":"Disabled unless a planner model, model override, or workspace default model is configured"})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workspace Root"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:me||"engine workspace root"})]}),ee||Re.length?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"MCP Servers"}),Re.length?e("div",{className:"flex flex-wrap gap-1",children:Re.map(re=>e("span",{className:"tcp-badge-info",children:re},re))}):e("span",{className:"text-sm font-medium text-slate-400",children:"None"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Tool Access"}),qe==="custom"?se.length?e("div",{className:"flex flex-wrap gap-1",children:se.map(re=>e("span",{className:"tcp-badge-info",children:re},re))}):e("span",{className:"text-sm font-medium text-slate-400",children:"Custom allowlist"}):e("span",{className:"text-sm font-medium text-slate-200",children:"All tools"})]}),a.routedSkill?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Reusable Flow Match"}),e("span",{className:"text-sm font-medium text-slate-200",children:[a.routedSkill,a.routingConfidence?` (${a.routingConfidence})`:""]})]}):null,a.cron?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Cron"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:a.cron})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workflow Plan"}),c?e("span",{className:"text-sm text-slate-300",children:"Planning workflow…"}):s?e("div",{className:"grid gap-1 text-sm text-slate-300",children:[e("span",{children:["Confidence: ",e("strong",{children:String(s?.confidence||"unknown")})]}),e("span",{children:["Execution target:"," ",e("strong",{children:String(s?.execution_target||"automation_v2")})]}),Me?e("span",{children:["Title: ",e("strong",{children:Me})]}):null,e("span",{children:["Steps:"," ",e("strong",{children:Array.isArray(s?.steps)?s.steps.length:0})]}),Array.isArray(s?.steps)&&s.steps.length?e("div",{className:"mt-1 grid gap-1",children:s.steps.map((re,Ce)=>(()=>{const gt=String(re?.step_id||re?.stepId||`step-${Ce+1}`),ie=!!H[gt];return e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>Ve(gt),children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-xs font-medium text-slate-200",children:[gt,re?.kind?e("span",{className:"ml-2 text-[11px] uppercase tracking-wide text-slate-500",children:String(re.kind)}):null]}),typeof re?.objective=="string"&&re.objective.trim()?e("div",{className:"mt-1 line-clamp-2 text-xs text-slate-400",children:re.objective}):null]}),e("span",{className:"tcp-subtle shrink-0 text-xs",children:ie?"Hide":"Details"})]}),ie&&typeof re?.objective=="string"&&re.objective.trim()?e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:"tcp-markdown tcp-markdown-ai text-sm",dangerouslySetInnerHTML:{__html:dn(re.objective||"")}})}):null]},`${gt}-${Ce}`)})())}):null,typeof s?.description=="string"&&s.description.trim()?e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>I(re=>!re),children:[e("span",{className:"text-sm text-slate-200",children:"Plan description"}),e("span",{className:"tcp-subtle text-xs",children:S?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${S?"":"max-h-24 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:dn(String(s.description||""))}})})]}):null]}):e("span",{className:"text-sm text-slate-400",children:"Workflow preview has not been generated yet."})]})]}),C?e("div",{className:"rounded-xl border border-red-500/40 bg-red-950/30 p-3 text-sm text-red-200",children:C}):null,ze?e("div",{className:"rounded-xl border border-amber-500/40 bg-amber-950/30 p-3 text-sm text-amber-100",children:[e("div",{className:"font-medium text-amber-200",children:"Planner fallback"}),e("div",{className:"mt-1",children:["Reason: ",e("code",{className:"text-xs",children:ze})]}),X?e("div",{className:"mt-2 text-xs text-amber-200/90 whitespace-pre-wrap",children:X}):null]}):null,u.length?e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-emerald-300",children:"Latest Plan Changes"}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:u.map((re,Ce)=>e("span",{className:"tcp-badge-ok",children:re},`${re}-${Ce}`))})]}):null,s?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/40 p-4 grid gap-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Planning Chat"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:x||!s?.plan_id,onClick:E,children:x?"Resetting…":"Reset Plan"})]}),e("div",{className:"rounded-lg border border-amber-500/30 bg-amber-950/20 px-3 py-2 text-xs text-amber-200",children:M?"With a planner model or model override configured, planning chat can attempt broader natural-language workflow rewrites across the allowed fixed step ids. Deterministic edits still act as the safety net for schedule, workspace root, title, MCP servers, execution mode, model overrides, safe workflow shapes, small workflow-step changes, and terminal output-style changes. Custom step types are still not supported in this slice.":"Planning chat is currently limited to deterministic edits like schedule, workspace root, title, MCP servers, execution mode, model overrides, switching between safe workflow shapes, small workflow-step changes like adding or removing input collection, analysis, or notifications, and terminal output-style changes like JSON, markdown, summary, URLs, or citations. Broader workflow rewrites require a planner model or model override, and custom step types are still not supported in this slice."}),e("div",{className:"max-h-56 overflow-auto rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:Array.isArray(d?.messages)&&d.messages.length?e("div",{className:"grid gap-3",children:d.messages.map((re,Ce)=>e("div",{className:"grid gap-1",children:[e("span",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:String(re?.role||"assistant")}),e("div",{className:"text-sm text-slate-200",children:String(re?.text||"").trim()})]},`${re?.created_at_ms||Ce}-${Ce}`))}):e("div",{className:"text-sm text-slate-400",children:"Add planning notes here to revise the workflow before creating it."})}),e("textarea",{className:"tcp-input min-h-[84px] text-sm",value:A,onInput:re=>G(re.target.value),placeholder:'Example: "Make this weekly, run it from /srv/acme/app, and remove notifications."'}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn-primary",disabled:N||!A.trim()||!s?.plan_id,onClick:()=>{const re=A.trim();re&&(p(re),G(""))},children:N?"Updating plan…":"Update Plan"})})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:e("label",{className:"flex items-start gap-3 rounded-lg border border-slate-700/50 bg-slate-900/30 p-3 text-sm text-slate-300",children:[e("input",{type:"checkbox",className:"mt-0.5",checked:a.exportPackDraft,onChange:t}),e("span",{className:"grid gap-1",children:[e("span",{className:"font-medium text-slate-200",children:"Also export a reusable pack draft"}),e("span",{className:"text-xs text-slate-400",children:"After creating the automation, Tandem will also create a Pack Builder draft so this workflow can be saved and reused later."})]})]})}),k||z?e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Reusable Skill Export"}),e("div",{className:"mt-1 grid gap-1",children:[k?e(aa,{children:[e("span",{children:["Draft status:"," ",e("strong",{className:"text-slate-300",children:String(k?.status||"generated")})]}),e("span",{className:"text-amber-200",children:"This draft is prompt-based and may be stale if you changed the workflow plan in planning chat. Regenerate it from Step 1 before saving if you want it to reflect the latest plan direction."})]}):null,z?e("span",{children:z}):null]})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:["💡 Tandem will save this automation and schedule a"," ",e("strong",{className:"text-slate-300",children:U?.label||v})," that runs"," ",e("strong",{className:"text-slate-300",children:Ue}),". You can pause, edit or delete it anytime."]}),e("button",{className:"tcp-btn-primary",disabled:r||c||!a.goal.trim()||!s,onClick:n,children:r?"Creating automation…":"🚀 Create Automation"})]})}function rm({client:a,api:t,toast:n,navigate:r,defaultProvider:s,defaultModel:c}){const d=na(),[u,p]=w(1),[N,E]=w("automations_page"),[x,C]=w([]),[O,k]=w(null),[z,A]=w(null),[G,B]=w([]),[ae,S]=w(""),[I,H]=w(null),[q,ye]=w(!1),[y,v]=w(""),[U,ue]=w(""),[ee,Oe]=w(""),[Ee,We]=w(null),[ne,ce]=w(!1),[M,me]=w("SKILL.md"),[Re,qe]=w(""),[se,Ue]=w(()=>Ps(s,c)),Me=Y({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),ze=Y({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),X=Y({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),Ve=Y({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),re=Y({queryKey:["automations","workspace-browser",y],enabled:q&&!!y,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(y)}`,{method:"GET"})}),Ce=K(()=>(Array.isArray(Me.data?.all)?Me.data.all:[]).map(J=>({id:String(J?.id||"").trim(),models:Object.keys(J?.models||{})})).filter(J=>!!J.id).sort((J,be)=>J.id.localeCompare(be.id)),[Me.data]),gt=K(()=>qi(X.data),[X.data]),ie=Array.isArray(re.data?.directories)?re.data.directories:[],L=String(re.data?.parent||"").trim(),st=String(re.data?.dir||y||"").trim(),pt=String(U||"").trim().toLowerCase(),lt=K(()=>pt?ie.filter(_=>String(_?.name||_?.path||"").trim().toLowerCase().includes(pt)):ie,[ie,pt]);fe(()=>{const _=String(ze.data?.default||s||"").trim();if(!_)return;const J=Ce.find(je=>je.id===_)?.models||[],be=String(ze.data?.providers?.[_]?.default_model||c||J[0]||"").trim();Ue(je=>je.modelProvider&&je.modelId?je:{...je,modelProvider:je.modelProvider||_,modelId:je.modelId||be})},[c,s,Ce,ze.data]),fe(()=>{const _=String(Ve.data?.workspaceRoot||Ve.data?.workspace_root||"").trim();_&&Ue(J=>String(J.workspaceRoot||"").trim()?J:{...J,workspaceRoot:_})},[Ve.data]);const Ct=xe({mutationFn:async _=>!_.trim()||!a?.skills?.match?null:a.skills.match({goal:_,maxMatches:3,threshold:.35}),onError:()=>{}}),De=xe({mutationFn:async()=>{if(!a?.workflowPlans?.chatStart)throw new Error("This control panel build is missing workflow planner client support. Rebuild the control panel against the local tandem client package.");return await a.workflowPlans.chatStart({prompt:se.goal,schedule:Tu(se),plan_source:N,allowed_mcp_servers:se.selectedMcpServers,workspace_root:se.workspaceRoot,operator_preferences:qu(se)})||null},onSuccess:_=>{k(_?.plan||null),A(_?.conversation||null),B([]),S(""),H(_?.planner_diagnostics||_?.plannerDiagnostics||null)},onError:_=>{k(null),A(null),B([]),S(_ instanceof Error?_.message:String(_)),H(null)}}),$t=xe({mutationFn:async _=>!a?.workflowPlans?.chatMessage||!O?.plan_id?null:a.workflowPlans.chatMessage({plan_id:O.plan_id,message:_}),onSuccess:_=>{k(_?.plan||null),A(_?.conversation||null),B(Array.isArray(_?.change_summary)?_.change_summary.map(J=>String(J||"").trim()).filter(Boolean):[]),S(typeof _?.clarifier?.question=="string"?String(_.clarifier.question):""),H(_?.planner_diagnostics||_?.plannerDiagnostics||null)},onError:_=>{const J=_ instanceof Error?_.message:String(_);S(J),n("err",J)}}),yt=xe({mutationFn:async()=>!a?.workflowPlans?.chatReset||!O?.plan_id?null:a.workflowPlans.chatReset({plan_id:O.plan_id}),onSuccess:_=>{k(_?.plan||null),A(_?.conversation||null),B([]),S(""),H(_?.planner_diagnostics||_?.plannerDiagnostics||null)},onError:_=>{const J=_ instanceof Error?_.message:String(_);S(J),n("err",J)}}),Ut=xe({mutationFn:async _=>{if(!a?.skills?.get||!a?.skills?.validate)return null;const be=(await a.skills.get(_))?.content;return be?a.skills.validate({content:be}):null},onSuccess:_=>{if(!_){Oe("");return}Oe(_.invalid>0?"not_validated":"validated")},onError:()=>Oe("not_validated")}),Je=xe({mutationFn:async()=>{if(!a?.skills?.generate||!se.goal.trim())return null;const _=se.advancedMode?[se.goal.trim(),se.customSkillName?`Skill name: ${se.customSkillName}`:"",se.customSkillDescription?`Description: ${se.customSkillDescription}`:"",`Workflow kind: ${se.customWorkflowKind}`].filter(Boolean).join(`
|
|
2443
|
-
`):se.goal;return a.skills.generate({prompt:_})},onSuccess:_=>{We(_);const J=Object.keys(_?.artifacts||{})[0];me(J||"SKILL.md"),ce(!1),qe("")},onError:()=>{We(null),ce(!1),qe("Optional skill generation failed.")}}),Ge=xe({mutationFn:async()=>{if(!a?.skills?.generateInstall)return null;const _=Ee?.artifacts;if(!_||!_["SKILL.md"])throw new Error("No generated artifacts available to install.");return a.skills.generateInstall({location:"project",conflictPolicy:"rename",artifacts:{"SKILL.md":_["SKILL.md"],"workflow.yaml":_["workflow.yaml"],"automation.example.yaml":_["automation.example.yaml"]}})},onSuccess:_=>{const J=_?.skill?.name;qe(J?`Installed optional skill as '${String(J)}' in project skills.`:"Installed optional skill in project skills."),d.invalidateQueries({queryKey:["automations"]})},onError:_=>qe(`Install failed: ${_ instanceof Error?_.message:String(_)}`)}),nt=xe({mutationFn:async()=>{if(!se.goal.trim())throw new Error("Please describe your goal first.");const _=O||await De.mutateAsync().catch(be=>{throw be instanceof Error?be:new Error(String(be))}),J=_?.plan||_;if(!J)throw new Error("Workflow plan preview failed.");return a.workflowPlans.apply({plan:J,creator_id:"control-panel",...se.exportPackDraft?{pack_builder_export:{enabled:!0,auto_apply:!1}}:{}})},onSuccess:async _=>{_?.pack_builder_export?.status==="preview_pending"?n("ok","🎉 Automation created and reusable pack draft exported. Check Pack Builder to continue."):n("ok","🎉 Automation created! Check 'My Automations' to see it running."),await Promise.all([d.invalidateQueries({queryKey:["automations"]}),d.invalidateQueries({queryKey:["mcp"]})]),Ue(Ps(s,c,String(Ve.data?.workspaceRoot||Ve.data?.workspace_root||"").trim())),C([]),E("automations_page"),k(null),A(null),B([]),S(""),Oe(""),We(null),ce(!1),me("SKILL.md"),qe(""),p(1)},onError:_=>{const J=_ instanceof Error?_.message:String(_);S(J),n("err",J)}}),ve=Pn(se.workspaceRoot),_e=tr(se.plannerModelProvider,se.plannerModelId),Ye=Mu(se.roleModelsJson),le=u===1?se.goal.trim().length>8:u===2?!!se.schedulePreset||!!se.cron.trim():u===3?!!se.mode&&!ve&&!_e&&!Ye:!0,it=async()=>{if(u===1){const J=await Ct.mutateAsync(se.goal);J&&J.decision==="match"&&J.skill_name?(Ut.mutateAsync(String(J.skill_name)),Ue(je=>({...je,routedSkill:String(J.skill_name),routingConfidence:typeof J.confidence=="number"?`${Math.round(J.confidence*100)}%`:""}))):(Oe(""),Ue(je=>({...je,routedSkill:"",routingConfidence:""})));const be=Array.isArray(J?.top_matches)?J.top_matches:[];C(be)}const _=u+1;if(_===4){S(""),k(null),A(null),B([]);try{await De.mutateAsync()}catch{return}}p(_)};return fe(()=>{if(u===1)try{const _=sessionStorage.getItem(Cs);if(!_)return;sessionStorage.removeItem(Cs);const J=JSON.parse(_),be=String(J?.prompt||"").trim();if(!be)return;const je=String(J?.plan_source||"chat_setup").trim()||"chat_setup";E(je),Ue(o=>({...o,goal:be}))}catch{}},[u]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex items-center gap-2",children:ma.steps.map((_,J)=>{const be=J+1,je=be===u,o=be<u;return e("div",{className:"flex-1",children:[e("button",{className:`mb-1 flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium transition-all ${je?"bg-amber-500/20 text-amber-300":o?"text-slate-400":"text-slate-600"}`,onClick:()=>o&&p(be),children:[e("span",{className:`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${je?"bg-amber-500 text-black":o?"bg-slate-600 text-white":"bg-slate-800 text-slate-500"}`,children:o?"✓":be}),_]}),e("div",{className:"h-0.5 w-full rounded-full bg-slate-800",children:e("div",{className:"h-full rounded-full bg-amber-500 transition-all",style:{width:o?"100%":je?"50%":"0%"}})})]},_)})}),e(Mt,{mode:"wait",children:e($e.div,{initial:{opacity:0,x:16},animate:{opacity:1,x:0},exit:{opacity:0,x:-16},transition:{duration:.18},children:u===1?e(em,{value:se.goal,onChange:_=>Ue(J=>({...J,goal:_})),routedSkill:se.routedSkill,routingConfidence:se.routingConfidence,validationBadge:ee,generatedSkill:Ee,advancedMode:se.advancedMode,customSkillName:se.customSkillName,customSkillDescription:se.customSkillDescription,customWorkflowKind:se.customWorkflowKind,onToggleAdvancedMode:()=>Ue(_=>({..._,advancedMode:!_.advancedMode})),onChangeCustomSkillName:_=>Ue(J=>({...J,customSkillName:_})),onChangeCustomSkillDescription:_=>Ue(J=>({...J,customSkillDescription:_})),onChangeCustomWorkflowKind:_=>Ue(J=>({...J,customWorkflowKind:_})),showArtifactPreview:ne,onToggleArtifactPreview:()=>ce(_=>!_),artifactPreviewKey:M,onSelectArtifactPreviewKey:_=>me(_),onGenerateSkill:()=>{Je.mutateAsync()},onInstallGeneratedSkill:()=>{Ge.mutateAsync()},isGeneratingSkill:Je.isPending,isInstallingSkill:Ge.isPending,installStatus:Re,topMatches:x,isMatching:Ct.isPending}):u===2?e(tm,{selected:se.schedulePreset,onSelect:_=>Ue(J=>({...J,schedulePreset:_.label,cron:_.cron})),customCron:se.cron,onCustomCron:_=>Ue(J=>({...J,cron:_,schedulePreset:""}))}):u===3?e(am,{selected:se.mode,onSelect:_=>Ue(J=>({...J,mode:_})),maxAgents:se.maxAgents,onMaxAgents:_=>Ue(J=>({...J,maxAgents:_})),workspaceRoot:se.workspaceRoot,onWorkspaceRootChange:_=>Ue(J=>({...J,workspaceRoot:_})),providerOptions:Ce,providerId:se.modelProvider,modelId:se.modelId,plannerProviderId:se.plannerModelProvider,plannerModelId:se.plannerModelId,onProviderChange:_=>Ue(J=>({...J,modelProvider:_,modelId:_===J.modelProvider?J.modelId:""})),onModelChange:_=>Ue(J=>({...J,modelId:_})),onPlannerProviderChange:_=>Ue(J=>({...J,plannerModelProvider:_,plannerModelId:_===J.plannerModelProvider?J.plannerModelId:""})),onPlannerModelChange:_=>Ue(J=>({...J,plannerModelId:_})),roleModelsJson:se.roleModelsJson,onRoleModelsChange:_=>Ue(J=>({...J,roleModelsJson:_})),roleModelsError:Ye,toolAccessMode:se.toolAccessMode,customToolsText:se.customToolsText,onToolAccessModeChange:_=>Ue(J=>({...J,toolAccessMode:_})),onCustomToolsTextChange:_=>Ue(J=>({...J,customToolsText:_})),mcpServers:gt,selectedMcpServers:se.selectedMcpServers,onToggleMcpServer:_=>Ue(J=>({...J,selectedMcpServers:J.selectedMcpServers.includes(_)?J.selectedMcpServers.filter(be=>be!==_):[...J.selectedMcpServers,_]})),onOpenMcpSettings:()=>r("mcp"),workspaceRootError:ve,plannerModelError:_e,workspaceBrowserOpen:q,workspaceBrowserDir:y,workspaceBrowserSearch:U,onWorkspaceBrowserSearchChange:ue,onOpenWorkspaceBrowser:()=>{const _=String(se.workspaceRoot||Ve.data?.workspaceRoot||Ve.data?.workspace_root||"/").trim();v(_||"/"),ue(""),ye(!0)},onCloseWorkspaceBrowser:()=>{ye(!1),ue("")},onBrowseWorkspaceParent:()=>{L&&v(L)},onBrowseWorkspaceDirectory:_=>v(_),onSelectWorkspaceDirectory:()=>{st&&(Ue(_=>({..._,workspaceRoot:st})),ye(!1),ue(""),n("ok",`Workspace selected: ${st}`))},workspaceBrowserParentDir:L,workspaceCurrentBrowseDir:st,filteredWorkspaceDirectories:lt}):e(nm,{wizard:se,onToggleExportPackDraft:()=>Ue(_=>({..._,exportPackDraft:!_.exportPackDraft})),onSubmit:()=>nt.mutate(),isPending:nt.isPending,planPreview:O,isPreviewing:De.isPending,planningConversation:z,planningChangeSummary:G,onSendPlanningMessage:_=>{$t.mutateAsync(_)},isSendingPlanningMessage:$t.isPending,onResetPlanningChat:()=>{yt.mutateAsync()},isResettingPlanningChat:yt.isPending,plannerError:ae,plannerDiagnostics:I,generatedSkill:Ee,installStatus:Re})},u)}),u<4?e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn",disabled:u===1||De.isPending,onClick:()=>p(_=>_-1),children:"← Back"}),e("button",{className:"tcp-btn-primary",disabled:!le||De.isPending,onClick:()=>{it()},children:De.isPending?"Generating Plan...":"Next →"})]}):null]})}function Ms({client:a,toast:t,navigate:n,viewMode:r,selectedRunId:s,onSelectRunId:c,onOpenRunningView:d,onOpenAdvancedEdit:u}){const p=na(),N=qt(null),[E,x]=w(null),[C,O]=w(null),[k,z]=w("all"),[A,G]=w([]),[B,ae]=w(""),[S,I]=w("all"),[H,q]=w(""),[ye,y]=w(""),[v,U]=w([]),ue=qt(null),ee=qt(null),Oe=qt(null),[Ee,We]=w(!0),[ne,ce]=w(null),M=s.startsWith("automation-v2-run-"),me=Y({queryKey:["automations","list"],queryFn:()=>a?.automations?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Re=Y({queryKey:["automations","v2","list"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),qe=K(()=>{const i=Ea(Re.data,"automations"),m=new Map;for(const D of i){const Z=String(D?.automation_id||D?.automationId||D?.id||"").trim();Z&&(m.has(Z)||m.set(Z,D))}return Array.from(m.values())},[Re.data]),se=Y({queryKey:["providers","catalog","workflow-edit"],queryFn:()=>a?.providers?.catalog?.().catch(()=>({providers:[]}))??Promise.resolve({providers:[]}),refetchInterval:3e4}),Ue=Y({queryKey:["mcp","servers","workflow-edit"],queryFn:()=>a?.mcp?.list?.().catch(()=>({servers:[]}))??Promise.resolve({servers:[]}),refetchInterval:15e3}),Me=Y({queryKey:["automations","runs"],queryFn:()=>a?.automations?.listRuns?.({limit:20}).catch(()=>({runs:[]}))??Promise.resolve({runs:[]}),refetchInterval:9e3}),ze=Y({queryKey:["automations","v2","runs","all"],queryFn:()=>zt("/api/engine/automations/v2/runs?limit=40").catch(()=>({runs:[]})),refetchInterval:9e3}),X=Y({queryKey:["automations","run",s],enabled:!!s,queryFn:()=>(M?a?.automationsV2?.getRun?.(s):a?.automations?.getRun?.(s))?.catch(()=>({run:null}))??Promise.resolve({run:null}),refetchInterval:s?5e3:!1}),Ve=Y({queryKey:["automations","run","artifacts",s],enabled:!!s&&!M,queryFn:()=>a?.automations?.listArtifacts?.(s).catch(()=>({artifacts:[]})),refetchInterval:s?8e3:!1}),re=Y({queryKey:["automations","run","task-reset-preview",s,H],enabled:!!s&&M&&String(H||"").startsWith("node-")&&!!String(H||"").trim()&&!!a?.automationsV2?.previewTaskReset,queryFn:()=>a?.automationsV2?.previewTaskReset(s,String(H||"").replace(/^node-/,"").trim()).catch(()=>({preview:null}))??Promise.resolve({preview:null}),refetchInterval:!1}),Ce=K(()=>ki(X.data?.run),[X.data]),gt=Hi({queries:Ce.map(i=>({queryKey:["automations","run","session",s,i,"messages"],enabled:!!s&&!!i,queryFn:()=>a?.sessions?.messages?.(i).catch(()=>[])??Promise.resolve([]),refetchInterval:s&&i&&Fa(X.data?.run?.status)?4e3:!1}))}),ie=String(X.data?.run?.automation_id||X.data?.run?.routine_id||"").trim(),L=String(X.data?.contextRunID||(M&&s?`automation-v2-${s}`:"")).trim(),st=Y({queryKey:["automations","history",ie],enabled:!!ie&&!M,queryFn:()=>a?.automations?.history?.(ie,80).catch(()=>({events:[]})),refetchInterval:s?1e4:!1}),pt=Y({queryKey:["automations","run","events",s],enabled:!!s&&!!a?.runEvents,queryFn:()=>a.runEvents(s,{tail:400}).catch(()=>[]),refetchInterval:s&&Fa(X.data?.run?.status)?5e3:!1}),lt=Y({queryKey:["automations","run","context",L],enabled:!!L,queryFn:()=>zt(`/api/engine/context/runs/${encodeURIComponent(L)}`).catch(()=>({run:null})),refetchInterval:L&&Fa(X.data?.run?.status)?5e3:!1}),Ct=Y({queryKey:["automations","run","context",L,"blackboard"],enabled:!!L,queryFn:()=>zt(`/api/engine/context/runs/${encodeURIComponent(L)}/blackboard`).catch(()=>({blackboard:null})),refetchInterval:L&&Fa(X.data?.run?.status)?5e3:!1}),De=Y({queryKey:["automations","run","context",L,"events"],enabled:!!L,queryFn:()=>zt(`/api/engine/context/runs/${encodeURIComponent(L)}/events`).catch(()=>({events:[]})),refetchInterval:L&&Fa(X.data?.run?.status)?5e3:!1}),$t=Y({queryKey:["automations","run","context",L,"patches"],enabled:!!L,queryFn:()=>zt(`/api/engine/context/runs/${encodeURIComponent(L)}/blackboard/patches`).catch(()=>({patches:[]})),refetchInterval:L&&Fa(X.data?.run?.status)?5e3:!1}),yt=Y({queryKey:["automations","packs"],queryFn:()=>a?.packs?.list?.().catch(()=>({packs:[]}))??Promise.resolve({packs:[]}),refetchInterval:3e4}),Ut=xe({mutationFn:i=>a?.automations?.runNow?.(i),onSuccess:async()=>{t("ok","Automation triggered."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Je=xe({mutationFn:i=>a?.automationsV2?.runNow?.(i),onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||"").trim();t("ok","Workflow automation triggered."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ge=xe({mutationFn:async({action:i,runId:m,family:D,reason:Z})=>D==="v2"?i==="pause"?a.automationsV2.pauseRun(m,Z):a.automationsV2.resumeRun(m,Z):i==="pause"?a.automations.pauseRun(m,Z):a.automations.resumeRun(m,Z),onSuccess:async()=>{t("ok","Run action applied."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),nt=xe({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.repairRun)throw new Error("Workflow repair is not available in this client.");return a.automationsV2.repairRun(i,{node_id:m,reason:D??""})},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Workflow continued from blocked step."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ve=xe({mutationFn:async({runId:i,reason:m})=>{if(!a?.automationsV2?.recoverRun)throw new Error("Workflow retry is not available in this client.");return a.automationsV2.recoverRun(i,m)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Workflow run queued again."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),_e=xe({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.retryTask)throw new Error("Task retry is not available in this client.");return a.automationsV2.retryTask(i,m,D)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Task retried and subtree requeued."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ye=xe({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.continueTask)throw new Error("Task continue is not available in this client.");return a.automationsV2.continueTask(i,m,D)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Blocked task continued with minimal reset."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),le=xe({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.requeueTask)throw new Error("Task requeue is not available in this client.");return a.automationsV2.requeueTask(i,m,D)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Task requeued and subtree reset."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),it=xe({mutationFn:async({runId:i,taskId:m,agentId:D,reason:Z})=>{if(!a?.automationsV2?.claimBacklogTask)throw new Error("Backlog task claim is not available in this client.");return a.automationsV2.claimBacklogTask(i,m,{agent_id:D,reason:Z})},onSuccess:async()=>{t("ok","Backlog task claimed."),await p.invalidateQueries({queryKey:["automations"]}),s&&(c(s),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),_=xe({mutationFn:async({runId:i,taskId:m,reason:D})=>{if(!a?.automationsV2?.requeueBacklogTask)throw new Error("Backlog task requeue is not available in this client.");return a.automationsV2.requeueBacklogTask(i,m,D)},onSuccess:async()=>{t("ok","Backlog task requeued."),await p.invalidateQueries({queryKey:["automations"]}),s&&(c(s),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),J=xe({mutationFn:async i=>{const m=String(i.name||"").trim(),D=String(i.objective||"").trim(),Z=String(i.cronExpression||"").trim(),de=Number(i.intervalSeconds);if(!m)throw new Error("Automation name is required.");if(!D)throw new Error("Objective is required.");if(i.scheduleKind==="cron"&&!Z)throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(de)||de<=0))throw new Error("Interval seconds must be greater than zero.");return a.automations.update(i.automationId,{name:m,mode:i.mode,mission:{objective:D},policy:{approval:{requires_approval:!!i.requiresApproval}},schedule:i.scheduleKind==="cron"?{cron:{expression:Z}}:{interval_seconds:{seconds:Math.round(de)}}})},onSuccess:async()=>{t("ok","Automation updated."),O(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),be=xe({mutationFn:async i=>{const m=String(i.name||"").trim(),D=String(i.description||"").trim(),Z=String(i.workspaceRoot||"").trim(),de=kr(i.modelProvider,i.modelId),rt=tr(i.plannerModelProvider,i.plannerModelId),Dt=Pn(Z);if(!m)throw new Error("Automation name is required.");if(Dt)throw new Error(Dt);if(de)throw new Error(de);if(rt)throw new Error(rt);if(i.scheduleKind==="cron"&&!String(i.cronExpression||"").trim())throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(Number(i.intervalSeconds))||Number(i.intervalSeconds)<=0))throw new Error("Interval seconds must be greater than zero.");const fa=Lu(i),ba=Wu(fa),ca=i.selectedMcpServers.map(l=>String(l||"").trim()).filter(Boolean),Ta=Eu(ca,i.toolAccessMode,i.customToolsText),Ht=qe.find(l=>String(l?.automation_id||l?.automationId||l?.id||"").trim()===i.automationId),Ra=Array.isArray(Ht?.agents)?Ht.agents.map(l=>({...l,model_policy:ba,modelPolicy:void 0,tool_policy:{...l?.tool_policy||{},allowlist:Ta,denylist:Array.isArray(l?.tool_policy?.denylist)?l.tool_policy.denylist:[]},mcp_policy:{...l?.mcp_policy||{},allowed_servers:ca,allowed_tools:null}})):[],rn=Array.isArray(Ht?.flow?.nodes)?Ht.flow.nodes.map((l,T)=>{const ke=String(l?.node_id||l?.nodeId||l?.id||`node-${T}`).trim(),Qe=i.nodes.find(Rt=>Rt.nodeId===ke);return Qe?{...l,objective:String(Qe.objective||"").trim()}:l}):[],pr=Ht?.metadata&&typeof Ht.metadata=="object"?Ht.metadata:{};return a.automationsV2.update(i.automationId,{name:m,description:D||null,schedule:Fu(i),workspace_root:Z,execution:{...Ht?.execution||{},max_parallel_agents:i.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(i.maxParallelAgents||"4"),10)||4)):1},flow:Ht?.flow?{...Ht.flow,nodes:rn}:Ht?.flow,agents:Ra,metadata:{...pr,workspace_root:Z,operator_preferences:fa,allowed_mcp_servers:ca}})},onSuccess:async()=>{t("ok","Workflow automation updated."),ce(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),je=xe({mutationFn:async({action:i,automationId:m,family:D})=>D==="v2"?i==="delete"?a.automationsV2.delete(m):i==="pause"?a.automationsV2.pause(m):a.automationsV2.resume(m):i==="delete"?a.automations.delete(m):a.automations.update(m,{status:i==="pause"?"paused":"enabled"}),onSuccess:async(i,m)=>{m.action==="delete"&&t("ok","Automation removed."),m.action==="pause"&&t("ok","Automation paused."),m.action==="resume"&&t("ok","Automation resumed."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),o=K(()=>{const i=[...Ea(me.data,"automations"),...Ea(me.data,"routines")],m=new Map;for(const D of i){const Z=String(D?.automation_id||D?.routine_id||D?.id||"").trim();Z&&(m.has(Z)||m.set(Z,D))}return Array.from(m.values())},[me.data]),f=Ea(Me.data,"runs"),R=K(()=>(Array.isArray(se.data?.providers)?se.data.providers:[]).map(m=>({id:String(m?.id||"").trim(),models:Array.isArray(m?.models)?m.models.map(D=>String(D||"").trim()).filter(Boolean):[]})).filter(m=>m.id).sort((m,D)=>m.id.localeCompare(D.id)),[se.data]),P=K(()=>qi(Ue.data),[Ue.data]),$=Ea(ze.data,"runs"),Xe=K(()=>{const i=[...f,...$],m=new Map;for(const D of i){const Z=String(D?.run_id||D?.runId||D?.id||"").trim();Z&&(m.has(Z)||m.set(Z,D))}return Array.from(m.values()).sort((D,Z)=>{const de=or(D?.started_at_ms||D?.startedAtMs||D?.created_at_ms||D?.createdAtMs||0);return or(Z?.started_at_ms||Z?.startedAtMs||Z?.created_at_ms||Z?.createdAtMs||0)-de})},[f,$]),et=Ea(yt.data,"packs"),bt=Xe.filter(i=>Fa(La(i))),Ot=Xe.filter(i=>{const m=La(i);return m==="failed"||m==="error"||m==="blocked"}),Ae=X.data?.run||null,xt=Ct.data?.blackboard||null,At=Array.isArray(De.data?.events)?De.data.events:[],te=Array.isArray($t.data?.patches)?$t.data.patches:[],Se=K(()=>{if(!M)return{tasks:[],currentTaskId:"",taskSource:"empty"};const i=Xu(Ae,[],v),m=Pi({run:lt.data?.run||null,tasks:Array.isArray(lt.data?.run?.steps)?lt.data?.run.steps:[],blackboard:xt,events:At});if(m.tasks.length){const D=i?m.tasks.map(Z=>Z.id===i&&["pending","runnable","assigned"].includes(Z.state)?{...Z,state:"in_progress"}:Z):m.tasks;return{...m,tasks:D,currentTaskId:m.currentTaskId||i}}return cd(Ae,i)},[M,Ae,v,xt,At,lt.data]),h=K(()=>Se.tasks.find(i=>i.id===H)||null,[H,Se.tasks]),j=K(()=>Se.tasks.find(i=>String(i.state||"").toLowerCase()==="blocked")||null,[Se.tasks]),Q=K(()=>{if(!h)return null;const i=String(h.id||"").replace(/^node-/,"");return ur(Ae,i)},[h,Ae]),W=K(()=>Jr(Q),[Q]),V=K(()=>jn(Q),[Q]),ge=K(()=>_d(h,Q),[h,Q]),Be=ge.touchedFiles,ht=ge.undeclaredFiles,ct=ge.researchReadPaths,kt=ge.discoveredRelevantPaths,tt=ge.reviewedPathsBackedByRead,Nt=ge.unreviewedRelevantPaths,Bt=ge.unmetResearchRequirements,Jt=String(h?.state||"").toLowerCase()==="blocked"?h:j,vt=String(Jt?.id||"").replace(/^node-/,"").trim(),dt=String(Ae?.status||"").trim().toLowerCase(),Ie=La(Ae),Pe=dt!==Ie&&(dt==="completed"||dt==="done")&&Xn(Ae)>0,ha=M&&["failed","paused"].includes(Ie)&&!!s,Ne=M&&!!s&&!!vt,pe=K(()=>{const i=Ae?.nodeRepairGuidance,m=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).map(([Z,de])=>({nodeId:String(Z||"").trim(),guidance:de||{}})).filter(Z=>Z.nodeId):[];if(m.length)return m;const D=Ae?.checkpoint?.node_outputs||Ae?.checkpoint?.nodeOutputs||{};return Object.entries(D).map(([Z,de])=>{const rt=de?.artifact_validation||de?.artifactValidation||{},Dt=de?.validator_summary||de?.validatorSummary||{},fa=Array.isArray(rt?.required_next_tool_actions||rt?.requiredNextToolActions)?rt.required_next_tool_actions||rt.requiredNextToolActions:[],ba=Array.isArray(Dt?.unmet_requirements||Dt?.unmetRequirements)?Dt.unmet_requirements||Dt.unmetRequirements:[],ca=String(Dt?.reason||de?.blocked_reason||de?.blockedReason||"").trim(),Ta=String(rt?.blocking_classification||rt?.blockingClassification||"").trim();return!fa.length&&!ba.length&&!ca&&!Ta?null:{nodeId:String(Z||"").trim(),guidance:{status:de?.status||"",failureKind:de?.failure_kind||de?.failureKind||"",reason:ca,unmetRequirements:ba,blockingClassification:Ta,requiredNextToolActions:fa,repairAttempt:rt?.repair_attempt??rt?.repairAttempt??null,repairAttemptsRemaining:rt?.repair_attempts_remaining??rt?.repairAttemptsRemaining??null}}}).filter(Boolean)},[Ae]);fe(()=>{!h||!ue.current||ue.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[h]),fe(()=>{y("")},[s,H]);const ut=M?Array.isArray(xt?.artifacts)?xt.artifacts:[]:Ea(Ve.data,"artifacts"),He=K(()=>ut.map((i,m)=>{const D=String(i?.id||i?.artifact_id||`artifact-${m+1}`).trim(),Z=String(i?.name||i?.label||i?.kind||i?.type||i?.path||D).trim(),de=String(i?.kind||i?.type||i?.path||"").trim(),rt=Jn(On(i));return{key:D,name:Z||D,kind:de,artifact:i,paths:rt}}),[ut]),_t=K(()=>h?Jn([...On(Q),...On(V),String(h.output_path||"").trim()]):[],[h,V,Q]),Kt=K(()=>_t.length?He.filter(i=>i.paths.some(m=>_t.includes(m))):[],[He,_t]),ia=ge.verificationOutcome,Et=ge.verificationPassed,Qt=ge.verificationResults,Pt=K(()=>String(h?.id||"").startsWith("node-")?String(h?.id||"").replace(/^node-/,"").trim():"",[h]),Xt=K(()=>String(h?.id||"").startsWith("node-"),[h]),Zt=K(()=>String(h?.task_type||"").trim()==="automation_backlog_item",[h]),ua=K(()=>String(h?.state||"").trim().toLowerCase(),[h]),xa=K(()=>Number(h?.lease_expires_at_ms||0)||0,[h]),b=K(()=>!!h?.is_stale||ua==="in_progress"&&xa>0&&xa<=Date.now(),[h,xa,ua]),F=ge.failureDetail,he=ge.workflowClass,Fe=ge.phase,Ke=ge.failureKind,at=ge.artifactCandidates,wt=K(()=>ud(Ae,Pt,8),[Pt,Ae]),Gt=K(()=>Yu(Se.tasks,h?.id||""),[h,Se.tasks]),ra=K(()=>Gt.map(i=>Se.tasks.find(m=>m.id===i)||null).filter(Boolean),[Gt,Se.tasks]),Da=K(()=>{const i=re.data?.preview,m=Array.isArray(i?.reset_nodes)?i.reset_nodes.map(D=>String(D||"").trim()).filter(Boolean):[];return m.length?m:Gt.map(D=>D.replace(/^node-/,"").trim()).filter(Boolean)},[Gt,re.data]),Tt=K(()=>{const i=re.data?.preview,m=Array.isArray(i?.cleared_outputs)?i.cleared_outputs.map(D=>String(D||"").trim()).filter(Boolean):[];return m.length?Jn(m):Jn(ra.map(D=>String(D?.output_path||"").trim()))},[ra,re.data]),ka=i=>{const m=String(i||"").trim(),D=He.find(Z=>Z.paths.includes(m));y(D?.key||""),ee.current&&ee.current.scrollIntoView({block:"nearest",behavior:"smooth"})},ja=M&&!!s&&Xt&&!!Pt&&["blocked","failed"].includes(ua),Na=M&&!!s&&Xt&&!!Pt&&ua==="blocked",bn=M&&!!s&&Xt&&!!Pt&&!["in_progress","done","blocked","failed"].includes(ua),vn=M&&!!s&&Zt&&!Xt&&["pending","runnable"].includes(ua),yn=M&&!!s&&Zt&&!Xt&&(["blocked","failed"].includes(ua)||b),oa=K(()=>{const i=re.data?.preview,m=String(h?.title||Pt||"task").trim(),D=Da.length,Z=Math.max(0,D-(Pt?1:0)),de=Tt.length;return{rootTitle:m,subtreeCount:D,descendantCount:Z,outputCount:de,previewBacked:!!re.data?.preview,preservesUpstreamOutputs:typeof i?.preserves_upstream_outputs=="boolean"?i.preserves_upstream_outputs:!0}},[h,Pt,Da.length,Tt.length,re.data]),la=zu(Ae,ut),an=M?(()=>{const i=vd(At,te);return i.length?i:yd(Array.isArray(pt.data)?pt.data:[],Ia)})():Array.isArray(st.data?.events)?st.data.events:Array.isArray(st.data?.history)?st.data.history:[],Bn=K(()=>wd(Array.isArray(pt.data)?pt.data:[],At,M,Ia),[M,pt.data,s,At]),Aa=K(()=>{const i=[...Bn,...A],m=new Set;return i.filter(D=>!D?.id||m.has(D.id)?!1:(m.add(D.id),!0)).sort((D,Z)=>Number(D.at||0)-Number(Z.at||0))},[Bn,A]),sa=Aa.filter(i=>k==="all"?!0:i.source===k),Ja=K(()=>Nd(sa),[sa]),Ua=K(()=>gt.flatMap((i,m)=>{const D=Ce[m]||"";return(Array.isArray(i.data)?i.data:[]).map(de=>({sessionId:D,message:de}))}),[Ce,gt]),mr=K(()=>{const i=[];return i.push({label:"status",value:Ie||"unknown"}),Pe&&i.push({label:"status note",value:"derived from blocked nodes"}),i.push({label:"artifacts",value:String(ut.length)}),M&&(i.push({label:"tasks",value:String(Se.tasks.length)}),i.push({label:"context events",value:String(At.length)}),i.push({label:"blackboard patches",value:String(te.length)}),i.push({label:"completed nodes",value:String(ps(Ae))}),i.push({label:"pending nodes",value:String(nd(Ae))}),i.push({label:"blocked nodes",value:String(Xn(Ae))})),String(Ae?.detail||"").trim()&&i.push({label:"detail",value:String(Ae.detail).trim()}),Ae?.requires_approval!==void 0&&i.push({label:"requires approval",value:String(!!Ae?.requires_approval)}),String(Ae?.approval_reason||"").trim()&&i.push({label:"approval reason",value:String(Ae.approval_reason).trim()}),String(Ae?.denial_reason||"").trim()&&i.push({label:"denial reason",value:String(Ae.denial_reason).trim()}),String(Ae?.paused_reason||"").trim()&&i.push({label:"paused reason",value:String(Ae.paused_reason).trim()}),i},[M,ut.length,Ie,Pe,Ae,At.length,te.length,Se.tasks.length]);K(()=>Di(Ae),[Ae]),fe(()=>{ae(i=>i&&Ce.includes(i)?i:Ce[0]||"")},[Ce]),fe(()=>{I(i=>i==="all"||i&&Ce.includes(i)?i:"all")},[Ce]),fe(()=>{G([]),z("all"),q(""),U([]),We(!0)},[s,L]);const wn=qt("");fe(()=>{!s||!Se.tasks.length||wn.current!==s&&(wn.current=s,q(Se.currentTaskId||Se.tasks.find(i=>["in_progress","blocked","assigned","runnable","pending"].includes(String(i.state||"").toLowerCase()))?.id||Se.tasks[0]?.id||""))},[s,Se.currentTaskId,Se.tasks]),en(s?M?`/api/engine/automations/v2/events?run_id=${encodeURIComponent(s)}`:`/api/engine/automations/events?run_id=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const D=ms(m);if(!D||D!==s)return;const Z=Ia(m),de=un(m),rt=`automations:${D}:${Z}:${de}:${Math.random().toString(16).slice(2,8)}`;G(Dt=>[...Dt.slice(-299),{id:rt,source:"automations",at:de,event:m}])}catch{return}},{enabled:!!s}),en(L?`/api/engine/context/runs/${encodeURIComponent(L)}/events/stream?tail=50`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const D=`context:${String(m?.seq||"")}:${String(m?.event_type||"")}`,Z=Oi(m?.created_at_ms||m?.timestamp_ms||m?.timestampMs)||Date.now();G(de=>de.some(rt=>rt.id===D)?de:[...de.slice(-399),{id:D,source:"context",at:Z,event:m}])}catch{return}},{enabled:!!L}),en(s&&B?`/event?sessionID=${encodeURIComponent(B)}&runID=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m)return;const D=Ia(m),Z=un(m),de=[D||"event",String(m?.properties?.sessionID||m?.sessionID||B||""),String(m?.properties?.runID||m?.runID||s||""),String(m?.properties?.messageID||m?.messageID||""),String(m?.properties?.part?.id||m?.properties?.seq||m?.timestamp_ms||Z)].join(":");U(rt=>rt.some(Dt=>Dt.id===de)?rt:[...rt.slice(-499),{id:de,at:Z,event:m}])}catch{return}},{enabled:!!s&&!!B}),en(s?"/api/global/event":"",i=>{try{const m=JSON.parse(String(i?.data||"{}")),D=ms(m);if(!D||D!==s)return;const Z=Ia(m);if(!Z||Z==="server.connected"||Z==="engine.lifecycle.ready")return;const de=un(m),rt=`global:${D}:${Z}:${de}:${Math.random().toString(16).slice(2,8)}`;G(Dt=>[...Dt.slice(-299),{id:rt,source:"global",at:de,event:m}])}catch{return}},{enabled:!!s}),fe(()=>{const i=N.current;i&&wa(i)},[o.length,qe.length,Xe.length,$.length,et.length,bt.length,Ot.length,!!C,!!s,!!B,!!h,A.length,v.length,J.isPending,Ge.isPending,Ut.isPending,Je.isPending]);const _a=i=>{const m=String(i||"").toLowerCase();return m==="active"||m==="completed"||m==="done"?"tcp-badge-ok":m==="running"||m==="in_progress"?"tcp-badge-warn":m==="blocked"?"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200":m==="failed"||m==="error"?"tcp-badge-err":"tcp-badge-info"},Te=i=>{const m=String(i?.automation_id||i?.id||i?.routine_id||"").trim();if(!m){t("err","Cannot edit automation without an id.");return}const D=$i(i?.schedule);O({automationId:m,name:String(i?.name||m||"").trim(),objective:String(i?.mission?.objective||i?.mission_snapshot?.objective||"").trim(),mode:String(i?.mode||"").toLowerCase()==="standalone"?"standalone":"orchestrated",requiresApproval:i?.requires_approval===!0||i?.policy?.approval?.requires_approval===!0,scheduleKind:D.scheduleKind==="cron"?"cron":"interval",cronExpression:D.cronExpression,intervalSeconds:String(D.intervalSeconds)})},Qa=i=>{const m=String(i?.status||"").trim().toLowerCase();return m==="paused"||m==="disabled"},nn=o.length,xn=qe.length,ga=nn+xn,Ga=K(()=>Zu(Ae,v,A),[Ae,v,A]),Pa=K(()=>{const i=Ua.map(({sessionId:Z,message:de},rt)=>({id:`message:${Z}:${Vu(de,rt)}`,kind:"message",sessionId:Z,at:Hu(de),variant:Qu(de),label:String(de?.info?.role||"session").trim()||"session",body:Yr(de),raw:de,parts:Gu(de),sessionLabel:Cn(Z)})),m=xd(v,B).map(Z=>({...Z,sessionLabel:Cn(gi(Z.raw,B))})),D=[...i,...m].sort((Z,de)=>Z.at-de.at);return S==="all"?D:D.filter(Z=>Z.sessionId===S)},[S,B,Ua,v]);return fe(()=>{const i=Oe.current;!i||!Ee||(i.scrollTop=i.scrollHeight)},[Pa,Ee]),e("div",{ref:N,className:"grid gap-4",children:[r==="list"&&et.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Installed Packs"}),et.map((i,m)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"📦"}),e("strong",{children:String(i?.name||i?.id||"Pack")})]}),e("span",{className:"tcp-badge-info",children:String(i?.version||"1.0.0")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:String(i?.description||i?.path||"")})]},String(i?.id||i?.name||m)))]}):null,r==="list"?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Saved Automations"}),e("span",{className:"tcp-badge-info",children:[ga," saved"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-[11px] font-medium uppercase tracking-[0.24em] text-slate-500",children:"Scheduled Automations"}),e("span",{className:"tcp-subtle text-xs",children:[nn," items"]})]}),o.length>0?o.map(i=>{const m=String(i?.automation_id||i?.id||i?.routine_id||"");return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"⏰"}),e("strong",{children:String(i?.name||m||"Automation")})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Te(i),children:e("i",{"data-lucide":"pencil"})}),e("span",{className:_a(i?.status),children:String(i?.status||"active")})]})]}),e("div",{className:"tcp-subtle text-xs",children:Ru(i?.schedule)}),e("div",{className:"mt-2",children:e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ut.mutate(m),children:[e("i",{"data-lucide":"play"}),"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>je.mutate({action:Qa(i)?"resume":"pause",automationId:m,family:"legacy"}),disabled:!m||je.isPending,children:[e("i",{"data-lucide":Qa(i)?"play":"pause"}),Qa(i)?"Resume":"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{const D=Xe.find(de=>String(de?.automation_id||de?.routine_id||de?.id||"").trim()===m),Z=String(D?.run_id||D?.id||"").trim();Z?(c(Z),d()):t("info","No runs yet for this automation.")},children:[e("i",{"data-lucide":"info"}),"Debug latest"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>x({automationId:m,family:"legacy",title:String(i?.name||i?.label||m||"automation")}),disabled:!m||je.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})})]},m)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No scheduled automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section shows automation definitions, not execution history."})]})]})]}):null,r==="list"?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-[11px] font-medium uppercase tracking-[0.24em] text-slate-500",children:"Workflow Automations"}),e("span",{className:"tcp-subtle text-xs",children:[xn," items"]})]}),qe.length>0?qe.map(i=>{const m=String(i?.automation_id||i?.automationId||"").trim(),D=String(i?.status||"draft").trim(),Z=D.toLowerCase()==="paused",de=Ku(i);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"🧩"}),e("strong",{children:String(i?.name||m||"Workflow automation")}),de?e("span",{className:"tcp-badge-ok",children:"Standup"}):null]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{if(Bu(i)){u(i);return}ce(Uu(i))},disabled:!m,title:"Edit workflow automation","aria-label":"Edit workflow automation",children:e("i",{"data-lucide":"pencil"})}),e("span",{className:_a(D),children:D})]})]}),String(i?.description||"").trim()?e("div",{className:"tcp-subtle text-xs",children:String(i.description)}):null,de?e("div",{className:"mt-1 text-xs text-emerald-200",children:["report: ",String(i?.metadata?.standup?.report_path_template||"")]}):null,e("div",{className:"tcp-subtle mt-1 text-xs",children:Mi(i?.schedule)}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Je.mutate(m),disabled:!m||Je.isPending,children:[e("i",{"data-lucide":"play"}),Je.isPending?"Starting...":"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>je.mutate({action:Z?"resume":"pause",automationId:m,family:"v2"}),disabled:!m||je.isPending,children:[e("i",{"data-lucide":Z?"play":"pause"}),Z?"Resume":"Pause"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>x({automationId:m,family:"v2",title:String(i?.name||m||"workflow automation")}),disabled:!m||je.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},m)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No workflow automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section is separate from run history and only shows workflow automation definitions."})]})]}):null,r==="running"?bt.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Active Running Tasks"}),e("span",{className:"tcp-badge-warn",children:[bt.length," active"]})]}),bt.slice(0,14).map((i,m)=>{const D=String(i?.run_id||i?.id||m).trim(),Z=La(i),de=i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs;return e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"font-medium text-sm",children:Nr(i)}),e("span",{className:"tcp-subtle text-xs",children:[D||"unknown run"," · running for ",Ts(i)]}),Ka(de)?e("span",{className:"tcp-subtle text-xs",children:["Started: ",Ka(de)]}):null,Xa(i)?e("span",{className:"text-xs text-slate-400",children:$n(Xa(i),160)}):null]}),e("span",{className:_a(Z),children:Z||"unknown"})]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>c(D),children:[e("i",{"data-lucide":"bug"}),"Inspect"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ge.mutate({action:"pause",runId:D,family:D.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!D||Ge.isPending,children:[e("i",{"data-lucide":"pause"}),"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ge.mutate({action:"resume",runId:D,family:D.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!D||Ge.isPending,children:[e("i",{"data-lucide":"play"}),"Resume"]})]})]},D||m)})]}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Active Running Tasks"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"No active runs right now. Start a run to inspect live task execution."})]}):null,r==="running"&&Ot.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Recently Blocked Or Failed Runs"}),e("span",{className:"tcp-badge-err",children:[Ot.length," issues"]})]}),Ot.slice(0,10).map((i,m)=>{const D=String(i?.run_id||i?.id||m).trim(),Z=La(i);return e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"font-medium text-sm",children:Nr(i)}),e("span",{className:"tcp-subtle text-xs",children:D||"unknown run"}),Ka(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Finished:"," ",Ka(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)]}):null,Xa(i)?e("span",{className:"text-xs text-slate-400",children:$n(Xa(i),160)}):null]}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:_a(Z),children:Z||"failed"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>c(D),children:[e("i",{"data-lucide":"bug"}),"Inspect"]})]})]})},`failed-${D||m}`)})]}):null,Xe.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:r==="running"?"Run Log Explorer":"Recent Runs"}),Xe.slice(0,12).map((i,m)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"font-medium text-sm",children:Nr(i)}),e("span",{className:_a(La(i)),children:La(i)||"unknown"})]}),e("div",{className:"mt-1 flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"tcp-subtle text-xs",children:String(i?.run_id||i?.id||"")}),Ka(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Started:"," ",Ka(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)]}):null,i?.finished_at_ms||i?.finishedAtMs?e("span",{className:"tcp-subtle text-xs",children:["Finished: ",Ka(i?.finished_at_ms||i?.finishedAtMs)]}):null,Xa(i)?e("span",{className:"text-xs text-slate-400",children:$n(Xa(i),160)}):null]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{c(String(i?.run_id||i?.id||"").trim()),d()},children:[e("i",{"data-lucide":"info"}),r==="running"?"Logs":"Details"]})]})]},String(i?.run_id||i?.id||m)))]}):null,!Xe.length&&r==="running"?e(Le,{text:"Run one automation, then use Logs to inspect full execution events."}):null,!ga&&!et.length&&!Xe.length&&r==="list"?e(Le,{text:"No automations yet. Create your first one with the wizard!"}):null,e(Mt,{children:[s?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>c(""),children:e($e.div,{className:"tcp-confirm-dialog tcp-run-debugger-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("div",{className:"mb-3 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e("div",{className:"grid gap-1",children:[e("h3",{className:"tcp-confirm-title",children:"Run Debugger"}),e("div",{className:"tcp-subtle text-xs",children:["automation:"," ",String(Ae?.automation_id||Ae?.routine_id||"unknown")," · ","run: ",s," · ","running for ",Ts(Ae)]}),M?e("div",{className:"tcp-subtle text-xs",children:["completed nodes: ",ps(Ae)," · ","blocked nodes: ",Xn(Ae)," · ","active sessions: ",hs(Ae)]}):null]}),e("div",{className:"flex w-full flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center lg:w-auto",children:[e("span",{className:_a(Ie),children:Ie||"unknown"}),Pe?e("span",{className:"tcp-subtle",children:"derived from blocked nodes"}):null,Ne?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>Ye.mutate({runId:s,nodeId:vt,reason:`continued blocked task ${vt} from run debugger`}),disabled:!vt||Ye.isPending||Ge.isPending,title:vt?`Continue blocked task ${vt} with minimal reset`:"Select a blocked node to continue",children:[e("i",{"data-lucide":"skip-forward"}),Ye.isPending?"Continuing...":"Continue"]}):null,ha?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>ve.mutate({runId:s,reason:"retried from run debugger"}),disabled:!s||ve.isPending||Ge.isPending,children:[e("i",{"data-lucide":"rotate-ccw"}),ve.isPending?"Retrying...":"Retry"]}):null,s?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>Ge.mutate({action:Ie==="paused"?"resume":"pause",runId:s,family:M?"v2":"legacy"}),disabled:!s||Ge.isPending||!(Ie==="paused"||Fa(Ie)),children:[e("i",{"data-lucide":Ie==="paused"?"play":"pause"}),Ie==="paused"?"Resume":"Pause"]}):null,e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>{Promise.all([p.invalidateQueries({queryKey:["automations","run",s]}),p.invalidateQueries({queryKey:["automations","run","artifacts",s]}),L?p.invalidateQueries({queryKey:["automations","run","context",L]}):Promise.resolve(),L?p.invalidateQueries({queryKey:["automations","run","context",L,"blackboard"]}):Promise.resolve(),L?p.invalidateQueries({queryKey:["automations","run","context",L,"events"]}):Promise.resolve(),L?p.invalidateQueries({queryKey:["automations","run","context",L,"patches"]}):Promise.resolve(),s?p.invalidateQueries({queryKey:["automations","run","session",s]}):Promise.resolve()])},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>c(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]}),e("div",{className:"flex-1 min-h-0 overflow-y-auto pr-1",children:e("div",{className:"grid min-h-full content-start gap-3",children:[e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Run Summary"}),e("div",{className:"mt-2 grid gap-2 text-xs text-slate-300 sm:grid-cols-2 xl:grid-cols-4",children:mr.map(i=>e("div",{className:"break-words",children:[i.label,": ",i.value]},i.label))})]}),M?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Workflow Board"}),e("div",{className:"tcp-subtle text-xs",children:["context run: ",ar(L||"unlinked",44)," · ","tasks: ",Se.tasks.length," · ","artifacts: ",ut.length]})]}),e("span",{className:"tcp-badge-info",children:Se.taskSource==="hybrid"?"blackboard + context":Se.taskSource==="checkpoint"?"run checkpoint":Se.taskSource})]}),e(Ti,{tasks:Se.tasks,currentTaskId:Se.currentTaskId,selectedTaskId:H,onTaskSelect:i=>q(m=>m===i.id?"":i.id)})]}):null,e("div",{className:"grid min-h-0 items-start gap-3 xl:grid-cols-[1.62fr_1fr]",children:[e("div",{className:"grid min-h-0 gap-3",children:[h?e("div",{ref:ue,className:"tcp-list-item relative max-h-[56vh] overflow-y-auto sm:max-h-[28rem]",children:[e("div",{className:"sticky -top-3 z-10 -mx-3 -mt-3 mb-2 flex items-center justify-between gap-2 rounded-t-xl border-b border-slate-800/80 bg-[color:color-mix(in_srgb,var(--color-surface-elevated)_96%,#000_4%)] px-3 py-3 backdrop-blur-sm",children:[e("div",{className:"font-medium",children:"Task Details"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7","aria-label":"Close task details",onClick:()=>q(""),children:e("i",{"data-lucide":"x-circle"})})]}),e("div",{className:"grid gap-2 pr-1 text-sm text-slate-200",children:[e("div",{className:"whitespace-pre-wrap break-words font-medium leading-snug",children:h.title}),h.description?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:h.description}):null,e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-badge-info",children:h.state}),h.assigned_role?e("span",{className:"tcp-badge-info",children:["agent: ",h.assigned_role]}):null,String(h.task_kind||"").trim()?e("span",{className:"tcp-badge-info",children:["task: ",String(h.task_kind).trim()]}):null,String(h.backlog_task_id||"").trim()?e("span",{className:"tcp-badge-info",children:["backlog:"," ",String(h.backlog_task_id).trim()]}):null,String(h.task_owner||"").trim()?e("span",{className:"tcp-badge-info",children:["owner: ",String(h.task_owner).trim()]}):null,h.session_id?e("span",{className:"tcp-badge-info",children:Cn(h.session_id)}):null]}),Q?e("div",{className:"flex flex-wrap gap-2 text-xs",children:[String(Q?.status||"").trim()?e("span",{className:String(Q?.status||"").trim().toLowerCase()==="blocked"?"tcp-badge-warn":"tcp-badge-ok",children:["status: ",String(Q?.status||"").trim()]}):null,typeof Q?.approved=="boolean"?e("span",{className:Q.approved?"tcp-badge-ok":"tcp-badge-warn",children:["approved: ",String(Q.approved)]}):null,W?.workspace_inspection_used?e("span",{className:"tcp-badge-info",children:"workspace inspected"}):null,W?.web_research_used?e("span",{className:"tcp-badge-info",children:"web research used"}):null,String(V?.rejected_artifact_reason||"").trim()?e("span",{className:"tcp-badge-warn",children:"artifact rejected"}):null]}):null,Xt?null:e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:Zt?"This is a projected backlog task derived from workflow output. You can claim or requeue it here without resetting the source workflow node.":"This is a projected backlog task derived from workflow output, not a direct automation node. Inspect it here, but use the source workflow stage for retry, continue, or requeue actions."}),h.runtime_detail?e("div",{className:"whitespace-pre-wrap break-words rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:h.runtime_detail}):null,he||Fe||Ke||at.length?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Stability Contract"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"workflow class"}),e("div",{className:"mt-1 font-medium text-slate-100",children:he||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"phase"}),e("div",{className:"mt-1 font-medium text-slate-100",children:Fe||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"failure kind"}),e("div",{className:"mt-1 font-medium text-slate-100",children:Ke||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"artifact candidates"}),e("div",{className:"mt-1 font-medium text-slate-100",children:at.length})]})]}),at.length?e("div",{className:"mt-3 grid gap-2",children:at.map((i,m)=>e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-badge-info",children:String(i?.source||"candidate")}),i?.accepted?e("span",{className:"tcp-badge-ok",children:"accepted"}):null,i?.substantive?e("span",{className:"tcp-badge-ok",children:"substantive"}):e("span",{className:"tcp-badge-warn",children:"non-substantive"}),i?.placeholder_like?e("span",{className:"tcp-badge-warn",children:"placeholder-like"}):null]}),e("div",{className:"mt-1 tcp-subtle",children:[Number(i?.length||0)," chars"]})]},`${String(i?.source||"candidate")}-${m}`))}):null,wt.length?e("div",{className:"mt-3 grid gap-2",children:[e("div",{className:"tcp-subtle",children:"recent workflow events"}),wt.map((i,m)=>e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-badge-info",children:i.event}),i.phase?e("span",{className:"tcp-badge-info",children:i.phase}):null,i.failureKind?e("span",{className:"tcp-badge-warn",children:i.failureKind}):null]}),e("div",{className:"mt-1 text-slate-300",children:i.reason})]},`${i.event}-${String(i.recordedAtMs||m)}`))]}):null]}):null,String(h.write_scope||"").trim()||String(h.repo_root||"").trim()||String(h.acceptance_criteria||"").trim()||String(h.task_dependencies||"").trim()||String(h.verification_state||"").trim()||String(h.verification_command||"").trim()||String(h.output_path||"").trim()?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Coding Task Context"}),e("div",{className:"mt-2 space-y-1",children:[e("div",{children:["backlog task:"," ",String(h.backlog_task_id||"").trim()||"n/a"]}),e("div",{children:["repo root:"," ",String(h.repo_root||"").trim()||"n/a"]}),e("div",{children:["output path:"," ",String(h.output_path||"").trim()||"n/a"]}),e("div",{children:["write scope:"," ",String(h.write_scope||"").trim()||"n/a"]}),e("div",{children:["acceptance criteria:"," ",String(h.acceptance_criteria||"").trim()||"n/a"]}),e("div",{children:["task dependencies:"," ",String(h.task_dependencies||"").trim()||"n/a"]}),e("div",{children:["verification state:"," ",String(h.verification_state||"").trim()||"n/a"]}),e("div",{children:["owner:"," ",String(h.task_owner||"").trim()||"n/a"]}),e("div",{children:["lease owner:"," ",String(h.lease_owner||"").trim()||"n/a"]}),e("div",{children:["lease expires:"," ",xa?Ka(xa):"n/a"]}),e("div",{children:["stale lease: ",b?"yes":"no"]}),e("div",{children:["verification:"," ",String(h.verification_command||"").trim()||"n/a"]})]})]}):null,ct.length||kt.length||Bt.length||V?.repair_attempted?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Research Requirement Status"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"discovered relevant files"}),e("div",{className:"mt-1 font-medium text-slate-100",children:kt.length})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"actual read calls backed by path"}),e("div",{className:"mt-1 font-medium text-slate-100",children:ct.length})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"reviewed paths backed by read"}),e("div",{className:"mt-1 font-medium text-slate-100",children:tt.length})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"web research"}),e("div",{className:"mt-1 font-medium text-slate-100",children:V?.web_research_attempted?V?.web_research_succeeded?"attempted and succeeded":"attempted but not successful":"not attempted"})]})]}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"repair pass"}),e("div",{className:"mt-1 font-medium text-slate-100",children:V?.repair_attempted?V?.repair_succeeded?"attempted and satisfied":V?.repair_exhausted?"attempted and exhausted":"attempted and still active":"not needed or not attempted"}),V?.repair_attempted?e("div",{className:"mt-1 tcp-subtle",children:["attempt"," ",Number(V?.repair_attempt||0)," ","of"," ",Number(V?.repair_attempt||0)+Number(V?.repair_attempts_remaining||0)]}):null]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"missing / unreviewed relevant files"}),e("div",{className:"mt-1 font-medium text-slate-100",children:Nt.length})]})]}),Bt.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle mb-1",children:"unmet requirements"}),e("div",{className:"flex flex-wrap gap-1",children:Bt.map(i=>e("span",{className:"rounded-full border border-emerald-500/30 bg-emerald-950/20 px-2 py-1 text-[11px] text-emerald-100/90",children:i},i))})]}):null,Nt.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle mb-1",children:"unreviewed relevant files"}),e("div",{className:"flex flex-wrap gap-1",children:Nt.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))})]}):null]}):null,Q||_t.length||F?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Coding Verification & Failures"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"verification outcome"}),e("div",{className:"mt-1 font-medium text-slate-100",children:ia})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"verification passed"}),e("div",{className:"mt-1 font-medium text-slate-100",children:typeof Et=="boolean"?Et?"yes":"no":"n/a"})]})]}),W?.verification_expected?e("div",{className:"mt-3 rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle mb-2",children:"verification plan"}),e("div",{className:"mb-2 text-slate-200/80",children:[Number(W?.verification_completed||0)," ","/"," ",Number(W?.verification_total||0)," ","checks ran"]}),Qt.length?e("div",{className:"grid gap-2",children:Qt.map((i,m)=>e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/40 p-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-badge-info",children:String(i?.kind||"verify")}),e("span",{className:i?.failed?"tcp-badge-warn":i?.ran?"tcp-badge-ok":"tcp-badge-info",children:i?.failed?"failed":i?.ran?"passed":"not run"})]}),e("div",{className:"mt-1 break-words font-mono text-[11px] text-slate-200",children:String(i?.command||"").trim()||"n/a"}),String(i?.failure||"").trim()?e("div",{className:"mt-1 whitespace-pre-wrap break-words text-[11px] text-emerald-100/90",children:String(i?.failure||"").trim()}):null]},`${String(i?.command||m)}-${m}`))}):null]}):null,F?e("div",{className:"mt-3 rounded-md border border-emerald-500/30 bg-emerald-950/20 p-2 text-emerald-100/90",children:[e("div",{className:"tcp-subtle mb-1 text-emerald-100/70",children:"failure detail"}),e("div",{className:"whitespace-pre-wrap break-words",children:F})]}):null,_t.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle mb-1",children:"related artifacts"}),e("div",{className:"flex flex-wrap gap-2",children:_t.map(i=>e("button",{type:"button",className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-200 transition hover:border-sky-500/40 hover:text-sky-100",onClick:()=>ka(i),title:i,children:["Open ",ar(i,44)]},i))}),Kt.length?e("div",{className:"mt-2 tcp-subtle",children:["matched run artifacts:"," ",Kt.map(i=>i.name).join(", ")]}):e("div",{className:"mt-2 tcp-subtle",children:"No matching run artifact found yet. The button will still jump to the artifacts section."})]}):null,(Na||ja||bn||vn||yn||ha)&&s?e("div",{className:"mt-3 space-y-3",children:[Xt?e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2 text-[11px] text-slate-300",children:[e("div",{className:"font-medium text-slate-100",children:"Action impact"}),e("div",{className:"mt-1 tcp-subtle",children:re.isLoading?"Loading engine preview...":oa.previewBacked?"Engine preview":"UI-estimated preview"}),e("div",{className:"mt-1",children:["Selected task: ",oa.rootTitle]}),e("div",{children:["Reset scope:"," ",Na?"minimal reset of the blocked task":`${oa.subtreeCount} task${oa.subtreeCount===1?"":"s"}${oa.descendantCount>0?` (${oa.descendantCount} descendant${oa.descendantCount===1?"":"s"})`:""}`]}),e("div",{children:["Preserves:"," ",oa.preservesUpstreamOutputs?"completed upstream outputs outside this subtree":"n/a"]}),e("div",{children:["Clears: stale outputs for"," ",oa.outputCount," declared artifact",oa.outputCount===1?"":"s"]}),Tt.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:Tt.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))}):null]}):Zt?e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2 text-[11px] text-slate-300",children:[e("div",{className:"font-medium text-slate-100",children:"Action impact"}),e("div",{className:"mt-1",children:"Claiming assigns this backlog task to an agent without resetting any workflow nodes."}),e("div",{children:"Requeueing clears stale lease state and returns the task to the runnable queue."}),e("div",{children:"Upstream workflow artifacts are preserved because this acts on the projected backlog task only."})]}):null,e("div",{className:"flex flex-wrap gap-2",children:[vn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>it.mutate({runId:s,taskId:String(h.id||""),agentId:String(h.task_owner||"").trim()||void 0,reason:`claimed backlog task ${String(h.id||"")} from debugger`}),disabled:it.isPending||_.isPending,children:it.isPending?"Claiming...":"Claim Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Assign this projected coding task and start its lease."})]}):null,yn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>_.mutate({runId:s,taskId:String(h.id||""),reason:`requeued backlog task ${String(h.id||"")} from debugger`}),disabled:it.isPending||_.isPending,children:_.isPending?"Requeueing...":"Requeue Backlog Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Use when the task is blocked, failed, or its lease went stale."})]}):null,Na?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>Ye.mutate({runId:s,nodeId:Pt,reason:`continued blocked task ${Pt} from debugger`}),disabled:Ye.isPending||_e.isPending||le.isPending||it.isPending||_.isPending,children:Ye.isPending?"Continuing...":"Continue Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Minimal reset: reruns the blocked task itself and preserves descendants unless they need to rerun later."})]}):null,ja?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>_e.mutate({runId:s,nodeId:Pt,reason:`retried task ${Pt} from debugger`}),disabled:Ye.isPending||_e.isPending||le.isPending||it.isPending||_.isPending,children:_e.isPending?"Retrying task...":"Retry Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Best for blocked or failed work that should rerun from this task downward."})]}):null,bn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>le.mutate({runId:s,nodeId:Pt,reason:`requeued task ${Pt} from debugger`}),disabled:Ye.isPending||_e.isPending||le.isPending||it.isPending||_.isPending,children:le.isPending?"Requeueing...":"Requeue Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Use when this task should go back onto the queue with its descendants reset."})]}):null,ua==="blocked"&&vt?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>nt.mutate({runId:s,nodeId:vt,reason:`continued from blocked node ${vt}`}),disabled:Ye.isPending||nt.isPending||!vt,children:nt.isPending?"Repairing...":"Repair Blocked Step"}),e("div",{className:"tcp-subtle text-[11px]",children:"Heavier reset/repair flow for blocked nodes when minimal continue is not enough."})]}):null,ha?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>ve.mutate({runId:s,reason:`retried from task ${String(h.id||"").replace(/^node-/,"")}`}),disabled:ve.isPending,children:ve.isPending?"Retrying...":"Retry Workflow"}),e("div",{className:"tcp-subtle text-[11px]",children:"Recover the whole run, not just this task subtree."})]}):null]})]}):null]}):null,V||W||Be.length||ht.length?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Coding Signals"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"execution mode"}),e("div",{className:"mt-1 font-medium text-slate-100",children:String(V?.execution_policy?.mode||"").trim()||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"git diff"}),e("div",{className:"mt-1 font-medium text-slate-100",children:String(V?.git_diff_summary?.stat||"").trim()||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"workspace inspection"}),e("div",{className:"mt-1 font-medium text-slate-100",children:W?.workspace_inspection_used?"yes":"no"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"web research"}),e("div",{className:"mt-1 font-medium text-slate-100",children:W?.web_research_used?"yes":"no"})]})]}),e("div",{className:"mt-3 space-y-2",children:[e("div",{children:[e("div",{className:"tcp-subtle mb-1",children:"touched files"}),Be.length?e("div",{className:"flex flex-wrap gap-1",children:Be.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))}):e("div",{className:"tcp-subtle",children:"none"})]}),e("div",{children:[e("div",{className:"tcp-subtle mb-1",children:"undeclared files"}),ht.length?e("div",{className:"flex flex-wrap gap-1",children:ht.map(i=>e("span",{className:"rounded-full border border-amber-500/30 bg-amber-950/20 px-2 py-1 font-mono text-[11px] text-amber-100",children:i},i))}):e("div",{className:"tcp-subtle",children:"none"})]})]})]}):null,String(h?.state||"").toLowerCase()==="blocked"?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:"Continue resets this blocked step and its descendants, preserves valid upstream outputs, and clears stale descendant artifacts before requeue."}):null,W?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:[e("div",{className:"mb-2 font-medium text-slate-100",children:"Node Tooling"}),e("div",{className:"grid gap-1",children:[e("div",{children:["offered:"," ",Array.isArray(W?.requested_tools)&&W.requested_tools.join(", ")||"n/a"]}),e("div",{children:["executed:"," ",Array.isArray(W?.executed_tools)&&W.executed_tools.join(", ")||"none"]}),e("div",{children:["workspace inspection:"," ",W?.workspace_inspection_used?"yes":"no"]}),e("div",{children:["web research:"," ",W?.web_research_used?"yes":"no"]})]})]}):null,V?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:[e("div",{className:"mb-2 font-medium text-slate-100",children:"Artifact Validation"}),e("div",{className:"grid gap-1",children:[e("div",{children:["accepted path:"," ",String(V?.accepted_artifact_path||"").trim()||"n/a"]}),e("div",{children:["rejected reason:"," ",String(V?.rejected_artifact_reason||"").trim()||"none"]}),e("div",{children:["auto-cleaned:"," ",String(!!V?.auto_cleaned)]}),e("div",{children:["undeclared files:"," ",ht.length?ht.join(", "):"none"]}),e("div",{children:["execution policy:"," ",String(V?.execution_policy?.mode||"").trim()||"n/a"]}),e("div",{children:["touched files:"," ",Be.length?Be.join(", "):"none"]}),e("div",{children:["git diff:"," ",String(V?.git_diff_summary?.stat||"").trim()||"n/a"]})]})]}):null,h.error_message?e("div",{className:"whitespace-pre-wrap break-words rounded-lg border border-rose-500/30 bg-rose-950/20 p-3 text-xs text-rose-200",children:h.error_message}):null,h.dependencies.length?e("div",{className:"flex flex-wrap gap-1 text-xs",children:h.dependencies.map(i=>e("span",{className:"tcp-badge-info",children:["depends on ",i]},i))}):null]})]}):null,e("div",{className:"tcp-list-item min-h-0 xl:order-2",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Live Session Log"}),e("div",{className:"tcp-subtle text-xs",children:B?S==="all"?`Merged timeline across ${Ce.length||1} session${Ce.length===1?"":"s"}`:`Filtered to ${S}`:"This run does not expose a session transcript."})]}),e("div",{className:"flex flex-wrap gap-2",children:[Ce.length>1?e("select",{className:"tcp-select h-7 min-w-[12rem] max-w-full shrink-0 text-xs sm:min-w-[14rem]",value:S,onInput:i=>I(i.target.value),children:[e("option",{value:"all",children:"All sessions"}),Ce.map(i=>e("option",{value:i,title:i,children:Cn(i)},i))]}):B?e("span",{className:"tcp-badge-info",title:B,children:Cn(B)}):null,B?e("span",{className:"tcp-badge-info",title:B,children:["live: ",ar(B,24)]}):null,e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:!Pa.length,onClick:async()=>{try{await navigator.clipboard.writeText(Pa.map(i=>{const m=new Date(i.at).toLocaleTimeString(),D=i.sessionId?` · ${i.sessionLabel}`:"";return`[${m}] ${i.label}${D}
|
|
2444
|
-
${i.body||
|
|
2442
|
+
websearch`}),e("div",{className:"text-xs text-slate-500",children:"Enter one tool per line or comma-separated. Example: `read`, `write`, `edit`, `bash`, `ls`, `glob`, `websearch`."})]}):e("div",{className:"text-xs text-slate-500",children:"All built-in tools are allowed. MCP tools are additionally controlled by the server selection below."})]}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"MCP Servers"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:y,children:"Add MCP Server"})]}),H.length?e("div",{className:"flex flex-wrap gap-2",children:H.map(Y=>{const Ze=M.includes(Y.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${Ze?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>xe(Y.name),children:[Y.name," ",Y.connected?"• connected":"• disconnected"]},Y.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet. Add one to allow external tools in this automation."})]})]})}function km({wizard:a,onToggleExportPackDraft:t,onSubmit:n,isPending:r,planPreview:s,isPreviewing:c,planningConversation:d,planningChangeSummary:u,onSendPlanningMessage:p,isSendingPlanningMessage:N,onResetPlanningChat:E,isResettingPlanningChat:x,plannerError:A,plannerDiagnostics:O,generatedSkill:_,installStatus:z}){const[P,Q]=w(""),[B,ne]=w(!1),[I,C]=w(!1),[H,M]=w({}),xe=a.cron?a.cron:ga.schedulePresets.find(ae=>ae.label===a.schedulePreset)?.intervalSeconds?`Every ${ga.schedulePresets.find(ae=>ae.label===a.schedulePreset).intervalSeconds/3600}h`:a.schedulePreset||"Manual",y=s&&typeof s=="object"?s.operator_preferences||s.operatorPreferences||{}:{},v=String(y?.execution_mode||a.mode||"team").trim(),j=ga.executionModes.find(ae=>ae.id===v),he=Number(y?.max_parallel_agents??y?.maxParallelAgents??(v==="swarm"?a.maxAgents:1)),ee=!!s,qe=String(ee?y?.model_provider||y?.modelProvider||"":a.modelProvider||"").trim(),$e=String(ee?y?.model_id||y?.modelId||"":a.modelId||"").trim(),Le=y&&typeof y=="object"&&(y?.role_models?.planner||y?.roleModels?.planner),re=String(ee?Le?.provider_id||Le?.providerId||"":a.plannerModelProvider||"").trim(),me=String(ee?Le?.model_id||Le?.modelId||"":a.plannerModelId||"").trim(),q=!!(re&&me||qe&&$e),ge=String(s?.workspace_root||s?.workspaceRoot||a.workspaceRoot||"").trim(),Pe=Array.isArray(s?.allowed_mcp_servers||s?.allowedMcpServers)?s?.allowed_mcp_servers||s?.allowedMcpServers||[]:a.selectedMcpServers,Te=String(ee?y?.tool_access_mode||y?.toolAccessMode||"all":a.toolAccessMode||"all").trim(),se=ee?Wn((y?.tool_allowlist||y?.toolAllowlist||[]).map(ae=>String(ae||"").trim())):ds(a.customToolsText),Oe=s?.schedule?Vi(s.schedule):xe,Me=String(s?.title||"").trim(),He=String(O?.fallback_reason||O?.fallbackReason||"").trim(),Y=String(O?.detail||"").trim(),Ze=ae=>M(Ae=>({...Ae,[ae]:!Ae[ae]}));return e("div",{className:"grid gap-4",children:[e("p",{className:"text-sm text-slate-400",children:"Review your automation before deploying."}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/40 p-4 grid gap-3",children:[Me?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Plan Title"}),e("span",{className:"text-sm font-semibold text-slate-100",children:Me})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Goal"}),e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>ne(ae=>!ae),children:[e("span",{className:"text-sm text-slate-100 italic",children:B?"Hide goal":"View goal"}),e("span",{className:"tcp-subtle text-xs",children:B?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${B?"":"max-h-28 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:pn(a.goal||"")}})})]})]}),e("div",{className:"grid grid-cols-2 gap-3",children:[e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Schedule"}),e("span",{className:"text-sm font-medium text-slate-200",children:Oe})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Execution Mode"}),e("span",{className:"text-sm font-medium text-slate-200",children:[j?.icon," ",j?.label||v,Number.isFinite(he)&&he>1?` · ${he} agents`:""]})]})]}),ee||qe||$e?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Model Override"}),e("span",{className:"text-sm font-medium text-slate-200",children:qe||$e?`${qe||"default provider"} / ${$e||"default model"}`:"Workspace default"})]}):null,ee||re||me?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Planner Model"}),e("span",{className:"text-sm font-medium text-slate-200",children:re||me?`${re||"default provider"} / ${me||"default model"}`:qe||$e?`Using model override: ${qe||"default provider"} / ${$e||"default model"}`:"Workspace default"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Broader Planner Revisions"}),e("span",{className:"text-sm font-medium text-slate-200",children:q?"Enabled. Tandem will use the planner model if set, otherwise it falls back to the selected model override.":"Disabled unless a planner model, model override, or workspace default model is configured"})]}),e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workspace Root"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:ge||"engine workspace root"})]}),ee||Pe.length?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"MCP Servers"}),Pe.length?e("div",{className:"flex flex-wrap gap-1",children:Pe.map(ae=>e("span",{className:"tcp-badge-info",children:ae},ae))}):e("span",{className:"text-sm font-medium text-slate-400",children:"None"})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Tool Access"}),Te==="custom"?se.length?e("div",{className:"flex flex-wrap gap-1",children:se.map(ae=>e("span",{className:"tcp-badge-info",children:ae},ae))}):e("span",{className:"text-sm font-medium text-slate-400",children:"Custom allowlist"}):e("span",{className:"text-sm font-medium text-slate-200",children:"All tools"})]}),a.routedSkill?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Reusable Flow Match"}),e("span",{className:"text-sm font-medium text-slate-200",children:[a.routedSkill,a.routingConfidence?` (${a.routingConfidence})`:""]})]}):null,a.cron?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Cron"}),e("code",{className:"rounded bg-slate-800/60 px-2 py-1 text-xs text-slate-300",children:a.cron})]}):null,e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Workflow Plan"}),c?e("span",{className:"text-sm text-slate-300",children:"Planning workflow…"}):s?e("div",{className:"grid gap-1 text-sm text-slate-300",children:[e("span",{children:["Confidence: ",e("strong",{children:String(s?.confidence||"unknown")})]}),e("span",{children:["Execution target:"," ",e("strong",{children:String(s?.execution_target||"automation_v2")})]}),Me?e("span",{children:["Title: ",e("strong",{children:Me})]}):null,e("span",{children:["Steps:"," ",e("strong",{children:Array.isArray(s?.steps)?s.steps.length:0})]}),Array.isArray(s?.steps)&&s.steps.length?e("div",{className:"mt-1 grid gap-1",children:s.steps.map((ae,Ae)=>(()=>{const St=String(ae?.step_id||ae?.stepId||`step-${Ae+1}`),oe=!!H[St];return e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>Ze(St),children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-xs font-medium text-slate-200",children:[St,ae?.kind?e("span",{className:"ml-2 text-[11px] uppercase tracking-wide text-slate-500",children:String(ae.kind)}):null]}),typeof ae?.objective=="string"&&ae.objective.trim()?e("div",{className:"mt-1 line-clamp-2 text-xs text-slate-400",children:ae.objective}):null]}),e("span",{className:"tcp-subtle shrink-0 text-xs",children:oe?"Hide":"Details"})]}),oe&&typeof ae?.objective=="string"&&ae.objective.trim()?e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:"tcp-markdown tcp-markdown-ai text-sm",dangerouslySetInnerHTML:{__html:pn(ae.objective||"")}})}):null]},`${St}-${Ae}`)})())}):null,typeof s?.description=="string"&&s.description.trim()?e("div",{className:"rounded-lg border border-slate-800 bg-slate-950/40",children:[e("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left",onClick:()=>C(ae=>!ae),children:[e("span",{className:"text-sm text-slate-200",children:"Plan description"}),e("span",{className:"tcp-subtle text-xs",children:I?"Collapse":"Expand"})]}),e("div",{className:"border-t border-slate-800 px-3 py-3",children:e("div",{className:`tcp-markdown tcp-markdown-ai text-sm ${I?"":"max-h-24 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:pn(String(s.description||""))}})})]}):null]}):e("span",{className:"text-sm text-slate-400",children:"Workflow preview has not been generated yet."})]})]}),A?e("div",{className:"rounded-xl border border-red-500/40 bg-red-950/30 p-3 text-sm text-red-200",children:A}):null,He?e("div",{className:"rounded-xl border border-amber-500/40 bg-amber-950/30 p-3 text-sm text-amber-100",children:[e("div",{className:"font-medium text-amber-200",children:"Planner fallback"}),e("div",{className:"mt-1",children:["Reason: ",e("code",{className:"text-xs",children:He})]}),Y?e("div",{className:"mt-2 text-xs text-amber-200/90 whitespace-pre-wrap",children:Y}):null]}):null,u.length?e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-emerald-300",children:"Latest Plan Changes"}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:u.map((ae,Ae)=>e("span",{className:"tcp-badge-ok",children:ae},`${ae}-${Ae}`))})]}):null,s?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/40 p-4 grid gap-3",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Planning Chat"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:x||!s?.plan_id,onClick:E,children:x?"Resetting…":"Reset Plan"})]}),e("div",{className:"rounded-lg border border-amber-500/30 bg-amber-950/20 px-3 py-2 text-xs text-amber-200",children:q?"With a planner model or model override configured, planning chat can attempt broader natural-language workflow rewrites across the allowed fixed step ids. Deterministic edits still act as the safety net for schedule, workspace root, title, MCP servers, execution mode, model overrides, safe workflow shapes, small workflow-step changes, and terminal output-style changes. Custom step types are still not supported in this slice.":"Planning chat is currently limited to deterministic edits like schedule, workspace root, title, MCP servers, execution mode, model overrides, switching between safe workflow shapes, small workflow-step changes like adding or removing input collection, analysis, or notifications, and terminal output-style changes like JSON, markdown, summary, URLs, or citations. Broader workflow rewrites require a planner model or model override, and custom step types are still not supported in this slice."}),e("div",{className:"max-h-56 overflow-auto rounded-lg border border-slate-800 bg-slate-950/50 p-3",children:Array.isArray(d?.messages)&&d.messages.length?e("div",{className:"grid gap-3",children:d.messages.map((ae,Ae)=>e("div",{className:"grid gap-1",children:[e("span",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:String(ae?.role||"assistant")}),e("div",{className:"text-sm text-slate-200",children:String(ae?.text||"").trim()})]},`${ae?.created_at_ms||Ae}-${Ae}`))}):e("div",{className:"text-sm text-slate-400",children:"Add planning notes here to revise the workflow before creating it."})}),e("textarea",{className:"tcp-input min-h-[84px] text-sm",value:P,onInput:ae=>Q(ae.target.value),placeholder:'Example: "Make this weekly, run it from /srv/acme/app, and remove notifications."'}),e("div",{className:"flex justify-end",children:e("button",{className:"tcp-btn-primary",disabled:N||!P.trim()||!s?.plan_id,onClick:()=>{const ae=P.trim();ae&&(p(ae),Q(""))},children:N?"Updating plan…":"Update Plan"})})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:e("label",{className:"flex items-start gap-3 rounded-lg border border-slate-700/50 bg-slate-900/30 p-3 text-sm text-slate-300",children:[e("input",{type:"checkbox",className:"mt-0.5",checked:a.exportPackDraft,onChange:t}),e("span",{className:"grid gap-1",children:[e("span",{className:"font-medium text-slate-200",children:"Also export a reusable pack draft"}),e("span",{className:"text-xs text-slate-400",children:"After creating the automation, Tandem will also create a Pack Builder draft so this workflow can be saved and reused later."})]})]})}),_||z?e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Reusable Skill Export"}),e("div",{className:"mt-1 grid gap-1",children:[_?e(la,{children:[e("span",{children:["Draft status:"," ",e("strong",{className:"text-slate-300",children:String(_?.status||"generated")})]}),e("span",{className:"text-amber-200",children:"This draft is prompt-based and may be stale if you changed the workflow plan in planning chat. Regenerate it from Step 1 before saving if you want it to reflect the latest plan direction."})]}):null,z?e("span",{children:z}):null]})]}):null,e("div",{className:"rounded-xl border border-slate-700/40 bg-slate-800/20 p-3 text-xs text-slate-400",children:["💡 Tandem will save this automation and schedule a"," ",e("strong",{className:"text-slate-300",children:j?.label||v})," that runs"," ",e("strong",{className:"text-slate-300",children:Oe}),". You can pause, edit or delete it anytime."]}),e("button",{className:"tcp-btn-primary",disabled:r||c||!a.goal.trim()||!s,onClick:n,children:r?"Creating automation…":"🚀 Create Automation"})]})}function Nm({client:a,api:t,toast:n,navigate:r,defaultProvider:s,defaultModel:c}){const d=ca(),[u,p]=w(1),[N,E]=w("automations_page"),[x,A]=w([]),[O,_]=w(null),[z,P]=w(null),[Q,B]=w([]),[ne,I]=w(""),[C,H]=w(null),[M,xe]=w(!1),[y,v]=w(""),[j,he]=w(""),[ee,qe]=w(""),[$e,Le]=w(null),[re,me]=w(!1),[q,ge]=w("SKILL.md"),[Pe,Te]=w(""),[se,Oe]=w(()=>Js(s,c)),Me=V({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[]})),refetchInterval:3e4}),He=V({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({})),refetchInterval:3e4}),Y=V({queryKey:["mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:12e3}),Ze=V({queryKey:["global","health"],queryFn:()=>a.health().catch(()=>({})),refetchInterval:3e4}),ae=V({queryKey:["automations","workspace-browser",y],enabled:M&&!!y,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(y)}`,{method:"GET"})}),Ae=F(()=>(Array.isArray(Me.data?.all)?Me.data.all:[]).map(G=>({id:String(G?.id||"").trim(),models:Object.keys(G?.models||{})})).filter(G=>!!G.id).sort((G,ue)=>G.id.localeCompare(ue.id)),[Me.data]),St=F(()=>Gi(Y.data),[Y.data]),oe=Array.isArray(ae.data?.directories)?ae.data.directories:[],W=String(ae.data?.parent||"").trim(),lt=String(ae.data?.dir||y||"").trim(),xt=String(j||"").trim().toLowerCase(),rt=F(()=>xt?oe.filter(S=>String(S?.name||S?.path||"").trim().toLowerCase().includes(xt)):oe,[oe,xt]);fe(()=>{const S=String(He.data?.default||s||"").trim();if(!S)return;const G=Ae.find(Ke=>Ke.id===S)?.models||[],ue=String(He.data?.providers?.[S]?.default_model||c||G[0]||"").trim();Oe(Ke=>Ke.modelProvider&&Ke.modelId?Ke:{...Ke,modelProvider:Ke.modelProvider||S,modelId:Ke.modelId||ue})},[c,s,Ae,He.data]),fe(()=>{const S=String(Ze.data?.workspaceRoot||Ze.data?.workspace_root||"").trim();S&&Oe(G=>String(G.workspaceRoot||"").trim()?G:{...G,workspaceRoot:S})},[Ze.data]);const Et=ke({mutationFn:async S=>!S.trim()||!a?.skills?.match?null:a.skills.match({goal:S,maxMatches:3,threshold:.35}),onError:()=>{}}),Fe=ke({mutationFn:async()=>{if(!a?.workflowPlans?.chatStart)throw new Error("This control panel build is missing workflow planner client support. Rebuild the control panel against the local tandem client package.");return await a.workflowPlans.chatStart({prompt:se.goal,schedule:Gu(se),plan_source:N,allowed_mcp_servers:se.selectedMcpServers,workspace_root:se.workspaceRoot,operator_preferences:Yu(se)})||null},onSuccess:S=>{_(S?.plan||null),P(S?.conversation||null),B([]),I(""),H(S?.planner_diagnostics||S?.plannerDiagnostics||null)},onError:S=>{_(null),P(null),B([]),I(S instanceof Error?S.message:String(S)),H(null)}}),Bt=ke({mutationFn:async S=>!a?.workflowPlans?.chatMessage||!O?.plan_id?null:a.workflowPlans.chatMessage({plan_id:O.plan_id,message:S}),onSuccess:S=>{_(S?.plan||null),P(S?.conversation||null),B(Array.isArray(S?.change_summary)?S.change_summary.map(G=>String(G||"").trim()).filter(Boolean):[]),I(typeof S?.clarifier?.question=="string"?String(S.clarifier.question):""),H(S?.planner_diagnostics||S?.plannerDiagnostics||null)},onError:S=>{const G=S instanceof Error?S.message:String(S);I(G),n("err",G)}}),At=ke({mutationFn:async()=>!a?.workflowPlans?.chatReset||!O?.plan_id?null:a.workflowPlans.chatReset({plan_id:O.plan_id}),onSuccess:S=>{_(S?.plan||null),P(S?.conversation||null),B([]),I(""),H(S?.planner_diagnostics||S?.plannerDiagnostics||null)},onError:S=>{const G=S instanceof Error?S.message:String(S);I(G),n("err",G)}}),$t=ke({mutationFn:async S=>{if(!a?.skills?.get||!a?.skills?.validate)return null;const ue=(await a.skills.get(S))?.content;return ue?a.skills.validate({content:ue}):null},onSuccess:S=>{if(!S){qe("");return}qe(S.invalid>0?"not_validated":"validated")},onError:()=>qe("not_validated")}),We=ke({mutationFn:async()=>{if(!a?.skills?.generate||!se.goal.trim())return null;const S=se.advancedMode?[se.goal.trim(),se.customSkillName?`Skill name: ${se.customSkillName}`:"",se.customSkillDescription?`Description: ${se.customSkillDescription}`:"",`Workflow kind: ${se.customWorkflowKind}`].filter(Boolean).join(`
|
|
2443
|
+
`):se.goal;return a.skills.generate({prompt:S})},onSuccess:S=>{Le(S);const G=Object.keys(S?.artifacts||{})[0];ge(G||"SKILL.md"),me(!1),Te("")},onError:()=>{Le(null),me(!1),Te("Optional skill generation failed.")}}),ze=ke({mutationFn:async()=>{if(!a?.skills?.generateInstall)return null;const S=$e?.artifacts;if(!S||!S["SKILL.md"])throw new Error("No generated artifacts available to install.");return a.skills.generateInstall({location:"project",conflictPolicy:"rename",artifacts:{"SKILL.md":S["SKILL.md"],"workflow.yaml":S["workflow.yaml"],"automation.example.yaml":S["automation.example.yaml"]}})},onSuccess:S=>{const G=S?.skill?.name;Te(G?`Installed optional skill as '${String(G)}' in project skills.`:"Installed optional skill in project skills."),d.invalidateQueries({queryKey:["automations"]})},onError:S=>Te(`Install failed: ${S instanceof Error?S.message:String(S)}`)}),tt=ke({mutationFn:async()=>{if(!se.goal.trim())throw new Error("Please describe your goal first.");const S=O||await Fe.mutateAsync().catch(ue=>{throw ue instanceof Error?ue:new Error(String(ue))}),G=S?.plan||S;if(!G)throw new Error("Workflow plan preview failed.");return a.workflowPlans.apply({plan:G,creator_id:"control-panel",...se.exportPackDraft?{pack_builder_export:{enabled:!0,auto_apply:!1}}:{}})},onSuccess:async S=>{S?.pack_builder_export?.status==="preview_pending"?n("ok","🎉 Automation created and reusable pack draft exported. Check Pack Builder to continue."):n("ok","🎉 Automation created! Check 'My Automations' to see it running."),await Promise.all([d.invalidateQueries({queryKey:["automations"]}),d.invalidateQueries({queryKey:["mcp"]})]),Oe(Js(s,c,String(Ze.data?.workspaceRoot||Ze.data?.workspace_root||"").trim())),A([]),E("automations_page"),_(null),P(null),B([]),I(""),qe(""),Le(null),me(!1),ge("SKILL.md"),Te(""),p(1)},onError:S=>{const G=S instanceof Error?S.message:String(S);I(G),n("err",G)}}),be=$n(se.workspaceRoot),Se=pr(se.plannerModelProvider,se.plannerModelId),Ve=Xu(se.roleModelsJson),ce=u===1?se.goal.trim().length>8:u===2?!!se.schedulePreset||!!se.cron.trim():u===3?!!se.mode&&!be&&!Se&&!Ve:!0,dt=async()=>{if(u===1){const G=await Et.mutateAsync(se.goal);G&&G.decision==="match"&&G.skill_name?($t.mutateAsync(String(G.skill_name)),Oe(Ke=>({...Ke,routedSkill:String(G.skill_name),routingConfidence:typeof G.confidence=="number"?`${Math.round(G.confidence*100)}%`:""}))):(qe(""),Oe(Ke=>({...Ke,routedSkill:"",routingConfidence:""})));const ue=Array.isArray(G?.top_matches)?G.top_matches:[];A(ue)}const S=u+1;if(S===4){I(""),_(null),P(null),B([]);try{await Fe.mutateAsync()}catch{return}}p(S)};return fe(()=>{if(u===1)try{const S=sessionStorage.getItem(Ws);if(!S)return;sessionStorage.removeItem(Ws);const G=JSON.parse(S),ue=String(G?.prompt||"").trim();if(!ue)return;const Ke=String(G?.plan_source||"chat_setup").trim()||"chat_setup";E(Ke),Oe(l=>({...l,goal:ue}))}catch{}},[u]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex items-center gap-2",children:ga.steps.map((S,G)=>{const ue=G+1,Ke=ue===u,l=ue<u;return e("div",{className:"flex-1",children:[e("button",{className:`mb-1 flex w-full items-center gap-1.5 rounded-lg px-2 py-1 text-xs font-medium transition-all ${Ke?"bg-amber-500/20 text-amber-300":l?"text-slate-400":"text-slate-600"}`,onClick:()=>l&&p(ue),children:[e("span",{className:`flex h-5 w-5 items-center justify-center rounded-full text-xs font-bold ${Ke?"bg-amber-500 text-black":l?"bg-slate-600 text-white":"bg-slate-800 text-slate-500"}`,children:l?"✓":ue}),S]}),e("div",{className:"h-0.5 w-full rounded-full bg-slate-800",children:e("div",{className:"h-full rounded-full bg-amber-500 transition-all",style:{width:l?"100%":Ke?"50%":"0%"}})})]},S)})}),e(Mt,{mode:"wait",children:e(Re.div,{initial:{opacity:0,x:16},animate:{opacity:1,x:0},exit:{opacity:0,x:-16},transition:{duration:.18},children:u===1?e(ym,{value:se.goal,onChange:S=>Oe(G=>({...G,goal:S})),routedSkill:se.routedSkill,routingConfidence:se.routingConfidence,validationBadge:ee,generatedSkill:$e,advancedMode:se.advancedMode,customSkillName:se.customSkillName,customSkillDescription:se.customSkillDescription,customWorkflowKind:se.customWorkflowKind,onToggleAdvancedMode:()=>Oe(S=>({...S,advancedMode:!S.advancedMode})),onChangeCustomSkillName:S=>Oe(G=>({...G,customSkillName:S})),onChangeCustomSkillDescription:S=>Oe(G=>({...G,customSkillDescription:S})),onChangeCustomWorkflowKind:S=>Oe(G=>({...G,customWorkflowKind:S})),showArtifactPreview:re,onToggleArtifactPreview:()=>me(S=>!S),artifactPreviewKey:q,onSelectArtifactPreviewKey:S=>ge(S),onGenerateSkill:()=>{We.mutateAsync()},onInstallGeneratedSkill:()=>{ze.mutateAsync()},isGeneratingSkill:We.isPending,isInstallingSkill:ze.isPending,installStatus:Pe,topMatches:x,isMatching:Et.isPending}):u===2?e(wm,{selected:se.schedulePreset,onSelect:S=>Oe(G=>({...G,schedulePreset:S.label,cron:S.cron})),customCron:se.cron,onCustomCron:S=>Oe(G=>({...G,cron:S,schedulePreset:""}))}):u===3?e(xm,{selected:se.mode,onSelect:S=>Oe(G=>({...G,mode:S})),maxAgents:se.maxAgents,onMaxAgents:S=>Oe(G=>({...G,maxAgents:S})),workspaceRoot:se.workspaceRoot,onWorkspaceRootChange:S=>Oe(G=>({...G,workspaceRoot:S})),providerOptions:Ae,providerId:se.modelProvider,modelId:se.modelId,plannerProviderId:se.plannerModelProvider,plannerModelId:se.plannerModelId,onProviderChange:S=>Oe(G=>({...G,modelProvider:S,modelId:S===G.modelProvider?G.modelId:""})),onModelChange:S=>Oe(G=>({...G,modelId:S})),onPlannerProviderChange:S=>Oe(G=>({...G,plannerModelProvider:S,plannerModelId:S===G.plannerModelProvider?G.plannerModelId:""})),onPlannerModelChange:S=>Oe(G=>({...G,plannerModelId:S})),roleModelsJson:se.roleModelsJson,onRoleModelsChange:S=>Oe(G=>({...G,roleModelsJson:S})),roleModelsError:Ve,toolAccessMode:se.toolAccessMode,customToolsText:se.customToolsText,onToolAccessModeChange:S=>Oe(G=>({...G,toolAccessMode:S})),onCustomToolsTextChange:S=>Oe(G=>({...G,customToolsText:S})),mcpServers:St,selectedMcpServers:se.selectedMcpServers,onToggleMcpServer:S=>Oe(G=>({...G,selectedMcpServers:G.selectedMcpServers.includes(S)?G.selectedMcpServers.filter(ue=>ue!==S):[...G.selectedMcpServers,S]})),onOpenMcpSettings:()=>r("mcp"),workspaceRootError:be,plannerModelError:Se,workspaceBrowserOpen:M,workspaceBrowserDir:y,workspaceBrowserSearch:j,onWorkspaceBrowserSearchChange:he,onOpenWorkspaceBrowser:()=>{const S=String(se.workspaceRoot||Ze.data?.workspaceRoot||Ze.data?.workspace_root||"/").trim();v(S||"/"),he(""),xe(!0)},onCloseWorkspaceBrowser:()=>{xe(!1),he("")},onBrowseWorkspaceParent:()=>{W&&v(W)},onBrowseWorkspaceDirectory:S=>v(S),onSelectWorkspaceDirectory:()=>{lt&&(Oe(S=>({...S,workspaceRoot:lt})),xe(!1),he(""),n("ok",`Workspace selected: ${lt}`))},workspaceBrowserParentDir:W,workspaceCurrentBrowseDir:lt,filteredWorkspaceDirectories:rt}):e(km,{wizard:se,onToggleExportPackDraft:()=>Oe(S=>({...S,exportPackDraft:!S.exportPackDraft})),onSubmit:()=>tt.mutate(),isPending:tt.isPending,planPreview:O,isPreviewing:Fe.isPending,planningConversation:z,planningChangeSummary:Q,onSendPlanningMessage:S=>{Bt.mutateAsync(S)},isSendingPlanningMessage:Bt.isPending,onResetPlanningChat:()=>{At.mutateAsync()},isResettingPlanningChat:At.isPending,plannerError:ne,plannerDiagnostics:C,generatedSkill:$e,installStatus:Pe})},u)}),u<4?e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn",disabled:u===1||Fe.isPending,onClick:()=>p(S=>S-1),children:"← Back"}),e("button",{className:"tcp-btn-primary",disabled:!ce||Fe.isPending,onClick:()=>{dt()},children:Fe.isPending?"Generating Plan...":"Next →"})]}):null]})}function Vs({client:a,toast:t,navigate:n,viewMode:r,selectedRunId:s,onSelectRunId:c,onOpenRunningView:d,onOpenAdvancedEdit:u}){const p=ca(),N=Rt(null),[E,x]=w(null),[A,O]=w(null),[_,z]=w("all"),[P,Q]=w([]),[B,ne]=w(""),[I,C]=w("all"),[H,M]=w(""),[xe,y]=w(""),[v,j]=w([]),he=Rt(null),ee=Rt(null),qe=Rt(null),[$e,Le]=w(!0),[re,me]=w(null),q=s.startsWith("automation-v2-run-"),ge=V({queryKey:["automations","list"],queryFn:()=>a?.automations?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Pe=V({queryKey:["automations","v2","list"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Te=F(()=>{const i=Fa(Pe.data,"automations"),m=new Map;for(const D of i){const Z=String(D?.automation_id||D?.automationId||D?.id||"").trim();Z&&(m.has(Z)||m.set(Z,D))}return Array.from(m.values())},[Pe.data]),se=V({queryKey:["providers","catalog","workflow-edit"],queryFn:()=>a?.providers?.catalog?.().catch(()=>({providers:[]}))??Promise.resolve({providers:[]}),refetchInterval:3e4}),Oe=V({queryKey:["mcp","servers","workflow-edit"],queryFn:()=>a?.mcp?.list?.().catch(()=>({servers:[]}))??Promise.resolve({servers:[]}),refetchInterval:15e3}),Me=V({queryKey:["automations","runs"],queryFn:()=>a?.automations?.listRuns?.({limit:20}).catch(()=>({runs:[]}))??Promise.resolve({runs:[]}),refetchInterval:9e3}),He=V({queryKey:["automations","v2","runs","all"],queryFn:()=>Xt("/api/engine/automations/v2/runs?limit=40").catch(()=>({runs:[]})),refetchInterval:9e3}),Y=V({queryKey:["automations","run",s],enabled:!!s,queryFn:()=>(q?a?.automationsV2?.getRun?.(s):a?.automations?.getRun?.(s))?.catch(()=>({run:null}))??Promise.resolve({run:null}),refetchInterval:s?5e3:!1}),Ze=V({queryKey:["automations","run","artifacts",s],enabled:!!s&&!q,queryFn:()=>a?.automations?.listArtifacts?.(s).catch(()=>({artifacts:[]})),refetchInterval:s?8e3:!1}),ae=V({queryKey:["automations","run","task-reset-preview",s,H],enabled:!!s&&q&&String(H||"").startsWith("node-")&&!!String(H||"").trim()&&!!a?.automationsV2?.previewTaskReset,queryFn:()=>a?.automationsV2?.previewTaskReset(s,String(H||"").replace(/^node-/,"").trim()).catch(()=>({preview:null}))??Promise.resolve({preview:null}),refetchInterval:!1}),Ae=F(()=>Ui(Y.data?.run),[Y.data]),St=go({queries:Ae.map(i=>({queryKey:["automations","run","session",s,i,"messages"],enabled:!!s&&!!i,queryFn:()=>a?.sessions?.messages?.(i).catch(()=>[])??Promise.resolve([]),refetchInterval:s&&i&&La(Y.data?.run?.status)?4e3:!1}))}),oe=String(Y.data?.run?.automation_id||Y.data?.run?.routine_id||"").trim(),W=String(Y.data?.contextRunID||(q&&s?`automation-v2-${s}`:"")).trim(),lt=V({queryKey:["automations","history",oe],enabled:!!oe&&!q,queryFn:()=>a?.automations?.history?.(oe,80).catch(()=>({events:[]})),refetchInterval:s?1e4:!1}),xt=V({queryKey:["automations","run","events",s],enabled:!!s&&!!a?.runEvents,queryFn:()=>a.runEvents(s,{tail:400}).catch(()=>[]),refetchInterval:s&&La(Y.data?.run?.status)?5e3:!1}),rt=V({queryKey:["automations","run","context",W],enabled:!!W,queryFn:()=>Xt(`/api/engine/context/runs/${encodeURIComponent(W)}`).catch(()=>({run:null})),refetchInterval:W&&La(Y.data?.run?.status)?5e3:!1}),Et=V({queryKey:["automations","run","context",W,"blackboard"],enabled:!!W,queryFn:()=>Xt(`/api/engine/context/runs/${encodeURIComponent(W)}/blackboard`).catch(()=>({blackboard:null})),refetchInterval:W&&La(Y.data?.run?.status)?5e3:!1}),Fe=V({queryKey:["automations","run","context",W,"events"],enabled:!!W,queryFn:()=>Xt(`/api/engine/context/runs/${encodeURIComponent(W)}/events`).catch(()=>({events:[]})),refetchInterval:W&&La(Y.data?.run?.status)?5e3:!1}),Bt=V({queryKey:["automations","run","context",W,"patches"],enabled:!!W,queryFn:()=>Xt(`/api/engine/context/runs/${encodeURIComponent(W)}/blackboard/patches`).catch(()=>({patches:[]})),refetchInterval:W&&La(Y.data?.run?.status)?5e3:!1}),At=V({queryKey:["automations","packs"],queryFn:()=>a?.packs?.list?.().catch(()=>({packs:[]}))??Promise.resolve({packs:[]}),refetchInterval:3e4}),$t=ke({mutationFn:i=>a?.automations?.runNow?.(i),onSuccess:async()=>{t("ok","Automation triggered."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),We=ke({mutationFn:i=>a?.automationsV2?.runNow?.(i),onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||"").trim();t("ok","Workflow automation triggered."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ze=ke({mutationFn:async({action:i,runId:m,family:D,reason:Z})=>D==="v2"?i==="pause"?a.automationsV2.pauseRun(m,Z):a.automationsV2.resumeRun(m,Z):i==="pause"?a.automations.pauseRun(m,Z):a.automations.resumeRun(m,Z),onSuccess:async()=>{t("ok","Run action applied."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),tt=ke({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.repairRun)throw new Error("Workflow repair is not available in this client.");return a.automationsV2.repairRun(i,{node_id:m,reason:D??""})},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Workflow continued from blocked step."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),be=ke({mutationFn:async({runId:i,reason:m})=>{if(!a?.automationsV2?.recoverRun)throw new Error("Workflow retry is not available in this client.");return a.automationsV2.recoverRun(i,m)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Workflow run queued again."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Se=ke({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.retryTask)throw new Error("Task retry is not available in this client.");return a.automationsV2.retryTask(i,m,D)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Task retried and subtree requeued."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ve=ke({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.continueTask)throw new Error("Task continue is not available in this client.");return a.automationsV2.continueTask(i,m,D)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Blocked task continued with minimal reset."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ce=ke({mutationFn:async({runId:i,nodeId:m,reason:D})=>{if(!a?.automationsV2?.requeueTask)throw new Error("Task requeue is not available in this client.");return a.automationsV2.requeueTask(i,m,D)},onSuccess:async i=>{const m=String(i?.run?.run_id||i?.run?.runId||s||"").trim();t("ok","Task requeued and subtree reset."),await p.invalidateQueries({queryKey:["automations"]}),m&&(c(m),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),dt=ke({mutationFn:async({runId:i,taskId:m,agentId:D,reason:Z})=>{if(!a?.automationsV2?.claimBacklogTask)throw new Error("Backlog task claim is not available in this client.");return a.automationsV2.claimBacklogTask(i,m,{agent_id:D,reason:Z})},onSuccess:async()=>{t("ok","Backlog task claimed."),await p.invalidateQueries({queryKey:["automations"]}),s&&(c(s),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),S=ke({mutationFn:async({runId:i,taskId:m,reason:D})=>{if(!a?.automationsV2?.requeueBacklogTask)throw new Error("Backlog task requeue is not available in this client.");return a.automationsV2.requeueBacklogTask(i,m,D)},onSuccess:async()=>{t("ok","Backlog task requeued."),await p.invalidateQueries({queryKey:["automations"]}),s&&(c(s),d())},onError:i=>t("err",i instanceof Error?i.message:String(i))}),G=ke({mutationFn:async i=>{const m=String(i.name||"").trim(),D=String(i.objective||"").trim(),Z=String(i.cronExpression||"").trim(),le=Number(i.intervalSeconds);if(!m)throw new Error("Automation name is required.");if(!D)throw new Error("Objective is required.");if(i.scheduleKind==="cron"&&!Z)throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(le)||le<=0))throw new Error("Interval seconds must be greater than zero.");return a.automations.update(i.automationId,{name:m,mode:i.mode,mission:{objective:D},policy:{approval:{requires_approval:!!i.requiresApproval}},schedule:i.scheduleKind==="cron"?{cron:{expression:Z}}:{interval_seconds:{seconds:Math.round(le)}}})},onSuccess:async()=>{t("ok","Automation updated."),O(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),ue=ke({mutationFn:async i=>{const m=String(i.name||"").trim(),D=String(i.description||"").trim(),Z=String(i.workspaceRoot||"").trim(),le=Er(i.modelProvider,i.modelId),nt=pr(i.plannerModelProvider,i.plannerModelId),Dt=$n(Z);if(!m)throw new Error("Automation name is required.");if(Dt)throw new Error(Dt);if(le)throw new Error(le);if(nt)throw new Error(nt);if(i.scheduleKind==="cron"&&!String(i.cronExpression||"").trim())throw new Error("Cron expression is required.");if(i.scheduleKind==="interval"&&(!Number.isFinite(Number(i.intervalSeconds))||Number(i.intervalSeconds)<=0))throw new Error("Interval seconds must be greater than zero.");const Na=lm(i),_a=cm(Na),ha=i.selectedMcpServers.map(jt=>String(jt||"").trim()).filter(Boolean),_e=tm(ha,i.toolAccessMode,i.customToolsText),ra=Te.find(jt=>String(jt?.automation_id||jt?.automationId||jt?.id||"").trim()===i.automationId),Ca=Array.isArray(ra?.agents)?ra.agents.map(jt=>({...jt,model_policy:_a,modelPolicy:void 0,tool_policy:{...jt?.tool_policy||{},allowlist:_e,denylist:Array.isArray(jt?.tool_policy?.denylist)?jt.tool_policy.denylist:[]},mcp_policy:{...jt?.mcp_policy||{},allowed_servers:ha,allowed_tools:null}})):[],sn=Array.isArray(ra?.flow?.nodes)?ra.flow.nodes.map((jt,_n)=>{const on=String(jt?.node_id||jt?.nodeId||jt?.id||`node-${_n}`).trim(),Sn=i.nodes.find(Vn=>Vn.nodeId===on);return Sn?{...jt,objective:String(Sn.objective||"").trim()}:jt}):[],Sa=ra?.metadata&&typeof ra.metadata=="object"?ra.metadata:{};return a.automationsV2.update(i.automationId,{name:m,description:D||null,schedule:im(i),workspace_root:Z,execution:{...ra?.execution||{},max_parallel_agents:i.executionMode==="swarm"?Math.max(1,Math.min(16,Number.parseInt(String(i.maxParallelAgents||"4"),10)||4)):1},flow:ra?.flow?{...ra.flow,nodes:sn}:ra?.flow,agents:Ca,metadata:{...Sa,workspace_root:Z,operator_preferences:Na,allowed_mcp_servers:ha}})},onSuccess:async()=>{t("ok","Workflow automation updated."),me(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),Ke=ke({mutationFn:async({action:i,automationId:m,family:D})=>D==="v2"?i==="delete"?a.automationsV2.delete(m):i==="pause"?a.automationsV2.pause(m):a.automationsV2.resume(m):i==="delete"?a.automations.delete(m):a.automations.update(m,{status:i==="pause"?"paused":"enabled"}),onSuccess:async(i,m)=>{m.action==="delete"&&t("ok","Automation removed."),m.action==="pause"&&t("ok","Automation paused."),m.action==="resume"&&t("ok","Automation resumed."),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),l=F(()=>{const i=[...Fa(ge.data,"automations"),...Fa(ge.data,"routines")],m=new Map;for(const D of i){const Z=String(D?.automation_id||D?.routine_id||D?.id||"").trim();Z&&(m.has(Z)||m.set(Z,D))}return Array.from(m.values())},[ge.data]),b=Fa(Me.data,"runs"),T=F(()=>(Array.isArray(se.data?.providers)?se.data.providers:[]).map(m=>({id:String(m?.id||"").trim(),models:Array.isArray(m?.models)?m.models.map(D=>String(D||"").trim()).filter(Boolean):[]})).filter(m=>m.id).sort((m,D)=>m.id.localeCompare(D.id)),[se.data]),R=F(()=>Gi(Oe.data),[Oe.data]),$=Fa(He.data,"runs"),Ye=F(()=>{const i=[...b,...$],m=new Map;for(const D of i){const Z=String(D?.run_id||D?.runId||D?.id||"").trim();Z&&(m.has(Z)||m.set(Z,D))}return Array.from(m.values()).sort((D,Z)=>{const le=yr(D?.started_at_ms||D?.startedAtMs||D?.created_at_ms||D?.createdAtMs||0);return yr(Z?.started_at_ms||Z?.startedAtMs||Z?.created_at_ms||Z?.createdAtMs||0)-le})},[b,$]),Xe=Fa(At.data,"packs"),Ot=Ye.filter(i=>La(Wa(i))),Ft=Ye.filter(i=>{const m=Wa(i);return m==="failed"||m==="error"||m==="blocked"}),Ie=Y.data?.run||null,Pt=Et.data?.blackboard||null,bt=Array.isArray(Fe.data?.events)?Fe.data.events:[],te=Array.isArray(Bt.data?.patches)?Bt.data.patches:[],Ne=F(()=>{if(!q)return{tasks:[],currentTaskId:"",taskSource:"empty"};const i=bm(Ie,[],v),m=Ji({run:rt.data?.run||null,tasks:Array.isArray(rt.data?.run?.steps)?rt.data?.run.steps:[],blackboard:Pt,events:bt});if(m.tasks.length){const D=i?m.tasks.map(Z=>Z.id===i&&["pending","runnable","assigned"].includes(Z.state)?{...Z,state:"in_progress"}:Z):m.tasks;return{...m,tasks:D,currentTaskId:m.currentTaskId||i}}return Ad(Ie,i)},[q,Ie,v,Pt,bt,rt.data]),h=F(()=>Ne.tasks.find(i=>i.id===H)||null,[H,Ne.tasks]),U=F(()=>Ne.tasks.find(i=>String(i.state||"").toLowerCase()==="blocked")||null,[Ne.tasks]),J=F(()=>{if(!h)return null;const i=String(h.id||"").replace(/^node-/,"");return Nr(Ie,i)},[h,Ie]),L=F(()=>is(J),[J]),X=F(()=>Kn(J),[J]),ye=F(()=>Kd(h,J),[h,J]),Ue=ye.touchedFiles,st=ye.undeclaredFiles,vt=ye.researchReadPaths,It=ye.discoveredRelevantPaths,et=ye.reviewedPathsBackedByRead,yt=ye.unreviewedRelevantPaths,Lt=ye.unmetResearchRequirements,Qt=String(h?.state||"").toLowerCase()==="blocked"?h:U,Ct=String(Qt?.id||"").replace(/^node-/,"").trim(),Ht=String(Ie?.status||"").trim().toLowerCase(),kt=Wa(Ie),Ge=Ht!==kt&&(Ht==="completed"||Ht==="done")&&dr(Ie)>0,da=q&&["failed","paused"].includes(kt)&&!!s,Ce=q&&!!s&&!!Ct,we=F(()=>{const i=Ie?.nodeRepairGuidance,m=i&&typeof i=="object"&&!Array.isArray(i)?Object.entries(i).map(([Z,le])=>({nodeId:String(Z||"").trim(),guidance:le||{}})).filter(Z=>Z.nodeId):[];if(m.length)return m;const D=Ie?.checkpoint?.node_outputs||Ie?.checkpoint?.nodeOutputs||{};return Object.entries(D).map(([Z,le])=>{const nt=le?.artifact_validation||le?.artifactValidation||{},Dt=le?.validator_summary||le?.validatorSummary||{},Na=Array.isArray(nt?.required_next_tool_actions||nt?.requiredNextToolActions)?nt.required_next_tool_actions||nt.requiredNextToolActions:[],_a=Array.isArray(Dt?.unmet_requirements||Dt?.unmetRequirements)?Dt.unmet_requirements||Dt.unmetRequirements:[],ha=String(Dt?.reason||le?.blocked_reason||le?.blockedReason||"").trim(),_e=String(nt?.blocking_classification||nt?.blockingClassification||"").trim();return!Na.length&&!_a.length&&!ha&&!_e?null:{nodeId:String(Z||"").trim(),guidance:{status:le?.status||"",failureKind:le?.failure_kind||le?.failureKind||"",reason:ha,unmetRequirements:_a,blockingClassification:_e,requiredNextToolActions:Na,repairAttempt:nt?.repair_attempt??nt?.repairAttempt??null,repairAttemptsRemaining:nt?.repair_attempts_remaining??nt?.repairAttemptsRemaining??null}}}).filter(Boolean)},[Ie]);fe(()=>{!h||!he.current||he.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[h]),fe(()=>{y("")},[s,H]);const ut=q?Array.isArray(Pt?.artifacts)?Pt.artifacts:[]:Fa(Ze.data,"artifacts"),Qe=F(()=>ut.map((i,m)=>{const D=String(i?.id||i?.artifact_id||`artifact-${m+1}`).trim(),Z=String(i?.name||i?.label||i?.kind||i?.type||i?.path||D).trim(),le=String(i?.kind||i?.type||i?.path||"").trim(),nt=rr(Bn(i));return{key:D,name:Z||D,kind:le,artifact:i,paths:nt}}),[ut]),qt=F(()=>h?rr([...Bn(J),...Bn(X),String(h.output_path||"").trim()]):[],[h,X,J]),ia=F(()=>qt.length?Qe.filter(i=>i.paths.some(m=>qt.includes(m))):[],[Qe,qt]),ba=ye.verificationOutcome,Kt=ye.verificationPassed,Gt=ye.verificationResults,mt=F(()=>String(h?.id||"").startsWith("node-")?String(h?.id||"").replace(/^node-/,"").trim():"",[h]),ua=F(()=>String(h?.id||"").startsWith("node-"),[h]),na=F(()=>String(h?.task_type||"").trim()==="automation_backlog_item",[h]),Nt=F(()=>String(h?.state||"").trim().toLowerCase(),[h]),Je=F(()=>Number(h?.lease_expires_at_ms||0)||0,[h]),f=F(()=>!!h?.is_stale||Nt==="in_progress"&&Je>0&&Je<=Date.now(),[h,Je,Nt]),K=ye.failureDetail,pe=ye.workflowClass,De=ye.phase,Be=ye.failureKind,it=ye.artifactCandidates,_t=F(()=>Td(Ie,mt,8),[mt,Ie]),zt=F(()=>fm(Ne.tasks,h?.id||""),[h,Ne.tasks]),oa=F(()=>zt.map(i=>Ne.tasks.find(m=>m.id===i)||null).filter(Boolean),[zt,Ne.tasks]),ka=F(()=>{const i=ae.data?.preview,m=Array.isArray(i?.reset_nodes)?i.reset_nodes.map(D=>String(D||"").trim()).filter(Boolean):[];return m.length?m:zt.map(D=>D.replace(/^node-/,"").trim()).filter(Boolean)},[zt,ae.data]),Zt=F(()=>{const i=ae.data?.preview,m=Array.isArray(i?.cleared_outputs)?i.cleared_outputs.map(D=>String(D||"").trim()).filter(Boolean):[];return m.length?rr(m):rr(oa.map(D=>String(D?.output_path||"").trim()))},[oa,ae.data]),va=i=>{const m=String(i||"").trim(),D=Qe.find(Z=>Z.paths.includes(m));y(D?.key||""),ee.current&&ee.current.scrollIntoView({block:"nearest",behavior:"smooth"})},Ma=q&&!!s&&ua&&!!mt&&["blocked","failed"].includes(Nt),Ia=q&&!!s&&ua&&!!mt&&Nt==="blocked",wn=q&&!!s&&ua&&!!mt&&!["in_progress","done","blocked","failed"].includes(Nt),zn=q&&!!s&&na&&!ua&&["pending","runnable"].includes(Nt),Jn=q&&!!s&&na&&!ua&&(["blocked","failed"].includes(Nt)||f),pa=F(()=>{const i=ae.data?.preview,m=String(h?.title||mt||"task").trim(),D=ka.length,Z=Math.max(0,D-(mt?1:0)),le=Zt.length;return{rootTitle:m,subtreeCount:D,descendantCount:Z,outputCount:le,previewBacked:!!ae.data?.preview,preservesUpstreamOutputs:typeof i?.preserves_upstream_outputs=="boolean"?i.preserves_upstream_outputs:!0}},[h,mt,ka.length,Zt.length,ae.data]),Qa=dm(Ie,ut),qa=q?(()=>{const i=Dd(bt,te);return i.length?i:jd(Array.isArray(xt.data)?xt.data:[],Ta)})():Array.isArray(lt.data?.events)?lt.data.events:Array.isArray(lt.data?.history)?lt.data.history:[],$a=F(()=>Ud(Array.isArray(xt.data)?xt.data:[],bt,q,Ta),[q,xt.data,s,bt]),an=F(()=>{const i=[...$a,...P],m=new Set;return i.filter(D=>!D?.id||m.has(D.id)?!1:(m.add(D.id),!0)).sort((D,Z)=>Number(D.at||0)-Number(Z.at||0))},[$a,P]),Ha=an.filter(i=>_==="all"?!0:i.source===_),nn=F(()=>Ld(Ha),[Ha]),rn=F(()=>St.flatMap((i,m)=>{const D=Ae[m]||"";return(Array.isArray(i.data)?i.data:[]).map(le=>({sessionId:D,message:le}))}),[Ae,St]),Qn=F(()=>{const i=[];return i.push({label:"status",value:kt||"unknown"}),Ge&&i.push({label:"status note",value:"derived from blocked nodes"}),i.push({label:"artifacts",value:String(ut.length)}),q&&(i.push({label:"tasks",value:String(Ne.tasks.length)}),i.push({label:"context events",value:String(bt.length)}),i.push({label:"blackboard patches",value:String(te.length)}),i.push({label:"completed nodes",value:String(Ts(Ie))}),i.push({label:"pending nodes",value:String(kd(Ie))}),i.push({label:"blocked nodes",value:String(dr(Ie))})),String(Ie?.detail||"").trim()&&i.push({label:"detail",value:String(Ie.detail).trim()}),Ie?.requires_approval!==void 0&&i.push({label:"requires approval",value:String(!!Ie?.requires_approval)}),String(Ie?.approval_reason||"").trim()&&i.push({label:"approval reason",value:String(Ie.approval_reason).trim()}),String(Ie?.denial_reason||"").trim()&&i.push({label:"denial reason",value:String(Ie.denial_reason).trim()}),String(Ie?.paused_reason||"").trim()&&i.push({label:"paused reason",value:String(Ie.paused_reason).trim()}),i},[q,ut.length,kt,Ge,Ie,bt.length,te.length,Ne.tasks.length]);F(()=>eo(Ie),[Ie]),fe(()=>{ne(i=>i&&Ae.includes(i)?i:Ae[0]||"")},[Ae]),fe(()=>{C(i=>i==="all"||i&&Ae.includes(i)?i:"all")},[Ae]),fe(()=>{Q([]),z("all"),M(""),j([]),Le(!0)},[s,W]);const Hn=Rt("");fe(()=>{!s||!Ne.tasks.length||Hn.current!==s&&(Hn.current=s,M(Ne.currentTaskId||Ne.tasks.find(i=>["in_progress","blocked","assigned","runnable","pending"].includes(String(i.state||"").toLowerCase()))?.id||Ne.tasks[0]?.id||""))},[s,Ne.currentTaskId,Ne.tasks]),en(s?q?`/api/engine/automations/v2/events?run_id=${encodeURIComponent(s)}`:`/api/engine/automations/events?run_id=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const D=Ps(m);if(!D||D!==s)return;const Z=Ta(m),le=hn(m),nt=`automations:${D}:${Z}:${le}:${Math.random().toString(16).slice(2,8)}`;Q(Dt=>[...Dt.slice(-299),{id:nt,source:"automations",at:le,event:m}])}catch{return}},{enabled:!!s}),en(W?`/api/engine/context/runs/${encodeURIComponent(W)}/events/stream?tail=50`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const D=`context:${String(m?.seq||"")}:${String(m?.event_type||"")}`,Z=Xi(m?.created_at_ms||m?.timestamp_ms||m?.timestampMs)||Date.now();Q(le=>le.some(nt=>nt.id===D)?le:[...le.slice(-399),{id:D,source:"context",at:Z,event:m}])}catch{return}},{enabled:!!W}),en(s&&B?`/event?sessionID=${encodeURIComponent(B)}&runID=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m)return;const D=Ta(m),Z=hn(m),le=[D||"event",String(m?.properties?.sessionID||m?.sessionID||B||""),String(m?.properties?.runID||m?.runID||s||""),String(m?.properties?.messageID||m?.messageID||""),String(m?.properties?.part?.id||m?.properties?.seq||m?.timestamp_ms||Z)].join(":");j(nt=>nt.some(Dt=>Dt.id===le)?nt:[...nt.slice(-499),{id:le,at:Z,event:m}])}catch{return}},{enabled:!!s&&!!B}),en(s?"/api/global/event":"",i=>{try{const m=JSON.parse(String(i?.data||"{}")),D=Ps(m);if(!D||D!==s)return;const Z=Ta(m);if(!Z||Z==="server.connected"||Z==="engine.lifecycle.ready")return;const le=hn(m),nt=`global:${D}:${Z}:${le}:${Math.random().toString(16).slice(2,8)}`;Q(Dt=>[...Dt.slice(-299),{id:nt,source:"global",at:le,event:m}])}catch{return}},{enabled:!!s}),fe(()=>{const i=N.current;i&&xa(i)},[l.length,Te.length,Ye.length,$.length,Xe.length,Ot.length,Ft.length,!!A,!!s,!!B,!!h,P.length,v.length,G.isPending,ze.isPending,$t.isPending,We.isPending]);const ea=i=>{const m=String(i||"").toLowerCase();return m==="active"||m==="completed"||m==="done"?"tcp-badge-ok":m==="running"||m==="in_progress"?"tcp-badge-warn":m==="blocked"?"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200":m==="failed"||m==="error"?"tcp-badge-err":"tcp-badge-info"},Gn=i=>{const m=String(i?.automation_id||i?.id||i?.routine_id||"").trim();if(!m){t("err","Cannot edit automation without an id.");return}const D=Yi(i?.schedule);O({automationId:m,name:String(i?.name||m||"").trim(),objective:String(i?.mission?.objective||i?.mission_snapshot?.objective||"").trim(),mode:String(i?.mode||"").toLowerCase()==="standalone"?"standalone":"orchestrated",requiresApproval:i?.requires_approval===!0||i?.policy?.approval?.requires_approval===!0,scheduleKind:D.scheduleKind==="cron"?"cron":"interval",cronExpression:D.cronExpression,intervalSeconds:String(D.intervalSeconds)})},Ga=i=>{const m=String(i?.status||"").trim().toLowerCase();return m==="paused"||m==="disabled"},Oa=l.length,xn=Te.length,kn=Oa+xn,Nn=F(()=>vm(Ie,v,P),[Ie,v,P]),Ea=F(()=>{const i=rn.map(({sessionId:Z,message:le},nt)=>({id:`message:${Z}:${gm(le,nt)}`,kind:"message",sessionId:Z,at:hm(le),variant:mm(le),label:String(le?.info?.role||"session").trim()||"session",body:us(le),raw:le,parts:pm(le),sessionLabel:Mn(Z)})),m=Bd(v,B).map(Z=>({...Z,sessionLabel:Mn(Mi(Z.raw,B))})),D=[...i,...m].sort((Z,le)=>Z.at-le.at);return I==="all"?D:D.filter(Z=>Z.sessionId===I)},[I,B,rn,v]);return fe(()=>{const i=qe.current;!i||!$e||(i.scrollTop=i.scrollHeight)},[Ea,$e]),e("div",{ref:N,className:"grid gap-4",children:[r==="list"&&Xe.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Installed Packs"}),Xe.map((i,m)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"📦"}),e("strong",{children:String(i?.name||i?.id||"Pack")})]}),e("span",{className:"tcp-badge-info",children:String(i?.version||"1.0.0")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:String(i?.description||i?.path||"")})]},String(i?.id||i?.name||m)))]}):null,r==="list"?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Saved Automations"}),e("span",{className:"tcp-badge-info",children:[kn," saved"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-[11px] font-medium uppercase tracking-[0.24em] text-slate-500",children:"Scheduled Automations"}),e("span",{className:"tcp-subtle text-xs",children:[Oa," items"]})]}),l.length>0?l.map(i=>{const m=String(i?.automation_id||i?.id||i?.routine_id||"");return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"⏰"}),e("strong",{children:String(i?.name||m||"Automation")})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Gn(i),children:e("i",{"data-lucide":"pencil"})}),e("span",{className:ea(i?.status),children:String(i?.status||"active")})]})]}),e("div",{className:"tcp-subtle text-xs",children:Vu(i?.schedule)}),e("div",{className:"mt-2",children:e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>$t.mutate(m),children:[e("i",{"data-lucide":"play"}),"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ke.mutate({action:Ga(i)?"resume":"pause",automationId:m,family:"legacy"}),disabled:!m||Ke.isPending,children:[e("i",{"data-lucide":Ga(i)?"play":"pause"}),Ga(i)?"Resume":"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{const D=Ye.find(le=>String(le?.automation_id||le?.routine_id||le?.id||"").trim()===m),Z=String(D?.run_id||D?.id||"").trim();Z?(c(Z),d()):t("info","No runs yet for this automation.")},children:[e("i",{"data-lucide":"info"}),"Debug latest"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>x({automationId:m,family:"legacy",title:String(i?.name||i?.label||m||"automation")}),disabled:!m||Ke.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})})]},m)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No scheduled automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section shows automation definitions, not execution history."})]})]})]}):null,r==="list"?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-[11px] font-medium uppercase tracking-[0.24em] text-slate-500",children:"Workflow Automations"}),e("span",{className:"tcp-subtle text-xs",children:[xn," items"]})]}),Te.length>0?Te.map(i=>{const m=String(i?.automation_id||i?.automationId||"").trim(),D=String(i?.status||"draft").trim(),Z=D.toLowerCase()==="paused",le=om(i);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"🧩"}),e("strong",{children:String(i?.name||m||"Workflow automation")}),le?e("span",{className:"tcp-badge-ok",children:"Standup"}):null]}),e("div",{className:"flex items-center gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{if(sm(i)){u(i);return}me(rm(i))},disabled:!m,title:"Edit workflow automation","aria-label":"Edit workflow automation",children:e("i",{"data-lucide":"pencil"})}),e("span",{className:ea(D),children:D})]})]}),String(i?.description||"").trim()?e("div",{className:"tcp-subtle text-xs",children:String(i.description)}):null,le?e("div",{className:"mt-1 text-xs text-emerald-200",children:["report: ",String(i?.metadata?.standup?.report_path_template||"")]}):null,e("div",{className:"tcp-subtle mt-1 text-xs",children:Vi(i?.schedule)}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>We.mutate(m),disabled:!m||We.isPending,children:[e("i",{"data-lucide":"play"}),We.isPending?"Starting...":"Run now"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ke.mutate({action:Z?"resume":"pause",automationId:m,family:"v2"}),disabled:!m||Ke.isPending,children:[e("i",{"data-lucide":Z?"play":"pause"}),Z?"Resume":"Pause"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>x({automationId:m,family:"v2",title:String(i?.name||m||"workflow automation")}),disabled:!m||Ke.isPending,children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},m)}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"No workflow automations saved yet"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"This section is separate from run history and only shows workflow automation definitions."})]})]}):null,r==="running"?Ot.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Active Running Tasks"}),e("span",{className:"tcp-badge-warn",children:[Ot.length," active"]})]}),Ot.slice(0,14).map((i,m)=>{const D=String(i?.run_id||i?.id||m).trim(),Z=Wa(i),le=i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs;return e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"font-medium text-sm",children:Dr(i)}),e("span",{className:"tcp-subtle text-xs",children:[D||"unknown run"," · running for ",Qs(i)]}),Ka(le)?e("span",{className:"tcp-subtle text-xs",children:["Started: ",Ka(le)]}):null,Xa(i)?e("span",{className:"text-xs text-slate-400",children:Un(Xa(i),160)}):null]}),e("span",{className:ea(Z),children:Z||"unknown"})]}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>c(D),children:[e("i",{"data-lucide":"bug"}),"Inspect"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>ze.mutate({action:"pause",runId:D,family:D.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!D||ze.isPending,children:[e("i",{"data-lucide":"pause"}),"Pause"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>ze.mutate({action:"resume",runId:D,family:D.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!D||ze.isPending,children:[e("i",{"data-lucide":"play"}),"Resume"]})]})]},D||m)})]}):e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Active Running Tasks"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"No active runs right now. Start a run to inspect live task execution."})]}):null,r==="running"&&Ft.length>0?e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("p",{className:"text-xs font-medium uppercase tracking-wide text-slate-500",children:"Recently Blocked Or Failed Runs"}),e("span",{className:"tcp-badge-err",children:[Ft.length," issues"]})]}),Ft.slice(0,10).map((i,m)=>{const D=String(i?.run_id||i?.id||m).trim(),Z=Wa(i);return e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"font-medium text-sm",children:Dr(i)}),e("span",{className:"tcp-subtle text-xs",children:D||"unknown run"}),Ka(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Finished:"," ",Ka(i?.finished_at_ms||i?.finishedAtMs||i?.updated_at_ms||i?.updatedAtMs)]}):null,Xa(i)?e("span",{className:"text-xs text-slate-400",children:Un(Xa(i),160)}):null]}),e("div",{className:"flex items-center gap-2",children:[e("span",{className:ea(Z),children:Z||"failed"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>c(D),children:[e("i",{"data-lucide":"bug"}),"Inspect"]})]})]})},`failed-${D||m}`)})]}):null,Ye.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:r==="running"?"Run Log Explorer":"Recent Runs"}),Ye.slice(0,12).map((i,m)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"font-medium text-sm",children:Dr(i)}),e("span",{className:ea(Wa(i)),children:Wa(i)||"unknown"})]}),e("div",{className:"mt-1 flex items-center justify-between gap-2",children:[e("div",{className:"grid gap-0.5",children:[e("span",{className:"tcp-subtle text-xs",children:String(i?.run_id||i?.id||"")}),Ka(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)?e("span",{className:"tcp-subtle text-xs",children:["Started:"," ",Ka(i?.started_at_ms||i?.startedAtMs||i?.created_at_ms||i?.createdAtMs)]}):null,i?.finished_at_ms||i?.finishedAtMs?e("span",{className:"tcp-subtle text-xs",children:["Finished: ",Ka(i?.finished_at_ms||i?.finishedAtMs)]}):null,Xa(i)?e("span",{className:"text-xs text-slate-400",children:Un(Xa(i),160)}):null]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{c(String(i?.run_id||i?.id||"").trim()),d()},children:[e("i",{"data-lucide":"info"}),r==="running"?"Logs":"Details"]})]})]},String(i?.run_id||i?.id||m)))]}):null,!Ye.length&&r==="running"?e(je,{text:"Run one automation, then use Logs to inspect full execution events."}):null,!kn&&!Xe.length&&!Ye.length&&r==="list"?e(je,{text:"No automations yet. Create your first one with the wizard!"}):null,e(Mt,{children:[s?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>c(""),children:e(Re.div,{className:"tcp-confirm-dialog tcp-run-debugger-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("div",{className:"mb-3 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e("div",{className:"grid gap-1",children:[e("h3",{className:"tcp-confirm-title",children:"Run Debugger"}),e("div",{className:"tcp-subtle text-xs",children:["automation:"," ",String(Ie?.automation_id||Ie?.routine_id||"unknown")," · ","run: ",s," · ","running for ",Qs(Ie)]}),q?e("div",{className:"tcp-subtle text-xs",children:["completed nodes: ",Ts(Ie)," · ","blocked nodes: ",dr(Ie)," · ","active sessions: ",Rs(Ie)]}):null]}),e("div",{className:"flex w-full flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center lg:w-auto",children:[e("span",{className:ea(kt),children:kt||"unknown"}),Ge?e("span",{className:"tcp-subtle",children:"derived from blocked nodes"}):null,Ce?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>Ve.mutate({runId:s,nodeId:Ct,reason:`continued blocked task ${Ct} from run debugger`}),disabled:!Ct||Ve.isPending||ze.isPending,title:Ct?`Continue blocked task ${Ct} with minimal reset`:"Select a blocked node to continue",children:[e("i",{"data-lucide":"skip-forward"}),Ve.isPending?"Continuing...":"Continue"]}):null,da?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>be.mutate({runId:s,reason:"retried from run debugger"}),disabled:!s||be.isPending||ze.isPending,children:[e("i",{"data-lucide":"rotate-ccw"}),be.isPending?"Retrying...":"Retry"]}):null,s?e("button",{type:"button",className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>ze.mutate({action:kt==="paused"?"resume":"pause",runId:s,family:q?"v2":"legacy"}),disabled:!s||ze.isPending||!(kt==="paused"||La(kt)),children:[e("i",{"data-lucide":kt==="paused"?"play":"pause"}),kt==="paused"?"Resume":"Pause"]}):null,e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>{Promise.all([p.invalidateQueries({queryKey:["automations","run",s]}),p.invalidateQueries({queryKey:["automations","run","artifacts",s]}),W?p.invalidateQueries({queryKey:["automations","run","context",W]}):Promise.resolve(),W?p.invalidateQueries({queryKey:["automations","run","context",W,"blackboard"]}):Promise.resolve(),W?p.invalidateQueries({queryKey:["automations","run","context",W,"events"]}):Promise.resolve(),W?p.invalidateQueries({queryKey:["automations","run","context",W,"patches"]}):Promise.resolve(),s?p.invalidateQueries({queryKey:["automations","run","session",s]}):Promise.resolve()])},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{className:"tcp-btn h-8 w-full px-2 text-xs sm:w-auto",onClick:()=>c(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]}),e("div",{className:"flex-1 min-h-0 overflow-y-auto pr-1",children:e("div",{className:"grid min-h-full content-start gap-3",children:[e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Run Summary"}),e("div",{className:"mt-2 grid gap-2 text-xs text-slate-300 sm:grid-cols-2 xl:grid-cols-4",children:Qn.map(i=>e("div",{className:"break-words",children:[i.label,": ",i.value]},i.label))})]}),q?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Workflow Board"}),e("div",{className:"tcp-subtle text-xs",children:["context run: ",hr(W||"unlinked",44)," · ","tasks: ",Ne.tasks.length," · ","artifacts: ",ut.length]})]}),e("span",{className:"tcp-badge-info",children:Ne.taskSource==="hybrid"?"blackboard + context":Ne.taskSource==="checkpoint"?"run checkpoint":Ne.taskSource})]}),e(Qi,{tasks:Ne.tasks,currentTaskId:Ne.currentTaskId,selectedTaskId:H,onTaskSelect:i=>M(m=>m===i.id?"":i.id)})]}):null,e("div",{className:"grid min-h-0 items-start gap-3 xl:grid-cols-[1.62fr_1fr]",children:[e("div",{className:"grid min-h-0 gap-3",children:[h?e("div",{ref:he,className:"tcp-list-item relative max-h-[56vh] overflow-y-auto sm:max-h-[28rem]",children:[e("div",{className:"sticky -top-3 z-10 -mx-3 -mt-3 mb-2 flex items-center justify-between gap-2 rounded-t-xl border-b border-slate-800/80 bg-[color:color-mix(in_srgb,var(--color-surface-elevated)_96%,#000_4%)] px-3 py-3 backdrop-blur-sm",children:[e("div",{className:"font-medium",children:"Task Details"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7","aria-label":"Close task details",onClick:()=>M(""),children:e("i",{"data-lucide":"x-circle"})})]}),e("div",{className:"grid gap-2 pr-1 text-sm text-slate-200",children:[e("div",{className:"whitespace-pre-wrap break-words font-medium leading-snug",children:h.title}),h.description?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:h.description}):null,e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-badge-info",children:h.state}),h.assigned_role?e("span",{className:"tcp-badge-info",children:["agent: ",h.assigned_role]}):null,String(h.task_kind||"").trim()?e("span",{className:"tcp-badge-info",children:["task: ",String(h.task_kind).trim()]}):null,String(h.backlog_task_id||"").trim()?e("span",{className:"tcp-badge-info",children:["backlog:"," ",String(h.backlog_task_id).trim()]}):null,String(h.task_owner||"").trim()?e("span",{className:"tcp-badge-info",children:["owner: ",String(h.task_owner).trim()]}):null,h.session_id?e("span",{className:"tcp-badge-info",children:Mn(h.session_id)}):null]}),J?e("div",{className:"flex flex-wrap gap-2 text-xs",children:[String(J?.status||"").trim()?e("span",{className:String(J?.status||"").trim().toLowerCase()==="blocked"?"tcp-badge-warn":"tcp-badge-ok",children:["status: ",String(J?.status||"").trim()]}):null,typeof J?.approved=="boolean"?e("span",{className:J.approved?"tcp-badge-ok":"tcp-badge-warn",children:["approved: ",String(J.approved)]}):null,L?.workspace_inspection_used?e("span",{className:"tcp-badge-info",children:"workspace inspected"}):null,L?.web_research_used?e("span",{className:"tcp-badge-info",children:"web research used"}):null,String(X?.rejected_artifact_reason||"").trim()?e("span",{className:"tcp-badge-warn",children:"artifact rejected"}):null]}):null,ua?null:e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:na?"This is a projected backlog task derived from workflow output. You can claim or requeue it here without resetting the source workflow node.":"This is a projected backlog task derived from workflow output, not a direct automation node. Inspect it here, but use the source workflow stage for retry, continue, or requeue actions."}),h.runtime_detail?e("div",{className:"whitespace-pre-wrap break-words rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:h.runtime_detail}):null,pe||De||Be||it.length?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Stability Contract"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"workflow class"}),e("div",{className:"mt-1 font-medium text-slate-100",children:pe||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"phase"}),e("div",{className:"mt-1 font-medium text-slate-100",children:De||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"failure kind"}),e("div",{className:"mt-1 font-medium text-slate-100",children:Be||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"artifact candidates"}),e("div",{className:"mt-1 font-medium text-slate-100",children:it.length})]})]}),it.length?e("div",{className:"mt-3 grid gap-2",children:it.map((i,m)=>e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-badge-info",children:String(i?.source||"candidate")}),i?.accepted?e("span",{className:"tcp-badge-ok",children:"accepted"}):null,i?.substantive?e("span",{className:"tcp-badge-ok",children:"substantive"}):e("span",{className:"tcp-badge-warn",children:"non-substantive"}),i?.placeholder_like?e("span",{className:"tcp-badge-warn",children:"placeholder-like"}):null]}),e("div",{className:"mt-1 tcp-subtle",children:[Number(i?.length||0)," chars"]})]},`${String(i?.source||"candidate")}-${m}`))}):null,_t.length?e("div",{className:"mt-3 grid gap-2",children:[e("div",{className:"tcp-subtle",children:"recent workflow events"}),_t.map((i,m)=>e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-badge-info",children:i.event}),i.phase?e("span",{className:"tcp-badge-info",children:i.phase}):null,i.failureKind?e("span",{className:"tcp-badge-warn",children:i.failureKind}):null]}),e("div",{className:"mt-1 text-slate-300",children:i.reason})]},`${i.event}-${String(i.recordedAtMs||m)}`))]}):null]}):null,String(h.write_scope||"").trim()||String(h.repo_root||"").trim()||String(h.acceptance_criteria||"").trim()||String(h.task_dependencies||"").trim()||String(h.verification_state||"").trim()||String(h.verification_command||"").trim()||String(h.output_path||"").trim()?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Coding Task Context"}),e("div",{className:"mt-2 space-y-1",children:[e("div",{children:["backlog task:"," ",String(h.backlog_task_id||"").trim()||"n/a"]}),e("div",{children:["repo root:"," ",String(h.repo_root||"").trim()||"n/a"]}),e("div",{children:["output path:"," ",String(h.output_path||"").trim()||"n/a"]}),e("div",{children:["write scope:"," ",String(h.write_scope||"").trim()||"n/a"]}),e("div",{children:["acceptance criteria:"," ",String(h.acceptance_criteria||"").trim()||"n/a"]}),e("div",{children:["task dependencies:"," ",String(h.task_dependencies||"").trim()||"n/a"]}),e("div",{children:["verification state:"," ",String(h.verification_state||"").trim()||"n/a"]}),e("div",{children:["owner:"," ",String(h.task_owner||"").trim()||"n/a"]}),e("div",{children:["lease owner:"," ",String(h.lease_owner||"").trim()||"n/a"]}),e("div",{children:["lease expires:"," ",Je?Ka(Je):"n/a"]}),e("div",{children:["stale lease: ",f?"yes":"no"]}),e("div",{children:["verification:"," ",String(h.verification_command||"").trim()||"n/a"]})]})]}):null,vt.length||It.length||Lt.length||X?.repair_attempted?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Research Requirement Status"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"discovered relevant files"}),e("div",{className:"mt-1 font-medium text-slate-100",children:It.length})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"actual read calls backed by path"}),e("div",{className:"mt-1 font-medium text-slate-100",children:vt.length})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"reviewed paths backed by read"}),e("div",{className:"mt-1 font-medium text-slate-100",children:et.length})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"web research"}),e("div",{className:"mt-1 font-medium text-slate-100",children:X?.web_research_attempted?X?.web_research_succeeded?"attempted and succeeded":"attempted but not successful":"not attempted"})]})]}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"repair pass"}),e("div",{className:"mt-1 font-medium text-slate-100",children:X?.repair_attempted?X?.repair_succeeded?"attempted and satisfied":X?.repair_exhausted?"attempted and exhausted":"attempted and still active":"not needed or not attempted"}),X?.repair_attempted?e("div",{className:"mt-1 tcp-subtle",children:["attempt"," ",Number(X?.repair_attempt||0)," ","of"," ",Number(X?.repair_attempt||0)+Number(X?.repair_attempts_remaining||0)]}):null]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"missing / unreviewed relevant files"}),e("div",{className:"mt-1 font-medium text-slate-100",children:yt.length})]})]}),Lt.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle mb-1",children:"unmet requirements"}),e("div",{className:"flex flex-wrap gap-1",children:Lt.map(i=>e("span",{className:"rounded-full border border-emerald-500/30 bg-emerald-950/20 px-2 py-1 text-[11px] text-emerald-100/90",children:i},i))})]}):null,yt.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle mb-1",children:"unreviewed relevant files"}),e("div",{className:"flex flex-wrap gap-1",children:yt.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))})]}):null]}):null,J||qt.length||K?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Coding Verification & Failures"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"verification outcome"}),e("div",{className:"mt-1 font-medium text-slate-100",children:ba})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"verification passed"}),e("div",{className:"mt-1 font-medium text-slate-100",children:typeof Kt=="boolean"?Kt?"yes":"no":"n/a"})]})]}),L?.verification_expected?e("div",{className:"mt-3 rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle mb-2",children:"verification plan"}),e("div",{className:"mb-2 text-slate-200/80",children:[Number(L?.verification_completed||0)," ","/"," ",Number(L?.verification_total||0)," ","checks ran"]}),Gt.length?e("div",{className:"grid gap-2",children:Gt.map((i,m)=>e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/40 p-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-badge-info",children:String(i?.kind||"verify")}),e("span",{className:i?.failed?"tcp-badge-warn":i?.ran?"tcp-badge-ok":"tcp-badge-info",children:i?.failed?"failed":i?.ran?"passed":"not run"})]}),e("div",{className:"mt-1 break-words font-mono text-[11px] text-slate-200",children:String(i?.command||"").trim()||"n/a"}),String(i?.failure||"").trim()?e("div",{className:"mt-1 whitespace-pre-wrap break-words text-[11px] text-emerald-100/90",children:String(i?.failure||"").trim()}):null]},`${String(i?.command||m)}-${m}`))}):null]}):null,K?e("div",{className:"mt-3 rounded-md border border-emerald-500/30 bg-emerald-950/20 p-2 text-emerald-100/90",children:[e("div",{className:"tcp-subtle mb-1 text-emerald-100/70",children:"failure detail"}),e("div",{className:"whitespace-pre-wrap break-words",children:K})]}):null,qt.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle mb-1",children:"related artifacts"}),e("div",{className:"flex flex-wrap gap-2",children:qt.map(i=>e("button",{type:"button",className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-200 transition hover:border-sky-500/40 hover:text-sky-100",onClick:()=>va(i),title:i,children:["Open ",hr(i,44)]},i))}),ia.length?e("div",{className:"mt-2 tcp-subtle",children:["matched run artifacts:"," ",ia.map(i=>i.name).join(", ")]}):e("div",{className:"mt-2 tcp-subtle",children:"No matching run artifact found yet. The button will still jump to the artifacts section."})]}):null,(Ia||Ma||wn||zn||Jn||da)&&s?e("div",{className:"mt-3 space-y-3",children:[ua?e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2 text-[11px] text-slate-300",children:[e("div",{className:"font-medium text-slate-100",children:"Action impact"}),e("div",{className:"mt-1 tcp-subtle",children:ae.isLoading?"Loading engine preview...":pa.previewBacked?"Engine preview":"UI-estimated preview"}),e("div",{className:"mt-1",children:["Selected task: ",pa.rootTitle]}),e("div",{children:["Reset scope:"," ",Ia?"minimal reset of the blocked task":`${pa.subtreeCount} task${pa.subtreeCount===1?"":"s"}${pa.descendantCount>0?` (${pa.descendantCount} descendant${pa.descendantCount===1?"":"s"})`:""}`]}),e("div",{children:["Preserves:"," ",pa.preservesUpstreamOutputs?"completed upstream outputs outside this subtree":"n/a"]}),e("div",{children:["Clears: stale outputs for"," ",pa.outputCount," declared artifact",pa.outputCount===1?"":"s"]}),Zt.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:Zt.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))}):null]}):na?e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2 text-[11px] text-slate-300",children:[e("div",{className:"font-medium text-slate-100",children:"Action impact"}),e("div",{className:"mt-1",children:"Claiming assigns this backlog task to an agent without resetting any workflow nodes."}),e("div",{children:"Requeueing clears stale lease state and returns the task to the runnable queue."}),e("div",{children:"Upstream workflow artifacts are preserved because this acts on the projected backlog task only."})]}):null,e("div",{className:"flex flex-wrap gap-2",children:[zn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>dt.mutate({runId:s,taskId:String(h.id||""),agentId:String(h.task_owner||"").trim()||void 0,reason:`claimed backlog task ${String(h.id||"")} from debugger`}),disabled:dt.isPending||S.isPending,children:dt.isPending?"Claiming...":"Claim Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Assign this projected coding task and start its lease."})]}):null,Jn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>S.mutate({runId:s,taskId:String(h.id||""),reason:`requeued backlog task ${String(h.id||"")} from debugger`}),disabled:dt.isPending||S.isPending,children:S.isPending?"Requeueing...":"Requeue Backlog Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Use when the task is blocked, failed, or its lease went stale."})]}):null,Ia?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>Ve.mutate({runId:s,nodeId:mt,reason:`continued blocked task ${mt} from debugger`}),disabled:Ve.isPending||Se.isPending||ce.isPending||dt.isPending||S.isPending,children:Ve.isPending?"Continuing...":"Continue Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Minimal reset: reruns the blocked task itself and preserves descendants unless they need to rerun later."})]}):null,Ma?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>Se.mutate({runId:s,nodeId:mt,reason:`retried task ${mt} from debugger`}),disabled:Ve.isPending||Se.isPending||ce.isPending||dt.isPending||S.isPending,children:Se.isPending?"Retrying task...":"Retry Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Best for blocked or failed work that should rerun from this task downward."})]}):null,wn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>ce.mutate({runId:s,nodeId:mt,reason:`requeued task ${mt} from debugger`}),disabled:Ve.isPending||Se.isPending||ce.isPending||dt.isPending||S.isPending,children:ce.isPending?"Requeueing...":"Requeue Task"}),e("div",{className:"tcp-subtle text-[11px]",children:"Use when this task should go back onto the queue with its descendants reset."})]}):null,Nt==="blocked"&&Ct?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>tt.mutate({runId:s,nodeId:Ct,reason:`continued from blocked node ${Ct}`}),disabled:Ve.isPending||tt.isPending||!Ct,children:tt.isPending?"Repairing...":"Repair Blocked Step"}),e("div",{className:"tcp-subtle text-[11px]",children:"Heavier reset/repair flow for blocked nodes when minimal continue is not enough."})]}):null,da?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>be.mutate({runId:s,reason:`retried from task ${String(h.id||"").replace(/^node-/,"")}`}),disabled:be.isPending,children:be.isPending?"Retrying...":"Retry Workflow"}),e("div",{className:"tcp-subtle text-[11px]",children:"Recover the whole run, not just this task subtree."})]}):null]})]}):null]}):null,X||L||Ue.length||st.length?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/20 p-3 text-xs text-slate-300",children:[e("div",{className:"font-medium text-slate-200",children:"Coding Signals"}),e("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"execution mode"}),e("div",{className:"mt-1 font-medium text-slate-100",children:String(X?.execution_policy?.mode||"").trim()||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"git diff"}),e("div",{className:"mt-1 font-medium text-slate-100",children:String(X?.git_diff_summary?.stat||"").trim()||"n/a"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"workspace inspection"}),e("div",{className:"mt-1 font-medium text-slate-100",children:L?.workspace_inspection_used?"yes":"no"})]}),e("div",{className:"rounded-md border border-slate-800/80 bg-slate-950/30 p-2",children:[e("div",{className:"tcp-subtle",children:"web research"}),e("div",{className:"mt-1 font-medium text-slate-100",children:L?.web_research_used?"yes":"no"})]})]}),e("div",{className:"mt-3 space-y-2",children:[e("div",{children:[e("div",{className:"tcp-subtle mb-1",children:"touched files"}),Ue.length?e("div",{className:"flex flex-wrap gap-1",children:Ue.map(i=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:i},i))}):e("div",{className:"tcp-subtle",children:"none"})]}),e("div",{children:[e("div",{className:"tcp-subtle mb-1",children:"undeclared files"}),st.length?e("div",{className:"flex flex-wrap gap-1",children:st.map(i=>e("span",{className:"rounded-full border border-amber-500/30 bg-amber-950/20 px-2 py-1 font-mono text-[11px] text-amber-100",children:i},i))}):e("div",{className:"tcp-subtle",children:"none"})]})]})]}):null,String(h?.state||"").toLowerCase()==="blocked"?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:"Continue resets this blocked step and its descendants, preserves valid upstream outputs, and clears stale descendant artifacts before requeue."}):null,L?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:[e("div",{className:"mb-2 font-medium text-slate-100",children:"Node Tooling"}),e("div",{className:"grid gap-1",children:[e("div",{children:["offered:"," ",Array.isArray(L?.requested_tools)&&L.requested_tools.join(", ")||"n/a"]}),e("div",{children:["executed:"," ",Array.isArray(L?.executed_tools)&&L.executed_tools.join(", ")||"none"]}),e("div",{children:["workspace inspection:"," ",L?.workspace_inspection_used?"yes":"no"]}),e("div",{children:["web research:"," ",L?.web_research_used?"yes":"no"]})]})]}):null,X?e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3 text-xs text-slate-300",children:[e("div",{className:"mb-2 font-medium text-slate-100",children:"Artifact Validation"}),e("div",{className:"grid gap-1",children:[e("div",{children:["accepted path:"," ",String(X?.accepted_artifact_path||"").trim()||"n/a"]}),e("div",{children:["rejected reason:"," ",String(X?.rejected_artifact_reason||"").trim()||"none"]}),e("div",{children:["auto-cleaned:"," ",String(!!X?.auto_cleaned)]}),e("div",{children:["undeclared files:"," ",st.length?st.join(", "):"none"]}),e("div",{children:["execution policy:"," ",String(X?.execution_policy?.mode||"").trim()||"n/a"]}),e("div",{children:["touched files:"," ",Ue.length?Ue.join(", "):"none"]}),e("div",{children:["git diff:"," ",String(X?.git_diff_summary?.stat||"").trim()||"n/a"]})]})]}):null,h.error_message?e("div",{className:"whitespace-pre-wrap break-words rounded-lg border border-rose-500/30 bg-rose-950/20 p-3 text-xs text-rose-200",children:h.error_message}):null,h.dependencies.length?e("div",{className:"flex flex-wrap gap-1 text-xs",children:h.dependencies.map(i=>e("span",{className:"tcp-badge-info",children:["depends on ",i]},i))}):null]})]}):null,e("div",{className:"tcp-list-item min-h-0 xl:order-2",children:[e("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:"Live Session Log"}),e("div",{className:"tcp-subtle text-xs",children:B?I==="all"?`Merged timeline across ${Ae.length||1} session${Ae.length===1?"":"s"}`:`Filtered to ${I}`:"This run does not expose a session transcript."})]}),e("div",{className:"flex flex-wrap gap-2",children:[Ae.length>1?e("select",{className:"tcp-select h-7 min-w-[12rem] max-w-full shrink-0 text-xs sm:min-w-[14rem]",value:I,onInput:i=>C(i.target.value),children:[e("option",{value:"all",children:"All sessions"}),Ae.map(i=>e("option",{value:i,title:i,children:Mn(i)},i))]}):B?e("span",{className:"tcp-badge-info",title:B,children:Mn(B)}):null,B?e("span",{className:"tcp-badge-info",title:B,children:["live: ",hr(B,24)]}):null,e("button",{className:"tcp-btn h-7 px-2 text-xs",disabled:!Ea.length,onClick:async()=>{try{await navigator.clipboard.writeText(Ea.map(i=>{const m=new Date(i.at).toLocaleTimeString(),D=i.sessionId?` · ${i.sessionLabel}`:"";return`[${m}] ${i.label}${D}
|
|
2444
|
+
${i.body||aa(i.raw)}`}).join(`
|
|
2445
2445
|
|
|
2446
|
-
`)),t("ok","Copied session log.")}catch(i){t("err",i instanceof Error?i.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy"}),"Copy session log"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{We(!0);const i=Oe.current;i&&(i.scrollTop=i.scrollHeight)},children:[e("i",{"data-lucide":"arrow-down"}),"Jump to latest"]})]})]}),e("div",{ref:Oe,className:"grid min-h-[12rem] gap-2 overflow-auto pr-1 sm:min-h-[14rem] sm:max-h-[18rem]",onScroll:i=>{const m=i.currentTarget,D=m.scrollHeight-(m.scrollTop+m.clientHeight)<48;We(D)},children:Pa.length?Pa.map(i=>e("div",{className:`rounded-lg border p-3 ${i.variant==="assistant"?"border-sky-500/30 bg-sky-950/10":i.variant==="user"?"border-slate-600/60 bg-slate-900/35":i.variant==="error"?"border-rose-500/35 bg-rose-950/20":"border-slate-700/50 bg-slate-900/25"}`,children:[e("div",{className:"mb-1 flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"text-xs font-medium uppercase tracking-wide text-slate-200",children:i.label}),i.sessionId?e("span",{className:"tcp-badge-info text-[10px]",children:i.sessionLabel}):null]}),e("span",{className:"tcp-subtle text-[11px]",children:new Date(i.at).toLocaleTimeString()})]}),i.body?e("div",{className:"whitespace-pre-wrap break-words text-sm text-slate-100",children:i.body}):e("div",{className:"tcp-subtle text-xs",children:"No textual body."}),i.kind==="message"&&i.parts.some(m=>String(m?.type||"")==="tool")?e("details",{className:"mt-2",children:[e("summary",{className:"cursor-pointer text-xs text-slate-400",children:"Tool payloads"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:Yt(i.parts)})]}):null,i.kind==="event"?e("details",{className:"mt-2",children:[e("summary",{className:"cursor-pointer text-xs text-slate-400",children:"Raw event"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:Yt(i.raw)})]}):null]},i.id)):e("div",{className:"tcp-subtle text-xs",children:Ce.length?"Waiting for session transcript or live session events.":"This run does not expose a session transcript."})})]}),e("div",{className:"tcp-list-item min-h-0 xl:order-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Run Telemetry"}),e("div",{className:"flex w-full flex-wrap gap-1 sm:w-auto",children:[e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="all"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("all"),children:["all (",Aa.length,")"]}),e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="automations"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("automations"),children:"automations"}),M?e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="context"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("context"),children:"context"}):null,e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${k==="global"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("global"),children:"global"})]})]}),Ja.length?e("div",{className:"grid gap-2 overflow-auto pr-1 sm:max-h-[12rem]",children:Ja.slice(-40).reverse().map(i=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/30 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:i.label}),e("span",{className:"tcp-subtle text-[11px]",children:[Rs(i.at)," · ",i.source]})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:i.detail})]}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:Yt(i.raw)})]},i.id))}):e("div",{className:"tcp-subtle text-xs",children:M?"No workflow, context, or global telemetry has been captured for this run yet.":"No automation/global telemetry captured for this run yet."})]})]}),e("div",{className:"grid min-h-0 content-start gap-3 overflow-visible",children:[Ga.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 font-medium",children:"Blockers"}),e("div",{className:"grid gap-2",children:Ga.map(i=>e("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("strong",{children:i.title}),e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:i.source}),i.at?e("span",{className:"tcp-subtle text-[11px]",children:new Date(i.at).toLocaleTimeString()}):null]}),e("div",{className:"whitespace-pre-wrap break-words text-sm text-emerald-100/90",children:i.reason})]},i.key))})]}):null,la.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-1 font-medium",children:"Debug hints"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:la.map(i=>e("div",{children:i},i))})]}):null,pe.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Next Required Actions"}),e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:[pe.length," node",pe.length===1?"":"s"]})]}),e("div",{className:"grid gap-2",children:pe.map(({nodeId:i,guidance:m})=>{const D=Array.isArray(m?.requiredNextToolActions)?m.requiredNextToolActions:[],Z=Array.isArray(m?.unmetRequirements)?m.unmetRequirements:[],de=String(m?.reason||"").trim(),rt=String(m?.blockingClassification||"").trim(),Dt=String(m?.failureKind||"").trim(),fa=String(m?.status||"").trim(),ba=fa.toLowerCase(),ca=hs(Ae)>0,Ta=M&&!!s&&!ca&&(["blocked","failed","needs_repair"].includes(ba)||ba==="completed"&&(D.length>0||Z.length>0)),Ht=M&&!!s&&!ca&&["blocked","needs_repair"].includes(ba);return e("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e("strong",{children:i}),fa?e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:fa}):null,rt?e("span",{className:"tcp-subtle text-[11px]",children:rt.replace(/_/g," ")}):null,m?.repairAttemptsRemaining!==null&&m?.repairAttemptsRemaining!==void 0?e("span",{className:"tcp-subtle text-[11px]",children:[String(m.repairAttemptsRemaining)," repair attempt",Number(m.repairAttemptsRemaining)===1?"":"s"," ","left"]}):null]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>q(`node-${i}`),children:"Focus"}),Ta?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>_e.mutate({runId:s,nodeId:i,reason:`retried task ${i} from repair guidance`}),disabled:_e.isPending||Ye.isPending||le.isPending,children:_e.isPending?"Retrying...":"Retry"}):null,Ht?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ye.mutate({runId:s,nodeId:i,reason:`continued task ${i} from repair guidance`}),disabled:_e.isPending||Ye.isPending||le.isPending,children:Ye.isPending?"Continuing...":"Continue"}):null]}),de?e("div",{className:"mb-2 whitespace-pre-wrap break-words text-sm text-emerald-100/90",children:de}):null,D.length?e("div",{className:"grid gap-1",children:D.map((Ra,rn)=>e("div",{className:"rounded-md border border-emerald-400/20 bg-black/20 px-2 py-1 text-xs text-emerald-50",children:String(Ra||"")},`${i}-action-${rn}`))}):null,!D.length&&Z.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:Z.map(Ra=>e("span",{className:"rounded-full border border-emerald-400/25 bg-black/20 px-2 py-1 text-[11px] text-emerald-100/90",children:String(Ra||"").replace(/_/g," ")},`${i}-${String(Ra)}`))}):null,Dt?e("div",{className:"tcp-subtle mt-2 text-[11px]",children:["failure kind: ",Dt]}):null]},i)})})]}):null,e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Mission Objective"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:String(Ae?.mission_snapshot?.objective||"n/a")})]}),e("div",{ref:ee,className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:["Artifacts (",ut.length,")"]}),ut.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-40",children:He.map(i=>e("details",{open:ye===i.key?!0:void 0,className:ye===i.key?"rounded-lg border border-sky-500/40 bg-sky-950/10 p-2":"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",onClick:()=>y(m=>m===i.key?"":i.key),children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:i.name}),e("span",{className:"tcp-subtle text-[11px]",children:i.kind||"artifact"})]})}),i.paths.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:i.paths.map(m=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:m},m))}):null,e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:Yt(i.artifact)})]},i.key))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:M?"No blackboard artifacts have been recorded for this workflow run yet.":"No run artifacts were persisted for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"font-medium",children:M?"Run History":"Persisted History"}),an.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-[14rem]",children:an.map((i,m)=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:String(i?.type||i?.event||i?.status||"history")}),e("span",{className:"tcp-subtle text-[11px]",children:Rs(i?.ts_ms||i?.tsMs||i?.at||i?.timestamp_ms)})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(i?.detail||i?.reason||i?.family||i?.status||"No summary available.")})]}),e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:Yt(i)})]},`${String(i?.id||i?.event||i?.type||"history")}-${m}`))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:M?"No context-run history has been persisted for this workflow run yet.":"No persisted history rows returned for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Raw Run Payload"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(["=== RUN ===",Yt(Ae),"=== ARTIFACTS ===",Yt(ut),"=== TELEMETRY ===",Yt(sa.map(i=>i.event)),"=== CONTEXT RUN ===",Yt(lt.data?.run||null),"=== BLACKBOARD ===",Yt(xt),"=== HISTORY ===",Yt(an),"=== SESSION MESSAGES ===",Yt(Ua)].join(`
|
|
2446
|
+
`)),t("ok","Copied session log.")}catch(i){t("err",i instanceof Error?i.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy"}),"Copy session log"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{Le(!0);const i=qe.current;i&&(i.scrollTop=i.scrollHeight)},children:[e("i",{"data-lucide":"arrow-down"}),"Jump to latest"]})]})]}),e("div",{ref:qe,className:"grid min-h-[12rem] gap-2 overflow-auto pr-1 sm:min-h-[14rem] sm:max-h-[18rem]",onScroll:i=>{const m=i.currentTarget,D=m.scrollHeight-(m.scrollTop+m.clientHeight)<48;Le(D)},children:Ea.length?Ea.map(i=>e("div",{className:`rounded-lg border p-3 ${i.variant==="assistant"?"border-sky-500/30 bg-sky-950/10":i.variant==="user"?"border-slate-600/60 bg-slate-900/35":i.variant==="error"?"border-rose-500/35 bg-rose-950/20":"border-slate-700/50 bg-slate-900/25"}`,children:[e("div",{className:"mb-1 flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("span",{className:"text-xs font-medium uppercase tracking-wide text-slate-200",children:i.label}),i.sessionId?e("span",{className:"tcp-badge-info text-[10px]",children:i.sessionLabel}):null]}),e("span",{className:"tcp-subtle text-[11px]",children:new Date(i.at).toLocaleTimeString()})]}),i.body?e("div",{className:"whitespace-pre-wrap break-words text-sm text-slate-100",children:i.body}):e("div",{className:"tcp-subtle text-xs",children:"No textual body."}),i.kind==="message"&&i.parts.some(m=>String(m?.type||"")==="tool")?e("details",{className:"mt-2",children:[e("summary",{className:"cursor-pointer text-xs text-slate-400",children:"Tool payloads"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:aa(i.parts)})]}):null,i.kind==="event"?e("details",{className:"mt-2",children:[e("summary",{className:"cursor-pointer text-xs text-slate-400",children:"Raw event"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:aa(i.raw)})]}):null]},i.id)):e("div",{className:"tcp-subtle text-xs",children:Ae.length?"Waiting for session transcript or live session events.":"This run does not expose a session transcript."})})]}),e("div",{className:"tcp-list-item min-h-0 xl:order-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Run Telemetry"}),e("div",{className:"flex w-full flex-wrap gap-1 sm:w-auto",children:[e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${_==="all"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("all"),children:["all (",an.length,")"]}),e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${_==="automations"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("automations"),children:"automations"}),q?e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${_==="context"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("context"),children:"context"}):null,e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${_==="global"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>z("global"),children:"global"})]})]}),nn.length?e("div",{className:"grid gap-2 overflow-auto pr-1 sm:max-h-[12rem]",children:nn.slice(-40).reverse().map(i=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/30 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:i.label}),e("span",{className:"tcp-subtle text-[11px]",children:[Hs(i.at)," · ",i.source]})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:i.detail})]}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto text-[11px]",children:aa(i.raw)})]},i.id))}):e("div",{className:"tcp-subtle text-xs",children:q?"No workflow, context, or global telemetry has been captured for this run yet.":"No automation/global telemetry captured for this run yet."})]})]}),e("div",{className:"grid min-h-0 content-start gap-3 overflow-visible",children:[Nn.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 font-medium",children:"Blockers"}),e("div",{className:"grid gap-2",children:Nn.map(i=>e("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("strong",{children:i.title}),e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:i.source}),i.at?e("span",{className:"tcp-subtle text-[11px]",children:new Date(i.at).toLocaleTimeString()}):null]}),e("div",{className:"whitespace-pre-wrap break-words text-sm text-emerald-100/90",children:i.reason})]},i.key))})]}):null,Qa.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-1 font-medium",children:"Debug hints"}),e("div",{className:"grid gap-1 text-xs text-slate-300",children:Qa.map(i=>e("div",{children:i},i))})]}):null,we.length?e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Next Required Actions"}),e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:[we.length," node",we.length===1?"":"s"]})]}),e("div",{className:"grid gap-2",children:we.map(({nodeId:i,guidance:m})=>{const D=Array.isArray(m?.requiredNextToolActions)?m.requiredNextToolActions:[],Z=Array.isArray(m?.unmetRequirements)?m.unmetRequirements:[],le=String(m?.reason||"").trim(),nt=String(m?.blockingClassification||"").trim(),Dt=String(m?.failureKind||"").trim(),Na=String(m?.status||"").trim(),_a=Na.toLowerCase(),ha=Rs(Ie)>0,_e=q&&!!s&&!ha&&(["blocked","failed","needs_repair"].includes(_a)||_a==="completed"&&(D.length>0||Z.length>0)),ra=q&&!!s&&!ha&&["blocked","needs_repair"].includes(_a);return e("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-950/20 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e("strong",{children:i}),Na?e("span",{className:"border border-emerald-400/60 bg-emerald-400/10 text-emerald-200 tcp-badge",children:Na}):null,nt?e("span",{className:"tcp-subtle text-[11px]",children:nt.replace(/_/g," ")}):null,m?.repairAttemptsRemaining!==null&&m?.repairAttemptsRemaining!==void 0?e("span",{className:"tcp-subtle text-[11px]",children:[String(m.repairAttemptsRemaining)," repair attempt",Number(m.repairAttemptsRemaining)===1?"":"s"," ","left"]}):null]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>M(`node-${i}`),children:"Focus"}),_e?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Se.mutate({runId:s,nodeId:i,reason:`retried task ${i} from repair guidance`}),disabled:Se.isPending||Ve.isPending||ce.isPending,children:Se.isPending?"Retrying...":"Retry"}):null,ra?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Ve.mutate({runId:s,nodeId:i,reason:`continued task ${i} from repair guidance`}),disabled:Se.isPending||Ve.isPending||ce.isPending,children:Ve.isPending?"Continuing...":"Continue"}):null]}),le?e("div",{className:"mb-2 whitespace-pre-wrap break-words text-sm text-emerald-100/90",children:le}):null,D.length?e("div",{className:"grid gap-1",children:D.map((Ca,sn)=>e("div",{className:"rounded-md border border-emerald-400/20 bg-black/20 px-2 py-1 text-xs text-emerald-50",children:String(Ca||"")},`${i}-action-${sn}`))}):null,!D.length&&Z.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:Z.map(Ca=>e("span",{className:"rounded-full border border-emerald-400/25 bg-black/20 px-2 py-1 text-[11px] text-emerald-100/90",children:String(Ca||"").replace(/_/g," ")},`${i}-${String(Ca)}`))}):null,Dt?e("div",{className:"tcp-subtle mt-2 text-[11px]",children:["failure kind: ",Dt]}):null]},i)})})]}):null,e("div",{className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:"Mission Objective"}),e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:String(Ie?.mission_snapshot?.objective||"n/a")})]}),e("div",{ref:ee,className:"tcp-list-item overflow-visible",children:[e("div",{className:"font-medium",children:["Artifacts (",ut.length,")"]}),ut.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-40",children:Qe.map(i=>e("details",{open:xe===i.key?!0:void 0,className:xe===i.key?"rounded-lg border border-sky-500/40 bg-sky-950/10 p-2":"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",onClick:()=>y(m=>m===i.key?"":i.key),children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:i.name}),e("span",{className:"tcp-subtle text-[11px]",children:i.kind||"artifact"})]})}),i.paths.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:i.paths.map(m=>e("span",{className:"rounded-full border border-slate-700/70 bg-slate-950/30 px-2 py-1 font-mono text-[11px] text-slate-300",children:m},m))}):null,e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:aa(i.artifact)})]},i.key))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:q?"No blackboard artifacts have been recorded for this workflow run yet.":"No run artifacts were persisted for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"font-medium",children:q?"Run History":"Persisted History"}),qa.length?e("div",{className:"mt-2 grid gap-2 overflow-auto pr-1 sm:max-h-[14rem]",children:qa.map((i,m)=>e("details",{className:"rounded-lg border border-slate-700/40 bg-slate-900/25 p-2",children:[e("summary",{className:"cursor-pointer list-none",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"text-xs font-medium text-slate-200",children:String(i?.type||i?.event||i?.status||"history")}),e("span",{className:"tcp-subtle text-[11px]",children:Hs(i?.ts_ms||i?.tsMs||i?.at||i?.timestamp_ms)})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(i?.detail||i?.reason||i?.family||i?.status||"No summary available.")})]}),e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto text-[11px]",children:aa(i)})]},`${String(i?.id||i?.event||i?.type||"history")}-${m}`))}):e("div",{className:"tcp-subtle mt-2 text-xs",children:q?"No context-run history has been persisted for this workflow run yet.":"No persisted history rows returned for this automation."})]}),e("div",{className:"tcp-list-item min-h-0",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Raw Run Payload"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(["=== RUN ===",aa(Ie),"=== ARTIFACTS ===",aa(ut),"=== TELEMETRY ===",aa(Ha.map(i=>i.event)),"=== CONTEXT RUN ===",aa(rt.data?.run||null),"=== BLACKBOARD ===",aa(Pt),"=== HISTORY ===",aa(qa),"=== SESSION MESSAGES ===",aa(rn)].join(`
|
|
2447
2447
|
|
|
2448
|
-
`)),t("ok","Copied full debug context.")}catch(i){t("err",i instanceof Error?i.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy all debug context"]})]}),e("pre",{className:"tcp-code overflow-auto sm:max-h-[18rem]",children:Yt({run:Ae,contextRun:lt.data?.run||null,blackboard:xt})})]})]})]})]})}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>n("feed"),children:[e("i",{"data-lucide":"radio"}),"Open Live Feed"]}),e("button",{className:"tcp-btn",onClick:()=>c(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]})}):null,C?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>O(null),children:e($e.div,{className:"tcp-confirm-dialog w-[min(40rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Edit automation"}),e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Name"}),e("input",{className:"tcp-input",value:C.name,onInput:i=>O(m=>m&&{...m,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[96px]",value:C.objective,onInput:i=>O(m=>m&&{...m,objective:i.target.value})})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Mode"}),e("select",{className:"tcp-input",value:C.mode,onInput:i=>O(m=>m&&{...m,mode:i.target.value}),children:[e("option",{value:"standalone",children:"standalone"}),e("option",{value:"orchestrated",children:"orchestrated"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Approval policy"}),e("button",{className:`tcp-input flex h-10 items-center justify-between px-3 text-xs ${C.requiresApproval?"border-amber-400/60 bg-amber-400/10":""}`,role:"switch","aria-checked":C.requiresApproval,onClick:()=>O(i=>i&&{...i,requiresApproval:!i.requiresApproval}),children:[e("span",{className:"flex items-center gap-2",children:[e("i",{"data-lucide":C.requiresApproval?"shield-alert":"shield-check"}),C.requiresApproval?"Manual approvals enabled":"Fully automated enabled"]}),e("span",{className:`relative h-5 w-9 rounded-full transition ${C.requiresApproval?"bg-amber-500/40":"bg-emerald-500/30"}`,children:e("span",{className:`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-slate-100 transition ${C.requiresApproval?"":"translate-x-4"}`})})]})]})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Schedule type"}),e("select",{className:"tcp-input",value:C.scheduleKind,onInput:i=>O(m=>m&&{...m,scheduleKind:i.target.value}),children:[e("option",{value:"interval",children:"interval"}),e("option",{value:"cron",children:"cron"})]})]})}),C.scheduleKind==="cron"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Cron expression"}),e("input",{className:"tcp-input font-mono",value:C.cronExpression,onInput:i=>O(m=>m&&{...m,cronExpression:i.target.value}),placeholder:"0 9 * * *"})]}):e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:C.intervalSeconds,onInput:i=>O(m=>m&&{...m,intervalSeconds:i.target.value})})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>O(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>C&&J.mutate(C),disabled:J.isPending,children:[e("i",{"data-lucide":"check"}),"Save"]})]})]})}):null,ne?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>ce(null),children:e($e.div,{className:"tcp-confirm-dialog tcp-workflow-editor-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("div",{className:"flex items-start justify-between gap-3 border-b border-slate-800/70 px-4 py-4",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Edit workflow automation"}),e("div",{className:"mt-1 text-sm text-slate-400",children:"Update scheduling, model routing, MCP access, and the actual step prompts."})]}),e("button",{className:"tcp-btn h-9 w-9 px-0",onClick:()=>ce(null),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"grid flex-1 gap-4 overflow-y-auto px-4 py-4 xl:grid-cols-[minmax(22rem,0.92fr)_minmax(0,1.35fr)]",children:[e("div",{className:"grid content-start gap-4",children:[e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Automation name"}),e("input",{className:"tcp-input",value:ne.name,onInput:i=>ce(m=>m&&{...m,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Notes / description"}),e("textarea",{className:"tcp-input min-h-[120px]",value:ne.description,onInput:i=>ce(m=>m&&{...m,description:i.target.value}),placeholder:"Add notes, delivery expectations, or operator guidance."})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("input",{className:`tcp-input ${Pn(ne.workspaceRoot)?"border-red-500/70 text-red-100":""}`,value:ne.workspaceRoot,onInput:i=>ce(m=>m&&{...m,workspaceRoot:i.target.value})}),Pn(ne.workspaceRoot)?e("div",{className:"text-xs text-red-300",children:Pn(ne.workspaceRoot)}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Execution"}),e("div",{className:"grid gap-2 sm:grid-cols-3",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Schedule type"}),e("select",{className:"tcp-select",value:ne.scheduleKind,onInput:i=>ce(m=>m&&{...m,scheduleKind:i.target.value}),children:[e("option",{value:"manual",children:"manual"}),e("option",{value:"cron",children:"cron"}),e("option",{value:"interval",children:"interval"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Execution mode"}),e("select",{className:"tcp-select",value:ne.executionMode,onInput:i=>ce(m=>m&&{...m,executionMode:i.target.value}),children:ma.executionModes.map(i=>e("option",{value:i.id,children:i.label},i.id))})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Max parallel agents"}),e("input",{type:"number",min:"1",max:"16",className:"tcp-input",value:ne.maxParallelAgents,onInput:i=>ce(m=>m&&{...m,maxParallelAgents:i.target.value}),disabled:ne.executionMode!=="swarm"})]})]}),ne.scheduleKind==="cron"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Cron expression"}),e("input",{className:"tcp-input font-mono",value:ne.cronExpression,onInput:i=>ce(m=>m&&{...m,cronExpression:i.target.value})})]}):ne.scheduleKind==="interval"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:ne.intervalSeconds,onInput:i=>ce(m=>m&&{...m,intervalSeconds:i.target.value})})]}):null]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model provider"}),e("select",{className:"tcp-select",value:ne.modelProvider,onInput:i=>ce(m=>m&&{...m,modelProvider:i.target.value,modelId:""}),children:[e("option",{value:"",children:"Workspace default"}),zn(R.map(i=>i.id),ne.modelProvider).map(i=>e("option",{value:i,children:i},i))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("select",{className:"tcp-select",value:ne.modelId,onInput:i=>ce(m=>m&&{...m,modelId:i.target.value}),children:[e("option",{value:"",children:"Workspace default"}),zn(R.find(i=>i.id===ne.modelProvider)?.models||[],ne.modelId).map(i=>e("option",{value:i,children:i},i))]}),kr(ne.modelProvider,ne.modelId)?e("div",{className:"text-xs text-red-300",children:kr(ne.modelProvider,ne.modelId)}):null]})]}),e("div",{className:"grid gap-2 rounded-lg border border-slate-800/70 bg-slate-950/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Planner fallback model"}),e("div",{className:"text-xs text-slate-400",children:"Optional. Override the workflow model only for planning and revisions."}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner provider"}),e("select",{className:"tcp-select",value:ne.plannerModelProvider,onInput:i=>ce(m=>m&&{...m,plannerModelProvider:i.target.value,plannerModelId:""}),children:[e("option",{value:"",children:"Use workflow model"}),zn(R.map(i=>i.id),ne.plannerModelProvider).map(i=>e("option",{value:i,children:i},`planner-${i}`))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("select",{className:"tcp-select",value:ne.plannerModelId,onInput:i=>ce(m=>m&&{...m,plannerModelId:i.target.value}),children:[e("option",{value:"",children:"Use workflow model"}),zn(R.find(i=>i.id===ne.plannerModelProvider)?.models||[],ne.plannerModelId).map(i=>e("option",{value:i,children:i},`planner-model-${i}`))]}),tr(ne.plannerModelProvider,ne.plannerModelId)?e("div",{className:"text-xs text-red-300",children:tr(ne.plannerModelProvider,ne.plannerModelId)}):null]})]})]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${ne.toolAccessMode==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>ce(i=>i&&{...i,toolAccessMode:"all"}),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access to workflow agents."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${ne.toolAccessMode==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>ce(i=>i&&{...i,toolAccessMode:"custom"}),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still follow the selected servers."})]})]}),ne.toolAccessMode==="custom"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Allowed built-in tools"}),e("textarea",{className:"tcp-input min-h-[96px] font-mono text-xs",value:ne.customToolsText,onInput:i=>ce(m=>m&&{...m,customToolsText:i.target.value}),placeholder:`read
|
|
2448
|
+
`)),t("ok","Copied full debug context.")}catch(i){t("err",i instanceof Error?i.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy all debug context"]})]}),e("pre",{className:"tcp-code overflow-auto sm:max-h-[18rem]",children:aa({run:Ie,contextRun:rt.data?.run||null,blackboard:Pt})})]})]})]})]})}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>n("feed"),children:[e("i",{"data-lucide":"radio"}),"Open Live Feed"]}),e("button",{className:"tcp-btn",onClick:()=>c(""),children:[e("i",{"data-lucide":"x"}),"Close"]})]})]})}):null,A?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>O(null),children:e(Re.div,{className:"tcp-confirm-dialog w-[min(40rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Edit automation"}),e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Name"}),e("input",{className:"tcp-input",value:A.name,onInput:i=>O(m=>m&&{...m,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Objective"}),e("textarea",{className:"tcp-input min-h-[96px]",value:A.objective,onInput:i=>O(m=>m&&{...m,objective:i.target.value})})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Mode"}),e("select",{className:"tcp-input",value:A.mode,onInput:i=>O(m=>m&&{...m,mode:i.target.value}),children:[e("option",{value:"standalone",children:"standalone"}),e("option",{value:"orchestrated",children:"orchestrated"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Approval policy"}),e("button",{className:`tcp-input flex h-10 items-center justify-between px-3 text-xs ${A.requiresApproval?"border-amber-400/60 bg-amber-400/10":""}`,role:"switch","aria-checked":A.requiresApproval,onClick:()=>O(i=>i&&{...i,requiresApproval:!i.requiresApproval}),children:[e("span",{className:"flex items-center gap-2",children:[e("i",{"data-lucide":A.requiresApproval?"shield-alert":"shield-check"}),A.requiresApproval?"Manual approvals enabled":"Fully automated enabled"]}),e("span",{className:`relative h-5 w-9 rounded-full transition ${A.requiresApproval?"bg-amber-500/40":"bg-emerald-500/30"}`,children:e("span",{className:`absolute left-0.5 top-0.5 h-4 w-4 rounded-full bg-slate-100 transition ${A.requiresApproval?"":"translate-x-4"}`})})]})]})]}),e("div",{className:"grid gap-1 sm:grid-cols-2 sm:gap-2",children:e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Schedule type"}),e("select",{className:"tcp-input",value:A.scheduleKind,onInput:i=>O(m=>m&&{...m,scheduleKind:i.target.value}),children:[e("option",{value:"interval",children:"interval"}),e("option",{value:"cron",children:"cron"})]})]})}),A.scheduleKind==="cron"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Cron expression"}),e("input",{className:"tcp-input font-mono",value:A.cronExpression,onInput:i=>O(m=>m&&{...m,cronExpression:i.target.value}),placeholder:"0 9 * * *"})]}):e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:A.intervalSeconds,onInput:i=>O(m=>m&&{...m,intervalSeconds:i.target.value})})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>O(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>A&&G.mutate(A),disabled:G.isPending,children:[e("i",{"data-lucide":"check"}),"Save"]})]})]})}):null,re?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>me(null),children:e(Re.div,{className:"tcp-confirm-dialog tcp-workflow-editor-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("div",{className:"flex items-start justify-between gap-3 border-b border-slate-800/70 px-4 py-4",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Edit workflow automation"}),e("div",{className:"mt-1 text-sm text-slate-400",children:"Update scheduling, model routing, MCP access, and the actual step prompts."})]}),e("button",{className:"tcp-btn h-9 w-9 px-0",onClick:()=>me(null),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"grid flex-1 gap-4 overflow-y-auto px-4 py-4 xl:grid-cols-[minmax(22rem,0.92fr)_minmax(0,1.35fr)]",children:[e("div",{className:"grid content-start gap-4",children:[e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Automation name"}),e("input",{className:"tcp-input",value:re.name,onInput:i=>me(m=>m&&{...m,name:i.target.value})})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Notes / description"}),e("textarea",{className:"tcp-input min-h-[120px]",value:re.description,onInput:i=>me(m=>m&&{...m,description:i.target.value}),placeholder:"Add notes, delivery expectations, or operator guidance."})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Workspace root"}),e("input",{className:`tcp-input ${$n(re.workspaceRoot)?"border-red-500/70 text-red-100":""}`,value:re.workspaceRoot,onInput:i=>me(m=>m&&{...m,workspaceRoot:i.target.value})}),$n(re.workspaceRoot)?e("div",{className:"text-xs text-red-300",children:$n(re.workspaceRoot)}):null]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Execution"}),e("div",{className:"grid gap-2 sm:grid-cols-3",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Schedule type"}),e("select",{className:"tcp-select",value:re.scheduleKind,onInput:i=>me(m=>m&&{...m,scheduleKind:i.target.value}),children:[e("option",{value:"manual",children:"manual"}),e("option",{value:"cron",children:"cron"}),e("option",{value:"interval",children:"interval"})]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Execution mode"}),e("select",{className:"tcp-select",value:re.executionMode,onInput:i=>me(m=>m&&{...m,executionMode:i.target.value}),children:ga.executionModes.map(i=>e("option",{value:i.id,children:i.label},i.id))})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Max parallel agents"}),e("input",{type:"number",min:"1",max:"16",className:"tcp-input",value:re.maxParallelAgents,onInput:i=>me(m=>m&&{...m,maxParallelAgents:i.target.value}),disabled:re.executionMode!=="swarm"})]})]}),re.scheduleKind==="cron"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Cron expression"}),e("input",{className:"tcp-input font-mono",value:re.cronExpression,onInput:i=>me(m=>m&&{...m,cronExpression:i.target.value})})]}):re.scheduleKind==="interval"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Interval seconds"}),e("input",{type:"number",min:"1",className:"tcp-input",value:re.intervalSeconds,onInput:i=>me(m=>m&&{...m,intervalSeconds:i.target.value})})]}):null]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Model Selection"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model provider"}),e("select",{className:"tcp-select",value:re.modelProvider,onInput:i=>me(m=>m&&{...m,modelProvider:i.target.value,modelId:""}),children:[e("option",{value:"",children:"Workspace default"}),nr(T.map(i=>i.id),re.modelProvider).map(i=>e("option",{value:i,children:i},i))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Model"}),e("select",{className:"tcp-select",value:re.modelId,onInput:i=>me(m=>m&&{...m,modelId:i.target.value}),children:[e("option",{value:"",children:"Workspace default"}),nr(T.find(i=>i.id===re.modelProvider)?.models||[],re.modelId).map(i=>e("option",{value:i,children:i},i))]}),Er(re.modelProvider,re.modelId)?e("div",{className:"text-xs text-red-300",children:Er(re.modelProvider,re.modelId)}):null]})]}),e("div",{className:"grid gap-2 rounded-lg border border-slate-800/70 bg-slate-950/30 p-3",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Planner fallback model"}),e("div",{className:"text-xs text-slate-400",children:"Optional. Override the workflow model only for planning and revisions."}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner provider"}),e("select",{className:"tcp-select",value:re.plannerModelProvider,onInput:i=>me(m=>m&&{...m,plannerModelProvider:i.target.value,plannerModelId:""}),children:[e("option",{value:"",children:"Use workflow model"}),nr(T.map(i=>i.id),re.plannerModelProvider).map(i=>e("option",{value:i,children:i},`planner-${i}`))]})]}),e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Planner model"}),e("select",{className:"tcp-select",value:re.plannerModelId,onInput:i=>me(m=>m&&{...m,plannerModelId:i.target.value}),children:[e("option",{value:"",children:"Use workflow model"}),nr(T.find(i=>i.id===re.plannerModelProvider)?.models||[],re.plannerModelId).map(i=>e("option",{value:i,children:i},`planner-model-${i}`))]}),pr(re.plannerModelProvider,re.plannerModelId)?e("div",{className:"text-xs text-red-300",children:pr(re.plannerModelProvider,re.plannerModelId)}):null]})]})]})]}),e("div",{className:"grid gap-3 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Tool Access"}),e("div",{className:"grid gap-2 sm:grid-cols-2",children:[e("button",{type:"button",className:`tcp-list-item text-left ${re.toolAccessMode==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>me(i=>i&&{...i,toolAccessMode:"all"}),children:[e("div",{className:"font-medium",children:"All tools"}),e("div",{className:"tcp-subtle text-xs",children:"Grant full built-in tool access to workflow agents."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${re.toolAccessMode==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>me(i=>i&&{...i,toolAccessMode:"custom"}),children:[e("div",{className:"font-medium",children:"Custom allowlist"}),e("div",{className:"tcp-subtle text-xs",children:"Restrict built-in tools manually. MCP tools still follow the selected servers."})]})]}),re.toolAccessMode==="custom"?e("div",{className:"grid gap-1",children:[e("label",{className:"text-xs text-slate-400",children:"Allowed built-in tools"}),e("textarea",{className:"tcp-input min-h-[96px] font-mono text-xs",value:re.customToolsText,onInput:i=>me(m=>m&&{...m,customToolsText:i.target.value}),placeholder:`read
|
|
2449
2449
|
write
|
|
2450
2450
|
edit
|
|
2451
2451
|
bash
|
|
2452
2452
|
ls
|
|
2453
2453
|
glob
|
|
2454
|
-
websearch`})]}):e("div",{className:"text-xs text-slate-500",children:"All built-in tools are allowed for this automation."})]}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"MCP Servers"}),P.length?e("div",{className:"flex flex-wrap gap-2",children:P.map(i=>{const m=ne.selectedMcpServers.includes(i.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${m?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>ce(D=>D&&{...D,selectedMcpServers:m?D.selectedMcpServers.filter(Z=>Z!==i.name):[...D.selectedMcpServers,i.name].sort()}),children:[i.name," ",i.connected?"• connected":"• disconnected"]},i.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet."})]})]}),e("div",{className:"grid content-start gap-4",children:e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{children:e("div",{children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Prompt Editor"}),e("div",{className:"mt-1 text-xs text-slate-400",children:"Edit the actual prompts Tandem sends for each workflow step. These objectives control what every node does at runtime."})]})}),ne.nodes.length?e("div",{className:"grid gap-3",children:ne.nodes.map((i,m)=>e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-sm text-slate-100",children:i.nodeId||i.title||`Step ${m+1}`}),i.agentId?e("span",{className:"tcp-badge-info",children:["agent: ",i.agentId]}):null]}),e("textarea",{className:"tcp-input min-h-[180px] text-sm leading-6",value:i.objective,onInput:D=>ce(Z=>Z&&{...Z,nodes:Z.nodes.map(de=>de.nodeId===i.nodeId?{...de,objective:D.target.value}:de)}),placeholder:"Describe exactly what this step should do."})]},i.nodeId||m))}):e("div",{className:"text-xs text-slate-400",children:"This workflow does not currently expose editable node objectives."})]})})]}),e("div",{className:"tcp-confirm-actions border-t border-slate-800/70 px-4 py-3",children:[e("button",{className:"tcp-btn",onClick:()=>ce(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>ne&&be.mutate(ne),disabled:be.isPending,children:[e("i",{"data-lucide":"check"}),be.isPending?"Saving...":"Save"]})]})]})}):null,E?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>x(null),children:e($e.div,{className:"tcp-confirm-dialog w-[min(34rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Delete automation"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:E.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>x(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger",disabled:je.isPending,onClick:()=>je.mutate({action:"delete",automationId:E.automationId,family:E.family},{onSettled:()=>x(null)}),children:[e("i",{"data-lucide":"trash-2"}),je.isPending?"Deleting...":"Delete automation"]})]})]})}):null]})]})}function sm({client:a,toast:t}){const n=na(),r=Y({queryKey:["automations","approvals"],queryFn:()=>a?.agentTeams?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),s=Y({queryKey:["automations","instances"],queryFn:()=>a?.agentTeams?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),c=xe({mutationFn:({requestId:p,decision:N})=>a?.agentTeams?.replyApproval?.(p,N),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["automations"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=Ea(r.data,"spawnApprovals"),u=Ea(s.data,"instances");return e("div",{className:"grid gap-4",children:[d.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Pending Approvals"}),d.map((p,N)=>{const E=String(p?.request_id||p?.id||`request-${N}`);return e("div",{className:"tcp-list-item border-amber-500/40",children:[e("div",{className:"mb-1 font-medium text-amber-300",children:["⚠️ ",String(p?.reason||p?.title||"Spawn request")]}),e("div",{className:"tcp-subtle text-xs",children:E}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{className:"tcp-btn-primary h-7 px-2 text-xs",onClick:()=>c.mutate({requestId:E,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>c.mutate({requestId:E,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},E)})]}):null,u.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Active Agent Teams"}),u.map((p,N)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"👥"}),e("strong",{children:String(p?.name||p?.template_id||p?.instance_id||"Instance")})]}),e("span",{className:"tcp-badge-info",children:String(p?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:["Mission: ",String(p?.mission_id||"—")]})]},String(p?.instance_id||p?.id||N)))]}):null,!d.length&&!u.length?e(Le,{text:"No pending approvals or active team instances."}):null]})}function im({client:a,api:t,toast:n,navigate:r,providerStatus:s}){const[c,d]=w("create"),[u,p]=w("simple"),[N,E]=w(""),[x,C]=w(null);return fe(()=>{try{const k=sessionStorage.getItem(As);if(!k)return;sessionStorage.removeItem(As);const z=JSON.parse(k||"{}");z?.tab==="running"&&d("running");const A=String(z?.runId||"").trim();A&&E(A)}catch{}},[]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex gap-1 rounded-xl border border-slate-700/50 bg-slate-900/40 p-1",children:[{id:"create",label:"Create",icon:"sparkles"},{id:"list",label:"Automations",icon:"clipboard-list"},{id:"running",label:"Tasks",icon:"activity"},{id:"optimize",label:"Optimize",icon:"flask-conical"},{id:"approvals",label:"Teams",icon:"users"}].map(k=>e("button",{onClick:()=>d(k.id),className:`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-all ${c===k.id?"bg-amber-500/20 text-amber-300 shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[e("i",{"data-lucide":k.icon}),e("span",{children:k.label})]},k.id))}),e(Mt,{mode:"wait",children:e($e.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-6},transition:{duration:.15},children:c==="create"?e(Wt,{title:"Create an Automation",subtitle:"Describe what you want, pick a schedule, and Tandem handles the rest",children:e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Builder Mode"}),e("div",{className:"tcp-subtle text-xs",children:"Keep the simple wizard for quick automations, or switch to the advanced swarm builder for orchestrated mission planning."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="simple"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>{p("simple"),C(null)},children:"Simple Wizard"}),e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="advanced"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>p("advanced"),children:"Advanced Swarm Builder"})]})]}),u==="advanced"?e(xu,{client:a,api:t,toast:n,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel,editingAutomation:x,onShowAutomations:()=>{C(null),d("list")},onShowRuns:()=>{C(null),d("running")},onClearEditing:()=>C(null)}):e(rm,{client:a,api:t,toast:n,navigate:r,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel})]})}):c==="list"?e(Wt,{title:"My Automations",subtitle:"Installed packs, routines and run history",children:e(Ms,{client:a,toast:n,navigate:r,viewMode:"list",selectedRunId:N,onSelectRunId:E,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:k=>{C(k),p("advanced"),d("create")}})}):c==="running"?e(Wt,{title:"Live Running Tasks",subtitle:"Inspect active runs and open detailed event logs for each run",children:e(Ms,{client:a,toast:n,navigate:r,viewMode:"running",selectedRunId:N,onSelectRunId:E,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:k=>{C(k),p("advanced"),d("create")}})}):c==="optimize"?e(Wt,{title:"Workflow Optimization",subtitle:"Create and inspect overnight shadow-eval optimization campaigns",children:e(Cu,{client:a,toast:n})}):e(Wt,{title:"Teams & Approvals",subtitle:"Active agent teams and pending spawn approvals",children:e(sm,{client:a,toast:n})})},c)})]})}function om(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function lm(a){return(Array.isArray(a)?a:Array.isArray(a?.servers)?a.servers:a&&typeof a=="object"?Object.entries(a).map(([n,r])=>({name:n,...r})):[]).map(n=>({name:String(n?.name||"").trim(),connected:!!n?.connected,enabled:n?.enabled!==!1,transport:String(n?.transport||"").trim(),lastError:String(n?.last_error||n?.lastError||"").trim()})).filter(n=>n.name).sort((n,r)=>n.name.localeCompare(r.name))}function cm(a){return(Array.isArray(a)?a:Array.isArray(a?.tools)?a.tools:[]).map(n=>typeof n=="string"?n:String(n?.namespaced_name||n?.namespacedName||n?.id||"").trim()).filter(Boolean)}function dm(a,t){return String(a?.run_id||a?.runId||a?.id||`run-${t}`).trim()}function um(a){return String(a?.objective||a?.title||a?.summary||a?.workflow_id||a?.workflowId||a?.run_type||a?.runType||a?.run_id||a?.runId||"Untitled run").trim()}function Xr(a){return String(a?.status||"unknown").trim().toLowerCase()}function $s(a){return String(a||"unknown").replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function mm(a){return!["completed","done","failed","cancelled"].includes(Xr(a))}function pm(a){const t=[{id:"queue",label:"Queue",hint:"Ready or waiting to be claimed",statuses:["queued","pending","idle"],items:[]},{id:"planning",label:"Planning",hint:"Task decomposition and board shaping",statuses:["planning","preflight","triage"],items:[]},{id:"active",label:"Active",hint:"Currently being executed",statuses:["running","executing","in_progress","active","working"],items:[]},{id:"waiting",label:"Waiting",hint:"Blocked, paused, or awaiting approval",statuses:["blocked","awaiting_approval","paused","needs_info","waiting"],items:[]},{id:"done",label:"Done",hint:"Finished or archived",statuses:["completed","done","cancelled","failed","archived"],items:[]},{id:"other",label:"Other",hint:"Unclassified run states",statuses:[],items:[]}];return a.forEach(n=>{const r=Xr(n);(t.find(c=>c.statuses.includes(r))||t[t.length-1]).items.push(n)}),t}function Qn({label:a,value:t,helper:n,tone:r="info"}){return e("div",{className:"rounded-2xl border border-white/10 bg-black/20 p-4 shadow-[0_12px_36px_rgba(0,0,0,0.12)]",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"tcp-kpi-label text-sm",children:a}),e(we,{tone:r,children:n})]}),e("div",{className:"mt-3 text-2xl font-semibold tracking-tight",children:t})]})}function hm({api:a,client:t}){const[n,r]=w("overview"),s=Y({queryKey:["coding-workflows","health"],queryFn:()=>a("/api/system/health"),refetchInterval:15e3}),c=Y({queryKey:["coding-workflows","swarm"],queryFn:()=>a("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),d=Y({queryKey:["coding-workflows","workflow-context-runs"],queryFn:()=>a("/api/engine/context/runs?limit=16").catch(()=>({runs:[]})),refetchInterval:6e3}),u=Y({queryKey:["coding-workflows","mcp-servers"],queryFn:()=>t.mcp.list().catch(()=>({})),refetchInterval:1e4}),p=Y({queryKey:["coding-workflows","mcp-tools"],queryFn:()=>t.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),N=K(()=>lm(u.data),[u.data]),E=K(()=>cm(p.data),[p.data]),x=K(()=>om(d.data,"runs").filter(ae=>["workflow","bug_monitor_triage","coding","coding_workflow","task"].includes(String(ae?.run_type||ae?.runType||"").trim().toLowerCase())),[d.data]),C=x.filter(mm),O=K(()=>pm(x),[x]),k=!!(s.data?.engine?.ready||s.data?.engine?.healthy),z=String(c.data?.status||"unknown"),A=N.some(B=>B.name.toLowerCase().includes("github")),G=[{id:"overview",label:"Overview",icon:"layout-dashboard"},{id:"board",label:"Board",icon:"kanban-square"},{id:"manual",label:"Manual tasks",icon:"code"},{id:"integrations",label:"Integrations",icon:"plug-zap"}];return e(gn,{className:"grid gap-4",children:[e(ot,{className:"overflow-hidden",children:e("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start",children:e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Coding workflows"}),e("h1",{className:"tcp-page-title",children:"Internal Kanban and task launch pad"}),e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:"A dedicated home for repo-bound coding runs, manual task launches, worker swarms, and integration status. This page is intentionally small now so we can layer in extra tabs later without changing the mental model."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e(we,{tone:k?"ok":"warn",children:k?"Engine healthy":"Engine checking"}),e(we,{tone:z==="unknown"?"ghost":"info",children:["Swarm ",$s(z)]}),e(we,{tone:A?"ok":"warn",children:A?"GitHub MCP connected":"GitHub MCP pending"}),e(va,{tone:C.length?"live":"info",text:`${C.length} active runs`})]})]})})}),e("div",{className:"tcp-settings-tabs",children:G.map(B=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${n===B.id?"active":""}`,onClick:()=>r(B.id),children:[e("i",{"data-lucide":B.icon}),B.label]},B.id))}),n==="overview"?e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(Qn,{label:"Workflow runs",value:x.length,helper:C.length?`${C.length} active`:"Idle",tone:C.length?"warn":"ok"}),e(Qn,{label:"Connected MCP servers",value:N.length,helper:A?"GitHub available":"MCP pending",tone:A?"ok":"warn"}),e(Qn,{label:"Registered tools",value:E.length,helper:"Tool surface",tone:E.length?"info":"ghost"}),e(Qn,{label:"Engine mode",value:String(s.data?.engine?.mode||"unknown"),helper:String(s.data?.engine?.version||"n/a"),tone:k?"ok":"warn"})]}):null,n==="board"?e("div",{className:"grid gap-4 xl:grid-cols-2 2xl:grid-cols-3",children:O.map(B=>e(ot,{title:`${B.label} (${B.items.length})`,subtitle:B.hint,className:"h-full",children:B.items.length?e("div",{className:"grid gap-2",children:B.items.map((ae,S)=>{const I=Xr(ae);return e("div",{className:"rounded-2xl border border-white/10 bg-black/20 p-3",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:um(ae)}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(ae?.workspaceRoot||ae?.workspace_root||"workspace")})]}),e(we,{tone:B.id==="done"?"ok":B.id==="waiting"?"warn":"info",children:$s(I)})]}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-xs text-slate-300",children:[e("span",{className:"rounded-full border border-white/10 px-2 py-1",children:String(ae?.run_type||ae?.runType||"workflow")}),String(ae?.run_id||ae?.runId||"").trim()?e("span",{className:"rounded-full border border-white/10 px-2 py-1",children:String(ae?.run_id||ae?.runId).slice(0,12)}):null]})]},dm(ae,S))})}):e(Le,{text:"No runs in this lane yet."})},B.id))}):null,n==="manual"?e(ot,{title:"Manual task launcher",subtitle:"Reserved for explicit coding tasks, branch-bound work, and user-triggered actions.",children:e("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(280px,0.75fr)] xl:items-start",children:e("div",{className:"grid gap-3",children:[e("p",{className:"tcp-subtle",children:"This is where we can later add buttons for claim, start, branch selection, worker fan-out, and task-typing controls. For now it gives us a dedicated place to hang the workflow UI without inventing another page."}),e("div",{className:"flex flex-wrap gap-2",children:[e(we,{tone:"info",children:"Future tab: claim task"}),e(we,{tone:"info",children:"Future tab: worker swarm"}),e(we,{tone:"info",children:"Future tab: branch control"})]})]})})}):null,n==="integrations"?e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(ot,{title:"Connected MCP servers",subtitle:"The integration layer this view depends on.",children:N.length?e("div",{className:"grid gap-2",children:N.map(B=>e("div",{className:"flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-black/20 px-3 py-2",children:[e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:B.name}),e("div",{className:"tcp-subtle text-xs",children:[B.transport||"transport pending",B.lastError?` · ${B.lastError}`:""]})]}),e(we,{tone:B.connected?"ok":B.enabled?"warn":"ghost",children:B.connected?"Connected":B.enabled?"Configured":"Disabled"})]},B.name))}):e(Le,{text:"No MCP servers detected yet."})}),e(ot,{title:"Tool surface",subtitle:"Useful for GitHub, repo, and orchestration actions.",children:E.length?e("div",{className:"flex flex-wrap gap-2",children:[E.slice(0,20).map(B=>e(we,{tone:"info",children:B},B)),E.length>20?e(we,{tone:"ghost",children:["+",E.length-20," more"]}):null]}):e(Le,{text:"No MCP tools discovered yet."})})]}):null]})}function gm({client:a,toast:t}){const n=na(),r=Y({queryKey:["channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),s=Y({queryKey:["channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),c=xe({mutationFn:async p=>{const E=(s.data||{})[p];if(!E)throw new Error(`No config found for ${p}`);await a.channels.put(p,E)},onSuccess:async()=>{t("ok","Channel reconfigured."),await n.invalidateQueries({queryKey:["channels"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=r.data&&typeof r.data=="object"?r.data:{},u=Object.entries(d);return e("div",{className:"grid gap-4",children:e(Wt,{title:"Channels",subtitle:"Connector health and quick reconnect",children:e("div",{className:"grid gap-2",children:u.length?u.map(([p,N])=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:p}),e("span",{className:N?.connected?"tcp-badge-ok":"tcp-badge-warn",children:N?.connected?"connected":"disconnected"})]}),e("div",{className:"tcp-subtle text-xs",children:String(N?.last_error||N?.error||"")||"No recent errors."}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>c.mutate(p),children:[e("i",{"data-lucide":"refresh-cw"}),"Reconnect"]})})]},p)):e(Le,{text:"No channels configured."})})})})}function Lt(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Ze(a){return String(a||"").trim()}function _r(a){try{return JSON.stringify(a,null,2)}catch{return"{}"}}function fm(a){return a?"ok":"ghost"}function bm(a){return Ze(a?.event_type||a?.type||a?.event||"workflow.event")}function vm({api:a,toast:t}){const n=na(),[r,s]=w(""),[c,d]=w(""),[u,p]=w(""),[N,E]=w("context.task.created"),[x,C]=w(`{
|
|
2454
|
+
websearch`})]}):e("div",{className:"text-xs text-slate-500",children:"All built-in tools are allowed for this automation."})]}),e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"MCP Servers"}),R.length?e("div",{className:"flex flex-wrap gap-2",children:R.map(i=>{const m=re.selectedMcpServers.includes(i.name);return e("button",{className:`tcp-btn h-7 px-2 text-xs ${m?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>me(D=>D&&{...D,selectedMcpServers:m?D.selectedMcpServers.filter(Z=>Z!==i.name):[...D.selectedMcpServers,i.name].sort()}),children:[i.name," ",i.connected?"• connected":"• disconnected"]},i.name)})}):e("div",{className:"text-xs text-slate-400",children:"No MCP servers configured yet."})]})]}),e("div",{className:"grid content-start gap-4",children:e("div",{className:"grid gap-2 rounded-xl border border-slate-700/50 bg-slate-900/30 p-4",children:[e("div",{children:e("div",{children:[e("div",{className:"text-xs uppercase tracking-wide text-slate-500",children:"Prompt Editor"}),e("div",{className:"mt-1 text-xs text-slate-400",children:"Edit the actual prompts Tandem sends for each workflow step. These objectives control what every node does at runtime."})]})}),re.nodes.length?e("div",{className:"grid gap-3",children:re.nodes.map((i,m)=>e("div",{className:"rounded-lg border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-sm text-slate-100",children:i.nodeId||i.title||`Step ${m+1}`}),i.agentId?e("span",{className:"tcp-badge-info",children:["agent: ",i.agentId]}):null]}),e("textarea",{className:"tcp-input min-h-[180px] text-sm leading-6",value:i.objective,onInput:D=>me(Z=>Z&&{...Z,nodes:Z.nodes.map(le=>le.nodeId===i.nodeId?{...le,objective:D.target.value}:le)}),placeholder:"Describe exactly what this step should do."})]},i.nodeId||m))}):e("div",{className:"text-xs text-slate-400",children:"This workflow does not currently expose editable node objectives."})]})})]}),e("div",{className:"tcp-confirm-actions border-t border-slate-800/70 px-4 py-3",children:[e("button",{className:"tcp-btn",onClick:()=>me(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>re&&ue.mutate(re),disabled:ue.isPending,children:[e("i",{"data-lucide":"check"}),ue.isPending?"Saving...":"Save"]})]})]})}):null,E?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>x(null),children:e(Re.div,{className:"tcp-confirm-dialog w-[min(34rem,96vw)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:i=>i.stopPropagation(),children:[e("h3",{className:"tcp-confirm-title",children:"Delete automation"}),e("p",{className:"tcp-confirm-message",children:["This will permanently remove ",e("strong",{children:E.title}),"."]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>x(null),children:[e("i",{"data-lucide":"x"}),"Cancel"]}),e("button",{className:"tcp-btn-danger",disabled:Ke.isPending,onClick:()=>Ke.mutate({action:"delete",automationId:E.automationId,family:E.family},{onSettled:()=>x(null)}),children:[e("i",{"data-lucide":"trash-2"}),Ke.isPending?"Deleting...":"Delete automation"]})]})]})}):null]})]})}function _m({client:a,toast:t}){const n=ca(),r=V({queryKey:["automations","approvals"],queryFn:()=>a?.agentTeams?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),s=V({queryKey:["automations","instances"],queryFn:()=>a?.agentTeams?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),c=ke({mutationFn:({requestId:p,decision:N})=>a?.agentTeams?.replyApproval?.(p,N),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["automations"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=Fa(r.data,"spawnApprovals"),u=Fa(s.data,"instances");return e("div",{className:"grid gap-4",children:[d.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Pending Approvals"}),d.map((p,N)=>{const E=String(p?.request_id||p?.id||`request-${N}`);return e("div",{className:"tcp-list-item border-amber-500/40",children:[e("div",{className:"mb-1 font-medium text-amber-300",children:["⚠️ ",String(p?.reason||p?.title||"Spawn request")]}),e("div",{className:"tcp-subtle text-xs",children:E}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{className:"tcp-btn-primary h-7 px-2 text-xs",onClick:()=>c.mutate({requestId:E,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>c.mutate({requestId:E,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},E)})]}):null,u.length>0?e("div",{className:"grid gap-2",children:[e("p",{className:"text-xs text-slate-500 uppercase tracking-wide font-medium",children:"Active Agent Teams"}),u.map((p,N)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"flex items-center gap-2",children:[e("span",{children:"👥"}),e("strong",{children:String(p?.name||p?.template_id||p?.instance_id||"Instance")})]}),e("span",{className:"tcp-badge-info",children:String(p?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs mt-1",children:["Mission: ",String(p?.mission_id||"—")]})]},String(p?.instance_id||p?.id||N)))]}):null,!d.length&&!u.length?e(je,{text:"No pending approvals or active team instances."}):null]})}function Sm({client:a,api:t,toast:n,navigate:r,providerStatus:s}){const[c,d]=w("create"),[u,p]=w("simple"),[N,E]=w(""),[x,A]=w(null);return fe(()=>{try{const _=sessionStorage.getItem(zs);if(!_)return;sessionStorage.removeItem(zs);const z=JSON.parse(_||"{}");z?.tab==="running"&&d("running");const P=String(z?.runId||"").trim();P&&E(P)}catch{}},[]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex gap-1 rounded-xl border border-slate-700/50 bg-slate-900/40 p-1",children:[{id:"create",label:"Create",icon:"sparkles"},{id:"list",label:"Automations",icon:"clipboard-list"},{id:"running",label:"Tasks",icon:"activity"},{id:"optimize",label:"Optimize",icon:"flask-conical"},{id:"approvals",label:"Teams",icon:"users"}].map(_=>e("button",{onClick:()=>d(_.id),className:`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-all ${c===_.id?"bg-amber-500/20 text-amber-300 shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[e("i",{"data-lucide":_.icon}),e("span",{children:_.label})]},_.id))}),e(Mt,{mode:"wait",children:e(Re.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-6},transition:{duration:.15},children:c==="create"?e(Yt,{title:"Create an Automation",subtitle:"Describe what you want, pick a schedule, and Tandem handles the rest",children:e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Builder Mode"}),e("div",{className:"tcp-subtle text-xs",children:"Keep the simple wizard for quick automations, or switch to the advanced swarm builder for orchestrated mission planning."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="simple"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>{p("simple"),A(null)},children:"Simple Wizard"}),e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${u==="advanced"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>p("advanced"),children:"Advanced Swarm Builder"})]})]}),u==="advanced"?e(Bu,{client:a,api:t,toast:n,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel,editingAutomation:x,onShowAutomations:()=>{A(null),d("list")},onShowRuns:()=>{A(null),d("running")},onClearEditing:()=>A(null)}):e(Nm,{client:a,api:t,toast:n,navigate:r,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel})]})}):c==="list"?e(Yt,{title:"My Automations",subtitle:"Installed packs, routines and run history",children:e(Vs,{client:a,toast:n,navigate:r,viewMode:"list",selectedRunId:N,onSelectRunId:E,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:_=>{A(_),p("advanced"),d("create")}})}):c==="running"?e(Yt,{title:"Live Running Tasks",subtitle:"Inspect active runs and open detailed event logs for each run",children:e(Vs,{client:a,toast:n,navigate:r,viewMode:"running",selectedRunId:N,onSelectRunId:E,onOpenRunningView:()=>d("running"),onOpenAdvancedEdit:_=>{A(_),p("advanced"),d("create")}})}):c==="optimize"?e(Yt,{title:"Workflow Optimization",subtitle:"Create and inspect overnight shadow-eval optimization campaigns",children:e(Ju,{client:a,toast:n})}):e(Yt,{title:"Teams & Approvals",subtitle:"Active agent teams and pending spawn approvals",children:e(_m,{client:a,toast:n})})},c)})]})}function Im(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Cm(a){return(Array.isArray(a)?a:Array.isArray(a?.servers)?a.servers:a&&typeof a=="object"?Object.entries(a).map(([n,r])=>({name:n,...r})):[]).map(n=>({name:String(n?.name||"").trim(),connected:!!n?.connected,enabled:n?.enabled!==!1,transport:String(n?.transport||"").trim(),lastError:String(n?.last_error||n?.lastError||"").trim()})).filter(n=>n.name).sort((n,r)=>n.name.localeCompare(r.name))}function Am(a){return(Array.isArray(a)?a:Array.isArray(a?.tools)?a.tools:[]).map(n=>typeof n=="string"?n:String(n?.namespaced_name||n?.namespacedName||n?.id||"").trim()).filter(Boolean)}function Pm(a,t){return String(a?.run_id||a?.runId||a?.id||`run-${t}`).trim()}function Tm(a){return String(a?.objective||a?.title||a?.summary||a?.workflow_id||a?.workflowId||a?.run_type||a?.runType||a?.run_id||a?.runId||"Untitled run").trim()}function ms(a){return String(a?.status||"unknown").trim().toLowerCase()}function Ys(a){return String(a||"unknown").replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function Rm(a){return!["completed","done","failed","cancelled"].includes(ms(a))}function Mm(a){const t=[{id:"queue",label:"Queue",hint:"Ready or waiting to be claimed",statuses:["queued","pending","idle"],items:[]},{id:"planning",label:"Planning",hint:"Task decomposition and board shaping",statuses:["planning","preflight","triage"],items:[]},{id:"active",label:"Active",hint:"Currently being executed",statuses:["running","executing","in_progress","active","working"],items:[]},{id:"waiting",label:"Waiting",hint:"Blocked, paused, or awaiting approval",statuses:["blocked","awaiting_approval","paused","needs_info","waiting"],items:[]},{id:"done",label:"Done",hint:"Finished or archived",statuses:["completed","done","cancelled","failed","archived"],items:[]},{id:"other",label:"Other",hint:"Unclassified run states",statuses:[],items:[]}];return a.forEach(n=>{const r=ms(n);(t.find(c=>c.statuses.includes(r))||t[t.length-1]).items.push(n)}),t}function sr({label:a,value:t,helper:n,tone:r="info"}){return e("div",{className:"rounded-2xl border border-white/10 bg-black/20 p-4 shadow-[0_12px_36px_rgba(0,0,0,0.12)]",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"tcp-kpi-label text-sm",children:a}),e(ve,{tone:r,children:n})]}),e("div",{className:"mt-3 text-2xl font-semibold tracking-tight",children:t})]})}function qm({api:a,client:t}){const[n,r]=w("overview"),s=V({queryKey:["coding-workflows","health"],queryFn:()=>a("/api/system/health"),refetchInterval:15e3}),c=V({queryKey:["coding-workflows","swarm"],queryFn:()=>a("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:6e3}),d=V({queryKey:["coding-workflows","workflow-context-runs"],queryFn:()=>a("/api/engine/context/runs?limit=16").catch(()=>({runs:[]})),refetchInterval:6e3}),u=V({queryKey:["coding-workflows","mcp-servers"],queryFn:()=>t.mcp.list().catch(()=>({})),refetchInterval:1e4}),p=V({queryKey:["coding-workflows","mcp-tools"],queryFn:()=>t.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),N=F(()=>Cm(u.data),[u.data]),E=F(()=>Am(p.data),[p.data]),x=F(()=>Im(d.data,"runs").filter(ne=>["workflow","bug_monitor_triage","coding","coding_workflow","task"].includes(String(ne?.run_type||ne?.runType||"").trim().toLowerCase())),[d.data]),A=x.filter(Rm),O=F(()=>Mm(x),[x]),_=!!(s.data?.engine?.ready||s.data?.engine?.healthy),z=String(c.data?.status||"unknown"),P=N.some(B=>B.name.toLowerCase().includes("github")),Q=[{id:"overview",label:"Overview",icon:"layout-dashboard"},{id:"board",label:"Board",icon:"kanban-square"},{id:"manual",label:"Manual tasks",icon:"code"},{id:"integrations",label:"Integrations",icon:"plug-zap"}];return e(vn,{className:"grid gap-4",children:[e(ot,{className:"overflow-hidden",children:e("div",{className:"grid gap-5 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)] xl:items-start",children:e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Coding workflows"}),e("h1",{className:"tcp-page-title",children:"Internal Kanban and task launch pad"}),e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:"A dedicated home for repo-bound coding runs, manual task launches, worker swarms, and integration status. This page is intentionally small now so we can layer in extra tabs later without changing the mental model."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e(ve,{tone:_?"ok":"warn",children:_?"Engine healthy":"Engine checking"}),e(ve,{tone:z==="unknown"?"ghost":"info",children:["Swarm ",Ys(z)]}),e(ve,{tone:P?"ok":"warn",children:P?"GitHub MCP connected":"GitHub MCP pending"}),e(ya,{tone:A.length?"live":"info",text:`${A.length} active runs`})]})]})})}),e("div",{className:"tcp-settings-tabs",children:Q.map(B=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${n===B.id?"active":""}`,onClick:()=>r(B.id),children:[e("i",{"data-lucide":B.icon}),B.label]},B.id))}),n==="overview"?e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(sr,{label:"Workflow runs",value:x.length,helper:A.length?`${A.length} active`:"Idle",tone:A.length?"warn":"ok"}),e(sr,{label:"Connected MCP servers",value:N.length,helper:P?"GitHub available":"MCP pending",tone:P?"ok":"warn"}),e(sr,{label:"Registered tools",value:E.length,helper:"Tool surface",tone:E.length?"info":"ghost"}),e(sr,{label:"Engine mode",value:String(s.data?.engine?.mode||"unknown"),helper:String(s.data?.engine?.version||"n/a"),tone:_?"ok":"warn"})]}):null,n==="board"?e("div",{className:"grid gap-4 xl:grid-cols-2 2xl:grid-cols-3",children:O.map(B=>e(ot,{title:`${B.label} (${B.items.length})`,subtitle:B.hint,className:"h-full",children:B.items.length?e("div",{className:"grid gap-2",children:B.items.map((ne,I)=>{const C=ms(ne);return e("div",{className:"rounded-2xl border border-white/10 bg-black/20 p-3",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:Tm(ne)}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(ne?.workspaceRoot||ne?.workspace_root||"workspace")})]}),e(ve,{tone:B.id==="done"?"ok":B.id==="waiting"?"warn":"info",children:Ys(C)})]}),e("div",{className:"mt-2 flex flex-wrap gap-2 text-xs text-slate-300",children:[e("span",{className:"rounded-full border border-white/10 px-2 py-1",children:String(ne?.run_type||ne?.runType||"workflow")}),String(ne?.run_id||ne?.runId||"").trim()?e("span",{className:"rounded-full border border-white/10 px-2 py-1",children:String(ne?.run_id||ne?.runId).slice(0,12)}):null]})]},Pm(ne,I))})}):e(je,{text:"No runs in this lane yet."})},B.id))}):null,n==="manual"?e(ot,{title:"Manual task launcher",subtitle:"Reserved for explicit coding tasks, branch-bound work, and user-triggered actions.",children:e("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_minmax(280px,0.75fr)] xl:items-start",children:e("div",{className:"grid gap-3",children:[e("p",{className:"tcp-subtle",children:"This is where we can later add buttons for claim, start, branch selection, worker fan-out, and task-typing controls. For now it gives us a dedicated place to hang the workflow UI without inventing another page."}),e("div",{className:"flex flex-wrap gap-2",children:[e(ve,{tone:"info",children:"Future tab: claim task"}),e(ve,{tone:"info",children:"Future tab: worker swarm"}),e(ve,{tone:"info",children:"Future tab: branch control"})]})]})})}):null,n==="integrations"?e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(ot,{title:"Connected MCP servers",subtitle:"The integration layer this view depends on.",children:N.length?e("div",{className:"grid gap-2",children:N.map(B=>e("div",{className:"flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-black/20 px-3 py-2",children:[e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:B.name}),e("div",{className:"tcp-subtle text-xs",children:[B.transport||"transport pending",B.lastError?` · ${B.lastError}`:""]})]}),e(ve,{tone:B.connected?"ok":B.enabled?"warn":"ghost",children:B.connected?"Connected":B.enabled?"Configured":"Disabled"})]},B.name))}):e(je,{text:"No MCP servers detected yet."})}),e(ot,{title:"Tool surface",subtitle:"Useful for GitHub, repo, and orchestration actions.",children:E.length?e("div",{className:"flex flex-wrap gap-2",children:[E.slice(0,20).map(B=>e(ve,{tone:"info",children:B},B)),E.length>20?e(ve,{tone:"ghost",children:["+",E.length-20," more"]}):null]}):e(je,{text:"No MCP tools discovered yet."})})]}):null]})}function $m({client:a,toast:t}){const n=ca(),r=V({queryKey:["channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),s=V({queryKey:["channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),c=ke({mutationFn:async p=>{const E=(s.data||{})[p];if(!E)throw new Error(`No config found for ${p}`);await a.channels.put(p,E)},onSuccess:async()=>{t("ok","Channel reconfigured."),await n.invalidateQueries({queryKey:["channels"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=r.data&&typeof r.data=="object"?r.data:{},u=Object.entries(d);return e("div",{className:"grid gap-4",children:e(Yt,{title:"Channels",subtitle:"Connector health and quick reconnect",children:e("div",{className:"grid gap-2",children:u.length?u.map(([p,N])=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:p}),e("span",{className:N?.connected?"tcp-badge-ok":"tcp-badge-warn",children:N?.connected?"connected":"disconnected"})]}),e("div",{className:"tcp-subtle text-xs",children:String(N?.last_error||N?.error||"")||"No recent errors."}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>c.mutate(p),children:[e("i",{"data-lucide":"refresh-cw"}),"Reconnect"]})})]},p)):e(je,{text:"No channels configured."})})})})}function Vt(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function at(a){return String(a||"").trim()}function jr(a){try{return JSON.stringify(a,null,2)}catch{return"{}"}}function Om(a){return a?"ok":"ghost"}function Em(a){return at(a?.event_type||a?.type||a?.event||"workflow.event")}function Dm({api:a,toast:t}){const n=ca(),[r,s]=w(""),[c,d]=w(""),[u,p]=w(""),[N,E]=w("context.task.created"),[x,A]=w(`{
|
|
2455
2455
|
"event_id": "demo-task-1"
|
|
2456
|
-
}`),[O,k]=w([]),z=Y({queryKey:["packs","list"],queryFn:()=>a("/api/engine/packs",{method:"GET"}).catch(()=>({packs:[]})),refetchInterval:15e3}),A=Y({queryKey:["workflows","list"],queryFn:()=>a("/api/engine/workflows",{method:"GET"}).catch(()=>({workflows:[]})),refetchInterval:15e3}),G=Y({queryKey:["workflows","hooks"],queryFn:()=>a("/api/engine/workflow-hooks",{method:"GET"}).catch(()=>({hooks:[]})),refetchInterval:15e3}),B=Lt(z.data,"packs"),ae=Lt(A.data,"workflows"),S=Lt(G.data,"hooks"),I=K(()=>c||Ze(B[0]?.pack_id||B[0]?.name),[B,c]),H=K(()=>u||Ze(ae[0]?.workflow_id),[u,ae]),q=Y({queryKey:["workflows","runs",H],queryFn:()=>a(`/api/engine/workflows/runs${H?`?workflow_id=${encodeURIComponent(H)}&limit=20`:"?limit=20"}`,{method:"GET"}).catch(()=>({runs:[]})),refetchInterval:6e3}),ye=Lt(q.data,"runs"),y=Y({queryKey:["packs","detail",I],enabled:!!I,queryFn:()=>a(`/api/engine/packs/${encodeURIComponent(I)}`,{method:"GET"})}),v=Y({queryKey:["workflows","detail",H],enabled:!!H,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(H)}`,{method:"GET"})}),U=xe({mutationFn:()=>a("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:r,source:{kind:"control-panel"}})}),onSuccess:async()=>{t("ok","Pack installed."),s(""),await Promise.all([n.invalidateQueries({queryKey:["packs"]}),n.invalidateQueries({queryKey:["workflows"]})])},onError:M=>t("err",M instanceof Error?M.message:String(M))}),ue=xe({mutationFn:M=>a(`/api/engine/workflows/${encodeURIComponent(M)}/run`,{method:"POST"}),onSuccess:async M=>{t("ok",`Workflow ${Ze(M?.run?.workflow_id||H)} started.`),await Promise.all([n.invalidateQueries({queryKey:["workflows"]}),n.invalidateQueries({queryKey:["workflows","runs"]})])},onError:M=>t("err",M instanceof Error?M.message:String(M))}),ee=xe({mutationFn:async()=>{let M={};const me=Ze(x);return me&&(M=JSON.parse(me)),a("/api/engine/workflows/simulate",{method:"POST",body:JSON.stringify({event_type:N,properties:M})})},onError:M=>t("err",M instanceof Error?M.message:String(M))}),Oe=xe({mutationFn:({bindingId:M,enabled:me})=>a(`/api/engine/workflow-hooks/${encodeURIComponent(M)}`,{method:"PATCH",body:JSON.stringify({enabled:me})}),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["workflows","hooks"]}),n.invalidateQueries({queryKey:["workflows","detail"]})])},onError:M=>t("err",M instanceof Error?M.message:String(M))}),Ee=y.data?.pack||null,We=v.data?.workflow||null,ne=Lt(v.data,"hooks"),ce=ee.data?.simulation||null;return en(`/api/engine/workflows/events${H?`?workflow_id=${encodeURIComponent(H)}`:""}`,M=>{try{const me=JSON.parse(M.data);if(me?.status==="ready")return;k(Re=>[...Re.slice(-59),{at:Date.now(),data:me}])}catch{}},{enabled:!0}),e(gn,{className:"grid gap-4",children:[e(hc,{eyebrow:"Operations",title:"Pack library and workflow lab",subtitle:"Inspect installed packs, see workflow extensions, toggle hooks, simulate lifecycle events, and run workflow definitions without leaving the control panel.",badges:e(aa,{children:[e(we,{tone:"info",children:[B.length," installed packs"]}),e(we,{tone:"warn",children:[ae.length," workflows"]}),e(we,{tone:"ghost",children:[S.length," hooks"]})]})}),e(Rn,{main:e("div",{className:"grid gap-4",children:[e(ot,{title:"Installed packs",subtitle:"Select a pack to inspect its manifest, declared workflow contents, and hook contributions.",children:e("div",{className:"grid gap-2",children:B.length?B.map((M,me)=>{const Re=Ze(M?.pack_id||M?.name||me);return e("button",{type:"button",className:`tcp-list-item text-left ${Re===I?"border-amber-400/70":""}`,onClick:()=>d(Re),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Ze(M?.name||Re)}),e("span",{className:"tcp-badge-info",children:Ze(M?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-subtle",children:Ze(M?.pack_type||"pack")}),e("span",{className:"tcp-subtle",children:Ze(M?.install_path||"")})]})]},Re)}):e(Le,{text:"No packs are installed yet."})})}),e(ot,{title:"Workflow registry",subtitle:"This is the live workflow registry resolved from built-ins, installed packs, and workspace-local overrides.",children:e("div",{className:"grid gap-2",children:ae.length?ae.map(M=>{const me=Ze(M?.workflow_id),Re=me===H,qe=Ze(M?.source?.kind||"unknown");return e("button",{type:"button",className:`tcp-list-item text-left ${Re?"border-amber-400/70":""}`,onClick:()=>p(me),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Ze(M?.name||me)}),e("span",{className:`tcp-badge-${qe==="pack"?"warn":"info"}`,children:qe})]}),e("div",{className:"tcp-subtle text-xs",children:[me," · ",Lt(M?.steps,"steps").length," steps"]})]},me)}):e(Le,{text:"No workflows are currently registered."})})})]}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Install pack",subtitle:"Install a local pack path and reload workflow contributions automatically.",children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:r,onInput:M=>s(M.target.value),placeholder:"/path/to/pack.zip"}),e("button",{className:"tcp-btn-primary",disabled:!r.trim()||U.isPending,onClick:()=>U.mutate(),children:[e("i",{"data-lucide":"download"}),"Install from path"]})]})}),e(ot,{title:"Pack inspector",subtitle:"Shows which workflows and hooks a pack contributes, alongside its current capability surface.",children:Ee?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Ze(Ee?.installed?.name||I)}),e(we,{tone:"info",children:Ze(Ee?.installed?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e(we,{tone:"ghost",children:[Number(Ee?.workflow_extensions?.workflow_count||0)," ","workflows"]}),e(we,{tone:"ghost",children:[Number(Ee?.workflow_extensions?.workflow_hook_count||0)," ","hooks"]}),e(we,{tone:"ghost",children:[Number(Ee?.risk?.required_capabilities_count||0)," ","required caps"]})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Entry Points"}),Lt(Ee?.workflow_extensions,"workflow_entrypoints").length?Lt(Ee?.workflow_extensions,"workflow_entrypoints").map((M,me)=>e("div",{className:"tcp-list-item text-sm",children:Ze(M)},`${Ze(M)}-${me}`)):e(Le,{text:"This pack does not declare workflow entrypoints."})]}),e("details",{className:"tcp-list-item",children:[e("summary",{className:"cursor-pointer font-medium",children:"Manifest"}),e("pre",{className:"tcp-subtle mt-3 overflow-x-auto text-xs",children:_r(Ee?.manifest||{})})]})]}):e(Le,{text:"Select an installed pack to inspect workflow extensions."})})]})}),e(Rn,{main:e(ot,{title:"Workflow viewer",subtitle:"Structured view of workflow steps and source provenance for the selected workflow.",actions:e("button",{className:"tcp-btn",disabled:!H||ue.isPending,onClick:()=>H&&ue.mutate(H),children:[e("i",{"data-lucide":"play"}),"Run workflow"]}),children:We?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Ze(We?.name||H)}),e(we,{tone:"info",children:Ze(We?.source?.kind||"unknown")})]}),e("div",{className:"tcp-subtle text-sm",children:Ze(We?.description||"No description provided.")})]}),e("div",{className:"grid gap-2",children:Lt(We,"steps").length?Lt(We,"steps").map((M,me)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 text-xs uppercase tracking-[0.24em] text-slate-400",children:["Step ",me+1]}),e("div",{className:"font-medium",children:Ze(M?.action||"unknown")}),M?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:_r(M.with)}):null]},Ze(M?.step_id||me))):e(Le,{text:"This workflow does not define any linear steps."})})]}):e(Le,{text:"Select a workflow to inspect its current resolved definition."})}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Hook manager",subtitle:"Enable or disable hook bindings on the live registry and inspect the attached actions.",children:e("div",{className:"grid gap-2",children:ne.length?ne.map(M=>{const me=Ze(M?.binding_id),Re=!!M?.enabled;return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:Ze(M?.event||me)}),e("div",{className:"tcp-subtle text-xs",children:me})]}),e("button",{className:"tcp-btn",disabled:Oe.isPending,onClick:()=>Oe.mutate({bindingId:me,enabled:!Re}),children:Re?"Disable":"Enable"})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e(we,{tone:fm(Re),children:Re?"Enabled":"Disabled"}),e(we,{tone:"ghost",children:[Lt(M,"actions").length," actions"]})]}),e("div",{className:"grid gap-1",children:Lt(M,"actions").map((qe,se)=>e("div",{className:"tcp-subtle text-xs",children:Ze(qe?.action||qe)},`${me}-${se}`))})]},me)}):e(Le,{text:"The selected workflow has no registered hooks."})})}),e(ot,{title:"Recent workflow runs",subtitle:"Latest workflow executions for the selected workflow, including hook-triggered runs.",children:e("div",{className:"grid gap-2",children:ye.length?ye.map((M,me)=>{const Re=Ze(M?.status||"unknown"),qe=Re==="completed"?"ok":Re==="failed"?"err":Re==="running"?"warn":"ghost";return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Ze(M?.run_id||`run-${me+1}`)}),e(we,{tone:qe,children:Re})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger: ",Ze(M?.trigger_event||"manual")]}),e("div",{className:"tcp-subtle text-xs",children:["actions: ",Lt(M,"actions").length]})]},Ze(M?.run_id||me))}):e(Le,{text:"No workflow runs have been recorded yet."})})})]})}),e(Rn,{main:e(ot,{title:"Workflow testing mode",subtitle:"Simulate a source event to see which hooks will match before triggering real actions.",actions:e("button",{className:"tcp-btn-primary",disabled:!N.trim()||ee.isPending,onClick:()=>ee.mutate(),children:[e("i",{"data-lucide":"flask-conical"}),"Simulate"]}),children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:N,onInput:M=>E(M.target.value),placeholder:"context.task.created"}),e("textarea",{className:"tcp-input min-h-[180px] font-mono text-xs",value:x,onInput:M=>C(M.target.value),spellCheck:!1}),ce?e("div",{className:"grid gap-3",children:[e("div",{className:"flex flex-wrap gap-2",children:Lt(ce,"canonical_events").map((M,me)=>e(we,{tone:"info",children:Ze(M)},`${Ze(M)}-${me}`))}),e("div",{className:"grid gap-2",children:Lt(ce,"matched_bindings").length?Lt(ce,"matched_bindings").map(M=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:Ze(M?.binding_id)}),e("div",{className:"tcp-subtle text-xs",children:[Ze(M?.event)," · ",Lt(M,"actions").length," ","actions"]})]},Ze(M?.binding_id))):e(Le,{text:"No workflow hooks matched this event."})})]}):e(Le,{text:"Run a simulation to inspect canonical events, matched bindings, and planned actions."})]})}),aside:e(ot,{title:"Triggered actions",subtitle:"Preview of actions the engine plans to execute for the simulated event.",children:e("div",{className:"grid gap-2",children:Lt(ce,"planned_actions").length?Lt(ce,"planned_actions").map((M,me)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:Ze(M?.action||M)}),M?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:_r(M.with)}):null]},`${Ze(M?.action||M)}-${me}`)):e(Le,{text:"No planned actions yet."})})})}),e(ot,{title:"Live workflow events",subtitle:"Real-time `workflow.*` events for the selected workflow, including run start, action completion, and failures.",actions:e("button",{className:"tcp-btn",onClick:()=>k([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear stream"]}),children:e("div",{className:"grid max-h-[28rem] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:O.length?[...O].reverse().map((M,me)=>{const Re=bm(M.data),qe=Re.endsWith(".failed")?"err":Re.endsWith(".completed")?"ok":Re.endsWith(".started")?"warn":"info";return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Re}),e(we,{tone:qe,children:new Date(M.at).toLocaleTimeString()})]}),e("div",{className:"tcp-subtle text-xs",children:["run: ",Ze(M.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle text-xs",children:["action:"," ",Ze(M.data?.properties?.action||M.data?.properties?.actionID||"-")]})]},`${M.at}-${me}`)}):e(Le,{text:"Run a workflow or trigger a hook to watch live workflow events here."})})})]})}function ji(a){return a>=1?"bg-rose-500":a>=.8?"bg-amber-500":"bg-emerald-500"}function Tn(a,t){return!t||t<=0?0:Math.min(a/t,1)}function Gn({label:a,used:t,max:n,unit:r,advisory:s=!1}){const c=Tn(t,n),d=s?c>=.8?"bg-sky-400":"bg-cyan-500":ji(c);return e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center justify-between text-xs",children:[e("span",{className:"tcp-subtle",children:a}),e("span",{className:"font-mono text-[11px] text-slate-200",children:[t.toLocaleString(),r||""," / ",n.toLocaleString(),r||""]})]}),e("div",{className:"h-1.5 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${d}`,style:{width:`${c*100}%`}})})]})}function ym({budget:a}){const[t,n]=w(!1),r=a.limits_enforced===!1,s=Math.max(Tn(a.iterations_used,a.max_iterations),Tn(a.tokens_used,a.max_tokens),Tn(a.wall_time_secs,a.max_wall_time_secs),Tn(a.subagent_runs_used,a.max_subagent_runs));return e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("button",{className:"flex w-full items-center justify-between",onClick:()=>n(c=>!c),children:[e("div",{className:"text-sm font-medium",children:"Budget + Tokens"}),e("div",{className:"flex items-center gap-2",children:[e("div",{className:"h-2 w-24 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${r?s>=.8?"bg-sky-400":"bg-cyan-500":ji(s)}`,style:{width:`${s*100}%`}})}),e("span",{className:"tcp-subtle text-xs",children:[Math.round(s*100),"%"]})]})]}),t?e("div",{className:"mt-3 grid gap-3 border-t border-slate-700/60 pt-3",children:[e(Gn,{label:"Iterations",used:a.iterations_used,max:a.max_iterations,advisory:r}),e(Gn,{label:"Tokens",used:a.tokens_used,max:a.max_tokens,advisory:r}),e(Gn,{label:"Wall time",used:a.wall_time_secs,max:a.max_wall_time_secs,unit:"s",advisory:r}),e(Gn,{label:"Agent calls",used:a.subagent_runs_used,max:a.max_subagent_runs,advisory:r}),r?e("div",{className:"rounded border border-cyan-500/30 bg-cyan-950/20 p-2 text-xs text-cyan-100",children:"Advisory usage only. This run does not expose explicit enforced budget caps, so these limits are relaxed defaults for visibility."}):null,a.exceeded&&a.exceeded_reason?e("div",{className:"rounded border border-rose-500/40 bg-rose-950/30 p-2 text-xs text-rose-200",children:a.exceeded_reason}):null]}):null]})}function Or(a,t=0){return String(a?.run_id||a?.runId||`run-${t}`).trim()}function Os(a){const t=Number(a?.updated_at_ms||a?.updatedAtMs||0),n=Number(a?.created_at_ms||a?.createdAtMs||0),r=Number.isFinite(t)&&t>0?t:n;return Number.isFinite(r)&&r>0?r:0}function wm(a,t=""){const n=String(t||"").trim(),r=[...Array.isArray(a)?a:[]].sort((d,u)=>Os(u)-Os(d));if(n){const d=r.find((u,p)=>Or(u,p)===n);if(d){const u=String(d?.status||"").trim().toLowerCase();if(!["completed","failed","cancelled"].includes(u))return n}}const c=r.find(d=>{const u=String(d?.status||"").trim().toLowerCase();return!["completed","failed","cancelled"].includes(u)})||r[0];return c?Or(c):""}function xm(a,t){if(t.type==="sync_runs"){const n={},r=[];for(let c=0;c<t.runs.length;c+=1){const d=t.runs[c],u=Or(d,c);u&&(n[u]=d,r.push(u))}let s=a.selectedRunId;return s||(s=wm(t.runs,t.preferredRunId)),{runsById:n,orderedRunIds:r,selectedRunId:s,cursorsByRunId:a.cursorsByRunId}}if(t.type==="select_run")return{...a,selectedRunId:String(t.runId||"").trim()};if(t.type==="clear_selection")return{...a,selectedRunId:""};if(t.type==="advance_cursor"){const n=String(t.runId||"").trim();if(!n)return a;const r=Number(t.seq||0);if(!Number.isFinite(r)||r<=0)return a;const s=String(t.kind||"").trim().toLowerCase(),c=a.cursorsByRunId[n]||{eventSeq:0,patchSeq:0},d={eventSeq:s==="context_run_event"?Math.max(c.eventSeq,r):c.eventSeq,patchSeq:s==="blackboard_patch"?Math.max(c.patchSeq,r):c.patchSeq};return d.eventSeq===c.eventSeq&&d.patchSeq===c.patchSeq?a:{...a,cursorsByRunId:{...a.cursorsByRunId,[n]:d}}}return a}function km(a,t=""){const[n,r]=Ji(xm,{runsById:{},orderedRunIds:[],selectedRunId:"",cursorsByRunId:{}});fe(()=>{r({type:"sync_runs",runs:Array.isArray(a)?a:[],preferredRunId:t})},[a,t]);const s=K(()=>n.orderedRunIds.map(c=>n.runsById[c]).filter(Boolean),[n.orderedRunIds,n.runsById]);return{runsById:n.runsById,orderedRunIds:n.orderedRunIds,orderedRuns:s,selectedRunId:n.selectedRunId,cursorsByRunId:n.cursorsByRunId,setSelectedRunId:c=>r({type:"select_run",runId:c}),clearSelectedRunId:()=>r({type:"clear_selection"}),advanceCursor:(c,d,u)=>r({type:"advance_cursor",runId:c,kind:d,seq:u})}}function Nm(a){const t={},n={};for(const[c,d]of Object.entries(a||{})){const u=Number(d?.eventSeq||0),p=Number(d?.patchSeq||0);u>0&&(t[c]=u),p>0&&(n[c]=p)}const s=JSON.stringify({events:t,patches:n});return!s||s==='{"events":{},"patches":{}}'?"":btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function _m({workspace:a,runIds:t,cursorToken:n,onEnvelope:r,onError:s}){const c=K(()=>[...new Set((t||[]).map(u=>String(u||"").trim()).filter(Boolean))],[t]),d=K(()=>{const u=String(a||"").trim();if(!u||!c.length)return"";const p=new URLSearchParams;return p.set("workspace",u),p.set("runIds",c.join(",")),n&&p.set("cursor",n),`/api/orchestrator/events?${p.toString()}`},[n,c,a]);fe(()=>{if(!d)return;const u=Br(d,p=>{let N=null;try{N=JSON.parse(String(p?.data||"{}"))}catch{return}!N||typeof N!="object"||r(N)},{onError:p=>{s&&s(p)}});return()=>u()},[r,s,d])}const Sm={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 Sa(a){const t=String(a||"").trim().toLowerCase();return t==="done"||t==="completed"||t==="active"?"tcp-badge-ok":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"tcp-badge-err":t==="running"||t==="in_progress"||t==="runnable"?"tcp-badge-warn":"tcp-badge-info"}function Im(a){const t=String(a||"").trim().toLowerCase();return{created:"Created",pending:"Pending",runnable:"Ready",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"}[t]||t||"Unknown"}function Es(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"Run":`Run ${new Date(t).toLocaleTimeString()}`}function Cm(a){return Number(a?.updated_at_ms||a?.created_at_ms||0)}function Wa(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"--:--:--":new Date(t).toLocaleTimeString()}function Am(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"0 B":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Pm(a){const t=String(a||"").trim(),n=t.lastIndexOf(".");return n<0?"":t.slice(n+1).toLowerCase()}function En(a){const t=String(a||"").trim().replace(/\\/g,"/");return t?t.startsWith("/")?t.replace(/\/{2,}/g,"/"):t:""}function Tm(a,t){const n=En(a).replace(/\/+$/,""),r=En(t).replace(/^\/+/,"");return n?r?`${n}/${r}`:n:r}function Ds(a,t){const n=En(a).replace(/\/+$/,""),r=En(t);return!n||!r?!1:r===n?!0:r.startsWith(`${n}/`)}function js(a){const t=[a?.workspace?.canonical_path,a?.workspace?.path,a?.workspace?.root,a?.workspace_root,a?.workspacePath,a?.cwd,a?.path];for(const n of t){const r=En(String(n||""));if(r.startsWith("/"))return r}return""}function Us(a){const t={};for(const n of a){const r=String(n?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(r))continue;const s=String(n?.step_id||"").trim();if(!s)continue;const c=Number(n?.seq||0);!Number.isFinite(c)||c<=0||(t[s]=Math.max(Number(t[s]||0),c))}return t}function Rm(a){return String(a?.event_type||a?.type||a?.event||"workflow.event").trim().toLowerCase()}function Bs(a){const t=[`type: ${String(a.type||"").trim()||"unknown"}`,`task: ${String(a.taskId||"").trim()||"n/a"}`,`title: ${String(a.title||"").trim()||"n/a"}`,`mode: ${String(a.mode||"").trim()||"strict"}`,`at: ${Wa(a.at)}`,"","reason:",String(a.reason||"").trim()||"No verification detail."],n=a.verification?.execution_trace;return n&&typeof n=="object"&&t.push("","execution_trace:",`session: ${String(n.session_id||"n/a")}`,`model: ${[String(n?.model?.provider||"").trim(),String(n?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"}`,`source: ${String(n?.model?.source||"n/a")}`),t.push("","verification_json:",JSON.stringify(a.verification||{},null,2)),t.join(`
|
|
2457
|
-
`)}function ln(a){const t=String(a?.task_id||a?.taskID||"").trim();if(t)return t;const n=a?.source_event_id||a?.sourceEventID,r=String(n||"").trim();if(!r)return"";const s=r.lastIndexOf(":");return s<0?"":r.slice(s+1).trim()}function qm({api:a,toast:t,navigate:n}){const r=na(),s=!!Vs(),c=qt(null),[d,u]=w(!0),[p,N]=w(!1),[E,x]=w(""),[C,O]=w(""),[k,z]=w(!1),[A,G]=w(""),[B,ae]=w(""),[S,I]=w(!1),[H,q]=w("4"),[ye,y]=w("3"),[v,U]=w("swarm.blackboard.default"),[ue,ee]=w(""),[Oe,Ee]=w(""),[We,ne]=w(""),[ce,M]=w(""),[me,Re]=w([]),[qe,se]=w(""),[Ue,Me]=w(""),[ze,X]=w(""),[Ve,re]=w(!1);fe(()=>{u(!0),lt()},[]);const Ce=Y({queryKey:["swarm","status"],queryFn:()=>a("/api/orchestrator/status"),refetchInterval:5e3}),gt=Y({queryKey:["swarm","runs",C],queryFn:()=>a(`/api/orchestrator/runs?workspace=${encodeURIComponent(C||"")}`),refetchInterval:6e3,enabled:!!Ce.data}),ie=Array.isArray(gt.data?.runs)?gt.data.runs:[],L=km(ie,String(Ce.data?.runId||"").trim()),st=L.selectedRunId,pt=L.setSelectedRunId,lt=L.clearSelectedRunId,Ct=L.advanceCursor,De=d?"":String(st||"").trim(),$t=L.orderedRuns,yt=K(()=>{if(!De)return null;for(const b of $t)if(String(b?.run_id||b?.runId||"").trim()===De)return b;return null},[$t,De]),Ut=K(()=>Nm(L.cursorsByRunId),[L.cursorsByRunId]),Je=String(C||Ce.data?.workspaceRoot||"").trim(),Ge=K(()=>{const b=String(De||"").trim();return b?[b]:[]},[De]),nt=qt(0),ve=mt(b=>{const F=String(b?.kind||"").trim().toLowerCase(),he=String(b?.run_id||b?.runId||"").trim();if(De&&he&&he!==De)return;const Fe=Number(b?.seq||0);he&&Fe>0&&(F==="context_run_event"||F==="blackboard_patch")&&Ct(he,F,Fe);const Ke=Date.now();Ke-nt.current<900||(nt.current=Ke,r.invalidateQueries({queryKey:["swarm","runs"]}),De&&r.invalidateQueries({queryKey:["swarm","run",De]}))},[Ct,r,De]);_m({workspace:Je,runIds:Ge,cursorToken:Ut,onEnvelope:ve});const _e=Y({queryKey:["swarm","run",De],queryFn:()=>a(`/api/orchestrator/run/${encodeURIComponent(De)}`),refetchInterval:4e3,enabled:!!De}),Ye=Y({queryKey:["swarm","workspace-browser",A],enabled:k&&!!A,queryFn:()=>a(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(A)}`)}),le=String(_e.data?.runStatus||_e.data?.run?.status||Ce.data?.status||"idle").trim().toLowerCase(),it=K(()=>Pi(_e.data),[_e.data]),_=it.tasks,J=K(()=>({...Sm,..._e.data?.budget||{}}),[_e.data?.budget]),be=String(js(_e.data?.run)||js(yt)||(De?"":String(Ce.data?.workspaceRoot||C||""))).trim();fe(()=>{be&&(Ee(b=>!b||!Ds(be,b)?be:b),ne(b=>Ds(be,b)?b:""))},[be]);const je=Array.isArray(Ye.data?.directories)?Ye.data.directories:[],o=String(B||"").trim().toLowerCase(),f=K(()=>o?je.filter(b=>String(b?.name||b?.path||"").trim().toLowerCase().includes(o)):je,[je,o]),R=String(Ye.data?.parent||"").trim(),P=String(Ye.data?.dir||A||"").trim(),$=Y({queryKey:["swarm","workspace-files",be,Oe],enabled:!!be&&!!Oe,queryFn:async()=>{const b=await a(`/api/orchestrator/workspaces/files?workspaceRoot=${encodeURIComponent(be)}&dir=${encodeURIComponent(Oe)}`).catch(()=>({directories:[],files:[],parent:null,dir:Oe})),F=Array.isArray(b?.directories)?b.directories:[],Fe=(Array.isArray(b?.files)?b.files:[]).map(Ke=>{const at=String(Ke?.path||"").trim();return{...Ke,name:String(Ke?.name||at||"file"),path:at||Tm(be,String(Ke?.name||""))}});return{ok:!0,dir:String(b?.dir||Oe),parent:b?.parent||null,directories:F,files:Fe,fileAccessAllowed:!0}},refetchInterval:1e4}),Xe=Y({queryKey:["swarm","workspace-file",be,We],enabled:!!be&&!!We,queryFn:async()=>a(`/api/orchestrator/workspaces/read?workspaceRoot=${encodeURIComponent(be)}&path=${encodeURIComponent(We)}`)}),et=Array.isArray($.data?.directories)?$.data.directories:[],bt=Array.isArray($.data?.files)?$.data.files:[],Ot=String($.data?.parent||"").trim(),Ae=$.data?.fileAccessAllowed!==!1,xt=String(Xe.data?.text||""),At=Pm(We),te=["md","markdown","mdx"].includes(At),Se=["html","htm"].includes(At);fe(()=>{Ve&&!Se&&re(!1)},[Se,Ve]);const h=K(()=>_.map(b=>`${b.id}:${b.state}:${b.error_message||""}`).join("|"),[_]),j=K(()=>_.find(b=>b.id===Ue)||null,[Ue,_]),Q=K(()=>{const b=Array.isArray(_e.data?.events)?_e.data.events:[];let F=null,he=0;for(const Fe of b){const Ke=String(Fe?.type||"").trim().toLowerCase();if(!["step_completed","task_completed"].includes(Ke))continue;const at=Fe?.payload&&typeof Fe.payload=="object"?Fe.payload:{},wt=String(at?.session_id||"").trim();if(!wt)continue;const Gt=Number(Fe?.ts_ms||0);(!F||Gt>=he)&&(F={sessionId:wt,event:Fe},he=Gt)}return F},[_e.data?.events]),W=K(()=>{const b=Array.isArray(_e.data?.events)?_e.data.events:[];for(let F=b.length-1;F>=0;F-=1){const he=b[F],Fe=String(he?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(Fe))continue;const Ke=he?.payload&&typeof he.payload=="object"?he.payload:{},at=String(Ke?.session_id||"").trim();if(at)return at}return String(Q?.sessionId||"").trim()},[Q?.sessionId,_e.data?.events]),V=K(()=>{const b=Array.isArray(_e.data?.events)?_e.data.events:[],F=Us(b),he=[];for(let Fe=b.length-1;Fe>=0;Fe-=1){const Ke=b[Fe],at=String(Ke?.type||"").trim().toLowerCase();if(!["task_started","task_completed","task_failed","step_started","step_completed","step_failed","run_resumed","run_paused","run_completed","run_failed"].includes(at))continue;const wt=Ke?.payload&&typeof Ke.payload=="object"?Ke.payload:{},Gt=String(Ke?.step_id||"").trim(),ra=Number(Ke?.seq||0);if((at==="task_failed"||at==="step_failed")&&Gt&&Number.isFinite(ra)&&ra>0&&Number(F[Gt]||0)>ra)continue;const Tt=String(wt?.step_title||Ke?.step_id||at).trim(),ka=String(wt?.why_next_step||wt?.error||"").trim();if(he.push({id:`${String(Ke?.seq||Fe)}-${at}`,type:at,title:Tt||at,detail:ka,at:Number(Ke?.ts_ms||0)}),he.length>=12)break}return he},[_e.data?.events]),ge=K(()=>{const b=Array.isArray(_e.data?.events)?_e.data.events:[];for(let F=b.length-1;F>=0;F-=1){const he=b[F],Fe=String(he?.type||"").trim().toLowerCase();if(Fe==="plan_seeded_llm")return"llm";if(Fe==="plan_seeded_local")return"fallback_local";if(Fe==="plan_failed_llm_required")return"llm_failed"}return"unknown"},[_e.data?.events]),Be=Y({queryKey:["swarm","run-output-session",String(W||"")],queryFn:()=>a(`/api/engine/session/${encodeURIComponent(String(W||""))}`),refetchInterval:6e3,enabled:!!W}),ht=K(()=>{const b=ui(Be.data,"Assistant");for(let F=b.length-1;F>=0;F-=1)if(b[F]?.role==="assistant"&&String(b[F]?.text||"").trim())return String(b[F]?.text||"").trim();return""},[Be.data]),ct=K(()=>{const b=Array.isArray(Be.data)?Be.data:Array.isArray(Be.data?.messages)?Be.data.messages:[],F=[];for(let he=b.length-1;he>=0;he-=1){const Fe=b[he],Ke=Array.isArray(Fe?.parts)?Fe.parts:[];for(let at=Ke.length-1;at>=0;at-=1){const wt=Ke[at];if(!String(wt?.type||wt?.part_type||"").trim().toLowerCase().includes("tool"))continue;const ra=String(wt?.tool||wt?.name||"").trim(),Da=String(wt?.state||wt?.status||"").trim(),Tt=String(wt?.error||"").trim(),ka=[ra||"tool",Da||null,Tt?`err=${Tt}`:null].filter(Boolean).join(" · ");if(F.push(ka),F.length>=10)return F}}return F},[Be.data]),kt=K(()=>{const b=Array.isArray(_e.data?.events)?_e.data.events:[],F=Us(b),he=[];for(let Fe=b.length-1;Fe>=0;Fe-=1){const Ke=b[Fe],at=String(Ke?.type||"").trim().toLowerCase();if(!["task_failed","step_failed","task_completed","step_completed"].includes(at))continue;const wt=Ke?.payload&&typeof Ke.payload=="object"?Ke.payload:{},Gt=String(Ke?.step_id||"").trim(),ra=Number(Ke?.seq||0);if((at==="task_failed"||at==="step_failed")&&Gt&&Number.isFinite(ra)&&ra>0&&Number(F[Gt]||0)>ra)continue;const Tt=wt?.verification&&typeof wt.verification=="object"?wt.verification:{},ka=String(Tt?.reason||wt?.error||"").trim(),ja=String(Tt?.mode||"strict").trim()||"strict";if(he.push({id:`${String(Ke?.seq||Fe)}-${at}`,taskId:Gt,title:String(wt?.step_title||Ke?.step_id||at),type:at,reason:ka,mode:ja,at:Number(Ke?.ts_ms||0),verification:Tt}),he.length>=8)break}return he},[_e.data?.events]),tt=K(()=>kt.find(b=>b.id===ze)||null,[ze,kt]);fe(()=>{if(!tt&&!j&&!Ve||typeof document>"u")return;const b=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=b}},[tt,j,Ve]);const Nt=String(_e.data?.run?.workflowId||_e.data?.run?.workflow_id||yt?.workflowId||yt?.workflow_id||v||"").trim(),Bt=Y({queryKey:["workflow","detail",Nt],enabled:!!Nt,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(Nt)}`),refetchInterval:15e3}),Jt=Y({queryKey:["workflow","runs",Nt],enabled:!!Nt,queryFn:()=>a(`/api/engine/workflows/runs?workflow_id=${encodeURIComponent(Nt)}&limit=12`).catch(()=>({runs:[]})),refetchInterval:5e3}),vt=Array.isArray(Jt.data?.runs)?Jt.data.runs:[],dt=K(()=>{const b={};for(const F of vt){const he=ln(F);if(!he)continue;const Fe=b[he]||{runs:0,failed:0};Fe.runs+=1,String(F?.status||"").trim().toLowerCase()==="failed"&&(Fe.failed+=1),b[he]=Fe}return b},[vt]),Ie=K(()=>qe?vt.filter(b=>ln(b)===qe):vt,[qe,vt]),Pe=K(()=>{const b=[];for(const F of Ie){const he=String(F?.run_id||"").trim(),Fe=ln(F);for(const Ke of Array.isArray(F?.actions)?F.actions:[])b.push({id:`${he}:${String(Ke?.action_id||Ke?.action||b.length)}`,runId:he,action:String(Ke?.action||"unknown action"),status:String(Ke?.status||"unknown"),detail:String(Ke?.detail||""),output:Ke?.output,updatedAt:Number(Ke?.updated_at_ms||F?.updated_at_ms||0),taskId:String(Ke?.task_id||Fe||"").trim()})}return b.sort((F,he)=>he.updatedAt-F.updatedAt),b},[Ie]);fe(()=>{const b=Ie;if(!b.length){M("");return}b.some(he=>{const Fe=String(he?.run_id||"").trim();return Fe&&Fe===ce})||M(String(b[0]?.run_id||"").trim())},[Ie,ce]);const Ne=Y({queryKey:["workflow","run",ce],enabled:!!ce,queryFn:()=>a(`/api/engine/workflows/runs/${encodeURIComponent(ce)}`),refetchInterval:5e3}).data?.run||null;fe(()=>{const b=ln(Ne);b&&se(b)},[Ne?.run_id,Ne?.source_event_id]),fe(()=>{Re([])},[Nt]),en(`/api/engine/workflows/events${Nt?`?workflow_id=${encodeURIComponent(Nt)}`:""}`,b=>{try{const F=JSON.parse(b.data);if(F?.status==="ready")return;Re(he=>[...he.slice(-79),{at:Date.now(),data:F}])}catch{}},{enabled:!!Nt});const pe=xe({mutationFn:()=>{const b=String(E||"").trim(),F=String(C||"").trim();if(!b)throw new Error("Enter a prompt first.");if(!F)throw new Error("Set workspace path first.");return a("/api/orchestrator/start",{method:"POST",body:JSON.stringify({objective:b,workspaceRoot:F,maxTasks:Number(H||4),maxAgents:Number(ye||3),workflowId:String(v||"swarm.blackboard.default").trim(),requireLlmPlan:!0,allowLocalPlannerFallback:!1,verificationMode:"strict"})})},onSuccess:async b=>{const F=String(b?.runId||"").trim();F&&pt(F),u(!1),t("ok","Planning started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:b=>t("err",b instanceof Error?b.message:String(b))}),ut=xe({mutationFn:({path:b,body:F})=>a(b,{method:"POST",body:JSON.stringify(F)}),onSuccess:async(b,F)=>{if(F.path==="/api/orchestrator/request_revision"){const he=String(b?.runId||"").trim();he&&(pt(he),ee("")),t("ok","Reworked plan created.")}F.path==="/api/orchestrator/approve"&&t("ok","Execution started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:b=>t("err",b instanceof Error?b.message:String(b))}),He=xe({mutationFn:async b=>{const F=String(b||"").trim();if(!F)throw new Error("Missing run id.");return await a("/api/orchestrator/cancel",{method:"POST",body:JSON.stringify({runId:F})}).catch(()=>null),await a("/api/orchestrator/runs/hide",{method:"POST",body:JSON.stringify({runIds:[F]})}).catch(()=>null),F},onSuccess:async()=>{lt(),u(!0),ee(""),x(""),t("ok","Discarded pending plan. You can start a new prompt now."),await r.invalidateQueries({queryKey:["swarm"]})},onError:b=>t("err",b instanceof Error?b.message:String(b))}),_t=mt(()=>{u(!0),lt(),N(!1),ee("")},[lt]);fe(()=>{const b=c.current;b&&wa(b)},[d,p,$t,De,le,Oe,et.length,bt.length,We,xt,Ue,ze,Ve,h]);const Kt=!De,ia=le==="planning"||le==="queued",Et=le==="awaiting_approval",Qt=["completed","failed","cancelled"].includes(le),Pt=le==="running",Xt=le==="paused",Zt=le==="failed"||le==="blocked",ua=["queued","planning","awaiting_approval","running","paused","blocked"].includes(le),xa=e(aa,{children:[e($e.aside,{className:`chat-sessions-panel ${p?"open":""}`,initial:!1,animate:s?{x:p?0:"-104%"}:{x:p?0:"-104%",transition:{duration:.18,ease:"easeOut"}},children:[e("div",{className:"chat-sessions-header",children:[e("h3",{className:"chat-sessions-title",children:[e("i",{"data-lucide":"history"}),"History"]}),e("div",{className:"flex items-center gap-1",children:e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{r.invalidateQueries({queryKey:["swarm","runs"]})},children:e("i",{"data-lucide":"refresh-cw"})})})]}),e("div",{className:"chat-session-list",children:[e(Mt,{children:$t.map((b,F)=>{const he=String(b?.run_id||b?.runId||`run-${F}`),Fe=he===De;return e($e.div,{className:"chat-session-row",initial:s?!1:{opacity:0,y:6},animate:s?void 0:{opacity:1,y:0},exit:s?void 0:{opacity:0,y:-6},children:e("button",{type:"button",className:`chat-session-btn ${Fe?"active":""}`,onClick:()=>{u(!1),pt(he),N(!1)},children:[e("span",{className:"mb-0.5 inline-flex items-center gap-1 text-xs font-medium",children:[e("i",{"data-lucide":"history"}),e("span",{children:Es(Cm(b))})]}),e("span",{className:"tcp-subtle line-clamp-2 block text-[11px]",children:String(b?.objective||"").trim()||"No objective"})]})},he)})}),$t.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No runs yet."})]})]}),e(Mt,{children:p?e($e.button,{type:"button",className:"chat-scrim open","aria-label":"Close history",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},onClick:()=>N(!1)}):null})]});if(Kt){const b=String(E||"").trim().length>0&&String(C||"").trim().length>0;return e(aa,{children:[e("div",{ref:c,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[xa,e("div",{className:"min-h-0 min-w-0 w-full",children:e("div",{className:"flex h-full min-h-0 w-full flex-col gap-4 p-4 md:p-5",children:[e("div",{className:"mb-3",children:[e("div",{className:"inline-flex items-center gap-2 text-sm font-semibold",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"History",onClick:()=>N(F=>!F),children:e("i",{"data-lucide":"history"})}),e("span",{children:"Orchestrator"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Describe the goal. The planner will build a task board."})]}),e("div",{className:"grid min-h-0 flex-1 w-full content-start gap-3",children:[e("textarea",{className:"tcp-input min-h-[360px] md:min-h-[52vh]",placeholder:"What do you want the agents to build?",value:E,onInput:F=>x(F.target.value)}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr]",children:[e("button",{className:"tcp-btn",onClick:()=>{const F=String(C||Ce.data?.workspaceRoot||"/").trim();G(F||"/"),ae(""),z(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,placeholder:"No workspace selected. Use Browse.",value:C})]}),e("div",{className:"tcp-subtle text-xs",children:["Selected folder: ",C||"none"]}),C?null:e("div",{className:"rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"Select a workspace folder before sending."}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("button",{className:"tcp-btn-primary",onClick:()=>pe.mutate(),disabled:pe.isPending||!b,children:[e("i",{"data-lucide":"send"}),"Send"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>I(F=>!F),children:[e("i",{"data-lucide":"sliders-horizontal"}),S?"Hide Advanced":"Show Advanced"]})]}),S?e("div",{className:"grid gap-2 rounded-lg border border-slate-700/60 bg-slate-900/20 p-2 md:grid-cols-3",children:[e("input",{className:"tcp-input",type:"number",min:"1",value:H,onInput:F=>q(F.target.value),title:"max tasks"}),e("input",{className:"tcp-input",type:"number",min:"1",max:"16",value:ye,onInput:F=>y(F.target.value),title:"max agents"}),e("input",{className:"tcp-input",value:v,onInput:F=>U(F.target.value),title:"workflow id"}),e("div",{className:"tcp-subtle md:col-span-3 text-xs",children:"Workflow id controls task routing template. Keep default unless you have a custom workflow."})]}):null]})]})})]}),k?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",P||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{R&&G(R)},disabled:!R,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{P&&(O(P),z(!1),ae(""),t("ok",`Workspace selected: ${P}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{z(!1),ae("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:B,onInput:F=>ae(F.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:f.length?f.map(F=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>G(String(F?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(F?.name||F?.path||"")]},String(F?.path||F?.name))):e(Le,{text:o?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}return e(aa,{children:[e("div",{ref:c,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[xa,e("div",{className:"min-h-0 min-w-0 w-full",children:e("div",{className:"grid h-full min-h-[calc(100vh-240px)] min-w-0 w-full gap-5 p-4 md:p-5 xl:grid-cols-[1.05fr_1fr]",children:[e("div",{className:"flex h-full min-h-0 w-full flex-col gap-3",children:[e("div",{className:"mb-3",children:[e("div",{className:"inline-flex items-center gap-2 text-sm font-semibold",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"History",onClick:()=>N(b=>!b),children:e("i",{"data-lucide":"history"})}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Back to start",onClick:_t,children:e("i",{"data-lucide":"arrow-left-to-line"})}),e("span",{children:"Orchestration Run"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Plan review and execution"})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Sa(le),children:le||"unknown"}),e("span",{className:"inline-flex items-center gap-1 tcp-subtle",children:[e("i",{"data-lucide":"history"}),e("span",{children:Es(_e.data?.run?.updated_at_ms||_e.data?.run?.created_at_ms)})]}),e("span",{className:"tcp-subtle",children:["id: ",De]}),e("span",{className:"tcp-subtle",children:["plan: ",ge]})]}),ia?e("div",{className:"mb-3 rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("div",{className:"mb-1 text-sm font-medium",children:"Planner is formulating a plan..."}),e("div",{className:"tcp-subtle text-xs",children:"Waiting for tasks to be generated."})]}):null,Et?e("div",{className:"mb-3 rounded-xl border border-amber-500/40 bg-amber-950/20 p-3",children:[e("div",{className:"mb-2 text-sm font-medium text-amber-200",children:"Plan Ready"}),e("div",{className:"mb-2 text-xs text-amber-100/90",children:"Review the kanban. Request a rework or execute."}),e("textarea",{className:"tcp-input mb-2 min-h-[80px]",placeholder:"Feedback to rework the plan...",value:ue,onInput:b=>ee(b.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",disabled:!ue.trim(),onClick:()=>ut.mutate({path:"/api/orchestrator/request_revision",body:{runId:De,feedback:ue,maxTasks:Number(H||4),maxAgents:Number(ye||3),workflowId:v}}),children:[e("i",{"data-lucide":"pencil"}),"Rework Plan"]}),e("button",{className:"tcp-btn-primary",onClick:()=>ut.mutate({path:"/api/orchestrator/approve",body:{runId:De}}),children:[e("i",{"data-lucide":"play"}),"Execute Plan"]}),e("button",{className:"tcp-btn-danger",disabled:He.isPending,onClick:()=>He.mutate(De),children:[e("i",{"data-lucide":"trash-2"}),"Discard Plan"]})]})]}):null,!ia&&!Et?e("div",{className:"mb-3 flex flex-wrap gap-2",children:[Pt?e("button",{className:"tcp-btn",onClick:()=>ut.mutate({path:"/api/orchestrator/pause",body:{runId:De}}),children:[e("i",{"data-lucide":"square"}),"Pause"]}):null,Xt?e("button",{className:"tcp-btn",onClick:()=>ut.mutate({path:"/api/orchestrator/resume",body:{runId:De}}),children:[e("i",{"data-lucide":"play"}),"Resume"]}):null,Zt?e("button",{className:"tcp-btn",onClick:()=>ut.mutate({path:"/api/orchestrator/continue",body:{runId:De}}),children:[e("i",{"data-lucide":"rotate-cw"}),"Continue Run"]}):null,ua?e("button",{className:"tcp-btn-danger",onClick:()=>ut.mutate({path:"/api/orchestrator/cancel",body:{runId:De}}),children:[e("i",{"data-lucide":"x"}),"Cancel"]}):null,e("button",{className:"tcp-btn",onClick:_t,children:[e("i",{"data-lucide":"plus"}),"New Prompt"]})]}):null,Qt?e("div",{className:"mb-3 rounded-lg border border-slate-700/60 bg-slate-900/25 p-2 text-xs tcp-subtle",children:le==="failed"?"This run is failed. Continue the run or retry a failed task.":`This run is ${le}. Start a new prompt to continue.`}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workspace Files"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Refresh","aria-label":"Refresh",onClick:()=>{$.refetch()},disabled:!be,children:e("i",{"data-lucide":"refresh-cw"})})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Up","aria-label":"Up",disabled:!Ot,onClick:()=>{Ot&&Ee(Ot)},children:e("i",{"data-lucide":"arrow-up-circle"})}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Root","aria-label":"Root",disabled:!be,onClick:()=>{be&&Ee(be)},children:e("i",{"data-lucide":"home"})})]}),e("div",{className:"mb-2 tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:Oe||be||"No workspace"}),Ae?null:e("div",{className:"mb-2 rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"File listing for this workspace is not exposed by the current server scope. Directory navigation still works."}),e("div",{className:"grid max-h-[220px] min-h-0 gap-1 overflow-auto",children:[et.map(b=>{const F=String(b?.path||"");return e("button",{className:"tcp-list-item text-left",onClick:()=>Ee(F),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(b?.name||F)})]})},`dir-${F}`)}),bt.map(b=>{const F=String(b?.path||"");return e("button",{className:`tcp-list-item text-left ${F===We?"border-amber-400/70":""}`,onClick:()=>ne(F),children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"inline-flex min-w-0 items-center gap-2",children:[e("i",{"data-lucide":"file-up"}),e("span",{className:"truncate",children:String(b?.name||F)})]}),e("span",{className:"tcp-subtle shrink-0 text-[11px]",children:Am(b?.size)})]})},`file-${F}`)}),!et.length&&!bt.length?e(Le,{text:"No files or folders in this workspace location."}):null]})]}),We?e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"File Preview"}),e("div",{className:"flex items-center gap-2",children:[Se?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>re(!0),children:[e("i",{"data-lucide":"fullscreen"}),"Fullscreen"]}):null,e("span",{className:"tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:We})]})]}),Xe.isLoading?e("div",{className:"tcp-subtle text-xs",children:"Loading file..."}):Se?e("div",{className:"max-h-[420px] overflow-auto rounded-lg border border-slate-700/60 bg-black",children:e("iframe",{className:"h-[420px] w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:xt,title:We,scrolling:"yes"})}):te?e("div",{className:"tcp-markdown tcp-markdown-ai max-h-[260px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-950/40 p-3",dangerouslySetInnerHTML:{__html:dn(xt)}}):e("pre",{className:"tcp-code max-h-[260px] overflow-auto whitespace-pre-wrap break-words",children:xt||"No text content."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Executor Verification"})}),kt.length?e("div",{className:"grid max-h-44 gap-2 overflow-auto",children:kt.map(b=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Sa(b.type.includes("failed")?"failed":"running"),children:b.type}),e("span",{className:"tcp-subtle",children:["mode: ",b.mode]})]}),e("div",{className:"font-medium",children:b.title}),e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:b.reason||"No verification detail."}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>X(b.id),children:[e("i",{"data-lucide":"search"}),"View details"]}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(Bs(b)),t("ok","Copied verification feedback.")}catch(F){t("err",F instanceof Error?F.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),b.verification?.execution_trace?e("div",{className:"mt-2 rounded border border-slate-700/50 bg-slate-950/40 p-2 tcp-subtle",children:[e("div",{children:["session:"," ",String(b.verification?.execution_trace?.session_id||"n/a")]}),e("div",{children:["model:"," ",[String(b.verification?.execution_trace?.model?.provider||"").trim(),String(b.verification?.execution_trace?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"]}),e("div",{children:["source:"," ",String(b.verification?.execution_trace?.model?.source||"n/a")]})]}):null]},b.id))}):e("div",{className:"tcp-subtle text-xs",children:"No verification telemetry yet."})]}),e("div",{className:"mt-3 grid gap-3 xl:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Live Activity"}),e("span",{className:"tcp-subtle text-xs",children:Wa(Date.now())})]}),V.length?e("div",{className:"grid max-h-40 gap-2 overflow-auto",children:V.map(b=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Sa(b.type.includes("failed")?"failed":"running"),children:b.type}),e("span",{className:"tcp-subtle",children:Wa(b.at)})]}),e("div",{className:"font-medium",children:b.title}),e("div",{className:"tcp-subtle",children:b.detail||"No additional detail."})]},b.id))}):e("div",{className:"tcp-subtle text-xs",children:"No activity events yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Latest Output"})}),W?e(aa,{children:[e("div",{className:"tcp-code max-h-28 overflow-auto whitespace-pre-wrap break-words",children:ht||"No assistant output text yet."}),e("div",{className:"mt-2 tcp-subtle text-xs",children:"Recent tool calls"}),e("div",{className:"tcp-code mt-1 max-h-24 overflow-auto whitespace-pre-wrap break-words",children:ct.length?ct.join(`
|
|
2458
|
-
`):"No tool call records found in current session yet."})]}):e("div",{className:"tcp-subtle text-xs",children:"No completed step output session yet."})]})]})]}),e("div",{className:"flex h-full min-h-0 w-full flex-col gap-3",children:[e("div",{className:"mb-3",children:[e("div",{className:"text-sm font-semibold",children:"Kanban + Budget"}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Tasks activate after execute"})]}),e("div",{className:"mb-3",children:e(ym,{budget:J})}),e(Ti,{tasks:_,currentTaskId:it.currentTaskId,selectedTaskId:qe,workflowSummaryByTaskId:dt,onTaskSelect:b=>{const F=qe===b.id?"":b.id;se(F),Me(b.id)},onRetryTask:b=>ut.mutate({path:"/api/orchestrator/retry",body:{runId:De,stepId:b.id}})}),qe?e("div",{className:"mt-3 rounded-xl border border-cyan-700/50 bg-cyan-950/20 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Selected Task Workflow Link"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>se(""),children:"Clear task focus"})]}),e("div",{className:"tcp-subtle text-xs",children:["Task ",e("strong",{children:qe})," is filtering workflow runs and event stream."]})]}):null,qe?e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Task Workflow Artifacts"}),e("span",{className:"tcp-subtle text-xs",children:[Pe.length," actions"]})]}),Pe.length?e("div",{className:"grid max-h-56 gap-2 overflow-auto",children:Pe.map(b=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:b.action}),e("span",{className:Sa(b.status),children:b.status})]}),e("div",{className:"tcp-subtle",children:["run: ",b.runId]}),e("div",{className:"tcp-subtle",children:["updated: ",Wa(b.updatedAt)]}),b.detail?e("div",{className:"mt-1 text-rose-200",children:b.detail}):null,b.output?e("pre",{className:"tcp-code mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(b.output,null,2)}):null]},b.id))}):e("div",{className:"tcp-subtle text-xs",children:"No workflow action artifacts are linked to this task yet."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workflow Automation"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>n("packs-detail"),children:"Open Workflow Lab"})]}),e("div",{className:"mb-2 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:"tcp-badge-info",children:Nt||"no workflow id"}),e("span",{className:"tcp-subtle",children:Array.isArray(Bt.data?.workflow?.steps)?`${Bt.data.workflow.steps.length} steps`:"workflow metadata pending"}),e("span",{className:"tcp-subtle",children:Array.isArray(Bt.data?.hooks)?`${Bt.data.hooks.length} hooks`:""})]}),e("div",{className:"grid gap-3 xl:grid-cols-[0.85fr_1.15fr]",children:[e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Runs"}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:Ie.length?Ie.map((b,F)=>{const he=String(b?.run_id||`workflow-run-${F}`).trim(),Fe=he===ce,Ke=String(b?.status||"unknown").trim(),at=ln(b);return e("button",{type:"button",className:`tcp-list-item text-left ${Fe?"border-amber-400/70":""}`,onClick:()=>M(he),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:he}),e("span",{className:Sa(Ke),children:Ke})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger:"," ",String(b?.trigger_event||"manual").trim()||"manual"]}),e("div",{className:"tcp-subtle text-xs",children:["task: ",at||"n/a"]}),e("div",{className:"tcp-subtle text-xs",children:["actions:"," ",Array.isArray(b?.actions)?b.actions.length:0]})]},he)}):e(Le,{text:qe?"No workflow runs are linked to the selected task yet.":"No workflow runs recorded for this orchestration workflow yet."})})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Run Drilldown"}),Ne?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Sa(String(Ne?.status||"unknown")),children:String(Ne?.status||"unknown")}),e("span",{className:"tcp-subtle",children:["trigger: ",String(Ne?.trigger_event||"manual")]}),e("span",{className:"tcp-subtle",children:["source: ",String(Ne?.source_event_id||"n/a")]})]}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:Array.isArray(Ne?.actions)&&Ne.actions.length?Ne.actions.map((b,F)=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:String(b?.action||"unknown action")}),e("span",{className:Sa(String(b?.status||"unknown")),children:String(b?.status||"unknown")})]}),e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-subtle",children:["task:"," ",String(b?.task_id||Ne?.task_id||"n/a")]}),String(b?.task_id||Ne?.task_id||"").trim()?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>se(String(b?.task_id||Ne?.task_id||"").trim()),children:"Focus task"}):null]}),e("div",{className:"tcp-subtle",children:["started: ",Wa(b?.started_at_ms)]}),e("div",{className:"tcp-subtle",children:["finished: ",Wa(b?.finished_at_ms)]}),String(b?.error||"").trim()?e("div",{className:"mt-1 text-rose-200",children:String(b.error)}):null]},`${String(b?.action||"action")}-${F}`)):e("div",{className:"tcp-subtle text-xs",children:"No recorded workflow actions for this run."})})]}):e(Le,{text:"Select a workflow run to inspect its action timeline."})]})]})]}),e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workflow Event Stream"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Clear workflow events","aria-label":"Clear workflow events",onClick:()=>Re([]),children:e("i",{"data-lucide":"trash-2"})})]}),me.length?e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:[...me].filter(b=>{const F=ln(b.data?.properties||{});if(qe&&F&&F!==qe)return!1;if(!ce)return!0;const he=String(b.data?.properties?.runID||"").trim();return!he||he===ce}).reverse().map((b,F)=>{const he=Rm(b.data);return e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Sa(he.endsWith(".failed")?"failed":he.endsWith(".completed")?"completed":"running"),children:he}),e("span",{className:"tcp-subtle",children:Wa(b.at)})]}),e("div",{className:"tcp-subtle",children:["run: ",String(b.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle",children:["action:"," ",String(b.data?.properties?.action||b.data?.properties?.actionID||"-")]})]},`${b.at}-${F}`)})}):e("div",{className:"tcp-subtle text-xs",children:"No workflow events streamed for this run yet."})]}),e(Mt,{children:[j?e($e.div,{className:"tcp-confirm-overlay",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close task details",onClick:()=>Me("")}),e($e.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:s?!1:{opacity:0,y:8,scale:.98},animate:s?void 0:{opacity:1,y:0,scale:1},exit:s?void 0:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Kanban Task Details"}),e("p",{className:"tcp-confirm-message",children:"Full task brief, dependencies, and runtime context for this kanban item."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>Me(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Sa(j.state),children:Im(j.state)}),e("span",{className:"tcp-badge-info",children:j.id}),j.assigned_role?e("span",{className:"tcp-subtle",children:["role: ",j.assigned_role]}):null,j.gate?e("span",{className:"tcp-subtle",children:["gate: ",j.gate]}):null,j.workflow_id?e("span",{className:"tcp-subtle",children:["workflow: ",j.workflow_id]}):null,j.session_id?e("span",{className:"tcp-subtle",children:["session: ",j.session_id]}):null]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Title"}),e("div",{className:"rounded-lg border border-slate-800/80 bg-slate-950/70 px-3 py-2 text-sm text-slate-100",children:j.title||"Untitled task"})]}),j.description?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Description"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:j.description})]}):null,e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Dependencies"}),j.dependencies.length?e("div",{className:"flex flex-wrap gap-2",children:j.dependencies.map(b=>e("span",{className:"rounded border border-slate-700/60 px-2 py-1 text-xs text-slate-200",children:["<-"," ",b]},`${j.id}-${b}`))}):e("div",{className:"tcp-subtle text-sm",children:"No blocking dependencies."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Runtime Context"}),e("div",{className:"grid gap-2 text-sm",children:[e("div",{className:"tcp-subtle",children:["runtime status: ",j.runtime_status||"n/a"]}),e("div",{className:"tcp-subtle",children:["retry count: ",Number(j.retry_count||0)]}),dt?.[j.id]?e("div",{className:"tcp-subtle",children:["workflow runs:"," ",dt[j.id].runs,dt[j.id].failed?`, failed ${dt[j.id].failed}`:""]}):null,j.runtime_detail?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:["detail: ",j.runtime_detail]}):null]})]})]}),String(j.error_message||"").trim()?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Error"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words text-rose-100",children:String(j.error_message||"").trim()})]}):null]}),e("div",{className:"tcp-confirm-actions mt-4",children:[e("button",{className:"tcp-btn",onClick:()=>{se(j.id),Me("")},children:"Focus task"}),e("button",{className:"tcp-btn",onClick:()=>Me(""),children:"Close"})]})]})]}):null,tt?e($e.div,{className:"tcp-confirm-overlay",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close verification details",onClick:()=>X("")}),e($e.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:s?!1:{opacity:0,y:8,scale:.98},animate:s?void 0:{opacity:1,y:0,scale:1},exit:s?void 0:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Executor Verification Details"}),e("p",{className:"tcp-confirm-message",children:"Raw verification and execution trace for debugging task feedback."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>X(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Sa(tt.type.includes("failed")?"failed":"running"),children:tt.type}),e("span",{className:"tcp-badge-info",children:tt.title}),e("span",{className:"tcp-subtle",children:["task: ",tt.taskId||"n/a"]}),e("span",{className:"tcp-subtle",children:["mode: ",tt.mode]}),e("span",{className:"tcp-subtle",children:["time: ",Wa(tt.at)]})]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Feedback"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(Bs(tt)),t("ok","Copied verification feedback.")}catch(b){t("err",b instanceof Error?b.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:tt.reason||"No verification detail."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Verification JSON"}),e("pre",{className:"tcp-code tcp-verification-code whitespace-pre-wrap break-words",children:JSON.stringify(tt.verification||{},null,2)})]})]}),e("div",{className:"tcp-confirm-actions mt-4",children:e("button",{className:"tcp-btn",onClick:()=>X(""),children:"Close"})})]})]}):null]})]})]})})]}),e(Mt,{children:Ve&&We&&Se?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>re(!1),children:e($e.div,{className:"relative h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] overflow-hidden rounded-[1.4rem] border border-slate-700/70 bg-slate-950 shadow-[0_28px_64px_rgba(0,0,0,0.55)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:b=>b.stopPropagation(),children:[e("div",{className:"flex items-center justify-between gap-3 border-b border-slate-800/80 px-5 py-4",children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-lg font-semibold text-slate-100",children:"Fullscreen Preview"}),e("div",{className:"tcp-subtle mt-1 text-xs",style:{overflowWrap:"anywhere"},children:We})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{Xe.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8","aria-label":"Close preview",title:"Close preview",onClick:()=>re(!1),children:e("i",{"data-lucide":"x"})})]})]}),e("div",{className:"h-[calc(100%-4.5rem)] p-3",children:e("div",{className:"h-full overflow-auto rounded-xl border border-slate-700/60 bg-black",children:e("iframe",{className:"h-full w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:xt,title:`${We} fullscreen preview`,scrolling:"yes"})})})]})}):null}),k?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",P||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{R&&G(R)},disabled:!R,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{P&&(O(P),z(!1),ae(""),t("ok",`Workspace selected: ${P}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{z(!1),ae("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:B,onInput:b=>ae(b.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:f.length?f.map(b=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>G(String(b?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(b?.name||b?.path||"")]},String(b?.path||b?.name))):e(Le,{text:o?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}function Mm(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function $m({api:a,toast:t}){const n=na(),[r,s]=w("uploads"),c=Y({queryKey:["files",r],queryFn:()=>a(`/api/files/list?dir=${encodeURIComponent(r)}`).catch(()=>({files:[]})),refetchInterval:12e3}),d=xe({mutationFn:p=>a("/api/files/delete",{method:"POST",body:JSON.stringify({path:p})}),onSuccess:async()=>{t("ok","File removed."),await n.invalidateQueries({queryKey:["files",r]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),u=Mm(c.data,"files");return e("div",{className:"grid gap-4",children:e(Wt,{title:"Files",subtitle:"Browse and delete uploaded files",children:[e("div",{className:"mb-3 flex gap-2",children:[e("input",{className:"tcp-input",value:r,onInput:p=>s(p.target.value),placeholder:"uploads"}),e("button",{className:"tcp-btn",onClick:()=>c.refetch(),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("div",{className:"grid gap-2",children:u.length?u.map((p,N)=>{const E=String(p?.path||p?.name||`file-${N}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{className:"truncate",children:E}),e("span",{className:"tcp-subtle text-xs",children:[String(p?.size||0)," bytes"]})]}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>d.mutate(E),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})})]},E)}):e(Le,{text:"No files found for this directory."})})]})})}function Om(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Em({client:a,toast:t}){const n=na(),[r,s]=w(""),[c,d]=w(null),u=Y({queryKey:["memory",r],queryFn:()=>(r.trim()?a.memory.search({query:r,limit:40}):a.memory.list({q:"",limit:40})).catch(()=>({items:[]})),refetchInterval:15e3}),p=xe({mutationFn:x=>a.memory.delete(x),onSuccess:async()=>{t("ok","Memory record deleted."),await n.invalidateQueries({queryKey:["memory"]})},onError:x=>t("err",x instanceof Error?x.message:String(x))}),N=Om(u.data,"items"),E=K(()=>N.map((x,C)=>{const O=String(x?.id||`mem-${C}`),k=String(x?.text||x?.content||x?.value||""),z=k.length>340?`${k.slice(0,340)}...`:k;return{id:O,text:k,compact:z,html:dn(k)}}),[N]);return e(gn,{className:"grid gap-4",children:e(ot,{title:"Memory",subtitle:"Search recent records and open full entry details inline.",actions:e(aa,{children:[e(we,{tone:"info",children:[E.length," results"]}),r.trim()?e(we,{tone:"ghost",children:["Filter: ",r]}):e(we,{tone:"ghost",children:"Browsing latest memory"})]}),children:[e(ya,{className:"mb-3",children:[e("input",{className:"tcp-input flex-1",value:r,onInput:x=>s(x.target.value),placeholder:"Search memory"}),e("button",{className:"tcp-btn",onClick:()=>u.refetch(),children:[e("i",{"data-lucide":"search"}),"Search"]})]}),e("div",{className:"grid gap-2",children:E.length?E.map(x=>{const C=c===x.id;return e($e.article,{layout:!0,className:`tcp-list-item cursor-pointer ${C?"border-amber-500/60":""}`,onClick:()=>d(C?null:x.id),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{className:"truncate",children:x.id}),e("div",{className:"flex items-center gap-2",children:[e(we,{tone:C?"info":"ghost",children:C?"expanded":"compact"}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:O=>{O.stopPropagation(),p.mutate(x.id)},children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]}),e(Mt,{initial:!1,mode:"wait",children:C?e($e.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.18,ease:"easeOut"},className:"overflow-hidden",children:e("div",{className:"tcp-markdown tcp-markdown-ai rounded-lg border border-slate-700/60 bg-black/20 p-3 text-sm",dangerouslySetInnerHTML:{__html:x.html}})},"expanded"):e($e.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.14,ease:"easeOut"},className:"tcp-subtle whitespace-pre-wrap text-xs",children:x.compact||"(empty)"},"compact")})]},x.id)}):e(Le,{text:"No memory records found."})})]})})}const Ui=[{label:"Every hour",intervalSeconds:3600},{label:"Every morning",cron:"0 9 * * *"},{label:"Every evening",cron:"0 18 * * *"},{label:"Daily at midnight",cron:"0 0 * * *"},{label:"Weekly Monday",cron:"0 9 * * 1"},{label:"Manual only",cron:""}];function Dm(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function jm(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Um(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function Bm(a,t){const n=String(t||"").trim();if(n)return{type:"cron",cron_expression:n,timezone:"UTC"};const r=Ui.find(s=>s.label===a);return r?.intervalSeconds?{type:"interval",interval_seconds:r.intervalSeconds}:r?.cron?{type:"cron",cron_expression:r.cron,timezone:"UTC"}:{type:"manual"}}function Fm(a){const t=String(a?.template_id||a?.templateID||a?.id||"").trim();if(!t)return null;const n=String(a?.display_name||a?.displayName||a?.name||"").trim(),r=String(a?.role||"worker").trim()||"worker",s=a?.default_model||a?.defaultModel||{},c=String(s?.provider_id||s?.providerId||"").trim(),d=String(s?.model_id||s?.modelId||"").trim();return{templateId:t,displayName:n||t,role:r,modelLabel:c&&d?`${c}/${d}`:""}}function Km({client:a,toast:t}){const n=na(),r=qt(null),[s,c]=w("Daily Engineering Standup"),[d,u]=w(""),[p,N]=w("Every morning"),[E,x]=w(""),[C,O]=w("docs/standups/{{date}}.md"),[k,z]=w([]),[A,G]=w(null),B=Y({queryKey:["teams","standup","templates"],queryFn:()=>a?.agentTeams?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:12e3}),ae=Y({queryKey:["teams","standup","health"],queryFn:()=>a?.health?.().catch(()=>({}))??Promise.resolve({}),refetchInterval:3e4});fe(()=>{const q=String(ae.data?.workspaceRoot||ae.data?.workspace_root||"").trim();q&&u(ye=>ye||q)},[ae.data]);const S=K(()=>Dm(B.data,"templates").map(Fm).filter(q=>!!q),[B.data]),I=xe({mutationFn:async()=>{const q=String(s||"").trim(),ye=String(d||"").trim();if(!q)throw new Error("Standup name is required.");const y=jm(ye);if(y)throw new Error(y);if(!k.length)throw new Error("Select at least one participant template.");return await a?.agentTeams?.composeStandup?.({name:q,workspaceRoot:ye,schedule:Bm(p,E),participantTemplateIds:k,reportPathTemplate:String(C||"").trim()||void 0})||null},onSuccess:q=>{G(q?.automation||null)},onError:q=>t("err",q instanceof Error?q.message:String(q))}),H=xe({mutationFn:async()=>{const q=A||(await I.mutateAsync())?.automation;if(!q)throw new Error("Standup compose failed.");return a?.automationsV2?.create?.(q)},onSuccess:async()=>{t("ok","Agent standup automation created."),G(null),await n.invalidateQueries({queryKey:["automations"]})},onError:q=>t("err",q instanceof Error?q.message:String(q))});return fe(()=>{const q=r.current;q&&wa(q)},[s,d,p,E,C,k.join(","),S.length,I.isPending,H.isPending,!!A]),e("div",{ref:r,className:"grid gap-4 rounded-2xl border border-emerald-500/20 bg-emerald-500/5 p-4",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-emerald-300",children:"Agent Standup"}),e("h3",{className:"mt-1 text-lg font-semibold text-white",children:"Build a scheduled standup from saved agents"}),e("p",{className:"mt-1 text-sm text-slate-300",children:"Choose the personalities that should participate, preview the workflow, and create the automation from the same place you manage those agents."})]}),e("span",{className:"tcp-badge-ok",children:"MVP"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"Standup name",value:s,onInput:q=>c(q.target.value)}),e("input",{className:"tcp-input",placeholder:"/absolute/workspace/root",value:d,onInput:q=>u(q.target.value)}),e("select",{className:"tcp-input",value:p,onInput:q=>N(q.target.value),children:Ui.map(q=>e("option",{value:q.label,children:q.label},q.label))}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"Custom cron (optional)",value:E,onInput:q=>x(q.target.value)})]}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"docs/standups/{{date}}.md",value:C,onInput:q=>O(q.target.value)}),e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3 text-sm text-slate-300",children:"The markdown report path controls where the synthesized standup is written. Participant personalities come from the saved agents below."}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Participants"}),S.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:S.map(q=>{const ye=k.includes(q.templateId);return e("button",{type:"button",className:`tcp-list-item text-left transition-all ${ye?"border-emerald-400/60 bg-emerald-400/10":""}`,onClick:()=>z(y=>y.includes(q.templateId)?y.filter(v=>v!==q.templateId):[...y,q.templateId]),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:q.displayName}),e("span",{className:"tcp-badge-info",children:q.role})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:q.templateId}),q.modelLabel?e("div",{className:"mt-2 text-xs text-emerald-200",children:q.modelLabel}):null]},q.templateId)})}):e(Le,{text:"Create at least one saved agent below before composing a standup."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:I.isPending||!S.length,onClick:()=>I.mutate(),children:[e("i",{"data-lucide":"file-search"}),I.isPending?"Composing…":"Preview Standup Workflow"]}),e("button",{type:"button",className:"tcp-btn-primary",disabled:H.isPending||!S.length,onClick:()=>H.mutate(),children:[e("i",{"data-lucide":"rocket"}),H.isPending?"Creating…":"Create Standup Automation"]})]}),A?e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("strong",{children:String(A?.name||"Standup preview")}),e("span",{className:"tcp-badge-info",children:[Array.isArray(A?.flow?.nodes)?A.flow.nodes.length:0," nodes"]})]}),e("div",{className:"grid gap-2 text-xs text-slate-300",children:[e("div",{children:["schedule: ",Um(A?.schedule)]}),e("div",{children:["report:"," ",String(A?.metadata?.standup?.report_path_template||C)]}),e("div",{children:["participants:"," ",String((A?.metadata?.standup?.participant_template_ids||k).join(", "))]})]})]}):null]})}const Fs=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],Lm={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."},Wm=["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."],Hn={templateId:"",displayName:"",avatarUrl:"",role:"worker",systemPrompt:"",modelProvider:"",modelId:""};function Sr(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function zm(a){const t=a?.default_model||a?.defaultModel||{};return{templateId:String(a?.template_id||a?.templateID||a?.id||"").trim(),displayName:String(a?.display_name||a?.displayName||a?.name||"").trim(),avatarUrl:String(a?.avatar_url||a?.avatarUrl||"").trim(),role:String(a?.role||"worker").trim()||"worker",systemPrompt:String(a?.system_prompt||a?.systemPrompt||"").trim(),modelProvider:String(t?.provider_id||t?.providerId||"").trim(),modelId:String(t?.model_id||t?.modelId||"").trim()}}function Jm(a){const t={templateID:a.templateId.trim(),display_name:a.displayName.trim()||void 0,avatar_url:a.avatarUrl.trim()||void 0,role:a.role,system_prompt:a.systemPrompt.trim()||void 0,skills:[],default_budget:{},capabilities:{}};return a.modelProvider.trim()&&a.modelId.trim()&&(t.default_model={provider_id:a.modelProvider.trim(),model_id:a.modelId.trim()}),t}function Ks({client:a,toast:t}){const n=na(),r=a?.agentTeams,s=qt(null),[c,d]=w(Hn),[u,p]=w(null),N=qt(null),E=Y({queryKey:["teams","templates"],queryFn:()=>r?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:8e3}),x=Y({queryKey:["teams","instances"],queryFn:()=>r?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),C=Y({queryKey:["teams","approvals"],queryFn:()=>r?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),O=xe({mutationFn:async()=>{if(!c.templateId.trim())throw new Error("Template ID is required.");return u?r?.updateTemplate?.(u,{display_name:c.displayName.trim()||void 0,avatar_url:c.avatarUrl.trim()||void 0,role:c.role,system_prompt:c.systemPrompt.trim()||void 0,default_model:c.modelProvider.trim()&&c.modelId.trim()?{provider_id:c.modelProvider.trim(),model_id:c.modelId.trim()}:void 0}):r?.createTemplate?.({template:Jm(c)})},onSuccess:async()=>{t("ok",u?"Template updated.":"Template created."),d(Hn),p(null),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),k=xe({mutationFn:y=>r?.deleteTemplate?.(y),onSuccess:async()=>{t("ok","Template deleted."),u&&(p(null),d(Hn)),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),z=xe({mutationFn:({requestId:y,decision:v})=>v==="approve"?r?.approveSpawn?.(y):r?.denySpawn?.(y),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),A=K(()=>Sr(E.data,"templates").map(zm).filter(y=>y.templateId),[E.data]),G=Sr(x.data,"instances"),B=Sr(C.data,"spawnApprovals"),ae=!!(u||c.templateId||c.displayName||c.systemPrompt),S=c.displayName.trim()||c.templateId.trim()||"New Agent",I=S.slice(0,1).toUpperCase()||"A",H=Lm[c.role],q=c.avatarUrl.trim();fe(()=>{const y=s.current;y&&wa(y)},[A.length,G.length,B.length,c.role,c.templateId,c.displayName,c.avatarUrl,c.modelProvider,c.modelId,c.systemPrompt,u,O.isPending,k.isPending,z.isPending]);const ye=y=>{if(!y)return;if(y.size>10*1024*1024){t("err","Avatar image is too large (max 10 MB).");return}const v=new FileReader;v.onload=()=>{const U=typeof v.result=="string"?v.result:"";if(!U){t("err","Failed to read avatar image.");return}d(ue=>({...ue,avatarUrl:U}))},v.onerror=()=>t("err","Failed to read avatar image."),v.readAsDataURL(y)};return e("div",{ref:s,className:"grid gap-4",children:[e(Wt,{title:"Agent Standup",subtitle:"Compose scheduled standups from the same saved agents you manage here",children:e(Km,{client:a,toast:t})}),e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(Wt,{title:"Agents",subtitle:"Create reusable agent personalities, prompts, and default models for automation workflows",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-cyan-300",children:"Reusable Personalities"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses."})]}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"template-id",value:c.templateId,disabled:!!u,onInput:y=>d(v=>({...v,templateId:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Display name",value:c.displayName,onInput:y=>d(v=>({...v,displayName:y.target.value}))}),e("select",{className:"tcp-input",value:c.role,onInput:y=>d(v=>({...v,role:y.target.value})),children:Fs.map(y=>e("option",{value:y,children:y},y))}),e("input",{className:"tcp-input",placeholder:"Avatar URL or upload (optional)",value:c.avatarUrl,onInput:y=>d(v=>({...v,avatarUrl:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model provider (optional)",value:c.modelProvider,onInput:y=>d(v=>({...v,modelProvider:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model ID (optional)",value:c.modelId,onInput:y=>d(v=>({...v,modelId:y.target.value}))})]}),e("div",{className:"grid gap-3 lg:grid-cols-[1.15fr_0.85fr]",children:[e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Prompt Guidance"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Write the lasting perspective for this agent, not a one-off task. Good prompts describe ownership and judgment: frontend lead, backend lead, product ops, incident watcher."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:Wm.map(y=>e("button",{type:"button",className:"tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs",onClick:()=>d(v=>({...v,systemPrompt:y})),children:"Use Example"},y))})]}),e("div",{className:"rounded-[28px] border border-slate-800/80 bg-[radial-gradient(circle_at_top,_rgba(34,211,238,0.18),_transparent_45%),linear-gradient(180deg,rgba(15,23,42,0.9),rgba(2,6,23,0.96))] p-5",children:[e("div",{className:"flex items-start justify-between gap-4",children:[e("div",{className:"flex items-start gap-4",children:[e("div",{className:"flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-lg font-semibold text-cyan-100",children:q?e("img",{src:q,alt:S,className:"h-full w-full object-cover"}):I}),e("div",{className:"min-w-0",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-white",children:S}),e("span",{className:"tcp-badge-info",children:c.role})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:c.templateId.trim()||"template-id"}),e("div",{className:"mt-2 text-sm text-slate-300",children:H})]})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>N.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{type:"button",className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>d(y=>({...y,avatarUrl:""})),children:e("i",{"data-lucide":"trash-2"})})]})]}),e("div",{className:"mt-3 text-xs text-slate-400",children:"Upload an image like Settings Identity preview, or paste a direct avatar URL."}),e("input",{ref:N,type:"file",accept:"image/*",className:"hidden",onChange:y=>{ye(y.target.files?.[0]||null),y.target.value=""}}),e("div",{className:"mt-4 rounded-2xl border border-slate-800/70 bg-black/20 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Personality Preview"}),e("div",{className:"mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-200",children:c.systemPrompt.trim()||"This agent will respond from the persistent personality you define here across workflows and standups."})]}),(c.modelProvider.trim()||c.modelId.trim())&&e("div",{className:"mt-3 text-xs text-cyan-200",children:["Default model: ",c.modelProvider.trim()||"provider","/",c.modelId.trim()||"model"]})]})]}),e("textarea",{className:"tcp-input min-h-[140px]",placeholder:"Persistent system prompt",value:c.systemPrompt,onInput:y=>d(v=>({...v,systemPrompt:y.target.value}))}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:O.isPending,onClick:()=>O.mutate(),children:[e("i",{"data-lucide":"save"}),u?"Update Agent":"Create Agent"]}),ae&&e("button",{type:"button",className:"tcp-btn",onClick:()=>{p(null),d(Hn)},children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Saved Agents"}),e("div",{className:"tcp-subtle text-xs",children:[A.length," saved"]})]}),A.length?A.map(y=>e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[e("strong",{children:y.displayName||y.templateId}),e("span",{className:"tcp-badge-info",children:y.role}),y.modelProvider&&y.modelId?e("span",{className:"tcp-badge-ok",children:[y.modelProvider,"/",y.modelId]}):null]}),e("div",{className:"tcp-subtle text-xs",children:y.templateId}),y.systemPrompt?e("div",{className:"mt-2 line-clamp-4 text-xs text-slate-300",children:y.systemPrompt}):e("div",{className:"mt-2 text-xs text-slate-500",children:"No persistent prompt set yet."})]}),e("div",{className:"flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{p(y.templateId),d({templateId:y.templateId,displayName:y.displayName,avatarUrl:y.avatarUrl,role:Fs.includes(y.role)?y.role:"worker",systemPrompt:y.systemPrompt,modelProvider:y.modelProvider,modelId:y.modelId})},children:[e("i",{"data-lucide":"pencil"}),"Edit"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>k.mutate(y.templateId),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]})},y.templateId)):e(Le,{title:"No agents yet",text:"Create your first saved personality here, then reuse it across automation workflows and standups."})]})]})}),e(Wt,{title:"Team Instances",subtitle:"Running collaborative agent instances",children:e("div",{className:"grid gap-2",children:G.length?G.map((y,v)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(y?.template_id||y?.templateID||y?.instance_id||"Instance")}),e("span",{className:"tcp-badge-info",children:String(y?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs",children:["mission: ",String(y?.mission_id||y?.missionID||"n/a")]})]},String(y?.instance_id||y?.id||v))):e(Le,{text:"No team instances found."})})}),e(Wt,{title:"Spawn Approvals",subtitle:"Pending team approval requests",children:e("div",{className:"grid gap-2",children:B.length?B.map((y,v)=>{const U=String(y?.approval_id||y?.request_id||y?.id||`request-${v}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:String(y?.reason||y?.title||U)}),e("div",{className:"tcp-subtle text-xs",children:U}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>z.mutate({requestId:U,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>z.mutate({requestId:U,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},U)}):e(Le,{text:"No pending approvals."})})})]})]})}function Vn(a){return a?.type||a?.event||"event"}function Ls(a){const t=String(a||"").trim().toLowerCase();return["server.connected","engine.lifecycle.ready","engine.heartbeat","engine.lifecycle.heartbeat"].includes(t)}function Ws(a){return String(a?.type||a?.event||"").trim()==="context.run.stream"&&String(a?.run_id||a?.runId||"").trim().startsWith("workflow-")}function Qm({client:a,toast:t,navigate:n}){const[r,s]=w([]),[c,d]=w(""),[u,p]=w("all"),[N,E]=w(!0),[x,C]=w(null),O=K(()=>!x||!Ws(x.data)?"":String(x.data?.run_id||x.data?.runId||"").trim(),[x]),k=Y({queryKey:["feed","workflow-context-run",O],enabled:!!O,queryFn:()=>zt(`/api/engine/context/runs/${encodeURIComponent(O)}`).catch(()=>({run:null}))}),z=Y({queryKey:["feed","workflow-context-blackboard",O],enabled:!!O,queryFn:()=>zt(`/api/engine/context/runs/${encodeURIComponent(O)}/blackboard`).catch(()=>({blackboard:null}))});en("/api/global/event",S=>{try{const I=JSON.parse(S.data);s(H=>[...H.slice(-299),{at:Date.now(),data:I}])}catch{}},{enabled:!0});const A=K(()=>{const S=new Map;for(const I of r){const H=Vn(I.data);N&&Ls(H)||S.set(H,(S.get(H)||0)+1)}return[...S.entries()].sort((I,H)=>H[1]-I[1])},[r,N]),G=K(()=>{const S=c.trim().toLowerCase();return r.filter(I=>{const H=Vn(I.data);return N&&Ls(H)||u!=="all"&&H!==u?!1:S?`${H} ${JSON.stringify(I.data||{})}`.toLowerCase().includes(S):!0}).slice(-240).reverse()},[r,c,u,N]);async function B(S){try{const I=await zt("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:S,source:{kind:"control_panel_feed",event:"pack.detected"}})});t("ok",`Installed ${I?.installed?.name||"pack"}`)}catch(I){t("err",I instanceof Error?I.message:String(I))}}async function ae(S){try{const I=await zt("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:String(S?.properties?.attachment_id||S?.attachment_id||""),path:String(S?.properties?.path||S?.path||""),connector:String(S?.properties?.connector||S?.connector||"")||void 0,channel_id:String(S?.properties?.channel_id||S?.channel_id||"")||void 0,sender_id:String(S?.properties?.sender_id||S?.sender_id||"")||void 0})});t("ok",`Installed ${I?.installed?.name||"pack"}`)}catch(I){t("err",I instanceof Error?I.message:String(I))}}return e(gn,{className:"grid gap-4",children:[e(ot,{title:"Live feed",subtitle:"Filter events and inspect raw payload details.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e("span",{className:"tcp-badge-info",children:[r.length," buffered"]}),e("span",{className:"tcp-badge tcp-badge-ghost",children:u==="all"?"All event types":u}),e("span",{className:N?"tcp-badge-ok":"tcp-badge-info",children:N?"noise hidden":"noise visible"}),e("button",{className:"tcp-btn",onClick:()=>s([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear feed"]}),e("button",{className:"tcp-btn",onClick:()=>n("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Pack library"]})]}),children:[e(ya,{className:"mb-3",children:[e("input",{className:"tcp-input min-w-[220px] flex-1",value:c,onInput:S=>d(S.target.value),placeholder:"Filter by type or payload"}),e(hr,{active:u==="all",onClick:()=>p("all"),children:[e("i",{"data-lucide":"list"}),"All"]}),e(hr,{active:N,onClick:()=>E(S=>!S),children:[e("i",{"data-lucide":N?"filter":"filter-x"}),N?"Hide noise":"Show noise"]}),A.slice(0,8).map(([S,I])=>e(hr,{active:u===S,onClick:()=>p(S),children:[e("i",{"data-lucide":"activity"}),S," (",I,")"]},S))]}),e("div",{className:"grid max-h-[68vh] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:G.length?G.map((S,I)=>{const H=Vn(S.data),q=String(H).startsWith("pack."),ye=Ws(S.data),y=String(S.data?.properties?.path||S.data?.path||""),v=String(S.data?.properties?.attachment_id||S.data?.attachment_id||"");return e("article",{className:"tcp-list-item cursor-pointer",onClick:()=>C(S),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:H}),e("div",{className:"flex items-center gap-2",children:[ye?e("span",{className:"tcp-badge-warn",children:"workflow context"}):null,e("span",{className:"tcp-badge-info",children:new Date(S.at).toLocaleTimeString()})]})]}),e("p",{className:"tcp-subtle mt-1 text-xs",children:ye?`run: ${String(S.data?.run_id||S.data?.runId||"n/a")}`:`session: ${String(S.data?.sessionID||S.data?.sessionId||"n/a")}`}),ye?e("p",{className:"tcp-subtle mt-1 text-xs",children:["kind: ",String(S.data?.kind||"context_run_event")," · seq:"," ",String(S.data?.seq||"-")]}):null,q?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open pack library"]}),y?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),B(y)},children:[e("i",{"data-lucide":"download"}),"Install from path"]}):null,y&&v?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),ae(S.data)},children:[e("i",{"data-lucide":"paperclip"}),"Install attachment"]}):null]}):null,ye?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),n("orchestrator")},children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:U=>{U.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open workflow lab"]})]}):null]},`${S.at}-${I}`)}):e(Le,{text:"No events have arrived yet."})})]}),e(sr,{open:!!x,onClose:()=>C(null),title:x?Vn(x.data):"Event",children:x?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Captured at"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:new Date(x.at).toLocaleString()})]}),O?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(k.data?.run?.objective||O)}),e("span",{className:"tcp-badge-info",children:String(k.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(z.data?.blackboard?.tasks)?z.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(z.data?.blackboard?.artifacts)?z.data.blackboard.artifacts.length:0]})]}):null,e("pre",{className:"tcp-code",children:Yt(x.data)}),O?e("pre",{className:"tcp-code",children:Yt({run:k.data?.run||null,blackboard:z.data?.blackboard||null})}):null]}):null})]})}function Gm({theme:a}){const t=a?.cssVars?.["--color-background"]||"#000000",n=a?.cssVars?.["--color-surface"]||"#111111",r=a?.cssVars?.["--color-primary"]||"#ffffff",s=a?.cssVars?.["--color-secondary"]||"#ffffff";return e("div",{className:"flex items-center gap-2",children:[e("span",{className:"tcp-theme-swatch",style:{background:t},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:n},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:r},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:s},"aria-hidden":"true"})]})}function Hm({themes:a,themeId:t,onChange:n}){return e("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:a.map(r=>{const s=r.id===t;return e($e.button,{type:"button",layout:!0,onClick:()=>n(r.id),className:`tcp-theme-tile ${s?"active":""}`,whileHover:{y:-2},whileTap:{scale:.985},transition:Ca.spring.gentle,children:[e("div",{className:"tcp-theme-tile-top",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-theme-tile-title",children:r.name}),e("p",{className:"tcp-subtle mt-1 text-xs",children:r.description})]}),e(Gm,{theme:r})]}),e("div",{className:"tcp-theme-preview",children:e("div",{className:"tcp-theme-preview-bg",style:{background:r.cssVars["--color-background"]||"#000"},children:e("div",{className:"tcp-theme-preview-card",style:{background:r.cssVars["--color-surface"]||"#111",borderColor:r.cssVars["--color-border"]||"rgba(255,255,255,0.1)"},children:[e("div",{className:"tcp-theme-preview-line short",style:{background:r.cssVars["--color-text"]||"#fff"}}),e("div",{className:"tcp-theme-preview-line",style:{background:r.cssVars["--color-text-muted"]||"#aaa"}}),e("div",{className:"tcp-theme-preview-pill",style:{background:r.cssVars["--color-primary"]||"#fff"}})]})})}),e(Mt,{initial:!1,children:s?e($e.span,{className:"tcp-theme-active",initial:{opacity:0,scale:.86},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.86},transition:Ca.spring.snappy,children:[e("i",{"data-lucide":"badge-check"}),"Active"]}):null})]},r.id)})})}const Vm=[{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"]}],Ym=["websearch","webfetch","webfetch_html","memory_search","memory_store","memory_list"];function Zr(a){try{return new URL(a)}catch{return null}}function Er(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"mcp-server"}function zs(a){const t=Zr(a);if(!t)return"";const n=String(t.hostname||"").toLowerCase();if(!n)return"";if(n.endsWith("composio.dev"))return"composio";const r=n.split(".").filter(Boolean);if(!r.length)return"";const s=["backend","api","mcp","www"].includes(r[0])&&r[1]||r[0];return Er(s)}function Bi(a){const t=Zr(a);return t?String(t.hostname||"").toLowerCase().endsWith("composio.dev"):!1}function Xm({authMode:a,token:t,customHeader:n,transport:r}){const s=String(t||"").trim();if(!s||a==="none")return{};if(a==="custom"){const d=String(n||"").trim();if(!d)throw new Error("Custom header name is required.");return{[d]:s}}return a==="x-api-key"?{"x-api-key":s}:a==="bearer"?{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}:Bi(r)?{"x-api-key":s}:{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}}function Zm(a,t,n,r){return!String(t||"").trim()||a==="none"?"No auth header will be sent.":a==="custom"?n?`Header preview: ${n}: <token>`:"Set a custom header name.":a==="x-api-key"?"Header preview: x-api-key: <token>":a==="bearer"?"Header preview: Authorization: Bearer <token>":Bi(r)?"Auto mode: selected x-api-key for this endpoint":"Auto mode: using Authorization Bearer token"}function Ir(a,t=""){if(!a||typeof a!="object")return null;const n=a,r=String(n.name||t||"").trim();return r?{name:r,transport:String(n.transport||"").trim(),connected:!!n.connected,enabled:n.enabled!==!1,lastError:String(n.last_error||n.lastError||"").trim(),headers:n.headers&&typeof n.headers=="object"?n.headers:{},toolCache:Array.isArray(n.tool_cache||n.toolCache)?n.tool_cache||n.toolCache:[]}:null}function ep(a){return Array.isArray(a)?a.map(t=>Ir(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):!a||typeof a!="object"?[]:Array.isArray(a.servers)?a.servers.map(t=>Ir(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):Object.entries(a).map(([t,n])=>Ir(n&&typeof n=="object"?n:{transport:String(n||"")},t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name))}function tp(a){return(Array.isArray(a)?a:Array.isArray(a?.tools)?a.tools:[]).map(n=>typeof n=="string"?n:!n||typeof n!="object"?"":String(n.namespaced_name||n.namespacedName||n.id||n.tool_name||n.toolName||"").trim()).filter(Boolean)}function ap(a){const t=a&&typeof a=="object"?a:{},n=Array.isArray(t.servers)?t.servers:[];return{generatedAt:String(t.generated_at||"").trim(),count:Number.isFinite(Number(t.count))?Number(t.count):n.length,servers:n.map(r=>!r||typeof r!="object"?null:{slug:String(r.slug||"").trim(),name:String(r.name||r.slug||"").trim(),description:String(r.description||"").trim(),transportUrl:String(r.transport_url||"").trim(),serverConfigName:String(r.server_config_name||r.slug||"").trim(),documentationUrl:String(r.documentation_url||"").trim(),directoryUrl:String(r.directory_url||"").trim(),toolCount:Number.isFinite(Number(r.tool_count))?Number(r.tool_count):0,requiresAuth:r.requires_auth!==!1,requiresSetup:!!r.requires_setup}).filter(r=>!!r&&!!r.slug&&!!r.transportUrl).sort((r,s)=>r.name.localeCompare(s.name))}}function Cr(a,t){const n=t&&typeof t=="object"?t:{};return{botToken:"",allowedUsers:Array.isArray(n.allowed_users)?n.allowed_users.join(", "):"",mentionOnly:n.mention_only!==!1&&a==="discord"?!0:!!n.mention_only,guildId:String(n.guild_id||"").trim(),channelId:String(n.channel_id||"").trim(),styleProfile:String(n.style_profile||"default").trim()||"default",securityProfile:String(n.security_profile||"operator").trim()||"operator"}}function Js(){return{enabled_tools:[],disabled_tools:[],enabled_mcp_servers:[]}}function mn(a){return Array.from(new Set(a.map(t=>t.trim()).filter(Boolean)))}function Qs(a){const t=a&&typeof a=="object"?a:{};return{enabled_tools:Array.isArray(t.enabled_tools)?mn(t.enabled_tools.map(n=>String(n))):[],disabled_tools:Array.isArray(t.disabled_tools)?mn(t.disabled_tools.map(n=>String(n))):[],enabled_mcp_servers:Array.isArray(t.enabled_mcp_servers)?mn(t.enabled_mcp_servers.map(n=>String(n))):[]}}function np(a,t){return a.disabled_tools.includes(t)?!1:a.enabled_tools.length===0||a.enabled_tools.includes(t)}function rp(a,t,n){const r=a.disabled_tools.filter(c=>c!==t),s=a.enabled_tools.length>0?[...a.enabled_tools]:[];return n?{...a,disabled_tools:r,enabled_tools:s.length>0?mn([...s,t]):[]}:{...a,disabled_tools:mn([...r,t]),enabled_tools:s.length>0?s.filter(c=>c!==t):s}}function sp(a,t,n){const r=a.enabled_mcp_servers.filter(s=>s!==t);return{...a,enabled_mcp_servers:n?mn([...r,t]):r}}function Fi(a,t){return a!=="public_demo"?!0:Ym.includes(t)}function ip(a,t,n){return Fi(n,t)&&np(a,t)}function op(a){const t=String(a||"").split(",").map(n=>n.trim()).filter(Boolean);return t.length?t:["*"]}function lp(a,t){const n=String(a?.catalog_source||"").trim().toLowerCase();return n==="remote"&&t>0?{tone:"ok",text:`${t} models`}:n==="config"&&t>0?{tone:"info",text:"configured models"}:{tone:"warn",text:"manual entry"}}function cp(a,t){const n=String(a?.catalog_message||"").trim();return n||`Default model: ${t||"none"}`}function Gs({client:a,api:t,toast:n,navigate:r,currentRoute:s,identity:c,themes:d,setTheme:u,themeId:p,refreshProviderStatus:N,refreshIdentityStatus:E}){const x=na(),C=qt(null),[O,k]=w({}),[z,A]=w(String(c?.botName||"Tandem")),[G,B]=w(String(c?.botAvatarUrl||"")),[ae,S]=w("Control Center"),[I,H]=w("providers"),[q,ye]=w("auto"),[y,v]=w(""),[U,ue]=w(""),[ee,Oe]=w("10000"),[Ee,We]=w(""),[ne,ce]=w(""),[M,me]=w(!1),[Re,qe]=w(!1),[se,Ue]=w(!1),[Me,ze]=w({}),[X,Ve]=w({}),[re,Ce]=w(!1),[gt,ie]=w(""),[L,st]=w(""),[pt,lt]=w("none"),[Ct,De]=w(""),[$t,yt]=w(""),[Ut,Je]=w(!0),[Ge,nt]=w(""),[ve,_e]=w("manual"),[Ye,le]=w(""),[it,_]=w(!1),[J,be]=w(!1),[je,o]=w(""),[f,R]=w(""),[P,$]=w(""),[Xe,et]=w("auto"),[bt,Ot]=w(""),[Ae,xt]=w(""),[At,te]=w(!0),[Se,h]=w(!1),[j,Q]=w(!0),[W,V]=w(!1),[ge,Be]=w(""),[ht,ct]=w(""),kt=qt(null),tt=async()=>{const l=a?.identity;return l?.get?l.get():t("/api/engine/config/identity",{method:"GET"})},Nt=async l=>{const T=a?.identity;return T?.patch?T.patch(l):t("/api/engine/config/identity",{method:"PATCH",body:JSON.stringify(l)})},Bt=Y({queryKey:["settings","identity","config"],queryFn:()=>tt().catch(()=>({identity:{}}))});fe(()=>{const l=Bt.data?.identity?.bot||{},T=l?.aliases||{},ke=String(l?.canonicalName||l?.canonical_name||c?.botName||"Tandem").trim(),Qe=String(l?.avatarUrl||l?.avatar_url||c?.botAvatarUrl||"").trim(),Rt=String(T?.controlPanel||T?.control_panel||"").trim();A(ke||"Tandem"),B(Qe),S(Rt||"Control Center")},[c?.botAvatarUrl,c?.botName,Bt.data]),fe(()=>{s==="mcp"&&H("mcp"),s==="channels"&&H("channels"),s==="bug-monitor"&&H("bug_monitor")},[s]);const Jt=Y({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[],connected:[]}))}),vt=Y({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({default:"",providers:{}}))}),dt=Y({queryKey:["settings","search","config"],queryFn:()=>t("/api/system/search-settings",{method:"GET"}).catch(()=>null)});fe(()=>{const l=dt.data?.settings||null;l&&(ye(String(l.backend||"auto").trim()||"auto"),v(String(l.tandem_url||"").trim()),ue(String(l.searxng_url||"").trim()),Oe(String(l.timeout_ms||1e4)))},[dt.data]);const Ie=Y({queryKey:["settings","browser","status"],queryFn:()=>t("/api/engine/browser/status",{method:"GET"}).catch(()=>null),refetchInterval:3e4}),[Pe,ha]=w(null),Ne=xe({mutationFn:()=>t("/api/engine/browser/install",{method:"POST"}),onSuccess:async()=>{n("ok","Browser sidecar installed on the engine host."),await Ie.refetch()},onError:l=>n("err",l instanceof Error?l.message:String(l))}),pe=xe({mutationFn:()=>t("/api/engine/browser/smoke-test",{method:"POST",body:JSON.stringify({url:"https://example.com"})}),onSuccess:async l=>{ha(l),n("ok","Browser smoke test passed."),await Ie.refetch()},onError:l=>{ha(null),n("err",l instanceof Error?l.message:String(l))}}),ut=Y({queryKey:["settings","mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:1e4}),He=Y({queryKey:["settings","mcp","tools"],queryFn:()=>a.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),_t=Y({queryKey:["settings","mcp","catalog"],queryFn:()=>t("/api/engine/mcp/catalog",{method:"GET"}).catch(()=>null),refetchInterval:6e4}),Kt=Y({queryKey:["settings","bug-monitor","config"],queryFn:()=>t("/api/engine/config/bug-monitor",{method:"GET"}).catch(()=>({bug_monitor:{}}))}),ia=Y({queryKey:["settings","bug-monitor","status"],queryFn:()=>t("/api/engine/bug-monitor/status",{method:"GET"}).catch(()=>({status:{}})),refetchInterval:1e4}),Et=Y({queryKey:["settings","bug-monitor","drafts"],queryFn:()=>t("/api/engine/bug-monitor/drafts?limit=10",{method:"GET"}).catch(()=>({drafts:[]})),refetchInterval:15e3}),Qt=Y({queryKey:["settings","bug-monitor","incidents"],queryFn:()=>t("/api/engine/bug-monitor/incidents?limit=10",{method:"GET"}).catch(()=>({incidents:[]})),refetchInterval:1e4}),Pt=Y({queryKey:["settings","bug-monitor","posts"],queryFn:()=>t("/api/engine/bug-monitor/posts?limit=10",{method:"GET"}).catch(()=>({posts:[]})),refetchInterval:15e3}),Xt=Y({queryKey:["settings","bug-monitor","workspace-browser",ge],enabled:W&&!!ge,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(ge)}`,{method:"GET"})}),Zt=Y({queryKey:["settings","channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),ua=Y({queryKey:["settings","channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),xa=Y({queryKey:["settings","channels","tool-preferences"],queryFn:async()=>{const l=await Promise.all(["telegram","discord","slack"].map(async T=>[T,Qs(await t(`/api/engine/channels/${T}/tool-preferences`,{method:"GET"}).catch(()=>Js()))]));return Object.fromEntries(l)},refetchInterval:15e3}),b=xe({mutationFn:async({providerId:l,modelId:T})=>a.providers.setDefaults(l,T),onSuccess:async()=>{n("ok","Updated provider defaults."),await Promise.all([x.invalidateQueries({queryKey:["settings","providers"]}),N()])},onError:l=>n("err",l instanceof Error?l.message:String(l))}),F=xe({mutationFn:async()=>t("/api/engine/config/bug-monitor",{method:"PATCH",body:JSON.stringify({bug_monitor:{enabled:it,paused:J,workspace_root:String(je||"").trim()||null,repo:String(f||"").trim()||null,mcp_server:String(P||"").trim()||null,provider_preference:String(Xe||"auto").trim(),model_policy:bt&&Ae?{default_model:{provider_id:bt,model_id:Ae}}:null,auto_create_new_issues:At,require_approval_for_new_issues:Se,auto_comment_on_matched_open_issues:j,label_mode:"reporter_only"}})}),onSuccess:async()=>{n("ok","Bug Monitor settings saved."),await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})])},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),he=xe({mutationFn:async()=>t("/api/engine/capabilities/bindings/refresh-builtins",{method:"POST"}),onSuccess:async()=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]}),x.invalidateQueries({queryKey:["settings","mcp"]})]),n("ok","Capability bindings refreshed from built-ins.")},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),Fe=xe({mutationFn:async({draftId:l,decision:T})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(l)}/${T}`,{method:"POST",body:JSON.stringify({reason:`${T}d from control panel settings`})}),onSuccess:async(l,T)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor draft ${T.decision==="approve"?"approved":"denied"}.`)},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),Ke=xe({mutationFn:async({draftId:l})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(l)}/triage-run`,{method:"POST"}),onSuccess:async l=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",l?.deduped?`Bug Monitor triage run already exists: ${l?.run?.run_id||"unknown"}`:`Bug Monitor triage run created: ${l?.run?.run_id||"unknown"}`)},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),at=xe({mutationFn:async({action:l})=>t(`/api/engine/bug-monitor/${l}`,{method:"POST"}),onSuccess:async(l,T)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor ${T.action==="pause"?"paused":"resumed"}.`)},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),wt=xe({mutationFn:async({incidentId:l})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(l)}/replay`,{method:"POST"}),onSuccess:async l=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",l?.deduped?`Bug Monitor triage run already exists: ${l?.run?.run_id||"unknown"}`:`Bug Monitor replay queued triage: ${l?.run?.run_id||"unknown"}`)},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),Gt=xe({mutationFn:async({draftId:l})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(l)}/publish`,{method:"POST"}),onSuccess:async l=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",l?.action==="comment_issue"?`Bug Monitor commented on issue #${l?.draft?.issue_number||"unknown"}.`:`Bug Monitor published issue #${l?.draft?.issue_number||"unknown"}.`)},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),ra=xe({mutationFn:async({draftId:l})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(l)}/recheck-match`,{method:"POST"}),onSuccess:async l=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`GitHub match result: ${String(l?.action||"rechecked").replaceAll("_"," ")}.`)},onError:l=>{const T=l instanceof Error?l.message:String(l?.detail||l?.error||l);n("err",T)}}),Da=xe({mutationFn:({providerId:l,apiKey:T})=>a.providers.setApiKey(l,T),onSuccess:async()=>{n("ok","API key updated."),await N()},onError:l=>n("err",l instanceof Error?l.message:String(l))}),Tt=xe({mutationFn:async l=>t("/api/system/search-settings",{method:"PATCH",body:JSON.stringify(l)}),onSuccess:async l=>{We(""),ce(""),await x.invalidateQueries({queryKey:["settings","search"]}),n("ok",l?.restart_required?"Search settings saved. Restart tandem-engine to apply them.":"Search settings saved.")},onError:l=>n("err",l instanceof Error?l.message:String(l))}),ka=xe({mutationFn:async()=>{const T=(Bt.data?.identity?.bot||{})?.aliases||{},ke=String(z||"").trim();if(!ke)throw new Error("Bot name is required.");const Qe=String(G||"").trim(),Rt=String(ae||"").trim();return Nt({identity:{bot:{canonical_name:ke,avatar_url:Qe||null,aliases:{...T,control_panel:Rt||void 0}}}})},onSuccess:async()=>{n("ok","Identity updated."),await Promise.all([x.invalidateQueries({queryKey:["settings","identity"]}),E()])},onError:l=>n("err",l instanceof Error?l.message:String(l))}),ja=mt(async()=>Promise.all([x.invalidateQueries({queryKey:["settings","channels"]}),x.invalidateQueries({queryKey:["settings","channels","tool-preferences"]})]),[x]),Na=xe({mutationFn:async({channel:l,payload:T})=>"reset"in T?t(`/api/engine/channels/${l}/tool-preferences`,{method:"PUT",body:JSON.stringify({reset:!0})}):t(`/api/engine/channels/${l}/tool-preferences`,{method:"PUT",body:JSON.stringify(T)}),onSuccess:async(l,T)=>{await x.invalidateQueries({queryKey:["settings","channels","tool-preferences"]}),n("ok",`Saved ${T.channel} channel tool scope.`)},onError:l=>n("err",l instanceof Error?l.message:String(l))}),bn=xe({mutationFn:async l=>{const T=Me[l];if(!T)throw new Error(`No draft found for ${l}.`);const ke={allowed_users:op(T.allowedUsers),mention_only:!!T.mentionOnly,security_profile:String(T.securityProfile||"operator").trim()||"operator"},Qe=String(T.botToken||"").trim();if(Qe&&(ke.bot_token=Qe),l==="telegram"&&(ke.style_profile=String(T.styleProfile||"default").trim()||"default"),l==="discord"&&(ke.guild_id=String(T.guildId||"").trim()),l==="slack"){const Rt=String(T.channelId||"").trim();if(!Rt&&!Zt.data?.slack?.channel_id)throw new Error("Slack channel ID is required.");Rt&&(ke.channel_id=Rt)}return a.channels.put(l,ke)},onSuccess:async(l,T)=>{n("ok",`Saved ${T} channel settings.`),Ve(ke=>({...ke,[T]:null})),ze(ke=>({...ke,[T]:{...ke[T],botToken:""}})),await ja()},onError:l=>n("err",l instanceof Error?l.message:String(l))}),vn=xe({mutationFn:async l=>a.channels.delete(l),onSuccess:async(l,T)=>{n("ok",`Removed ${T} channel settings.`),Ve(ke=>({...ke,[T]:null})),ze(ke=>({...ke,[T]:Cr(T,null)})),await ja()},onError:l=>n("err",l instanceof Error?l.message:String(l))}),yn=xe({mutationFn:async l=>{const T=Me[l],ke={bot_token:String(T?.botToken||"").trim()||void 0};return a.channels.verify(l,ke)},onSuccess:(l,T)=>{Ve(ke=>({...ke,[T]:l})),n("ok",`${T} verification complete.`)},onError:l=>n("err",l instanceof Error?l.message:String(l))}),oa=mt(async()=>x.invalidateQueries({queryKey:["settings","mcp"]}),[x]),la=xe({mutationFn:async({action:l,server:T})=>{if(!T)throw new Error("No MCP server selected.");if(l==="connect")return a.mcp.connect(T.name);if(l==="disconnect")return a.mcp.disconnect(T.name);if(l==="refresh")return a.mcp.refresh(T.name);if(l==="toggle-enabled")return a.mcp.setEnabled(T.name,!T.enabled);if(l==="delete")return t(`/api/engine/mcp/${encodeURIComponent(T.name)}`,{method:"DELETE"});throw new Error(`Unknown action: ${l}`)},onSuccess:async(l,T)=>{await oa(),T.action==="connect"&&n("ok",`Connected ${T.server?.name}.`),T.action==="disconnect"&&n("ok",`Disconnected ${T.server?.name}.`),T.action==="refresh"&&n("ok",`Refreshed ${T.server?.name}.`),T.action==="toggle-enabled"&&n("ok",`${T.server?.enabled?"Disabled":"Enabled"} ${T.server?.name}.`),T.action==="delete"&&n("ok",`Deleted ${T.server?.name}.`)},onError:l=>n("err",l instanceof Error?l.message:String(l))}),an=xe({mutationFn:async()=>{const l=String(L||"").trim(),T=zs(l),ke=Er(gt||T);if(!l)throw new Error("Transport URL is required.");if(!Zr(l)&&!l.startsWith("stdio:"))throw new Error("Transport must be a valid URL or stdio:* transport.");const Qe=Xm({authMode:pt,token:Ct,customHeader:$t,transport:l}),Rt={name:ke,transport:l,enabled:!0};Object.keys(Qe).length&&(Rt.headers=Qe);const ea=String(Ge||"").trim();if(ea&&ea!==ke&&await t(`/api/engine/mcp/${encodeURIComponent(ea)}`,{method:"DELETE"}).catch(()=>null),await a.mcp.add(Rt),Ut&&!(await a.mcp.connect(Rt.name))?.ok)throw new Error(`Added "${Rt.name}" but connect failed.`);return Rt.name},onSuccess:async l=>{await oa(),Ce(!1),ie(""),st(""),lt("none"),De(""),yt(""),Je(!0),nt(""),n("ok",`Saved MCP "${l}".`)},onError:l=>n("err",l instanceof Error?l.message:String(l))}),Bn=l=>{if(!l)return;if(l.size>10*1024*1024){n("err","Avatar image is too large (max 10 MB).");return}const T=new FileReader;T.onload=()=>{const ke=typeof T.result=="string"?T.result:"";if(!ke){n("err","Failed to read avatar image.");return}B(ke)},T.onerror=()=>n("err","Failed to read avatar image."),T.readAsDataURL(l)},Aa=Array.isArray(Jt.data?.all)?Jt.data.all:[],sa=K(()=>ep(ut.data),[ut.data]),Ja=K(()=>tp(He.data),[He.data]),Ua=K(()=>ap(_t.data?.catalog||_t.data||null),[_t.data]),mr=K(()=>new Set(sa.map(l=>l.name.toLowerCase())),[sa]),wn=K(()=>{const l=String(Ye||"").trim().toLowerCase();return Ua.servers.filter(T=>l?T.name.toLowerCase().includes(l)||T.slug.toLowerCase().includes(l)||T.transportUrl.toLowerCase().includes(l):!0).slice(0,36)},[Ua.servers,Ye]),_a=sa.filter(l=>l.connected).length,Te=K(()=>ia.data?.status||{},[ia.data]),Qa=K(()=>Array.isArray(Et.data?.drafts)?Et.data.drafts||[]:[],[Et.data]),nn=K(()=>Array.isArray(Qt.data?.incidents)?Qt.data.incidents||[]:[],[Qt.data]),xn=K(()=>Array.isArray(Pt.data?.posts)?Pt.data.posts||[]:[],[Pt.data]),ga=K(()=>sa.find(l=>l.name.toLowerCase()===String(P||"").trim().toLowerCase())||null,[P,sa]),Ga=K(()=>Aa.find(l=>String(l?.id||"").toLowerCase()===String(bt||"").trim().toLowerCase())||null,[bt,Aa]),Pa=K(()=>{const l=Ga&&typeof Ga=="object"?Ga.models||{}:{};return Object.keys(l).sort((T,ke)=>T.localeCompare(ke))},[Ga]),i=Array.isArray(Ie.data?.blocking_issues)?Ie.data?.blocking_issues||[]:[],m=Array.isArray(Ie.data?.recommendations)?Ie.data?.recommendations||[]:[],D=Array.isArray(Ie.data?.install_hints)?Ie.data?.install_hints||[]:[],Z=["telegram","discord","slack"],de=Z.filter(l=>!!ua.data?.[l]?.connected).length,rt=Array.isArray(Xt.data?.directories)?Xt.data.directories:[],Dt=String(ht||"").trim().toLowerCase(),fa=K(()=>Dt?rt.filter(l=>String(l?.name||l?.path||"").trim().toLowerCase().includes(Dt)):rt,[rt,Dt]),ba=String(Xt.data?.parent||"").trim(),ca=String(Xt.data?.dir||ge||"").trim();fe(()=>{const l=Kt.data?.bug_monitor&&typeof Kt.data?.bug_monitor=="object"?Kt.data.bug_monitor:{};_(!!l.enabled),be(!!l.paused),o(String(l.workspace_root||"").trim()),R(String(l.repo||"").trim()),$(String(l.mcp_server||"").trim()),et(String(l.provider_preference||"auto").trim()||"auto"),Ot(String(l.model_policy?.default_model?.provider_id||"").trim()),xt(String(l.model_policy?.default_model?.model_id||"").trim()),te(l.auto_create_new_issues!==!1),h(!!l.require_approval_for_new_issues),Q(l.auto_comment_on_matched_open_issues!==!1)},[Kt.data]),fe(()=>{const l=Zt.data&&typeof Zt.data=="object"?Zt.data:{};ze(T=>{const ke={...T};for(const Qe of Z)ke[Qe]||(ke[Qe]=Cr(Qe,l[Qe]));return ke})},[Zt.data]);const Ta=(l,T)=>{const ke=String(T||"").trim();ke&&b.mutate({providerId:l,modelId:ke})},Ht=l=>{if(l){_e("manual");const T=l.headers&&typeof l.headers=="object"?l.headers:{},ke=Object.keys(T),Qe=ke.find(ea=>String(ea).toLowerCase()==="authorization"),Rt=ke.find(ea=>String(ea).toLowerCase()==="x-api-key");nt(l.name),ie(l.name),st(l.transport||""),Je(l.connected||!1),Rt?(lt("x-api-key"),yt(""),De(String(T[Rt]||"").trim())):Qe?(lt("bearer"),yt(""),De(String(T[Qe]||"").replace(/^bearer\s+/i,"").trim())):ke.length===1?(lt("custom"),yt(ke[0]),De(String(T[ke[0]]||"").trim())):(lt("none"),yt(""),De(""))}else _e("catalog"),nt(""),ie(""),st(""),lt("none"),yt(""),De(""),Je(!0);Ce(!0)},Ra=async()=>{const l=await t("/api/engine/bug-monitor/debug",{method:"GET"});await navigator.clipboard.writeText(JSON.stringify(l,null,2)),n("ok","Bug Monitor debug payload copied.")},rn=[{id:"providers",label:"Providers",icon:"cpu"},{id:"search",label:"Web Search",icon:"globe"},{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"}],pr=K(()=>Zm(pt,Ct,$t,L),[pt,$t,Ct,L]);return fe(()=>{const l=C.current;l?wa(l):wa()},[I,it,J,je,P,Te.readiness?.runtime_ready,Te.runtime?.monitoring_active,Te.runtime?.paused,Te.runtime?.pending_incidents,Te.pending_drafts,Qa.length,nn.length,he.isPending,at.isPending,Fe.isPending,wt.isPending,Ke.isPending,F.isPending,la.isPending,Tt.isPending]),e(gn,{className:"grid gap-4",children:e("div",{ref:C,className:"grid gap-4",children:[e("div",{className:"tcp-settings-tabs",children:rn.map(l=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${I===l.id?"active":""}`,onClick:()=>H(l.id),children:[e("i",{"data-lucide":l.icon}),l.label]},l.id))}),e(Rn,{main:e(uc,{className:"grid gap-4",children:[I==="providers"?e(ot,{title:"Provider defaults",subtitle:"Provider catalog, model selection, and API key entry.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(we,{tone:String(vt.data?.default||"").trim()?"ok":"warn",children:["Default: ",String(vt.data?.default||"none")]}),e(we,{tone:"info",children:[String(Jt.data?.connected?.length||0)," connected"]}),e("button",{className:"tcp-btn",onClick:()=>N().then(()=>n("ok","Provider status refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh provider"]})]}),children:e("div",{className:"grid gap-3",children:[e("button",{type:"button",className:"tcp-list-item text-left",onClick:()=>Ue(l=>!l),"aria-expanded":se,children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":se?"chevron-down":"chevron-right"}),e("span",{children:se?"Hide provider catalog":"Show provider catalog"})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Aa.length," providers available for configuration. Expand to change models and API keys."]})]}),e(we,{tone:"info",children:[String(Jt.data?.connected?.length||0)," connected"]})]})}),e(Mt,{initial:!1,children:se?e($e.div,{className:"grid gap-3",initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:Aa.length?Aa.map(l=>{const T=String(l?.id||""),ke=Object.keys(l?.models||{}),Qe=String(vt.data?.providers?.[T]?.default_model||ke[0]||""),Rt=String(O[T]??Qe).trim(),ea=Rt.toLowerCase(),qa=ke.filter(ta=>ea?ta.toLowerCase().includes(ea):!0).slice(0,80),Fn=lp(l,ke.length),St=cp(l,Qe),It=oi[T]||null,Ha=String(It?.keyUrl||"").trim();return e($e.details,{layout:!0,className:"tcp-list-item",children:[e("summary",{className:"cursor-pointer list-none",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium",children:T}),e("div",{className:"tcp-subtle text-xs",children:St})]}),e(we,{tone:Fn.tone,children:Fn.text})]})}),e("div",{className:"mt-3 grid gap-3",children:[Ha?e("div",{className:"flex justify-end",children:e("a",{className:"tcp-btn h-8 px-3 text-xs",href:Ha,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Get API key"]})}):null,e("form",{className:"grid gap-2",onSubmit:ta=>{ta.preventDefault(),Ta(T,Rt)},children:[e("div",{className:"flex gap-2",children:[e("input",{className:"tcp-input",value:Rt,placeholder:`Type model id for ${T}`,onInput:ta=>k(Ba=>({...Ba,[T]:ta.target.value}))}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"badge-check"}),"Apply"]})]}),e("div",{className:"max-h-48 overflow-auto rounded-xl border border-slate-700/60 bg-slate-900/20 p-1",children:qa.length?qa.map(ta=>e("button",{type:"button",className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${ta===Qe?"bg-slate-700/40":""}`,onClick:()=>{k(Ba=>({...Ba,[T]:ta})),Ta(T,ta)},children:ta},ta)):e("div",{className:"tcp-subtle px-2 py-1 text-xs",children:ke.length?"No matching models.":"No live catalog available. Type a model ID manually."})})]}),e("form",{onSubmit:ta=>{ta.preventDefault();const Ba=ta.currentTarget.elements.namedItem("apiKey"),ts=String(Ba?.value||"").trim();ts&&(Da.mutate({providerId:T,apiKey:ts}),Ba.value="")},className:"flex gap-2",children:[e("input",{name:"apiKey",className:"tcp-input",placeholder:String(It?.placeholder||`Set ${T} API key`)}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"save"}),"Save"]})]})]})]},T)}):e(Le,{text:"No providers were detected from the engine catalog."})}):null})]})}):null,I==="search"?e(ot,{title:"Web Search",subtitle:"Configure the engine's `websearch` backend and provider keys.",actions:e(ya,{children:[e(we,{tone:dt.data?.settings?.has_brave_key?"ok":"warn",children:["Brave"," ",dt.data?.settings?.has_brave_key?"configured":"missing"]}),e(we,{tone:dt.data?.settings?.has_exa_key?"ok":"warn",children:["Exa"," ",dt.data?.settings?.has_exa_key?"configured":"missing"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Tt.mutate({backend:q,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(ee||"10000",10),brave_api_key:Ee.trim()||void 0,exa_api_key:ne.trim()||void 0}),disabled:!dt.data?.available||Tt.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:dt.data?.available?e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4 text-sm",children:[e("div",{className:"font-medium",children:"Engine env file"}),e("div",{className:"tcp-subtle mt-1 break-all",children:dt.data?.managed_env_path||"/etc/tandem/engine.env"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:dt.data?.restart_hint||"Restart tandem-engine after saving search settings."})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Backend"}),e("select",{className:"tcp-select",value:q,onChange:l=>ye(l.target.value),children:[e("option",{value:"auto",children:"Auto failover"}),e("option",{value:"brave",children:"Brave Search"}),e("option",{value:"exa",children:"Exa"}),e("option",{value:"searxng",children:"SearxNG"}),e("option",{value:"tandem",children:"Tandem hosted search"}),e("option",{value:"none",children:"Disable websearch"})]})]}),e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Timeout (ms)"}),e("input",{className:"tcp-input",type:"number",min:1e3,max:12e4,value:ee,onInput:l=>Oe(l.target.value)})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Tandem search URL"}),e("input",{className:"tcp-input",placeholder:"https://search.tandem.frumu.ai",value:y,onInput:l=>v(l.target.value)})]}),e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"SearxNG URL"}),e("input",{className:"tcp-input",placeholder:"http://127.0.0.1:8080",value:U,onInput:l=>ue(l.target.value)})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Brave Search key"}),e(we,{tone:dt.data?.settings?.has_brave_key?"ok":"warn",children:dt.data?.settings?.has_brave_key?"Saved":"Missing"})]}),e("input",{className:"tcp-input",type:"password",placeholder:"Paste Brave Search key",value:Ee,onInput:l=>We(l.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Tt.mutate({backend:q,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(ee||"10000",10),brave_api_key:Ee.trim()||void 0}),disabled:!Ee.trim()||Tt.isPending,children:"Save Brave Key"}),dt.data?.settings?.has_brave_key?e("button",{className:"tcp-btn",onClick:()=>Tt.mutate({backend:q,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(ee||"10000",10),clear_brave_key:!0}),disabled:Tt.isPending,children:"Remove"}):null]})]}),e("div",{className:"grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Exa key"}),e(we,{tone:dt.data?.settings?.has_exa_key?"ok":"warn",children:dt.data?.settings?.has_exa_key?"Saved":"Missing"})]}),e("input",{className:"tcp-input",type:"password",placeholder:"Paste Exa API key",value:ne,onInput:l=>ce(l.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Tt.mutate({backend:q,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(ee||"10000",10),exa_api_key:ne.trim()||void 0}),disabled:!ne.trim()||Tt.isPending,children:"Save Exa Key"}),dt.data?.settings?.has_exa_key?e("button",{className:"tcp-btn",onClick:()=>Tt.mutate({backend:q,tandem_url:y,searxng_url:U,timeout_ms:Number.parseInt(ee||"10000",10),clear_exa_key:!0}),disabled:Tt.isPending,children:"Remove"}):null]})]})]}),e("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."})]}):e(Le,{text:dt.data?.reason||"Search settings are only editable here when the panel points at a local engine host."})}):null,I==="identity"?e(ot,{title:"Identity preview",subtitle:"Live preview of how the assistant appears across the panel.",actions:e(ya,{children:[e("button",{className:"tcp-btn",onClick:()=>E().then(()=>n("ok","Identity refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh identity"]}),e("button",{className:"tcp-btn-primary",onClick:()=>ka.mutate(),disabled:ka.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"inline-flex items-center gap-3",children:[e("span",{className:"tcp-brand-avatar inline-grid h-12 w-12 rounded-xl",children:G?e("img",{src:G,alt:z||"Bot",className:"block h-full w-full object-cover"}):e("i",{"data-lucide":"cpu"})}),e("div",{children:[e("div",{className:"font-semibold",children:z||"Tandem"}),e("div",{className:"tcp-subtle text-xs",children:ae||"Control Center"})]})]}),e(ya,{children:[e("button",{className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>kt.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>B(""),children:e("i",{"data-lucide":"trash-2"})})]})]})}),e("input",{className:"tcp-input",value:z,onInput:l=>A(l.target.value),placeholder:"Bot name"}),e("input",{className:"tcp-input",value:ae,onInput:l=>S(l.target.value),placeholder:"Control panel alias"}),e("input",{className:"tcp-input",value:G,onInput:l=>B(l.target.value),placeholder:"Avatar URL or data URL"}),e("input",{ref:kt,type:"file",accept:"image/*",className:"hidden",onChange:l=>Bn(l.target.files?.[0]||null)})]})}):null,I==="theme"?e(ot,{title:"Theme studio",subtitle:"Preview tiles with richer feedback and immediate switching.",children:e(Hm,{themes:d,themeId:p,onChange:u})}):null,I==="channels"?e(ot,{title:"Channel connections",subtitle:"Telegram, Discord, and Slack delivery setup and live listener status.",actions:e(ya,{children:[e(we,{tone:de?"ok":"warn",children:[de,"/",Z.length," connected"]}),e("button",{className:"tcp-btn",onClick:()=>{ja()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh channels"]})]}),children:e("div",{className:"grid gap-3",children:Z.map(l=>{const T=Zt.data?.[l]||{},ke=ua.data?.[l]||{},Qe=Me[l]||Cr(l,T),Rt=X[l],ea=Qs(xa.data?.[l]||Js()),qa=Qe.securityProfile==="public_demo",Fn=!!T?.has_token||!!(Array.isArray(T?.allowed_users)&&T.allowed_users.length)||!!String(T?.guild_id||"").trim()||!!String(T?.channel_id||"").trim();return e("div",{className:"tcp-list-item grid gap-3",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-semibold capitalize",children:l}),e("div",{className:"tcp-subtle text-xs",children:l==="telegram"?"Bot token, allowed users, and style profile.":l==="discord"?"Bot token, allowed users, mention policy, and guild targeting.":"Bot token, allowed users, mention policy, and default channel."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(we,{tone:ke.connected?"ok":"warn",children:ke.connected?"Connected":ke.enabled?"Configured":"Disconnected"}),e(we,{tone:T.has_token?"info":"warn",children:T.has_token?"Token saved":"No token"})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",type:"password",placeholder:T.has_token?String(T.token_masked||"********"):`Paste ${l} bot token`,value:Qe.botToken,onInput:St=>ze(It=>({...It,[l]:{...Qe,botToken:St.target.value}}))}),T.has_token&&!Qe.botToken?e("div",{className:"tcp-subtle text-xs",children:"Token is already stored. Enter a new token only if you want to replace it."}):null,e("input",{className:"tcp-input",placeholder:"Allowed users (comma separated)",value:Qe.allowedUsers,onInput:St=>ze(It=>({...It,[l]:{...Qe,allowedUsers:St.target.value}}))})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("select",{className:"tcp-input",value:Qe.securityProfile,onInput:St=>ze(It=>({...It,[l]:{...Qe,securityProfile:St.target.value}})),children:[e("option",{value:"operator",children:"Operator"}),e("option",{value:"trusted_team",children:"Trusted team"}),e("option",{value:"public_demo",children:"Public demo"})]}),l==="telegram"?e("input",{className:"tcp-input",placeholder:"Style profile",value:Qe.styleProfile,onInput:St=>ze(It=>({...It,[l]:{...Qe,styleProfile:St.target.value}}))}):null,l==="discord"?e("input",{className:"tcp-input",placeholder:"Guild ID (optional)",value:Qe.guildId,onInput:St=>ze(It=>({...It,[l]:{...Qe,guildId:St.target.value}}))}):null,l==="slack"?e("input",{className:"tcp-input",placeholder:"Default channel ID",value:Qe.channelId,onInput:St=>ze(It=>({...It,[l]:{...Qe,channelId:St.target.value}}))}):null,e("label",{className:"inline-flex items-center gap-2 rounded-xl border border-slate-700/60 bg-slate-900/20 px-3 py-2 text-sm",children:[e("input",{type:"checkbox",checked:Qe.mentionOnly,onChange:St=>ze(It=>({...It,[l]:{...Qe,mentionOnly:St.target.checked}}))}),"Mention only"]})]}),Qe.securityProfile==="public_demo"?e("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,e("div",{className:"tcp-subtle text-xs",children:["Active sessions: ",Number(ke.active_sessions||0),ke.last_error?` · Last error: ${ke.last_error}`:""]}),Rt?.hints?.length?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3 text-xs",children:[e("div",{className:"mb-1 font-medium",children:"Verification hints"}),e("div",{className:"grid gap-1",children:Rt.hints.map((St,It)=>e("div",{className:"tcp-subtle",children:St},`${l}-hint-${It}`))})]}):null,e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-3 flex flex-wrap items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium",children:"Channel tool scope"}),e("div",{className:"tcp-subtle text-xs",children:["Built-in tools and MCP servers available to ",l," sessions."]}),ea.enabled_tools.length>0?e("div",{className:"mt-1 text-xs text-amber-300",children:"Explicit built-in allowlist is active for this channel."}):null,qa?e("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]}),e("button",{className:"tcp-btn",disabled:Na.isPending,onClick:()=>Na.mutate({channel:l,payload:{reset:!0}}),children:"Reset scope"})]}),e("div",{className:"grid gap-3",children:[Vm.map(St=>e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-[11px] uppercase tracking-[0.24em]",children:St.label}),e("div",{className:"grid gap-2 md:grid-cols-2",children:St.tools.map(It=>{const Ha=Fi(Qe.securityProfile,It),ta=ip(ea,It,Qe.securityProfile);return e("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:[e("div",{className:"flex flex-col",children:[e("span",{className:"font-mono text-xs",children:It}),Ha?null:e("span",{className:"tcp-subtle text-[11px]",children:"Disabled by security profile"})]}),e("input",{type:"checkbox",checked:ta,disabled:Na.isPending||!Ha,onChange:Ba=>Na.mutate({channel:l,payload:rp(ea,It,Ba.currentTarget.checked)})})]},`${l}-${It}`)})})]},`${l}-${St.label}`)),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-[11px] uppercase tracking-[0.24em]",children:"MCP servers"}),sa.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:sa.map(St=>{const It=!qa&&ea.enabled_mcp_servers.includes(St.name);return e("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:[e("div",{className:"flex flex-col",children:[e("span",{className:"font-mono text-xs",children:St.name}),qa?e("span",{className:"tcp-subtle text-[11px]",children:"Disabled by security profile"}):null]}),e("input",{type:"checkbox",checked:It,disabled:Na.isPending||qa,onChange:Ha=>Na.mutate({channel:l,payload:sp(ea,St.name,Ha.currentTarget.checked)})})]},`${l}-mcp-${St.name}`)})}):e("div",{className:"tcp-subtle text-xs",children:qa?"MCP servers stay disabled in public demo mode.":"No MCP servers configured yet."})]})]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:bn.isPending,onClick:()=>bn.mutate(l),children:[e("i",{"data-lucide":"save"}),"Save"]}),l==="discord"?e("button",{className:"tcp-btn",disabled:yn.isPending,onClick:()=>yn.mutate("discord"),children:[e("i",{"data-lucide":"shield-check"}),"Verify"]}):null,e("button",{className:"tcp-btn-danger",disabled:vn.isPending||!Fn,onClick:()=>vn.mutate(l),children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},l)})})}):null,I==="mcp"?e(ot,{title:"MCP connections",subtitle:"Configured MCP servers, connection state, and discovered tool coverage.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(we,{tone:_a?"ok":"warn",children:[_a,"/",sa.length," connected"]}),e(we,{tone:"info",children:[Ja.length," tools"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Ht(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]}),e("button",{className:"tcp-btn",onClick:()=>{oa()},children:[e("i",{"data-lucide":"refresh-cw"}),"Reload"]})]}),children:e("div",{className:"grid gap-3",children:[sa.length?sa.map(l=>{const T=Object.keys(l.headers||{}).filter(Boolean),ke=Array.isArray(l.toolCache)?l.toolCache.length:0;return e("div",{className:"tcp-list-item grid gap-2",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:l.name}),e("div",{className:"tcp-subtle text-sm",children:l.transport||"No transport set"})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(we,{tone:l.connected?"ok":"warn",children:l.connected?"Connected":"Disconnected"}),e(we,{tone:l.enabled?"info":"warn",children:l.enabled?"Enabled":"Disabled"}),e(we,{tone:"info",children:[ke," tools"]})]})]}),l.lastError?e("div",{className:"rounded-xl border border-rose-700/60 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:l.lastError}):null,e("div",{className:"tcp-subtle text-xs",children:T.length?`Auth headers: ${T.join(", ")}`:"No stored auth headers."}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Ht(l),children:"Edit"}),e("button",{className:"tcp-btn",disabled:la.isPending,onClick:()=>la.mutate({action:l.connected?"disconnect":"connect",server:l}),children:l.connected?"Disconnect":"Connect"}),e("button",{className:"tcp-btn",disabled:la.isPending,onClick:()=>la.mutate({action:"refresh",server:l}),children:"Refresh"}),e("button",{className:"tcp-btn",disabled:la.isPending,onClick:()=>la.mutate({action:"toggle-enabled",server:l}),children:l.enabled?"Disable":"Enable"}),e("button",{className:"tcp-btn-danger",disabled:la.isPending,onClick:()=>la.mutate({action:"delete",server:l}),children:"Delete"})]})]},l.name)}):e("div",{className:"grid gap-3",children:[e(Le,{text:"No MCP servers configured."}),e("div",{className:"flex justify-start",children:e("button",{className:"tcp-btn-primary",onClick:()=>Ht(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]})})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Discovered tools"}),e("pre",{className:"tcp-code max-h-56 overflow-auto whitespace-pre-wrap break-words",children:Ja.length?Ja.slice(0,250).join(`
|
|
2459
|
-
`):"No MCP tools discovered yet. Connect a server first."})]})]})}):null,I==="bug_monitor"?e(ot,{title:"Bug monitor",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(we,{tone:Te.runtime?.monitoring_active?Te.readiness?.publish_ready?"ok":"info":Te.readiness?.ingest_ready?"info":"warn",children:Te.runtime?.monitoring_active?Te.readiness?.publish_ready?"Monitoring":"Watching locally":Te.readiness?.ingest_ready?"Ready":"Not ready"}),J||Te.runtime?.paused?e(we,{tone:"warn",children:"Paused"}):null,e(we,{tone:"info",children:[Number(Te.runtime?.pending_incidents||0)," incidents"]}),e(we,{tone:"info",children:[Number(Te.pending_drafts||0)," pending drafts"]}),e(we,{tone:"info",children:[Number(Te.pending_posts||0)," post attempts"]}),e("button",{className:"tcp-icon-btn",title:"Reload status","aria-label":"Reload status",onClick:()=>Promise.all([ia.refetch(),Et.refetch(),Qt.refetch(),Pt.refetch()]).then(()=>n("ok","Bug Monitor status refreshed.")),children:e("i",{"data-lucide":"refresh-cw"})}),e("button",{className:"tcp-icon-btn",title:J||Te.runtime?.paused?"Resume monitoring":"Pause monitoring","aria-label":J||Te.runtime?.paused?"Resume monitoring":"Pause monitoring",disabled:at.isPending,onClick:()=>at.mutate({action:J||Te.runtime?.paused?"resume":"pause"}),children:e("i",{"data-lucide":J||Te.runtime?.paused?"play":"pause"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:he.isPending,onClick:()=>he.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Ra()},children:e("i",{"data-lucide":"copy"})}),e("button",{className:"tcp-icon-btn",title:"Open GitHub MCP guide","aria-label":"Open GitHub MCP guide",onClick:()=>qe(!0),children:e("i",{"data-lucide":"book-open"})})]}),children:e("div",{className:"grid gap-4",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Reporter state"}),e("button",{type:"button",className:`tcp-list-item text-left ${it?"ring-1 ring-emerald-400/40":""}`,onClick:()=>_(l=>!l),children:[e("div",{className:"font-medium",children:it?J?"Paused":"Enabled":"Disabled"}),e("div",{className:"tcp-subtle text-xs",children:it?J?"Monitoring is paused. Resume to process new failures.":"Failure events can be analyzed once readiness is green.":"No reporter work will execute."})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Local directory"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn",type:"button",onClick:()=>{const l=String(je||"/").trim();Be(l||"/"),ct(""),V(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,value:je,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>o(""),disabled:!je,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),e("div",{className:"tcp-subtle text-xs",children:je?`Reporter analysis root: ${je}`:"Defaults to the engine workspace root if not set."})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Target repo"}),e("input",{className:"tcp-input",value:f,onChange:l=>R(l.target.value),placeholder:"owner/repo"})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"MCP server"}),e("select",{className:"tcp-input",value:P,onChange:l=>$(l.target.value),children:[e("option",{value:"",children:"Select an MCP server"}),sa.map(l=>e("option",{value:l.name,children:l.name},l.name))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider preference"}),e("select",{className:"tcp-input",value:Xe,onChange:l=>et(l.target.value),children:[e("option",{value:"auto",children:"Auto"}),e("option",{value:"official_github",children:"Official GitHub"}),e("option",{value:"composio",children:"Composio"}),e("option",{value:"arcade",children:"Arcade"})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider"}),e("select",{className:"tcp-input",value:bt,onChange:l=>{const T=l.target.value;Ot(T),xt("")},children:[e("option",{value:"",children:"Select a provider"}),Aa.map(l=>e("option",{value:String(l?.id||""),children:String(l?.id||"")},String(l?.id||"")))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Model"}),e("input",{className:"tcp-input",value:Ae,onChange:l=>xt(l.target.value),list:"bug-monitor-models",disabled:!bt,placeholder:bt?"Type or paste a model id":"Choose a provider first",spellCheck:!1}),e("datalist",{id:"bug-monitor-models",children:Pa.map(l=>e("option",{value:l},l))}),e("div",{className:"tcp-subtle text-xs",children:bt?Pa.length?`${Pa.length} suggested models from provider catalog`:"No provider catalog models available. Manual model ids are allowed.":"Select a provider to load model suggestions."})]}),e("div",{className:"grid gap-2 md:col-span-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"GitHub posting"}),e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("button",{type:"button",className:`tcp-list-item text-left ${At&&!Se?"ring-1 ring-emerald-400/40":""}`,onClick:()=>{te(l=>!l),Se&&At&&h(!1)},children:[e("div",{className:"font-medium",children:"Auto-create new issues"}),e("div",{className:"tcp-subtle text-xs",children:At?"New drafts post to GitHub automatically.":"New drafts stay internal until published manually."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${Se?"ring-1 ring-amber-400/40":""}`,onClick:()=>{h(l=>{const T=!l;return T&&te(!1),T})},children:[e("div",{className:"font-medium",children:"Require approval"}),e("div",{className:"tcp-subtle text-xs",children:Se?"New drafts wait for a manual publish click.":"Approval gate disabled."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${j?"ring-1 ring-sky-400/40":""}`,onClick:()=>Q(l=>!l),children:[e("div",{className:"font-medium",children:"Auto-comment matches"}),e("div",{className:"tcp-subtle text-xs",children:j?"Open matching GitHub issues receive new evidence comments.":"Matching issues are detected but not updated automatically."})]})]})]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:F.isPending,title:"Save Bug Monitor settings","aria-label":"Save Bug Monitor settings",onClick:()=>F.mutate(),children:[e("i",{"data-lucide":"save"}),F.isPending?"Saving...":null]}),e("button",{className:"tcp-icon-btn",title:"Add MCP server","aria-label":"Add MCP server",onClick:()=>Ht(),children:e("i",{"data-lucide":"plus"})}),e("button",{className:"tcp-icon-btn",title:"Open setup guide","aria-label":"Open setup guide",onClick:()=>qe(!0),children:e("i",{"data-lucide":"external-link"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:he.isPending,onClick:()=>he.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{Ra()},children:e("i",{"data-lucide":"copy"})}),ga?e("button",{className:"tcp-icon-btn",title:ga.connected?"Refresh selected MCP":"Connect selected MCP","aria-label":ga.connected?"Refresh selected MCP":"Connect selected MCP",disabled:la.isPending,onClick:()=>la.mutate({action:ga.connected?"refresh":"connect",server:ga}),children:e("i",{"data-lucide":ga.connected?"refresh-cw":"plug-zap"})}):null]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Readiness"}),e("div",{className:"mt-1 text-sm",children:Te.runtime?.monitoring_active?Te.readiness?.publish_ready?"Monitoring":"Watching locally":Te.runtime?.paused||J?"Paused":Te.readiness?.ingest_ready?"Ready":"Blocked"}),e("div",{className:"tcp-subtle text-xs",children:Te.runtime?.last_runtime_error||Te.last_error||"No blocking issue reported."}),!Te.readiness?.publish_ready&&Array.isArray(Te.missing_required_capabilities)&&Te.missing_required_capabilities.length?e("div",{className:"tcp-subtle mt-2 text-xs",children:["Missing: ",Te.missing_required_capabilities.join(", ")]}):null]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Selected MCP"}),e("div",{className:"mt-1 text-sm",children:ga?.name||"None selected"}),e("div",{className:"tcp-subtle text-xs",children:ga?ga.connected?"Connected":"Disconnected":"No server selected"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Bindings: ",Te.binding_source_version||"unknown version",Te.bindings_last_merged_at_ms?` · merged ${new Date(Te.bindings_last_merged_at_ms).toLocaleString()}`:""]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Local directory:"," ",je||String(Te.config?.workspace_root||"").trim()||"engine workspace root"]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last event:"," ",String(Te.runtime?.last_incident_event_type||"").trim()||"No incidents processed yet"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Model route"}),e("div",{className:"mt-1 break-all text-sm",children:Te.selected_model?.provider_id&&Te.selected_model?.model_id?`${Te.selected_model.provider_id} / ${Te.selected_model.model_id}`:"No dedicated model selected"}),e("div",{className:"tcp-subtle text-xs",children:Te.readiness?.selected_model_ready?"Available":"Fail-closed when unavailable"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last processed:"," ",Te.runtime?.last_processed_at_ms?new Date(Number(Te.runtime.last_processed_at_ms)).toLocaleString():"Not processed yet"]})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Capability readiness"}),e("div",{className:"tcp-subtle mt-2 grid gap-1 text-xs",children:[e("div",{children:["github.list_issues:"," ",Te.required_capabilities?.github_list_issues?"ready":"missing"]}),e("div",{children:["github.get_issue:"," ",Te.required_capabilities?.github_get_issue?"ready":"missing"]}),e("div",{children:["github.create_issue:"," ",Te.required_capabilities?.github_create_issue?"ready":"missing"]}),e("div",{children:["github.comment_on_issue:"," ",Te.required_capabilities?.github_comment_on_issue?"ready":"missing"]})]}),Array.isArray(Te.resolved_capabilities)&&Te.resolved_capabilities.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:Te.resolved_capabilities.map((l,T)=>e("div",{children:[String(l.capability_id||"unknown"),":"," ",String(l.tool_name||"unresolved")]},`${l.capability_id||"cap"}-${T}`))}):null,Array.isArray(Te.selected_server_binding_candidates)&&Te.selected_server_binding_candidates.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:Te.selected_server_binding_candidates.map((l,T)=>e("div",{children:[String(l.capability_id||"unknown"),":"," ",String(l.binding_tool_name||"unknown"),l.matched?" · matched":" · candidate"]},`${l.capability_id||"candidate"}-${T}`))}):null,Array.isArray(Te.discovered_mcp_tools)&&Te.discovered_mcp_tools.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle text-xs font-medium",children:"Discovered MCP tools"}),e("pre",{className:"tcp-code mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs",children:Te.discovered_mcp_tools.join(`
|
|
2460
|
-
`)})]}):e("div",{className:"tcp-subtle mt-3 text-xs",children:"No MCP tools were discovered for the selected server."})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Posting policy"}),e("div",{className:"tcp-subtle mt-2 grid gap-1 text-xs",children:[e("div",{children:["New issues:"," ",Se?"Manual publish":At?"Auto-create":"Internal draft only"]}),e("div",{children:["Matched open issues:"," ",j?"Auto-comment":"Detect only"]}),e("div",{children:"Dedupe: Fingerprint marker + label"}),e("div",{children:"Labels: bug-monitor"}),e("div",{children:"Workspace write tools: Disabled"}),e("div",{children:"Model fallback: Fail closed"})]})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent incidents"}),nn.length?e("div",{className:"grid gap-2",children:nn.map(l=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:l.title||l.event_type}),e(we,{tone:l.last_error?"warn":"info",children:l.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[l.event_type," · seen"," ",Number(l.occurrence_count||0),"x"," · ",l.updated_at_ms?new Date(l.updated_at_ms).toLocaleString():"time unavailable"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:l.workspace_root||"engine workspace root"}),l.last_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:l.last_error}):null,l.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:l.detail}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-icon-btn",title:"Replay triage for this incident","aria-label":"Replay triage for this incident",disabled:wt.isPending,onClick:()=>wt.mutate({incidentId:l.incident_id}),children:e("i",{"data-lucide":"rotate-cw"})}),l.triage_run_id?e("span",{className:"tcp-subtle text-xs",children:["triage run: ",l.triage_run_id]}):null,l.draft_id?e("span",{className:"tcp-subtle text-xs",children:["draft: ",l.draft_id]}):null]})]},l.incident_id))}):e(Le,{text:"No Bug Monitor incidents yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent reporter drafts"}),Qa.length?e("div",{className:"grid gap-2",children:Qa.map(l=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:l.title||l.fingerprint}),e(we,{tone:l.status==="approval_required"?"warn":"info",children:l.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[l.repo," ·"," ",l.issue_number?`issue #${l.issue_number}`:"draft only"," ","·"," ",l.created_at_ms?new Date(l.created_at_ms).toLocaleString():"time unavailable"]}),l.github_status?e("div",{className:"tcp-subtle mt-1 text-xs",children:["GitHub: ",l.github_status,l.matched_issue_number?` · matched #${l.matched_issue_number}${l.matched_issue_state?` (${l.matched_issue_state})`:""}`:""]}):null,l.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:l.detail}):null,l.last_post_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:l.last_post_error}):null,l.triage_run_id?e("div",{className:"tcp-subtle mt-2 text-xs",children:["triage run: ",l.triage_run_id]}):null,l.status==="approval_required"?e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:Fe.isPending,title:"Approve draft","aria-label":"Approve draft",onClick:()=>Fe.mutate({draftId:l.draft_id,decision:"approve"}),children:[e("i",{"data-lucide":"check"}),Fe.isPending?"Updating...":null]}),e("button",{className:"tcp-icon-btn",title:"Deny draft","aria-label":"Deny draft",disabled:Fe.isPending,onClick:()=>Fe.mutate({draftId:l.draft_id,decision:"deny"}),children:e("i",{"data-lucide":"x"})})]}):null,l.issue_number?null:e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-icon-btn",title:"Publish this draft to GitHub now","aria-label":"Publish this draft to GitHub now",disabled:Gt.isPending,onClick:()=>Gt.mutate({draftId:l.draft_id}),children:e("i",{"data-lucide":"bug-play"})}),e("button",{className:"tcp-icon-btn",title:"Recheck GitHub for an existing matching issue","aria-label":"Recheck GitHub for an existing matching issue",disabled:ra.isPending,onClick:()=>ra.mutate({draftId:l.draft_id}),children:e("i",{"data-lucide":"refresh-cw"})})]}),(l.github_issue_url||l.github_comment_url)&&e("div",{className:"mt-3 flex flex-wrap gap-2 text-xs",children:[l.github_issue_url?e("a",{className:"tcp-btn",href:l.github_issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,l.github_comment_url?e("a",{className:"tcp-btn",href:l.github_comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]}),(l.status==="draft_ready"||l.status==="triage_queued")&&!l.triage_run_id?e("div",{className:"mt-3 flex flex-wrap gap-2",children:e("button",{className:"tcp-icon-btn",title:"Create triage run","aria-label":"Create triage run",disabled:Ke.isPending,onClick:()=>Ke.mutate({draftId:l.draft_id}),children:e("i",{"data-lucide":"sparkles"})})}):null]},l.draft_id))}):e(Le,{text:"No Bug Monitor drafts yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent GitHub posts"}),xn.length?e("div",{className:"grid gap-2",children:xn.map(l=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:l.operation}),e(we,{tone:l.status==="posted"?"ok":"warn",children:l.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[l.repo,l.issue_number?` · issue #${l.issue_number}`:"",l.updated_at_ms?` · ${new Date(l.updated_at_ms).toLocaleString()}`:""]}),l.error?e("div",{className:"tcp-subtle mt-1 text-xs",children:l.error}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[l.issue_url?e("a",{className:"tcp-btn",href:l.issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,l.comment_url?e("a",{className:"tcp-btn",href:l.comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]})]},l.post_id))}):e(Le,{text:"No GitHub post attempts yet."})]})]})}):null,I==="browser"?e(ot,{title:"Browser readiness",subtitle:"Operational browser status, diagnostics, and recovery actions.",actions:e(ya,{children:[e("button",{className:"tcp-btn",onClick:()=>{Ie.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>Ne.mutate(),disabled:Ne.isPending,children:[e("i",{"data-lucide":"download"}),Ne.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[e("i",{"data-lucide":"globe"}),pe.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>me(!0),children:[e("i",{"data-lucide":"activity"}),"Diagnostics"]})]}),children:[e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Status"}),e("div",{className:"mt-1 text-sm",children:Ie.data?Ie.data.runnable?"Ready":Ie.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",Ie.data?.headless_default?"yes":"no"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Sidecar"}),e("div",{className:"mt-1 break-all text-sm",children:Ie.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Ie.data?.sidecar?.version||"No version detected"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Browser"}),e("div",{className:"mt-1 break-all text-sm",children:Ie.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Ie.data?.browser?.version||Ie.data?.browser?.channel||"No version detected"})]})]}),i.length?e("div",{className:"mt-3 grid gap-2",children:i.map((l,T)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:l.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:l.message||"Unknown browser issue."})]},`${l.code||"issue"}-${T}`))}):null,Pe?e("div",{className:"mt-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:[e("div",{className:"font-medium",children:["Smoke test passed",Pe.title?`: ${Pe.title}`:""]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:Pe.final_url||Pe.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",Pe.load_state||"unknown"," · elements:"," ",String(Pe.element_count??0)," · closed:"," ",Pe.closed?"yes":"no"]}),Pe.excerpt?e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words",children:Pe.excerpt}):null]}):null]}):null]}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Readiness snapshot",subtitle:"High-signal operational summary for this configuration state.",children:e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Connected providers"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[String(Jt.data?.connected?.length||0)," connected, default"," ",String(vt.data?.default||"none")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Browser automation"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:Ie.data?Ie.data.runnable?"Ready":Ie.data.enabled?"Enabled but blocked":"Disabled":"Unknown"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Theme"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:d.find(l=>l.id===p)?.name||p})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"MCP"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[_a," connected, ",Ja.length," discovered tools"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Bug monitor"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Te.readiness?.runtime_ready?"Ready":it?"Enabled but blocked":"Disabled"," · ",Number(Te.pending_drafts||0)," pending drafts"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Channels"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[de," connected, ",Z.length," available"]})]})]})}),e(ot,{title:"Quick access",subtitle:"Jump straight to the section you need.",children:e("div",{className:"grid gap-2",children:rn.map(l=>e("button",{className:"tcp-list-item flex items-center justify-between text-left",onClick:()=>H(l.id),children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":l.icon}),l.label]}),I===l.id?e(we,{tone:"ok",children:"open"}):null]},l.id))})})]})}),e(sr,{open:Re,onClose:()=>qe(!1),title:"Official GitHub MCP guide",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Recommended for Bug Monitor: use the official GitHub MCP endpoint instead of a third-party wrapper when you want stable issue read/write operations."}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Transport URL"}),e("div",{className:"mt-1 break-all text-sm",children:"https://api.githubcopilot.com/mcp/"}),e("div",{className:"tcp-subtle text-xs",children:"Use this as the MCP server transport in Tandem Settings."})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Auth mode"}),e("div",{className:"mt-1 text-sm",children:"Authorization Bearer"}),e("div",{className:"tcp-subtle text-xs",children:"Paste a GitHub token in the MCP server dialog and use bearer auth."})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommended setup"}),e("div",{className:"tcp-list-item text-sm",children:["1. Open `Add MCP server`.",e("br",{}),"2. Name it `github` or another stable name.",e("br",{}),"3. Set transport to `https://api.githubcopilot.com/mcp/`.",e("br",{}),"4. Set auth mode to `Authorization Bearer`.",e("br",{}),"5. Paste a GitHub Personal Access Token.",e("br",{}),"6. Save, connect, then select that MCP server in Bug Monitor settings."]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Token guidance"}),e("div",{className:"tcp-list-item text-sm",children:"For failure reporting, the token needs issue read/write access on the target repository so the runtime can create issues and add comments."})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Direct links"}),e("div",{className:"flex flex-wrap gap-2",children:[e("a",{className:"tcp-btn",href:"https://github.com/github/github-mcp-server?tab=readme-ov-file",target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"GitHub MCP README"]}),e("a",{className:"tcp-btn",href:"https://docs.github.com/en/copilot/how-tos/provide-context/use-mcp/use-the-github-mcp-server",target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"GitHub Docs"]})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Issue tools to expect"}),e("div",{className:"tcp-list-item text-sm",children:"The reporter should be able to resolve issue-list, issue-read, issue-create, and issue-comment operations from the selected GitHub MCP server. If readiness still fails, compare the discovered MCP tools shown in Settings against those issue operations."})]})]})}),e(Mt,{children:W?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close Bug Monitor workspace dialog",onClick:()=>{V(!1),ct("")}}),e($e.div,{className:"tcp-confirm-dialog max-w-2xl",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Select Bug Monitor Directory"}),e("p",{className:"tcp-confirm-message",children:["Current: ",ca||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{ba&&Be(ba)},disabled:!ba,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{ca&&(o(ca),V(!1),ct(""),n("ok",`Bug Monitor directory selected: ${ca}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{V(!1),ct("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ht,onInput:l=>ct(l.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:fa.length?fa.map(l=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Be(String(l?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(l?.name||l?.path||"")]},String(l?.path||l?.name))):e(Le,{text:Dt?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e(sr,{open:M,onClose:()=>me(!1),title:"Browser diagnostics",children:e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Status"}),e("div",{className:"mt-1 text-sm",children:Ie.data?Ie.data.runnable?"Ready":Ie.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",Ie.data?.headless_default?"yes":"no"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Sidecar"}),e("div",{className:"mt-1 break-all text-sm",children:Ie.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Ie.data?.sidecar?.version||"No version detected"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Browser"}),e("div",{className:"mt-1 break-all text-sm",children:Ie.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Ie.data?.browser?.version||Ie.data?.browser?.channel||"No version detected"})]})]}),e(ya,{children:[e("button",{className:"tcp-btn",onClick:()=>{Ie.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>Ne.mutate(),disabled:Ne.isPending,children:[e("i",{"data-lucide":"download"}),Ne.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[e("i",{"data-lucide":"globe"}),pe.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>t("/api/engine/browser/status",{method:"GET"}).then(()=>n("ok","Browser diagnostics refreshed.")).catch(l=>n("err",l instanceof Error?l.message:String(l))),children:[e("i",{"data-lucide":"activity"}),"Re-run diagnostics"]})]}),Ie.isLoading?e(Le,{text:"Loading browser diagnostics..."}):Ie.data?e(aa,{children:[i.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Blocking issues"}),i.map((l,T)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:l.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:l.message||"Unknown browser issue."})]},`${l.code||"issue"}-${T}`))]}):e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Browser automation is ready on this machine."}),Pe?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Latest smoke test"}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:Pe.title||"Smoke test"}),e("div",{className:"tcp-subtle text-xs",children:Pe.final_url||Pe.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",Pe.load_state||"unknown"," · elements:"," ",String(Pe.element_count??0)," · closed:"," ",Pe.closed?"yes":"no"]}),Pe.excerpt?e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:Pe.excerpt}):null]})]}):null,m.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommendations"}),m.map((l,T)=>e("div",{className:"tcp-list-item text-sm",children:l},`browser-recommendation-${T}`))]}):null,D.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Install hints"}),D.map((l,T)=>e("div",{className:"tcp-list-item text-sm",children:l},`browser-install-hint-${T}`))]}):null,Ie.data?.last_error?e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-3 text-xs",children:["Last error: ",Ie.data.last_error]}):null]}):e(Le,{text:"Browser diagnostics are unavailable."})]})}),e(Mt,{children:re?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close MCP server dialog",onClick:()=>Ce(!1)}),e($e.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:Ge?"Edit MCP Server":"Add MCP Server"}),e("p",{className:"tcp-confirm-message",children:"Configure transport and auth without leaving Settings."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>Ce(!1),children:e("i",{"data-lucide":"x"})})]}),e("form",{className:"grid gap-3",onSubmit:l=>{l.preventDefault(),an.mutate()},children:[e("div",{className:"tcp-settings-tabs",children:[e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${ve==="catalog"?"active":""}`,onClick:()=>_e("catalog"),children:[e("i",{"data-lucide":"blocks"}),"Built-in packs"]}),e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${ve==="manual"?"active":""}`,onClick:()=>_e("manual"),children:[e("i",{"data-lucide":"square-pen"}),"Manual"]})]}),ve==="catalog"?e("div",{className:"grid gap-3",children:[e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"tcp-subtle text-sm",children:Ua.generatedAt?`Built-in MCP packs · generated ${Ua.generatedAt}`:"Built-in MCP packs"}),e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{_t.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("input",{className:"tcp-input",value:Ye,onInput:l=>le(l.target.value),placeholder:"Search built-in MCP packs"}),e("div",{className:"grid max-h-[26rem] gap-2 overflow-auto pr-1 md:grid-cols-2",children:wn.length?wn.map(l=>{const T=mr.has(String(l.serverConfigName||l.slug||"").toLowerCase());return e("div",{className:"tcp-list-item grid gap-2",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:l.name}),e("div",{className:"tcp-subtle text-xs",children:[l.slug,l.requiresSetup?" · setup required":""]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(we,{tone:"info",children:[l.toolCount," tools"]}),e(we,{tone:l.requiresAuth?"warn":"ok",children:l.requiresAuth?"Auth":"Authless"})]})]}),e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:l.description||l.transportUrl}),e("div",{className:"tcp-subtle break-all text-xs",children:l.transportUrl}),e("div",{className:"mt-auto flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{ie(Er(l.serverConfigName||l.slug||l.name)),st(l.transportUrl),_e("manual"),n("ok",`Loaded ${l.name}. Review and save when ready.`)},children:"Use pack"}),l.documentationUrl?e("a",{className:"tcp-btn h-8 px-3 text-xs",href:l.documentationUrl,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Docs"]}):null,T?e(we,{tone:"ok",children:"added"}):null]})]},l.slug)}):e(Le,{text:"No built-in MCP packs match this search."})})]}):e(aa,{children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Name"}),e("input",{className:"tcp-input",value:gt,onInput:l=>ie(l.target.value),placeholder:"mcp-server"})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Auth mode"}),e("select",{className:"tcp-select",value:pt,onChange:l=>lt(l.target.value),children:[e("option",{value:"none",children:"No Auth Header"}),e("option",{value:"auto",children:"Auto"}),e("option",{value:"x-api-key",children:"x-api-key"}),e("option",{value:"bearer",children:"Authorization Bearer"}),e("option",{value:"custom",children:"Custom Header"})]})]})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Transport URL"}),e("input",{className:"tcp-input",value:L,onInput:l=>{const T=l.target.value;if(st(T),!String(gt||"").trim()||gt==="mcp-server"){const ke=zs(T);ke&&ie(ke)}},placeholder:"https://example.com/mcp"})]}),pt==="custom"?e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Custom header name"}),e("input",{className:"tcp-input",value:$t,onInput:l=>yt(l.target.value),placeholder:"X-My-Token"})]}):null,e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Token"}),e("input",{className:"tcp-input",type:"password",value:Ct,onInput:l=>De(l.target.value),placeholder:"token"}),e("div",{className:"tcp-subtle text-xs",children:pr})]}),e("label",{className:"inline-flex items-center gap-2 text-sm text-slate-200",children:[e("input",{type:"checkbox",className:"accent-slate-400",checked:Ut,onChange:l=>Je(l.target.checked)}),"Connect after save"]})]}),e("div",{className:"tcp-confirm-actions mt-2",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>Ce(!1),children:"Cancel"}),e("button",{type:"submit",className:"tcp-btn-primary",disabled:an.isPending,children:[e("i",{"data-lucide":"save"}),"Save MCP server"]})]})]})]})]}):null})]})})}function dp({routeId:a,pageProps:t}){switch(Ur(a)){case"chat":return e(td,{...t});case"studio":return e(Zd,{...t});case"automations":case"packs":case"teams":return e(im,{...t});case"coding":return e(hm,{...t});case"agents":return e(Ks,{...t});case"channels":return e(gm,{...t});case"mcp":return e(Gs,{...t});case"packs-detail":return e(vm,{...t});case"orchestrator":return e(qm,{...t});case"files":return e($m,{...t});case"memory":return e(Em,{...t});case"teams-detail":return e(Ks,{...t});case"feed":return e(Qm,{...t});case"settings":return e(Gs,{...t});default:return e(Cc,{...t})}}const up={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."},studio:{title:"Studio",subtitle:"Template-first workflow builder with reusable role prompts and visual stages."},automations:{title:"Automations",subtitle:"Templates, routines, approvals, and execution history."},coding:{title:"Coding Workflows",subtitle:"Internal Kanban, manual task launchers, and MCP-aware coding runs."},agents:{title:"Agents",subtitle:"Persistent personalities, default models, and prompts reused across automation workflows."},orchestrator:{title:"Orchestrator",subtitle:"Plan-driven task execution with workspace visibility and approvals."},memory:{title:"Memory",subtitle:"Searchable memory records and operational context snapshots."},feed:{title:"Live Feed",subtitle:"Global event stream with pack-aware actions and debugging detail."},settings:{title:"Settings",subtitle:"Provider defaults, identity, themes, and runtime diagnostics."},mcp:{title:"MCP",subtitle:"Catalog, readiness, and generated integration details."},files:{title:"Files",subtitle:"Uploaded assets and workspace-adjacent file management."},"packs-detail":{title:"Packs",subtitle:"Starter packs, installation paths, and detected attachments."},"teams-detail":{title:"Teams",subtitle:"Team instances, approvals, and shared execution state."}};function mp({identity:a,currentRoute:t,providerLocked:n,navRoutes:r,onNavigate:s,onPaletteOpen:c,onThemeCycle:d,onLogout:u,statusBar:p,routeKey:N,children:E,providerGate:x}){const[C,O]=w(!1),[k,z]=w(!1),A=String(a.botAvatarUrl||"").trim(),G=ni();fe(()=>{O(!1)},[t]),fe(()=>{try{wa()}catch{}},[t,C,p.bugMonitor?.enabled,p.bugMonitor?.monitoringActive,p.bugMonitor?.paused,p.bugMonitor?.pendingIncidents,p.bugMonitor?.blocked]),fe(()=>{z(!1)},[A]);const B=up[t]||{title:String(r.find(([y])=>y===t)?.[1]||"Control Panel"),subtitle:"Desktop-inspired operations UI for Tandem."},ae=K(()=>r.find(([y])=>y===t)||r[0],[t,r]),S=K(()=>{const y=p.bugMonitor;return y?.enabled?y.blocked?{toneClass:"blocked",label:"Bug Monitor blocked",shortLabel:"Blocked"}:y.paused?{toneClass:"paused",label:"Bug Monitor paused",shortLabel:"Paused"}:y.pendingIncidents>0?{toneClass:"incidents",label:`Bug Monitor incidents: ${y.pendingIncidents}`,shortLabel:`${y.pendingIncidents} incident${y.pendingIncidents===1?"":"s"}`}:y.monitoringActive?{toneClass:"watching",label:"Bug Monitor watching",shortLabel:"Watching"}:{toneClass:"ready",label:"Bug Monitor ready",shortLabel:"Ready"}:null},[p.bugMonitor]),I=()=>A&&!k?e("img",{src:A,alt:a.botName,className:"block h-full w-full object-cover",onError:()=>z(!0)}):e("span",{className:"text-sm font-semibold uppercase",children:String(a.botName||"T").trim().slice(0,1)||"T"}),H=()=>r.map(([y,v,U])=>{const ue=t===y,ee=n&&y!=="settings";return e("button",{type:"button",title:v,disabled:ee,className:`tcp-rail-icon ${ue?"active":""} ${ee?"locked":""}`,onClick:()=>s(y),children:[ue?e($e.span,{layoutId:"tcp-icon-indicator",className:"tcp-rail-icon-indicator"}):null,e("i",{"data-lucide":U})]},y)}),q=(y=!1)=>r.map(([v,U,ue])=>{const ee=t===v,Oe=n&&v!=="settings";return e("button",{type:"button",disabled:Oe,className:`tcp-context-link ${ee?"active":""} ${Oe?"locked":""}`,onClick:()=>{s(v),y&&O(!1)},children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":ue}),e("span",{children:U})]}),ee?e("span",{className:"tcp-context-link-dot"}):null]},v)}),ye=(y=!1)=>e(aa,{children:[y?e("div",{className:"tcp-context-hero",children:[e(rr,{className:"tcp-context-hero-glow"}),e("div",{className:"relative z-10 flex items-center gap-3",children:[e("div",{className:"tcp-brand-avatar h-11 w-11",children:I()}),e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:a.controlPanelName||`${a.botName} Control Panel`}),e("div",{className:"tcp-subtle text-xs",children:"Workspace navigation and system status"})]})]})]}):null,e("div",{className:`tcp-context-section ${y?"":"xl:hidden"}`.trim(),children:[e("div",{className:"tcp-context-section-label",children:"Navigation"}),e("nav",{className:"grid gap-1",children:q(y)})]}),y?e("div",{className:"tcp-context-section",children:[e("div",{className:"tcp-context-section-label",children:"System"}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Engine"}),p.engineHealthy?e(va,{tone:"ok",text:"healthy"}):e(va,{tone:"warn",text:"checking"})]}),e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Provider"}),e("span",{className:p.providerBadge,children:p.providerText})]}),e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Active runs"}),p.activeRuns>0?e(va,{tone:"live",text:String(p.activeRuns)}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"idle"})]}),S?e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Bug Monitor"}),e("button",{type:"button",className:`tcp-bug-monitor-pill ${S.toneClass}`,title:p.bugMonitor?.lastError?`${S.label}: ${p.bugMonitor.lastError}`:S.label,onClick:()=>{s("bug-monitor"),y&&O(!1)},children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:S.shortLabel})]})]}):null]})]}):null,e("div",{className:"tcp-context-section mt-auto",children:[e("div",{className:"tcp-context-section-label",children:"Actions"}),e("div",{className:"grid gap-2",children:[e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{c(),y&&O(!1)},children:[e("i",{"data-lucide":"search"}),"Command palette"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{d(),y&&O(!1)},children:[e("i",{"data-lucide":"paint-bucket"}),"Cycle theme"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{u(),y&&O(!1)},children:[e("i",{"data-lucide":"log-out"}),"Logout"]})]})]})]});return e("div",{className:`tcp-shell ${t==="chat"?"tcp-shell-chat":""}`.trim(),children:[e(rr,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("aside",{className:"tcp-icon-rail hidden xl:flex",children:[e("button",{type:"button",className:"tcp-rail-brand",onClick:()=>s("dashboard"),children:e("div",{className:"tcp-brand-avatar h-10 w-10",children:I()})}),e("nav",{className:"tcp-rail-nav",children:H()}),e("div",{className:"tcp-rail-footer",children:[e(An,{title:"Command palette",onClick:c,children:e("i",{"data-lucide":"search"})}),e(An,{title:"Cycle theme",onClick:d,children:e("i",{"data-lucide":"paint-bucket"})}),e(An,{title:"Logout",onClick:u,children:e("i",{"data-lucide":"log-out"})}),e("div",{className:"mt-2 flex justify-center",children:p.engineHealthy?e(va,{tone:"ok"}):e(va,{tone:"warn"})})]})]}),e("aside",{className:"tcp-context-rail hidden lg:flex xl:hidden",children:ye(!1)}),e("main",{className:`tcp-main-shell ${t==="chat"?"tcp-main-shell-fill":""}`.trim(),children:[e("section",{className:"tcp-mobile-topbar lg:hidden",children:[e("button",{type:"button",className:"tcp-btn h-10 px-3",onClick:()=>O(!0),children:[e("i",{"data-lucide":"menu"}),"Menu"]}),e("div",{className:"min-w-0 flex-1",children:[e("div",{className:"truncate text-sm font-semibold",children:B.title}),e("div",{className:"tcp-subtle truncate text-xs",children:ae?.[1]||B.subtitle})]}),S?e("button",{type:"button",className:`tcp-bug-monitor-pill ${S.toneClass}`,title:p.bugMonitor?.lastError?`${S.label}: ${p.bugMonitor.lastError}`:S.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"})]}):null,p.activeRuns>0?e(va,{tone:"live",text:String(p.activeRuns)}):null]}),e("section",{className:"tcp-topbar",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Tandem Control"}),e("h1",{className:"tcp-main-title",children:B.title}),e("p",{className:"tcp-subtle mt-1 max-w-2xl",children:B.subtitle})]}),e("div",{className:"tcp-topbar-status",children:[S?e("button",{type:"button",className:`tcp-bug-monitor-pill ${S.toneClass}`,title:p.bugMonitor?.lastError?`${S.label}: ${p.bugMonitor.lastError}`:S.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:S.shortLabel})]}):null,e("span",{className:p.providerBadge,children:p.providerText}),p.engineHealthy?e(va,{tone:"ok",text:"Engine healthy"}):e(va,{tone:"warn",text:"Checking engine"}),p.activeRuns>0?e(va,{tone:"live",text:`${p.activeRuns} run`}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"No active runs"})]})]}),e(Mt,{mode:"wait",children:e($e.section,{className:`tcp-main-content ${t==="chat"?"tcp-main-content-fill":""}`.trim(),initial:G?!1:{opacity:0,y:18},animate:G?void 0:{opacity:1,y:0},exit:G?void 0:{opacity:0,y:-14},transition:G?void 0:{duration:Ca.duration.normal,ease:Ca.easing.standard},children:E},N)})]}),e(Mt,{children:C?e($e.div,{className:"tcp-mobile-drawer lg:hidden",initial:G?!1:{opacity:0},animate:G?void 0:{opacity:1},exit:G?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-mobile-drawer-backdrop","aria-label":"Close navigation",onClick:()=>O(!1)}),e($e.aside,{className:"tcp-mobile-drawer-panel",initial:G?!1:{x:"-100%"},animate:G?void 0:{x:0},exit:G?void 0:{x:"-100%"},transition:G?void 0:Ca.spring.drawer,children:[e("div",{className:"mb-3 flex items-center justify-between",children:[e("div",{children:[e("div",{className:"text-sm font-semibold",children:a.botName}),e("div",{className:"tcp-subtle text-xs",children:B.title})]}),e(An,{title:"Close",onClick:()=>O(!1),children:e("i",{"data-lucide":"x"})})]}),ye(!0)]})]}):null}),e(Mt,{children:x||null})]})}function Ki(a){const t=String(a||"").trim().toLowerCase();return!!t&&t!=="ollama"&&t!=="local"}function pp(a,t){const n=String(t||"").trim().toLowerCase();if(!n||!a||typeof a!="object")return!1;const r=s=>!s||typeof s!="object"?!1:s.has_key===!0||s.hasKey===!0||s.configured===!0&&!Ki(n);return r(a[n])||r(a.providers?.[n])}function hp(a,t,n){const r=String(a?.default||a?.selected_model?.provider_id||"").trim(),s=a?.providers?.[r]||{},c=String(s.default_model||s.defaultModel||a?.selected_model?.model_id||"").trim(),d=Array.isArray(t?.connected)?t.connected:[],u=new Set(d.map(E=>String(E||"").trim().toLowerCase())),p=pp(n,r),N=!!r&&!!c&&u.has(r.toLowerCase())&&(!Ki(r)||p);return{ready:N,defaultProvider:r,defaultModel:c,connected:[...u],error:"",needsOnboarding:!N}}const es="tandem_control_panel_token";function Hs(){try{return localStorage.getItem(es)||""}catch{return""}}function gp(a){try{localStorage.setItem(es,a)}catch{}}function fp(){try{localStorage.removeItem(es)}catch{}}function bp(a,t){return Y({queryKey:["provider","status"],enabled:t&&!!a,refetchInterval:t?15e3:!1,queryFn:async()=>{if(!a)return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:"",needsOnboarding:!1};try{const[n,r,s]=await Promise.all([a.providers.config(),a.providers.catalog(),a.providers.authStatus().catch(()=>({}))]);return hp(n,r,s)}catch(n){return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:n instanceof Error?n.message:String(n),needsOnboarding:!0}}}})}function vp(a,t){return Y({queryKey:["identity"],enabled:t&&!!a,refetchInterval:t?3e4:!1,queryFn:async()=>{if(!a)return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"};try{const r=(await zt("/api/engine/config/identity",{method:"GET"}))?.identity||{},s=String(r?.bot?.canonical_name||r?.bot?.canonicalName||"").trim(),c=r?.bot?.aliases||{},d=String(r?.bot?.avatar_url||r?.bot?.avatarUrl||"").trim(),u=String(c?.control_panel||c?.controlPanel||"").trim(),p=s||"Tandem";return{botName:p,botAvatarUrl:d,controlPanelName:u||`${p} Control Panel`}}catch{return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"}}}})}function yp(a){return Y({queryKey:["bug-monitor","status"],enabled:a,refetchInterval:a?1e4:!1,queryFn:async()=>{try{return await zt("/api/engine/bug-monitor/status",{method:"GET"})}catch{return null}}})}function wp(){const a=na(),{toast:t}=Sc(),{route:n,navigate:r}=Nc(),[s,c]=w(oc()),[d,u]=w(!1),[p,N]=w(!1),E=qt(!1);fe(()=>{lc(s)},[s]);const C=Y({queryKey:["auth","me"],retry:!1,refetchInterval:3e4,queryFn:()=>zt("/api/auth/me",{method:"GET"})}).isSuccess;fe(()=>{try{wa()}catch{}},[C,n]);const O=K(()=>C?new El({baseUrl:"/api/engine",token:"session"}):null,[C]),k=bp(O,C),z=vp(O,C),A=Ni(C),G=Sd(C),B=yp(C),ae=xe({mutationFn:async({token:Me})=>{await zt("/api/auth/login",{method:"POST",body:JSON.stringify({token:Me})})},onSuccess:(Me,ze)=>{ze.remember?gp(ze.token):fp(),a.invalidateQueries({queryKey:["auth","me"]}),t("ok","Signed in."),r("dashboard")},onError:Me=>{t("err",Me instanceof Error?Me.message:String(Me))}});fe(()=>{if(C||ae.isPending||E.current)return;const Me=Hs().trim();if(!Me){E.current=!0;return}E.current=!0,ae.mutate({token:Me,remember:!0})},[C,ae]);const S=mt(async()=>{await zt("/api/auth/logout",{method:"POST"}).catch(()=>{}),a.removeQueries({queryKey:["auth"]}),a.removeQueries({queryKey:["provider"]}),a.removeQueries({queryKey:["identity"]}),a.invalidateQueries({queryKey:["auth","me"]}),t("info","Logged out.")},[a,t]),I=K(()=>new Set(["chat","studio","agents","orchestrator","teams"]),[]),H=!!k.data?.needsOnboarding,q=C&&H;fe(()=>{if(!q){N(!1);return}I.has(n)&&(r("settings"),p||(N(!0),t("info","Set provider + default model first to unlock the control panel.")))},[I,r,p,q,n,t]);const ye=q&&I.has(n)?"settings":n,y=mt(async()=>{await a.invalidateQueries({queryKey:["provider","status"]})},[a]),v=mt(async()=>{await a.invalidateQueries({queryKey:["identity"]})},[a]),U=mt(Me=>{const ze=cc(Me);return c(ze.id),ze},[c]),ue=z.data||{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"},ee={client:O,api:zt,toast:t,navigate:r,currentRoute:ye,providerStatus:{ready:!!k.data?.ready,defaultProvider:k.data?.defaultProvider||"",defaultModel:k.data?.defaultModel||"",connected:k.data?.connected||[],error:k.data?.error||"",needsOnboarding:!!k.data?.needsOnboarding},identity:ue,refreshProviderStatus:y,refreshIdentityStatus:v,providerHints:oi,themes:cn,setTheme:U,themeId:s},Oe=K(()=>{const Me=li.map(([X,Ve])=>({id:`route:${X}`,label:`Go to ${Ve}`,group:"Routes",onSelect:()=>r(X)})),ze=[{id:"action:new-chat",label:"New chat session",group:"Actions",onSelect:()=>{window.dispatchEvent(new CustomEvent("tcp:new-chat")),r("chat")}},{id:"action:start-engine-check",label:"Check engine health",group:"Actions",onSelect:async()=>{try{const X=await zt("/api/system/health"),Ve=X?.engine?.ready||X?.engine?.healthy?"healthy":"unhealthy";t("info",`Engine ${Ve}: ${X?.engineUrl||"n/a"}`)}catch(X){t("err",X instanceof Error?X.message:String(X))}}},{id:"action:open-settings",label:"Open provider settings",group:"Actions",onSelect:()=>r("settings")},{id:"action:open-orchestrator",label:"Open orchestrator",group:"Actions",onSelect:()=>r("orchestrator")}];return[...Me,...ze]},[r,t]);if(fc(()=>u(Me=>!Me)),!C)return e(gc,{loginMutation:ae,savedToken:Hs(),controlPanelName:ue.controlPanelName,onCheckEngine:async()=>{const Me=await zt("/api/system/health");return`Engine check: ${Me?.engine?.ready||Me?.engine?.healthy?"healthy":"unhealthy"} at ${Me?.engineUrl||"n/a"}`}});const Ee=k.data?.ready?"tcp-badge-ok":"tcp-badge-warn",We=k.data?.ready?`${k.data?.defaultProvider||"none"}/${k.data?.defaultModel||"none"}`:"provider setup required",ne=B.data||null,ce=!!ne?.config?.enabled,M=Number(ne?.runtime?.pending_incidents||0),me=!!ne?.runtime?.monitoring_active,Re=!!ne?.runtime?.paused,qe=!!ne?.readiness?.ingest_ready,se=!!ne?.readiness?.publish_ready,Ue=String(ne?.runtime?.last_runtime_error||ne?.last_error||"").trim();return e(aa,{children:[e(mp,{identity:ue,currentRoute:ye,providerLocked:q,navRoutes:yc,onNavigate:r,onPaletteOpen:()=>u(!0),onThemeCycle:()=>U(ic(s)),onLogout:S,statusBar:{engineHealthy:!!(A.data?.engine?.ready||A.data?.engine?.healthy),providerBadge:Ee,providerText:We,activeRuns:["planning","awaiting_approval","running"].includes(String(G.data?.status||"").toLowerCase())?1:0,bugMonitor:ce?{enabled:!0,monitoringActive:me,paused:Re,pendingIncidents:M,blocked:!qe,lastError:me&&!se&&Ue?`Watching locally only. ${Ue}`:Ue}:null},routeKey:ye,providerGate:q&&ye!=="settings"?e($e.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e($e.div,{className:"tcp-confirm-dialog",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Provider Setup Required"}),e("p",{className:"tcp-confirm-message",children:"Configure provider and default model in Settings to unlock all sections."}),e("div",{className:"tcp-confirm-actions",children:e("button",{className:"tcp-btn-primary",onClick:()=>r("settings"),children:"Open Settings"})})]})}):null,children:e(dp,{routeId:ye,pageProps:ee})}),e(bc,{open:d,onClose:()=>u(!1),actions:Oe})]})}function xp(){return e(_c,{children:e(wp,{})})}const kp=new bl({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),Li=document.getElementById("app");if(!Li)throw new Error("Missing #app host");Qi(Li).render(e(Gi,{children:e(Vi,{client:kp,children:e(xp,{})})}));
|
|
2456
|
+
}`),[O,_]=w([]),z=V({queryKey:["packs","list"],queryFn:()=>a("/api/engine/packs",{method:"GET"}).catch(()=>({packs:[]})),refetchInterval:15e3}),P=V({queryKey:["workflows","list"],queryFn:()=>a("/api/engine/workflows",{method:"GET"}).catch(()=>({workflows:[]})),refetchInterval:15e3}),Q=V({queryKey:["workflows","hooks"],queryFn:()=>a("/api/engine/workflow-hooks",{method:"GET"}).catch(()=>({hooks:[]})),refetchInterval:15e3}),B=Vt(z.data,"packs"),ne=Vt(P.data,"workflows"),I=Vt(Q.data,"hooks"),C=F(()=>c||at(B[0]?.pack_id||B[0]?.name),[B,c]),H=F(()=>u||at(ne[0]?.workflow_id),[u,ne]),M=V({queryKey:["workflows","runs",H],queryFn:()=>a(`/api/engine/workflows/runs${H?`?workflow_id=${encodeURIComponent(H)}&limit=20`:"?limit=20"}`,{method:"GET"}).catch(()=>({runs:[]})),refetchInterval:6e3}),xe=Vt(M.data,"runs"),y=V({queryKey:["packs","detail",C],enabled:!!C,queryFn:()=>a(`/api/engine/packs/${encodeURIComponent(C)}`,{method:"GET"})}),v=V({queryKey:["workflows","detail",H],enabled:!!H,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(H)}`,{method:"GET"})}),j=ke({mutationFn:()=>a("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:r,source:{kind:"control-panel"}})}),onSuccess:async()=>{t("ok","Pack installed."),s(""),await Promise.all([n.invalidateQueries({queryKey:["packs"]}),n.invalidateQueries({queryKey:["workflows"]})])},onError:q=>t("err",q instanceof Error?q.message:String(q))}),he=ke({mutationFn:q=>a(`/api/engine/workflows/${encodeURIComponent(q)}/run`,{method:"POST"}),onSuccess:async q=>{t("ok",`Workflow ${at(q?.run?.workflow_id||H)} started.`),await Promise.all([n.invalidateQueries({queryKey:["workflows"]}),n.invalidateQueries({queryKey:["workflows","runs"]})])},onError:q=>t("err",q instanceof Error?q.message:String(q))}),ee=ke({mutationFn:async()=>{let q={};const ge=at(x);return ge&&(q=JSON.parse(ge)),a("/api/engine/workflows/simulate",{method:"POST",body:JSON.stringify({event_type:N,properties:q})})},onError:q=>t("err",q instanceof Error?q.message:String(q))}),qe=ke({mutationFn:({bindingId:q,enabled:ge})=>a(`/api/engine/workflow-hooks/${encodeURIComponent(q)}`,{method:"PATCH",body:JSON.stringify({enabled:ge})}),onSuccess:async()=>{await Promise.all([n.invalidateQueries({queryKey:["workflows","hooks"]}),n.invalidateQueries({queryKey:["workflows","detail"]})])},onError:q=>t("err",q instanceof Error?q.message:String(q))}),$e=y.data?.pack||null,Le=v.data?.workflow||null,re=Vt(v.data,"hooks"),me=ee.data?.simulation||null;return en(`/api/engine/workflows/events${H?`?workflow_id=${encodeURIComponent(H)}`:""}`,q=>{try{const ge=JSON.parse(q.data);if(ge?.status==="ready")return;_(Pe=>[...Pe.slice(-59),{at:Date.now(),data:ge}])}catch{}},{enabled:!0}),e(vn,{className:"grid gap-4",children:[e(qc,{eyebrow:"Operations",title:"Pack library and workflow lab",subtitle:"Inspect installed packs, see workflow extensions, toggle hooks, simulate lifecycle events, and run workflow definitions without leaving the control panel.",badges:e(la,{children:[e(ve,{tone:"info",children:[B.length," installed packs"]}),e(ve,{tone:"warn",children:[ne.length," workflows"]}),e(ve,{tone:"ghost",children:[I.length," hooks"]})]})}),e(En,{main:e("div",{className:"grid gap-4",children:[e(ot,{title:"Installed packs",subtitle:"Select a pack to inspect its manifest, declared workflow contents, and hook contributions.",children:e("div",{className:"grid gap-2",children:B.length?B.map((q,ge)=>{const Pe=at(q?.pack_id||q?.name||ge);return e("button",{type:"button",className:`tcp-list-item text-left ${Pe===C?"border-amber-400/70":""}`,onClick:()=>d(Pe),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:at(q?.name||Pe)}),e("span",{className:"tcp-badge-info",children:at(q?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e("span",{className:"tcp-subtle",children:at(q?.pack_type||"pack")}),e("span",{className:"tcp-subtle",children:at(q?.install_path||"")})]})]},Pe)}):e(je,{text:"No packs are installed yet."})})}),e(ot,{title:"Workflow registry",subtitle:"This is the live workflow registry resolved from built-ins, installed packs, and workspace-local overrides.",children:e("div",{className:"grid gap-2",children:ne.length?ne.map(q=>{const ge=at(q?.workflow_id),Pe=ge===H,Te=at(q?.source?.kind||"unknown");return e("button",{type:"button",className:`tcp-list-item text-left ${Pe?"border-amber-400/70":""}`,onClick:()=>p(ge),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:at(q?.name||ge)}),e("span",{className:`tcp-badge-${Te==="pack"?"warn":"info"}`,children:Te})]}),e("div",{className:"tcp-subtle text-xs",children:[ge," · ",Vt(q?.steps,"steps").length," steps"]})]},ge)}):e(je,{text:"No workflows are currently registered."})})})]}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Install pack",subtitle:"Install a local pack path and reload workflow contributions automatically.",children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:r,onInput:q=>s(q.target.value),placeholder:"/path/to/pack.zip"}),e("button",{className:"tcp-btn-primary",disabled:!r.trim()||j.isPending,onClick:()=>j.mutate(),children:[e("i",{"data-lucide":"download"}),"Install from path"]})]})}),e(ot,{title:"Pack inspector",subtitle:"Shows which workflows and hooks a pack contributes, alongside its current capability surface.",children:$e?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:at($e?.installed?.name||C)}),e(ve,{tone:"info",children:at($e?.installed?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e(ve,{tone:"ghost",children:[Number($e?.workflow_extensions?.workflow_count||0)," ","workflows"]}),e(ve,{tone:"ghost",children:[Number($e?.workflow_extensions?.workflow_hook_count||0)," ","hooks"]}),e(ve,{tone:"ghost",children:[Number($e?.risk?.required_capabilities_count||0)," ","required caps"]})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Entry Points"}),Vt($e?.workflow_extensions,"workflow_entrypoints").length?Vt($e?.workflow_extensions,"workflow_entrypoints").map((q,ge)=>e("div",{className:"tcp-list-item text-sm",children:at(q)},`${at(q)}-${ge}`)):e(je,{text:"This pack does not declare workflow entrypoints."})]}),e("details",{className:"tcp-list-item",children:[e("summary",{className:"cursor-pointer font-medium",children:"Manifest"}),e("pre",{className:"tcp-subtle mt-3 overflow-x-auto text-xs",children:jr($e?.manifest||{})})]})]}):e(je,{text:"Select an installed pack to inspect workflow extensions."})})]})}),e(En,{main:e(ot,{title:"Workflow viewer",subtitle:"Structured view of workflow steps and source provenance for the selected workflow.",actions:e("button",{className:"tcp-btn",disabled:!H||he.isPending,onClick:()=>H&&he.mutate(H),children:[e("i",{"data-lucide":"play"}),"Run workflow"]}),children:Le?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:at(Le?.name||H)}),e(ve,{tone:"info",children:at(Le?.source?.kind||"unknown")})]}),e("div",{className:"tcp-subtle text-sm",children:at(Le?.description||"No description provided.")})]}),e("div",{className:"grid gap-2",children:Vt(Le,"steps").length?Vt(Le,"steps").map((q,ge)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 text-xs uppercase tracking-[0.24em] text-slate-400",children:["Step ",ge+1]}),e("div",{className:"font-medium",children:at(q?.action||"unknown")}),q?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:jr(q.with)}):null]},at(q?.step_id||ge))):e(je,{text:"This workflow does not define any linear steps."})})]}):e(je,{text:"Select a workflow to inspect its current resolved definition."})}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Hook manager",subtitle:"Enable or disable hook bindings on the live registry and inspect the attached actions.",children:e("div",{className:"grid gap-2",children:re.length?re.map(q=>{const ge=at(q?.binding_id),Pe=!!q?.enabled;return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-2 flex items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-medium",children:at(q?.event||ge)}),e("div",{className:"tcp-subtle text-xs",children:ge})]}),e("button",{className:"tcp-btn",disabled:qe.isPending,onClick:()=>qe.mutate({bindingId:ge,enabled:!Pe}),children:Pe?"Disable":"Enable"})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e(ve,{tone:Om(Pe),children:Pe?"Enabled":"Disabled"}),e(ve,{tone:"ghost",children:[Vt(q,"actions").length," actions"]})]}),e("div",{className:"grid gap-1",children:Vt(q,"actions").map((Te,se)=>e("div",{className:"tcp-subtle text-xs",children:at(Te?.action||Te)},`${ge}-${se}`))})]},ge)}):e(je,{text:"The selected workflow has no registered hooks."})})}),e(ot,{title:"Recent workflow runs",subtitle:"Latest workflow executions for the selected workflow, including hook-triggered runs.",children:e("div",{className:"grid gap-2",children:xe.length?xe.map((q,ge)=>{const Pe=at(q?.status||"unknown"),Te=Pe==="completed"?"ok":Pe==="failed"?"err":Pe==="running"?"warn":"ghost";return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:at(q?.run_id||`run-${ge+1}`)}),e(ve,{tone:Te,children:Pe})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger: ",at(q?.trigger_event||"manual")]}),e("div",{className:"tcp-subtle text-xs",children:["actions: ",Vt(q,"actions").length]})]},at(q?.run_id||ge))}):e(je,{text:"No workflow runs have been recorded yet."})})})]})}),e(En,{main:e(ot,{title:"Workflow testing mode",subtitle:"Simulate a source event to see which hooks will match before triggering real actions.",actions:e("button",{className:"tcp-btn-primary",disabled:!N.trim()||ee.isPending,onClick:()=>ee.mutate(),children:[e("i",{"data-lucide":"flask-conical"}),"Simulate"]}),children:e("div",{className:"grid gap-3",children:[e("input",{className:"tcp-input",value:N,onInput:q=>E(q.target.value),placeholder:"context.task.created"}),e("textarea",{className:"tcp-input min-h-[180px] font-mono text-xs",value:x,onInput:q=>A(q.target.value),spellCheck:!1}),me?e("div",{className:"grid gap-3",children:[e("div",{className:"flex flex-wrap gap-2",children:Vt(me,"canonical_events").map((q,ge)=>e(ve,{tone:"info",children:at(q)},`${at(q)}-${ge}`))}),e("div",{className:"grid gap-2",children:Vt(me,"matched_bindings").length?Vt(me,"matched_bindings").map(q=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:at(q?.binding_id)}),e("div",{className:"tcp-subtle text-xs",children:[at(q?.event)," · ",Vt(q,"actions").length," ","actions"]})]},at(q?.binding_id))):e(je,{text:"No workflow hooks matched this event."})})]}):e(je,{text:"Run a simulation to inspect canonical events, matched bindings, and planned actions."})]})}),aside:e(ot,{title:"Triggered actions",subtitle:"Preview of actions the engine plans to execute for the simulated event.",children:e("div",{className:"grid gap-2",children:Vt(me,"planned_actions").length?Vt(me,"planned_actions").map((q,ge)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:at(q?.action||q)}),q?.with?e("pre",{className:"tcp-subtle mt-2 overflow-x-auto text-xs",children:jr(q.with)}):null]},`${at(q?.action||q)}-${ge}`)):e(je,{text:"No planned actions yet."})})})}),e(ot,{title:"Live workflow events",subtitle:"Real-time `workflow.*` events for the selected workflow, including run start, action completion, and failures.",actions:e("button",{className:"tcp-btn",onClick:()=>_([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear stream"]}),children:e("div",{className:"grid max-h-[28rem] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:O.length?[...O].reverse().map((q,ge)=>{const Pe=Em(q.data),Te=Pe.endsWith(".failed")?"err":Pe.endsWith(".completed")?"ok":Pe.endsWith(".started")?"warn":"info";return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:Pe}),e(ve,{tone:Te,children:new Date(q.at).toLocaleTimeString()})]}),e("div",{className:"tcp-subtle text-xs",children:["run: ",at(q.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle text-xs",children:["action:"," ",at(q.data?.properties?.action||q.data?.properties?.actionID||"-")]})]},`${q.at}-${ge}`)}):e(je,{text:"Run a workflow or trigger a hook to watch live workflow events here."})})})]})}function to(a){return a>=1?"bg-rose-500":a>=.8?"bg-amber-500":"bg-emerald-500"}function On(a,t){return!t||t<=0?0:Math.min(a/t,1)}function ir({label:a,used:t,max:n,unit:r,advisory:s=!1}){const c=On(t,n),d=s?c>=.8?"bg-sky-400":"bg-cyan-500":to(c);return e("div",{className:"grid gap-1",children:[e("div",{className:"flex items-center justify-between text-xs",children:[e("span",{className:"tcp-subtle",children:a}),e("span",{className:"font-mono text-[11px] text-slate-200",children:[t.toLocaleString(),r||""," / ",n.toLocaleString(),r||""]})]}),e("div",{className:"h-1.5 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${d}`,style:{width:`${c*100}%`}})})]})}function jm({budget:a}){const[t,n]=w(!1),r=a.limits_enforced===!1,s=Math.max(On(a.iterations_used,a.max_iterations),On(a.tokens_used,a.max_tokens),On(a.wall_time_secs,a.max_wall_time_secs),On(a.subagent_runs_used,a.max_subagent_runs));return e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("button",{className:"flex w-full items-center justify-between",onClick:()=>n(c=>!c),children:[e("div",{className:"text-sm font-medium",children:"Budget + Tokens"}),e("div",{className:"flex items-center gap-2",children:[e("div",{className:"h-2 w-24 overflow-hidden rounded-full bg-slate-800/80",children:e("div",{className:`h-full ${r?s>=.8?"bg-sky-400":"bg-cyan-500":to(s)}`,style:{width:`${s*100}%`}})}),e("span",{className:"tcp-subtle text-xs",children:[Math.round(s*100),"%"]})]})]}),t?e("div",{className:"mt-3 grid gap-3 border-t border-slate-700/60 pt-3",children:[e(ir,{label:"Iterations",used:a.iterations_used,max:a.max_iterations,advisory:r}),e(ir,{label:"Tokens",used:a.tokens_used,max:a.max_tokens,advisory:r}),e(ir,{label:"Wall time",used:a.wall_time_secs,max:a.max_wall_time_secs,unit:"s",advisory:r}),e(ir,{label:"Agent calls",used:a.subagent_runs_used,max:a.max_subagent_runs,advisory:r}),r?e("div",{className:"rounded border border-cyan-500/30 bg-cyan-950/20 p-2 text-xs text-cyan-100",children:"Advisory usage only. This run does not expose explicit enforced budget caps, so these limits are relaxed defaults for visibility."}):null,a.exceeded&&a.exceeded_reason?e("div",{className:"rounded border border-rose-500/40 bg-rose-950/30 p-2 text-xs text-rose-200",children:a.exceeded_reason}):null]}):null]})}function Gr(a,t=0){return String(a?.run_id||a?.runId||`run-${t}`).trim()}function Xs(a){const t=Number(a?.updated_at_ms||a?.updatedAtMs||0),n=Number(a?.created_at_ms||a?.createdAtMs||0),r=Number.isFinite(t)&&t>0?t:n;return Number.isFinite(r)&&r>0?r:0}function Um(a,t=""){const n=String(t||"").trim(),r=[...Array.isArray(a)?a:[]].sort((d,u)=>Xs(u)-Xs(d));if(n){const d=r.find((u,p)=>Gr(u,p)===n);if(d){const u=String(d?.status||"").trim().toLowerCase();if(!["completed","failed","cancelled"].includes(u))return n}}const c=r.find(d=>{const u=String(d?.status||"").trim().toLowerCase();return!["completed","failed","cancelled"].includes(u)})||r[0];return c?Gr(c):""}function Bm(a,t){if(t.type==="sync_runs"){const n={},r=[];for(let c=0;c<t.runs.length;c+=1){const d=t.runs[c],u=Gr(d,c);u&&(n[u]=d,r.push(u))}let s=a.selectedRunId;return s||(s=Um(t.runs,t.preferredRunId)),{runsById:n,orderedRunIds:r,selectedRunId:s,cursorsByRunId:a.cursorsByRunId}}if(t.type==="select_run")return{...a,selectedRunId:String(t.runId||"").trim()};if(t.type==="clear_selection")return{...a,selectedRunId:""};if(t.type==="advance_cursor"){const n=String(t.runId||"").trim();if(!n)return a;const r=Number(t.seq||0);if(!Number.isFinite(r)||r<=0)return a;const s=String(t.kind||"").trim().toLowerCase(),c=a.cursorsByRunId[n]||{eventSeq:0,patchSeq:0},d={eventSeq:s==="context_run_event"?Math.max(c.eventSeq,r):c.eventSeq,patchSeq:s==="blackboard_patch"?Math.max(c.patchSeq,r):c.patchSeq};return d.eventSeq===c.eventSeq&&d.patchSeq===c.patchSeq?a:{...a,cursorsByRunId:{...a.cursorsByRunId,[n]:d}}}return a}function Fm(a,t=""){const[n,r]=mo(Bm,{runsById:{},orderedRunIds:[],selectedRunId:"",cursorsByRunId:{}});fe(()=>{r({type:"sync_runs",runs:Array.isArray(a)?a:[],preferredRunId:t})},[a,t]);const s=F(()=>n.orderedRunIds.map(c=>n.runsById[c]).filter(Boolean),[n.orderedRunIds,n.runsById]);return{runsById:n.runsById,orderedRunIds:n.orderedRunIds,orderedRuns:s,selectedRunId:n.selectedRunId,cursorsByRunId:n.cursorsByRunId,setSelectedRunId:c=>r({type:"select_run",runId:c}),clearSelectedRunId:()=>r({type:"clear_selection"}),advanceCursor:(c,d,u)=>r({type:"advance_cursor",runId:c,kind:d,seq:u})}}function Lm(a){const t={},n={};for(const[c,d]of Object.entries(a||{})){const u=Number(d?.eventSeq||0),p=Number(d?.patchSeq||0);u>0&&(t[c]=u),p>0&&(n[c]=p)}const s=JSON.stringify({events:t,patches:n});return!s||s==='{"events":{},"patches":{}}'?"":btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function Km({workspace:a,runIds:t,cursorToken:n,onEnvelope:r,onError:s}){const c=F(()=>[...new Set((t||[]).map(u=>String(u||"").trim()).filter(Boolean))],[t]),d=F(()=>{const u=String(a||"").trim();if(!u||!c.length)return"";const p=new URLSearchParams;return p.set("workspace",u),p.set("runIds",c.join(",")),n&&p.set("cursor",n),`/api/orchestrator/events?${p.toString()}`},[n,c,a]);fe(()=>{if(!d)return;const u=es(d,p=>{let N=null;try{N=JSON.parse(String(p?.data||"{}"))}catch{return}!N||typeof N!="object"||r(N)},{onError:p=>{s&&s(p)}});return()=>u()},[r,s,d])}const Wm={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 Pa(a){const t=String(a||"").trim().toLowerCase();return t==="done"||t==="completed"||t==="active"?"tcp-badge-ok":t==="failed"||t==="error"||t==="cancelled"||t==="canceled"?"tcp-badge-err":t==="running"||t==="in_progress"||t==="runnable"?"tcp-badge-warn":"tcp-badge-info"}function zm(a){const t=String(a||"").trim().toLowerCase();return{created:"Created",pending:"Pending",runnable:"Ready",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"}[t]||t||"Unknown"}function Zs(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"Run":`Run ${new Date(t).toLocaleTimeString()}`}function Jm(a){return Number(a?.updated_at_ms||a?.created_at_ms||0)}function za(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"--:--:--":new Date(t).toLocaleTimeString()}function Qm(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"0 B":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Hm(a){const t=String(a||"").trim(),n=t.lastIndexOf(".");return n<0?"":t.slice(n+1).toLowerCase()}function Fn(a){const t=String(a||"").trim().replace(/\\/g,"/");return t?t.startsWith("/")?t.replace(/\/{2,}/g,"/"):t:""}function Gm(a,t){const n=Fn(a).replace(/\/+$/,""),r=Fn(t).replace(/^\/+/,"");return n?r?`${n}/${r}`:n:r}function ei(a,t){const n=Fn(a).replace(/\/+$/,""),r=Fn(t);return!n||!r?!1:r===n?!0:r.startsWith(`${n}/`)}function ti(a){const t=[a?.workspace?.canonical_path,a?.workspace?.path,a?.workspace?.root,a?.workspace_root,a?.workspacePath,a?.cwd,a?.path];for(const n of t){const r=Fn(String(n||""));if(r.startsWith("/"))return r}return""}function ai(a){const t={};for(const n of a){const r=String(n?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(r))continue;const s=String(n?.step_id||"").trim();if(!s)continue;const c=Number(n?.seq||0);!Number.isFinite(c)||c<=0||(t[s]=Math.max(Number(t[s]||0),c))}return t}function Vm(a){return String(a?.event_type||a?.type||a?.event||"workflow.event").trim().toLowerCase()}function ni(a){const t=[`type: ${String(a.type||"").trim()||"unknown"}`,`task: ${String(a.taskId||"").trim()||"n/a"}`,`title: ${String(a.title||"").trim()||"n/a"}`,`mode: ${String(a.mode||"").trim()||"strict"}`,`at: ${za(a.at)}`,"","reason:",String(a.reason||"").trim()||"No verification detail."],n=a.verification?.execution_trace;return n&&typeof n=="object"&&t.push("","execution_trace:",`session: ${String(n.session_id||"n/a")}`,`model: ${[String(n?.model?.provider||"").trim(),String(n?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"}`,`source: ${String(n?.model?.source||"n/a")}`),t.push("","verification_json:",JSON.stringify(a.verification||{},null,2)),t.join(`
|
|
2457
|
+
`)}function dn(a){const t=String(a?.task_id||a?.taskID||"").trim();if(t)return t;const n=a?.source_event_id||a?.sourceEventID,r=String(n||"").trim();if(!r)return"";const s=r.lastIndexOf(":");return s<0?"":r.slice(s+1).trim()}function Ym({api:a,toast:t,navigate:n}){const r=ca(),s=!!pi(),c=Rt(null),[d,u]=w(!0),[p,N]=w(!1),[E,x]=w(""),[A,O]=w(""),[_,z]=w(!1),[P,Q]=w(""),[B,ne]=w(""),[I,C]=w(!1),[H,M]=w("4"),[xe,y]=w("3"),[v,j]=w("swarm.blackboard.default"),[he,ee]=w(""),[qe,$e]=w(""),[Le,re]=w(""),[me,q]=w(""),[ge,Pe]=w([]),[Te,se]=w(""),[Oe,Me]=w(""),[He,Y]=w(""),[Ze,ae]=w(!1);fe(()=>{u(!0),rt()},[]);const Ae=V({queryKey:["swarm","status"],queryFn:()=>a("/api/orchestrator/status"),refetchInterval:5e3}),St=V({queryKey:["swarm","runs",A],queryFn:()=>a(`/api/orchestrator/runs?workspace=${encodeURIComponent(A||"")}`),refetchInterval:6e3,enabled:!!Ae.data}),oe=Array.isArray(St.data?.runs)?St.data.runs:[],W=Fm(oe,String(Ae.data?.runId||"").trim()),lt=W.selectedRunId,xt=W.setSelectedRunId,rt=W.clearSelectedRunId,Et=W.advanceCursor,Fe=d?"":String(lt||"").trim(),Bt=W.orderedRuns,At=F(()=>{if(!Fe)return null;for(const f of Bt)if(String(f?.run_id||f?.runId||"").trim()===Fe)return f;return null},[Bt,Fe]),$t=F(()=>Lm(W.cursorsByRunId),[W.cursorsByRunId]),We=String(A||Ae.data?.workspaceRoot||"").trim(),ze=F(()=>{const f=String(Fe||"").trim();return f?[f]:[]},[Fe]),tt=Rt(0),be=ft(f=>{const K=String(f?.kind||"").trim().toLowerCase(),pe=String(f?.run_id||f?.runId||"").trim();if(Fe&&pe&&pe!==Fe)return;const De=Number(f?.seq||0);pe&&De>0&&(K==="context_run_event"||K==="blackboard_patch")&&Et(pe,K,De);const Be=Date.now();Be-tt.current<900||(tt.current=Be,r.invalidateQueries({queryKey:["swarm","runs"]}),Fe&&r.invalidateQueries({queryKey:["swarm","run",Fe]}))},[Et,r,Fe]);Km({workspace:We,runIds:ze,cursorToken:$t,onEnvelope:be});const Se=V({queryKey:["swarm","run",Fe],queryFn:()=>a(`/api/orchestrator/run/${encodeURIComponent(Fe)}`),refetchInterval:4e3,enabled:!!Fe}),Ve=V({queryKey:["swarm","workspace-browser",P],enabled:_&&!!P,queryFn:()=>a(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(P)}`)}),ce=String(Se.data?.runStatus||Se.data?.run?.status||Ae.data?.status||"idle").trim().toLowerCase(),dt=F(()=>Ji(Se.data),[Se.data]),S=dt.tasks,G=F(()=>({...Wm,...Se.data?.budget||{}}),[Se.data?.budget]),ue=String(ti(Se.data?.run)||ti(At)||(Fe?"":String(Ae.data?.workspaceRoot||A||""))).trim();fe(()=>{ue&&($e(f=>!f||!ei(ue,f)?ue:f),re(f=>ei(ue,f)?f:""))},[ue]);const Ke=Array.isArray(Ve.data?.directories)?Ve.data.directories:[],l=String(B||"").trim().toLowerCase(),b=F(()=>l?Ke.filter(f=>String(f?.name||f?.path||"").trim().toLowerCase().includes(l)):Ke,[Ke,l]),T=String(Ve.data?.parent||"").trim(),R=String(Ve.data?.dir||P||"").trim(),$=V({queryKey:["swarm","workspace-files",ue,qe],enabled:!!ue&&!!qe,queryFn:async()=>{const f=await a(`/api/orchestrator/workspaces/files?workspaceRoot=${encodeURIComponent(ue)}&dir=${encodeURIComponent(qe)}`).catch(()=>({directories:[],files:[],parent:null,dir:qe})),K=Array.isArray(f?.directories)?f.directories:[],De=(Array.isArray(f?.files)?f.files:[]).map(Be=>{const it=String(Be?.path||"").trim();return{...Be,name:String(Be?.name||it||"file"),path:it||Gm(ue,String(Be?.name||""))}});return{ok:!0,dir:String(f?.dir||qe),parent:f?.parent||null,directories:K,files:De,fileAccessAllowed:!0}},refetchInterval:1e4}),Ye=V({queryKey:["swarm","workspace-file",ue,Le],enabled:!!ue&&!!Le,queryFn:async()=>a(`/api/orchestrator/workspaces/read?workspaceRoot=${encodeURIComponent(ue)}&path=${encodeURIComponent(Le)}`)}),Xe=Array.isArray($.data?.directories)?$.data.directories:[],Ot=Array.isArray($.data?.files)?$.data.files:[],Ft=String($.data?.parent||"").trim(),Ie=$.data?.fileAccessAllowed!==!1,Pt=String(Ye.data?.text||""),bt=Hm(Le),te=["md","markdown","mdx"].includes(bt),Ne=["html","htm"].includes(bt);fe(()=>{Ze&&!Ne&&ae(!1)},[Ne,Ze]);const h=F(()=>S.map(f=>`${f.id}:${f.state}:${f.error_message||""}`).join("|"),[S]),U=F(()=>S.find(f=>f.id===Oe)||null,[Oe,S]),J=F(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[];let K=null,pe=0;for(const De of f){const Be=String(De?.type||"").trim().toLowerCase();if(!["step_completed","task_completed"].includes(Be))continue;const it=De?.payload&&typeof De.payload=="object"?De.payload:{},_t=String(it?.session_id||"").trim();if(!_t)continue;const zt=Number(De?.ts_ms||0);(!K||zt>=pe)&&(K={sessionId:_t,event:De},pe=zt)}return K},[Se.data?.events]),L=F(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[];for(let K=f.length-1;K>=0;K-=1){const pe=f[K],De=String(pe?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(De))continue;const Be=pe?.payload&&typeof pe.payload=="object"?pe.payload:{},it=String(Be?.session_id||"").trim();if(it)return it}return String(J?.sessionId||"").trim()},[J?.sessionId,Se.data?.events]),X=F(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[],K=ai(f),pe=[];for(let De=f.length-1;De>=0;De-=1){const Be=f[De],it=String(Be?.type||"").trim().toLowerCase();if(!["task_started","task_completed","task_failed","step_started","step_completed","step_failed","run_resumed","run_paused","run_completed","run_failed"].includes(it))continue;const _t=Be?.payload&&typeof Be.payload=="object"?Be.payload:{},zt=String(Be?.step_id||"").trim(),oa=Number(Be?.seq||0);if((it==="task_failed"||it==="step_failed")&&zt&&Number.isFinite(oa)&&oa>0&&Number(K[zt]||0)>oa)continue;const Zt=String(_t?.step_title||Be?.step_id||it).trim(),va=String(_t?.why_next_step||_t?.error||"").trim();if(pe.push({id:`${String(Be?.seq||De)}-${it}`,type:it,title:Zt||it,detail:va,at:Number(Be?.ts_ms||0)}),pe.length>=12)break}return pe},[Se.data?.events]),ye=F(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[];for(let K=f.length-1;K>=0;K-=1){const pe=f[K],De=String(pe?.type||"").trim().toLowerCase();if(De==="plan_seeded_llm")return"llm";if(De==="plan_seeded_local")return"fallback_local";if(De==="plan_failed_llm_required")return"llm_failed"}return"unknown"},[Se.data?.events]),Ue=V({queryKey:["swarm","run-output-session",String(L||"")],queryFn:()=>a(`/api/engine/session/${encodeURIComponent(String(L||""))}`),refetchInterval:6e3,enabled:!!L}),st=F(()=>{const f=Ai(Ue.data,"Assistant");for(let K=f.length-1;K>=0;K-=1)if(f[K]?.role==="assistant"&&String(f[K]?.text||"").trim())return String(f[K]?.text||"").trim();return""},[Ue.data]),vt=F(()=>{const f=Array.isArray(Ue.data)?Ue.data:Array.isArray(Ue.data?.messages)?Ue.data.messages:[],K=[];for(let pe=f.length-1;pe>=0;pe-=1){const De=f[pe],Be=Array.isArray(De?.parts)?De.parts:[];for(let it=Be.length-1;it>=0;it-=1){const _t=Be[it];if(!String(_t?.type||_t?.part_type||"").trim().toLowerCase().includes("tool"))continue;const oa=String(_t?.tool||_t?.name||"").trim(),ka=String(_t?.state||_t?.status||"").trim(),Zt=String(_t?.error||"").trim(),va=[oa||"tool",ka||null,Zt?`err=${Zt}`:null].filter(Boolean).join(" · ");if(K.push(va),K.length>=10)return K}}return K},[Ue.data]),It=F(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[],K=ai(f),pe=[];for(let De=f.length-1;De>=0;De-=1){const Be=f[De],it=String(Be?.type||"").trim().toLowerCase();if(!["task_failed","step_failed","task_completed","step_completed"].includes(it))continue;const _t=Be?.payload&&typeof Be.payload=="object"?Be.payload:{},zt=String(Be?.step_id||"").trim(),oa=Number(Be?.seq||0);if((it==="task_failed"||it==="step_failed")&&zt&&Number.isFinite(oa)&&oa>0&&Number(K[zt]||0)>oa)continue;const Zt=_t?.verification&&typeof _t.verification=="object"?_t.verification:{},va=String(Zt?.reason||_t?.error||"").trim(),Ma=String(Zt?.mode||"strict").trim()||"strict";if(pe.push({id:`${String(Be?.seq||De)}-${it}`,taskId:zt,title:String(_t?.step_title||Be?.step_id||it),type:it,reason:va,mode:Ma,at:Number(Be?.ts_ms||0),verification:Zt}),pe.length>=8)break}return pe},[Se.data?.events]),et=F(()=>It.find(f=>f.id===He)||null,[He,It]);fe(()=>{if(!et&&!U&&!Ze||typeof document>"u")return;const f=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=f}},[et,U,Ze]);const yt=String(Se.data?.run?.workflowId||Se.data?.run?.workflow_id||At?.workflowId||At?.workflow_id||v||"").trim(),Lt=V({queryKey:["workflow","detail",yt],enabled:!!yt,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(yt)}`),refetchInterval:15e3}),Qt=V({queryKey:["workflow","runs",yt],enabled:!!yt,queryFn:()=>a(`/api/engine/workflows/runs?workflow_id=${encodeURIComponent(yt)}&limit=12`).catch(()=>({runs:[]})),refetchInterval:5e3}),Ct=Array.isArray(Qt.data?.runs)?Qt.data.runs:[],Ht=F(()=>{const f={};for(const K of Ct){const pe=dn(K);if(!pe)continue;const De=f[pe]||{runs:0,failed:0};De.runs+=1,String(K?.status||"").trim().toLowerCase()==="failed"&&(De.failed+=1),f[pe]=De}return f},[Ct]),kt=F(()=>Te?Ct.filter(f=>dn(f)===Te):Ct,[Te,Ct]),Ge=F(()=>{const f=[];for(const K of kt){const pe=String(K?.run_id||"").trim(),De=dn(K);for(const Be of Array.isArray(K?.actions)?K.actions:[])f.push({id:`${pe}:${String(Be?.action_id||Be?.action||f.length)}`,runId:pe,action:String(Be?.action||"unknown action"),status:String(Be?.status||"unknown"),detail:String(Be?.detail||""),output:Be?.output,updatedAt:Number(Be?.updated_at_ms||K?.updated_at_ms||0),taskId:String(Be?.task_id||De||"").trim()})}return f.sort((K,pe)=>pe.updatedAt-K.updatedAt),f},[kt]);fe(()=>{const f=kt;if(!f.length){q("");return}f.some(pe=>{const De=String(pe?.run_id||"").trim();return De&&De===me})||q(String(f[0]?.run_id||"").trim())},[kt,me]);const Ce=V({queryKey:["workflow","run",me],enabled:!!me,queryFn:()=>a(`/api/engine/workflows/runs/${encodeURIComponent(me)}`),refetchInterval:5e3}).data?.run||null;fe(()=>{const f=dn(Ce);f&&se(f)},[Ce?.run_id,Ce?.source_event_id]),fe(()=>{Pe([])},[yt]),en(`/api/engine/workflows/events${yt?`?workflow_id=${encodeURIComponent(yt)}`:""}`,f=>{try{const K=JSON.parse(f.data);if(K?.status==="ready")return;Pe(pe=>[...pe.slice(-79),{at:Date.now(),data:K}])}catch{}},{enabled:!!yt});const we=ke({mutationFn:()=>{const f=String(E||"").trim(),K=String(A||"").trim();if(!f)throw new Error("Enter a prompt first.");if(!K)throw new Error("Set workspace path first.");return a("/api/orchestrator/start",{method:"POST",body:JSON.stringify({objective:f,workspaceRoot:K,maxTasks:Number(H||4),maxAgents:Number(xe||3),workflowId:String(v||"swarm.blackboard.default").trim(),requireLlmPlan:!0,allowLocalPlannerFallback:!1,verificationMode:"strict"})})},onSuccess:async f=>{const K=String(f?.runId||"").trim();K&&xt(K),u(!1),t("ok","Planning started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),ut=ke({mutationFn:({path:f,body:K})=>a(f,{method:"POST",body:JSON.stringify(K)}),onSuccess:async(f,K)=>{if(K.path==="/api/orchestrator/request_revision"){const pe=String(f?.runId||"").trim();pe&&(xt(pe),ee("")),t("ok","Reworked plan created.")}K.path==="/api/orchestrator/approve"&&t("ok","Execution started."),await r.invalidateQueries({queryKey:["swarm"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),Qe=ke({mutationFn:async f=>{const K=String(f||"").trim();if(!K)throw new Error("Missing run id.");return await a("/api/orchestrator/cancel",{method:"POST",body:JSON.stringify({runId:K})}).catch(()=>null),await a("/api/orchestrator/runs/hide",{method:"POST",body:JSON.stringify({runIds:[K]})}).catch(()=>null),K},onSuccess:async()=>{rt(),u(!0),ee(""),x(""),t("ok","Discarded pending plan. You can start a new prompt now."),await r.invalidateQueries({queryKey:["swarm"]})},onError:f=>t("err",f instanceof Error?f.message:String(f))}),qt=ft(()=>{u(!0),rt(),N(!1),ee("")},[rt]);fe(()=>{const f=c.current;f&&xa(f)},[d,p,Bt,Fe,ce,qe,Xe.length,Ot.length,Le,Pt,Oe,He,Ze,h]);const ia=!Fe,ba=ce==="planning"||ce==="queued",Kt=ce==="awaiting_approval",Gt=["completed","failed","cancelled"].includes(ce),mt=ce==="running",ua=ce==="paused",na=ce==="failed"||ce==="blocked",Nt=["queued","planning","awaiting_approval","running","paused","blocked"].includes(ce),Je=e(la,{children:[e(Re.aside,{className:`chat-sessions-panel ${p?"open":""}`,initial:!1,animate:s?{x:p?0:"-104%"}:{x:p?0:"-104%",transition:{duration:.18,ease:"easeOut"}},children:[e("div",{className:"chat-sessions-header",children:[e("h3",{className:"chat-sessions-title",children:[e("i",{"data-lucide":"history"}),"History"]}),e("div",{className:"flex items-center gap-1",children:e("button",{type:"button",className:"tcp-btn h-8 px-2.5 text-xs",onClick:()=>{r.invalidateQueries({queryKey:["swarm","runs"]})},children:e("i",{"data-lucide":"refresh-cw"})})})]}),e("div",{className:"chat-session-list",children:[e(Mt,{children:Bt.map((f,K)=>{const pe=String(f?.run_id||f?.runId||`run-${K}`),De=pe===Fe;return e(Re.div,{className:"chat-session-row",initial:s?!1:{opacity:0,y:6},animate:s?void 0:{opacity:1,y:0},exit:s?void 0:{opacity:0,y:-6},children:e("button",{type:"button",className:`chat-session-btn ${De?"active":""}`,onClick:()=>{u(!1),xt(pe),N(!1)},children:[e("span",{className:"mb-0.5 inline-flex items-center gap-1 text-xs font-medium",children:[e("i",{"data-lucide":"history"}),e("span",{children:Zs(Jm(f))})]}),e("span",{className:"tcp-subtle line-clamp-2 block text-[11px]",children:String(f?.objective||"").trim()||"No objective"})]})},pe)})}),Bt.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No runs yet."})]})]}),e(Mt,{children:p?e(Re.button,{type:"button",className:"chat-scrim open","aria-label":"Close history",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},onClick:()=>N(!1)}):null})]});if(ia){const f=String(E||"").trim().length>0&&String(A||"").trim().length>0;return e(la,{children:[e("div",{ref:c,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[Je,e("div",{className:"min-h-0 min-w-0 w-full",children:e("div",{className:"flex h-full min-h-0 w-full flex-col gap-4 p-4 md:p-5",children:[e("div",{className:"mb-3",children:[e("div",{className:"inline-flex items-center gap-2 text-sm font-semibold",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"History",onClick:()=>N(K=>!K),children:e("i",{"data-lucide":"history"})}),e("span",{children:"Orchestrator"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Describe the goal. The planner will build a task board."})]}),e("div",{className:"grid min-h-0 flex-1 w-full content-start gap-3",children:[e("textarea",{className:"tcp-input min-h-[360px] md:min-h-[52vh]",placeholder:"What do you want the agents to build?",value:E,onInput:K=>x(K.target.value)}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr]",children:[e("button",{className:"tcp-btn",onClick:()=>{const K=String(A||Ae.data?.workspaceRoot||"/").trim();Q(K||"/"),ne(""),z(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,placeholder:"No workspace selected. Use Browse.",value:A})]}),e("div",{className:"tcp-subtle text-xs",children:["Selected folder: ",A||"none"]}),A?null:e("div",{className:"rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"Select a workspace folder before sending."}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("button",{className:"tcp-btn-primary",onClick:()=>we.mutate(),disabled:we.isPending||!f,children:[e("i",{"data-lucide":"send"}),"Send"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>C(K=>!K),children:[e("i",{"data-lucide":"sliders-horizontal"}),I?"Hide Advanced":"Show Advanced"]})]}),I?e("div",{className:"grid gap-2 rounded-lg border border-slate-700/60 bg-slate-900/20 p-2 md:grid-cols-3",children:[e("input",{className:"tcp-input",type:"number",min:"1",value:H,onInput:K=>M(K.target.value),title:"max tasks"}),e("input",{className:"tcp-input",type:"number",min:"1",max:"16",value:xe,onInput:K=>y(K.target.value),title:"max agents"}),e("input",{className:"tcp-input",value:v,onInput:K=>j(K.target.value),title:"workflow id"}),e("div",{className:"tcp-subtle md:col-span-3 text-xs",children:"Workflow id controls task routing template. Keep default unless you have a custom workflow."})]}):null]})]})})]}),_?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",R||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{T&&Q(T)},disabled:!T,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{R&&(O(R),z(!1),ne(""),t("ok",`Workspace selected: ${R}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{z(!1),ne("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:B,onInput:K=>ne(K.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:b.length?b.map(K=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Q(String(K?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(K?.name||K?.path||"")]},String(K?.path||K?.name))):e(je,{text:l?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}return e(la,{children:[e("div",{ref:c,className:"chat-layout min-w-0 min-h-0 h-full w-full flex-1",children:[Je,e("div",{className:"min-h-0 min-w-0 w-full",children:e("div",{className:"grid h-full min-h-[calc(100vh-240px)] min-w-0 w-full gap-5 p-4 md:p-5 xl:grid-cols-[1.05fr_1fr]",children:[e("div",{className:"flex h-full min-h-0 w-full flex-col gap-3",children:[e("div",{className:"mb-3",children:[e("div",{className:"inline-flex items-center gap-2 text-sm font-semibold",children:[e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"History",onClick:()=>N(f=>!f),children:e("i",{"data-lucide":"history"})}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8",title:"Back to start",onClick:qt,children:e("i",{"data-lucide":"arrow-left-to-line"})}),e("span",{children:"Orchestration Run"})]}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Plan review and execution"})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Pa(ce),children:ce||"unknown"}),e("span",{className:"inline-flex items-center gap-1 tcp-subtle",children:[e("i",{"data-lucide":"history"}),e("span",{children:Zs(Se.data?.run?.updated_at_ms||Se.data?.run?.created_at_ms)})]}),e("span",{className:"tcp-subtle",children:["id: ",Fe]}),e("span",{className:"tcp-subtle",children:["plan: ",ye]})]}),ba?e("div",{className:"mb-3 rounded-xl border border-slate-700/60 bg-slate-900/25 p-3",children:[e("div",{className:"mb-1 text-sm font-medium",children:"Planner is formulating a plan..."}),e("div",{className:"tcp-subtle text-xs",children:"Waiting for tasks to be generated."})]}):null,Kt?e("div",{className:"mb-3 rounded-xl border border-amber-500/40 bg-amber-950/20 p-3",children:[e("div",{className:"mb-2 text-sm font-medium text-amber-200",children:"Plan Ready"}),e("div",{className:"mb-2 text-xs text-amber-100/90",children:"Review the kanban. Request a rework or execute."}),e("textarea",{className:"tcp-input mb-2 min-h-[80px]",placeholder:"Feedback to rework the plan...",value:he,onInput:f=>ee(f.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",disabled:!he.trim(),onClick:()=>ut.mutate({path:"/api/orchestrator/request_revision",body:{runId:Fe,feedback:he,maxTasks:Number(H||4),maxAgents:Number(xe||3),workflowId:v}}),children:[e("i",{"data-lucide":"pencil"}),"Rework Plan"]}),e("button",{className:"tcp-btn-primary",onClick:()=>ut.mutate({path:"/api/orchestrator/approve",body:{runId:Fe}}),children:[e("i",{"data-lucide":"play"}),"Execute Plan"]}),e("button",{className:"tcp-btn-danger",disabled:Qe.isPending,onClick:()=>Qe.mutate(Fe),children:[e("i",{"data-lucide":"trash-2"}),"Discard Plan"]})]})]}):null,!ba&&!Kt?e("div",{className:"mb-3 flex flex-wrap gap-2",children:[mt?e("button",{className:"tcp-btn",onClick:()=>ut.mutate({path:"/api/orchestrator/pause",body:{runId:Fe}}),children:[e("i",{"data-lucide":"square"}),"Pause"]}):null,ua?e("button",{className:"tcp-btn",onClick:()=>ut.mutate({path:"/api/orchestrator/resume",body:{runId:Fe}}),children:[e("i",{"data-lucide":"play"}),"Resume"]}):null,na?e("button",{className:"tcp-btn",onClick:()=>ut.mutate({path:"/api/orchestrator/continue",body:{runId:Fe}}),children:[e("i",{"data-lucide":"rotate-cw"}),"Continue Run"]}):null,Nt?e("button",{className:"tcp-btn-danger",onClick:()=>ut.mutate({path:"/api/orchestrator/cancel",body:{runId:Fe}}),children:[e("i",{"data-lucide":"x"}),"Cancel"]}):null,e("button",{className:"tcp-btn",onClick:qt,children:[e("i",{"data-lucide":"plus"}),"New Prompt"]})]}):null,Gt?e("div",{className:"mb-3 rounded-lg border border-slate-700/60 bg-slate-900/25 p-2 text-xs tcp-subtle",children:ce==="failed"?"This run is failed. Continue the run or retry a failed task.":`This run is ${ce}. Start a new prompt to continue.`}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workspace Files"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Refresh","aria-label":"Refresh",onClick:()=>{$.refetch()},disabled:!ue,children:e("i",{"data-lucide":"refresh-cw"})})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Up","aria-label":"Up",disabled:!Ft,onClick:()=>{Ft&&$e(Ft)},children:e("i",{"data-lucide":"arrow-up-circle"})}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Root","aria-label":"Root",disabled:!ue,onClick:()=>{ue&&$e(ue)},children:e("i",{"data-lucide":"home"})})]}),e("div",{className:"mb-2 tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:qe||ue||"No workspace"}),Ie?null:e("div",{className:"mb-2 rounded-lg border border-amber-400/40 bg-amber-950/20 p-2 text-xs text-amber-200",children:"File listing for this workspace is not exposed by the current server scope. Directory navigation still works."}),e("div",{className:"grid max-h-[220px] min-h-0 gap-1 overflow-auto",children:[Xe.map(f=>{const K=String(f?.path||"");return e("button",{className:"tcp-list-item text-left",onClick:()=>$e(K),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(f?.name||K)})]})},`dir-${K}`)}),Ot.map(f=>{const K=String(f?.path||"");return e("button",{className:`tcp-list-item text-left ${K===Le?"border-amber-400/70":""}`,onClick:()=>re(K),children:e("div",{className:"flex items-center justify-between gap-2",children:[e("span",{className:"inline-flex min-w-0 items-center gap-2",children:[e("i",{"data-lucide":"file-up"}),e("span",{className:"truncate",children:String(f?.name||K)})]}),e("span",{className:"tcp-subtle shrink-0 text-[11px]",children:Qm(f?.size)})]})},`file-${K}`)}),!Xe.length&&!Ot.length?e(je,{text:"No files or folders in this workspace location."}):null]})]}),Le?e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"File Preview"}),e("div",{className:"flex items-center gap-2",children:[Ne?e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>ae(!0),children:[e("i",{"data-lucide":"fullscreen"}),"Fullscreen"]}):null,e("span",{className:"tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:Le})]})]}),Ye.isLoading?e("div",{className:"tcp-subtle text-xs",children:"Loading file..."}):Ne?e("div",{className:"max-h-[420px] overflow-auto rounded-lg border border-slate-700/60 bg-black",children:e("iframe",{className:"h-[420px] w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:Pt,title:Le,scrolling:"yes"})}):te?e("div",{className:"tcp-markdown tcp-markdown-ai max-h-[260px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-950/40 p-3",dangerouslySetInnerHTML:{__html:pn(Pt)}}):e("pre",{className:"tcp-code max-h-[260px] overflow-auto whitespace-pre-wrap break-words",children:Pt||"No text content."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Executor Verification"})}),It.length?e("div",{className:"grid max-h-44 gap-2 overflow-auto",children:It.map(f=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Pa(f.type.includes("failed")?"failed":"running"),children:f.type}),e("span",{className:"tcp-subtle",children:["mode: ",f.mode]})]}),e("div",{className:"font-medium",children:f.title}),e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:f.reason||"No verification detail."}),e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Y(f.id),children:[e("i",{"data-lucide":"search"}),"View details"]}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(ni(f)),t("ok","Copied verification feedback.")}catch(K){t("err",K instanceof Error?K.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),f.verification?.execution_trace?e("div",{className:"mt-2 rounded border border-slate-700/50 bg-slate-950/40 p-2 tcp-subtle",children:[e("div",{children:["session:"," ",String(f.verification?.execution_trace?.session_id||"n/a")]}),e("div",{children:["model:"," ",[String(f.verification?.execution_trace?.model?.provider||"").trim(),String(f.verification?.execution_trace?.model?.model_id||"").trim()].filter(Boolean).join(" / ")||"unknown"]}),e("div",{children:["source:"," ",String(f.verification?.execution_trace?.model?.source||"n/a")]})]}):null]},f.id))}):e("div",{className:"tcp-subtle text-xs",children:"No verification telemetry yet."})]}),e("div",{className:"mt-3 grid gap-3 xl:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Live Activity"}),e("span",{className:"tcp-subtle text-xs",children:za(Date.now())})]}),X.length?e("div",{className:"grid max-h-40 gap-2 overflow-auto",children:X.map(f=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Pa(f.type.includes("failed")?"failed":"running"),children:f.type}),e("span",{className:"tcp-subtle",children:za(f.at)})]}),e("div",{className:"font-medium",children:f.title}),e("div",{className:"tcp-subtle",children:f.detail||"No additional detail."})]},f.id))}):e("div",{className:"tcp-subtle text-xs",children:"No activity events yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:e("div",{className:"font-medium",children:"Latest Output"})}),L?e(la,{children:[e("div",{className:"tcp-code max-h-28 overflow-auto whitespace-pre-wrap break-words",children:st||"No assistant output text yet."}),e("div",{className:"mt-2 tcp-subtle text-xs",children:"Recent tool calls"}),e("div",{className:"tcp-code mt-1 max-h-24 overflow-auto whitespace-pre-wrap break-words",children:vt.length?vt.join(`
|
|
2458
|
+
`):"No tool call records found in current session yet."})]}):e("div",{className:"tcp-subtle text-xs",children:"No completed step output session yet."})]})]})]}),e("div",{className:"flex h-full min-h-0 w-full flex-col gap-3",children:[e("div",{className:"mb-3",children:[e("div",{className:"text-sm font-semibold",children:"Kanban + Budget"}),e("div",{className:"tcp-subtle mt-1 text-sm",children:"Tasks activate after execute"})]}),e("div",{className:"mb-3",children:e(jm,{budget:G})}),e(Qi,{tasks:S,currentTaskId:dt.currentTaskId,selectedTaskId:Te,workflowSummaryByTaskId:Ht,onTaskSelect:f=>{const K=Te===f.id?"":f.id;se(K),Me(f.id)},onRetryTask:f=>ut.mutate({path:"/api/orchestrator/retry",body:{runId:Fe,stepId:f.id}})}),Te?e("div",{className:"mt-3 rounded-xl border border-cyan-700/50 bg-cyan-950/20 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Selected Task Workflow Link"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>se(""),children:"Clear task focus"})]}),e("div",{className:"tcp-subtle text-xs",children:["Task ",e("strong",{children:Te})," is filtering workflow runs and event stream."]})]}):null,Te?e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Task Workflow Artifacts"}),e("span",{className:"tcp-subtle text-xs",children:[Ge.length," actions"]})]}),Ge.length?e("div",{className:"grid max-h-56 gap-2 overflow-auto",children:Ge.map(f=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:f.action}),e("span",{className:Pa(f.status),children:f.status})]}),e("div",{className:"tcp-subtle",children:["run: ",f.runId]}),e("div",{className:"tcp-subtle",children:["updated: ",za(f.updatedAt)]}),f.detail?e("div",{className:"mt-1 text-rose-200",children:f.detail}):null,f.output?e("pre",{className:"tcp-code mt-2 max-h-28 overflow-auto whitespace-pre-wrap break-words",children:JSON.stringify(f.output,null,2)}):null]},f.id))}):e("div",{className:"tcp-subtle text-xs",children:"No workflow action artifacts are linked to this task yet."})]}):null,e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workflow Automation"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>n("packs-detail"),children:"Open Workflow Lab"})]}),e("div",{className:"mb-2 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:"tcp-badge-info",children:yt||"no workflow id"}),e("span",{className:"tcp-subtle",children:Array.isArray(Lt.data?.workflow?.steps)?`${Lt.data.workflow.steps.length} steps`:"workflow metadata pending"}),e("span",{className:"tcp-subtle",children:Array.isArray(Lt.data?.hooks)?`${Lt.data.hooks.length} hooks`:""})]}),e("div",{className:"grid gap-3 xl:grid-cols-[0.85fr_1.15fr]",children:[e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Runs"}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:kt.length?kt.map((f,K)=>{const pe=String(f?.run_id||`workflow-run-${K}`).trim(),De=pe===me,Be=String(f?.status||"unknown").trim(),it=dn(f);return e("button",{type:"button",className:`tcp-list-item text-left ${De?"border-amber-400/70":""}`,onClick:()=>q(pe),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:pe}),e("span",{className:Pa(Be),children:Be})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger:"," ",String(f?.trigger_event||"manual").trim()||"manual"]}),e("div",{className:"tcp-subtle text-xs",children:["task: ",it||"n/a"]}),e("div",{className:"tcp-subtle text-xs",children:["actions:"," ",Array.isArray(f?.actions)?f.actions.length:0]})]},pe)}):e(je,{text:Te?"No workflow runs are linked to the selected task yet.":"No workflow runs recorded for this orchestration workflow yet."})})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-xs uppercase tracking-[0.24em]",children:"Workflow Run Drilldown"}),Ce?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Pa(String(Ce?.status||"unknown")),children:String(Ce?.status||"unknown")}),e("span",{className:"tcp-subtle",children:["trigger: ",String(Ce?.trigger_event||"manual")]}),e("span",{className:"tcp-subtle",children:["source: ",String(Ce?.source_event_id||"n/a")]})]}),e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:Array.isArray(Ce?.actions)&&Ce.actions.length?Ce.actions.map((f,K)=>e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:"font-medium",children:String(f?.action||"unknown action")}),e("span",{className:Pa(String(f?.status||"unknown")),children:String(f?.status||"unknown")})]}),e("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e("span",{className:"tcp-subtle",children:["task:"," ",String(f?.task_id||Ce?.task_id||"n/a")]}),String(f?.task_id||Ce?.task_id||"").trim()?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>se(String(f?.task_id||Ce?.task_id||"").trim()),children:"Focus task"}):null]}),e("div",{className:"tcp-subtle",children:["started: ",za(f?.started_at_ms)]}),e("div",{className:"tcp-subtle",children:["finished: ",za(f?.finished_at_ms)]}),String(f?.error||"").trim()?e("div",{className:"mt-1 text-rose-200",children:String(f.error)}):null]},`${String(f?.action||"action")}-${K}`)):e("div",{className:"tcp-subtle text-xs",children:"No recorded workflow actions for this run."})})]}):e(je,{text:"Select a workflow run to inspect its action timeline."})]})]})]}),e("div",{className:"mt-3 rounded-xl border border-slate-700/60 bg-slate-900/30 p-3",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Workflow Event Stream"}),e("button",{type:"button",className:"chat-icon-btn h-7 w-7",title:"Clear workflow events","aria-label":"Clear workflow events",onClick:()=>Pe([]),children:e("i",{"data-lucide":"trash-2"})})]}),ge.length?e("div",{className:"grid max-h-48 gap-2 overflow-auto",children:[...ge].filter(f=>{const K=dn(f.data?.properties||{});if(Te&&K&&K!==Te)return!1;if(!me)return!0;const pe=String(f.data?.properties?.runID||"").trim();return!pe||pe===me}).reverse().map((f,K)=>{const pe=Vm(f.data);return e("div",{className:"rounded border border-slate-700/60 p-2 text-xs",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("span",{className:Pa(pe.endsWith(".failed")?"failed":pe.endsWith(".completed")?"completed":"running"),children:pe}),e("span",{className:"tcp-subtle",children:za(f.at)})]}),e("div",{className:"tcp-subtle",children:["run: ",String(f.data?.properties?.runID||"n/a")]}),e("div",{className:"tcp-subtle",children:["action:"," ",String(f.data?.properties?.action||f.data?.properties?.actionID||"-")]})]},`${f.at}-${K}`)})}):e("div",{className:"tcp-subtle text-xs",children:"No workflow events streamed for this run yet."})]}),e(Mt,{children:[U?e(Re.div,{className:"tcp-confirm-overlay",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close task details",onClick:()=>Me("")}),e(Re.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:s?!1:{opacity:0,y:8,scale:.98},animate:s?void 0:{opacity:1,y:0,scale:1},exit:s?void 0:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Kanban Task Details"}),e("p",{className:"tcp-confirm-message",children:"Full task brief, dependencies, and runtime context for this kanban item."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>Me(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Pa(U.state),children:zm(U.state)}),e("span",{className:"tcp-badge-info",children:U.id}),U.assigned_role?e("span",{className:"tcp-subtle",children:["role: ",U.assigned_role]}):null,U.gate?e("span",{className:"tcp-subtle",children:["gate: ",U.gate]}):null,U.workflow_id?e("span",{className:"tcp-subtle",children:["workflow: ",U.workflow_id]}):null,U.session_id?e("span",{className:"tcp-subtle",children:["session: ",U.session_id]}):null]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Title"}),e("div",{className:"rounded-lg border border-slate-800/80 bg-slate-950/70 px-3 py-2 text-sm text-slate-100",children:U.title||"Untitled task"})]}),U.description?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Description"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:U.description})]}):null,e("div",{className:"grid gap-3 lg:grid-cols-2",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Dependencies"}),U.dependencies.length?e("div",{className:"flex flex-wrap gap-2",children:U.dependencies.map(f=>e("span",{className:"rounded border border-slate-700/60 px-2 py-1 text-xs text-slate-200",children:["<-"," ",f]},`${U.id}-${f}`))}):e("div",{className:"tcp-subtle text-sm",children:"No blocking dependencies."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Runtime Context"}),e("div",{className:"grid gap-2 text-sm",children:[e("div",{className:"tcp-subtle",children:["runtime status: ",U.runtime_status||"n/a"]}),e("div",{className:"tcp-subtle",children:["retry count: ",Number(U.retry_count||0)]}),Ht?.[U.id]?e("div",{className:"tcp-subtle",children:["workflow runs:"," ",Ht[U.id].runs,Ht[U.id].failed?`, failed ${Ht[U.id].failed}`:""]}):null,U.runtime_detail?e("div",{className:"tcp-subtle whitespace-pre-wrap break-words",children:["detail: ",U.runtime_detail]}):null]})]})]}),String(U.error_message||"").trim()?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Error"}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words text-rose-100",children:String(U.error_message||"").trim()})]}):null]}),e("div",{className:"tcp-confirm-actions mt-4",children:[e("button",{className:"tcp-btn",onClick:()=>{se(U.id),Me("")},children:"Focus task"}),e("button",{className:"tcp-btn",onClick:()=>Me(""),children:"Close"})]})]})]}):null,et?e(Re.div,{className:"tcp-confirm-overlay",initial:s?!1:{opacity:0},animate:s?void 0:{opacity:1},exit:s?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close verification details",onClick:()=>Y("")}),e(Re.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:s?!1:{opacity:0,y:8,scale:.98},animate:s?void 0:{opacity:1,y:0,scale:1},exit:s?void 0:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:"Executor Verification Details"}),e("p",{className:"tcp-confirm-message",children:"Raw verification and execution trace for debugging task feedback."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>Y(""),children:e("i",{"data-lucide":"x"})})]}),e("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs",children:[e("span",{className:Pa(et.type.includes("failed")?"failed":"running"),children:et.type}),e("span",{className:"tcp-badge-info",children:et.title}),e("span",{className:"tcp-subtle",children:["task: ",et.taskId||"n/a"]}),e("span",{className:"tcp-subtle",children:["mode: ",et.mode]}),e("span",{className:"tcp-subtle",children:["time: ",za(et.at)]})]}),e("div",{className:"tcp-verification-content grid gap-3",children:[e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Feedback"}),e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:async()=>{try{await navigator.clipboard.writeText(ni(et)),t("ok","Copied verification feedback.")}catch(f){t("err",f instanceof Error?f.message:"Copy failed.")}},children:[e("i",{"data-lucide":"copy-plus"}),"Copy feedback"]})]}),e("pre",{className:"tcp-code tcp-verification-feedback whitespace-pre-wrap break-words",children:et.reason||"No verification detail."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-950/30 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Verification JSON"}),e("pre",{className:"tcp-code tcp-verification-code whitespace-pre-wrap break-words",children:JSON.stringify(et.verification||{},null,2)})]})]}),e("div",{className:"tcp-confirm-actions mt-4",children:e("button",{className:"tcp-btn",onClick:()=>Y(""),children:"Close"})})]})]}):null]})]})]})})]}),e(Mt,{children:Ze&&Le&&Ne?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>ae(!1),children:e(Re.div,{className:"relative h-[calc(100dvh-1rem)] w-[calc(100vw-1rem)] overflow-hidden rounded-[1.4rem] border border-slate-700/70 bg-slate-950 shadow-[0_28px_64px_rgba(0,0,0,0.55)]",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},onClick:f=>f.stopPropagation(),children:[e("div",{className:"flex items-center justify-between gap-3 border-b border-slate-800/80 px-5 py-4",children:[e("div",{className:"min-w-0",children:[e("div",{className:"text-lg font-semibold text-slate-100",children:"Fullscreen Preview"}),e("div",{className:"tcp-subtle mt-1 text-xs",style:{overflowWrap:"anywhere"},children:Le})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{Ye.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]}),e("button",{type:"button",className:"chat-icon-btn h-8 w-8","aria-label":"Close preview",title:"Close preview",onClick:()=>ae(!1),children:e("i",{"data-lucide":"x"})})]})]}),e("div",{className:"h-[calc(100%-4.5rem)] p-3",children:e("div",{className:"h-full overflow-auto rounded-xl border border-slate-700/60 bg-black",children:e("iframe",{className:"h-full w-full bg-black",sandbox:"allow-scripts allow-forms allow-pointer-lock allow-modals allow-downloads",allow:"fullscreen; autoplay; clipboard-write",allowFullScreen:!0,srcDoc:Pt,title:`${Le} fullscreen preview`,scrolling:"yes"})})})]})}):null}),_?e("div",{className:"tcp-confirm-overlay",children:e("div",{className:"tcp-confirm-dialog max-w-2xl",children:[e("h3",{className:"tcp-confirm-title",children:"Select Workspace Folder"}),e("p",{className:"tcp-confirm-message",children:["Current: ",R||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{T&&Q(T)},disabled:!T,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{R&&(O(R),z(!1),ne(""),t("ok",`Workspace selected: ${R}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{z(!1),ne("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:B,onInput:f=>ne(f.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:b.length?b.map(f=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Q(String(f?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(f?.name||f?.path||"")]},String(f?.path||f?.name))):e(je,{text:l?"No folders match your search.":"No subdirectories in this folder."})})]})}):null]})}function Xm(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Zm({api:a,toast:t}){const n=ca(),[r,s]=w("uploads"),c=V({queryKey:["files",r],queryFn:()=>a(`/api/files/list?dir=${encodeURIComponent(r)}`).catch(()=>({files:[]})),refetchInterval:12e3}),d=ke({mutationFn:p=>a("/api/files/delete",{method:"POST",body:JSON.stringify({path:p})}),onSuccess:async()=>{t("ok","File removed."),await n.invalidateQueries({queryKey:["files",r]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),u=Xm(c.data,"files");return e("div",{className:"grid gap-4",children:e(Yt,{title:"Files",subtitle:"Browse and delete uploaded files",children:[e("div",{className:"mb-3 flex gap-2",children:[e("input",{className:"tcp-input",value:r,onInput:p=>s(p.target.value),placeholder:"uploads"}),e("button",{className:"tcp-btn",onClick:()=>c.refetch(),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("div",{className:"grid gap-2",children:u.length?u.map((p,N)=>{const E=String(p?.path||p?.name||`file-${N}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{className:"truncate",children:E}),e("span",{className:"tcp-subtle text-xs",children:[String(p?.size||0)," bytes"]})]}),e("div",{className:"mt-2",children:e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>d.mutate(E),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})})]},E)}):e(je,{text:"No files found for this directory."})})]})})}function ep(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function tp({client:a,toast:t}){const n=ca(),[r,s]=w(""),[c,d]=w(null),u=V({queryKey:["memory",r],queryFn:()=>(r.trim()?a.memory.search({query:r,limit:40}):a.memory.list({q:"",limit:40})).catch(()=>({items:[]})),refetchInterval:15e3}),p=ke({mutationFn:x=>a.memory.delete(x),onSuccess:async()=>{t("ok","Memory record deleted."),await n.invalidateQueries({queryKey:["memory"]})},onError:x=>t("err",x instanceof Error?x.message:String(x))}),N=ep(u.data,"items"),E=F(()=>N.map((x,A)=>{const O=String(x?.id||`mem-${A}`),_=String(x?.text||x?.content||x?.value||""),z=_.length>340?`${_.slice(0,340)}...`:_;return{id:O,text:_,compact:z,html:pn(_)}}),[N]);return e(vn,{className:"grid gap-4",children:e(ot,{title:"Memory",subtitle:"Search recent records and open full entry details inline.",actions:e(la,{children:[e(ve,{tone:"info",children:[E.length," results"]}),r.trim()?e(ve,{tone:"ghost",children:["Filter: ",r]}):e(ve,{tone:"ghost",children:"Browsing latest memory"})]}),children:[e(wa,{className:"mb-3",children:[e("input",{className:"tcp-input flex-1",value:r,onInput:x=>s(x.target.value),placeholder:"Search memory"}),e("button",{className:"tcp-btn",onClick:()=>u.refetch(),children:[e("i",{"data-lucide":"search"}),"Search"]})]}),e("div",{className:"grid gap-2",children:E.length?E.map(x=>{const A=c===x.id;return e(Re.article,{layout:!0,className:`tcp-list-item cursor-pointer ${A?"border-amber-500/60":""}`,onClick:()=>d(A?null:x.id),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{className:"truncate",children:x.id}),e("div",{className:"flex items-center gap-2",children:[e(ve,{tone:A?"info":"ghost",children:A?"expanded":"compact"}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:O=>{O.stopPropagation(),p.mutate(x.id)},children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]}),e(Mt,{initial:!1,mode:"wait",children:A?e(Re.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},transition:{duration:.18,ease:"easeOut"},className:"overflow-hidden",children:e("div",{className:"tcp-markdown tcp-markdown-ai rounded-lg border border-slate-700/60 bg-black/20 p-3 text-sm",dangerouslySetInnerHTML:{__html:x.html}})},"expanded"):e(Re.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.14,ease:"easeOut"},className:"tcp-subtle whitespace-pre-wrap text-xs",children:x.compact||"(empty)"},"compact")})]},x.id)}):e(je,{text:"No memory records found."})})]})})}const ao=[{label:"Every hour",intervalSeconds:3600},{label:"Every morning",cron:"0 9 * * *"},{label:"Every evening",cron:"0 18 * * *"},{label:"Daily at midnight",cron:"0 0 * * *"},{label:"Weekly Monday",cron:"0 9 * * 1"},{label:"Manual only",cron:""}];function ap(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function np(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function rp(a){const t=String(a?.type||"").trim().toLowerCase();if(t==="cron")return String(a?.cron_expression||a?.cronExpression||"cron");if(t==="interval"){const n=Number(a?.interval_seconds||a?.intervalSeconds||0);return!Number.isFinite(n)||n<=0?"interval":n%3600===0?`Every ${n/3600}h`:n%60===0?`Every ${n/60}m`:`Every ${n}s`}return"manual"}function sp(a,t){const n=String(t||"").trim();if(n)return{type:"cron",cron_expression:n,timezone:"UTC"};const r=ao.find(s=>s.label===a);return r?.intervalSeconds?{type:"interval",interval_seconds:r.intervalSeconds}:r?.cron?{type:"cron",cron_expression:r.cron,timezone:"UTC"}:{type:"manual"}}function ip(a){const t=String(a?.template_id||a?.templateID||a?.id||"").trim();if(!t)return null;const n=String(a?.display_name||a?.displayName||a?.name||"").trim(),r=String(a?.role||"worker").trim()||"worker",s=a?.default_model||a?.defaultModel||{},c=String(s?.provider_id||s?.providerId||"").trim(),d=String(s?.model_id||s?.modelId||"").trim();return{templateId:t,displayName:n||t,role:r,modelLabel:c&&d?`${c}/${d}`:""}}function op({client:a,toast:t}){const n=ca(),r=Rt(null),[s,c]=w("Daily Engineering Standup"),[d,u]=w(""),[p,N]=w("Every morning"),[E,x]=w(""),[A,O]=w("docs/standups/{{date}}.md"),[_,z]=w([]),[P,Q]=w(null),B=V({queryKey:["teams","standup","templates"],queryFn:()=>a?.agentTeams?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:12e3}),ne=V({queryKey:["teams","standup","health"],queryFn:()=>a?.health?.().catch(()=>({}))??Promise.resolve({}),refetchInterval:3e4});fe(()=>{const M=String(ne.data?.workspaceRoot||ne.data?.workspace_root||"").trim();M&&u(xe=>xe||M)},[ne.data]);const I=F(()=>ap(B.data,"templates").map(ip).filter(M=>!!M),[B.data]),C=ke({mutationFn:async()=>{const M=String(s||"").trim(),xe=String(d||"").trim();if(!M)throw new Error("Standup name is required.");const y=np(xe);if(y)throw new Error(y);if(!_.length)throw new Error("Select at least one participant template.");return await a?.agentTeams?.composeStandup?.({name:M,workspaceRoot:xe,schedule:sp(p,E),participantTemplateIds:_,reportPathTemplate:String(A||"").trim()||void 0})||null},onSuccess:M=>{Q(M?.automation||null)},onError:M=>t("err",M instanceof Error?M.message:String(M))}),H=ke({mutationFn:async()=>{const M=P||(await C.mutateAsync())?.automation;if(!M)throw new Error("Standup compose failed.");return a?.automationsV2?.create?.(M)},onSuccess:async()=>{t("ok","Agent standup automation created."),Q(null),await n.invalidateQueries({queryKey:["automations"]})},onError:M=>t("err",M instanceof Error?M.message:String(M))});return fe(()=>{const M=r.current;M&&xa(M)},[s,d,p,E,A,_.join(","),I.length,C.isPending,H.isPending,!!P]),e("div",{ref:r,className:"grid gap-4 rounded-2xl border border-emerald-500/20 bg-emerald-500/5 p-4",children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-emerald-300",children:"Agent Standup"}),e("h3",{className:"mt-1 text-lg font-semibold text-white",children:"Build a scheduled standup from saved agents"}),e("p",{className:"mt-1 text-sm text-slate-300",children:"Choose the personalities that should participate, preview the workflow, and create the automation from the same place you manage those agents."})]}),e("span",{className:"tcp-badge-ok",children:"MVP"})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"Standup name",value:s,onInput:M=>c(M.target.value)}),e("input",{className:"tcp-input",placeholder:"/absolute/workspace/root",value:d,onInput:M=>u(M.target.value)}),e("select",{className:"tcp-input",value:p,onInput:M=>N(M.target.value),children:ao.map(M=>e("option",{value:M.label,children:M.label},M.label))}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"Custom cron (optional)",value:E,onInput:M=>x(M.target.value)})]}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"docs/standups/{{date}}.md",value:A,onInput:M=>O(M.target.value)}),e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3 text-sm text-slate-300",children:"The markdown report path controls where the synthesized standup is written. Participant personalities come from the saved agents below."}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Participants"}),I.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:I.map(M=>{const xe=_.includes(M.templateId);return e("button",{type:"button",className:`tcp-list-item text-left transition-all ${xe?"border-emerald-400/60 bg-emerald-400/10":""}`,onClick:()=>z(y=>y.includes(M.templateId)?y.filter(v=>v!==M.templateId):[...y,M.templateId]),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:M.displayName}),e("span",{className:"tcp-badge-info",children:M.role})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:M.templateId}),M.modelLabel?e("div",{className:"mt-2 text-xs text-emerald-200",children:M.modelLabel}):null]},M.templateId)})}):e(je,{text:"Create at least one saved agent below before composing a standup."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:C.isPending||!I.length,onClick:()=>C.mutate(),children:[e("i",{"data-lucide":"file-search"}),C.isPending?"Composing…":"Preview Standup Workflow"]}),e("button",{type:"button",className:"tcp-btn-primary",disabled:H.isPending||!I.length,onClick:()=>H.mutate(),children:[e("i",{"data-lucide":"rocket"}),H.isPending?"Creating…":"Create Standup Automation"]})]}),P?e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/40 p-3",children:[e("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e("strong",{children:String(P?.name||"Standup preview")}),e("span",{className:"tcp-badge-info",children:[Array.isArray(P?.flow?.nodes)?P.flow.nodes.length:0," nodes"]})]}),e("div",{className:"grid gap-2 text-xs text-slate-300",children:[e("div",{children:["schedule: ",rp(P?.schedule)]}),e("div",{children:["report:"," ",String(P?.metadata?.standup?.report_path_template||A)]}),e("div",{children:["participants:"," ",String((P?.metadata?.standup?.participant_template_ids||_).join(", "))]})]})]}):null]})}const ri=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],lp={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."},cp=["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."],or={templateId:"",displayName:"",avatarUrl:"",role:"worker",systemPrompt:"",modelProvider:"",modelId:""};function Ur(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function dp(a){const t=a?.default_model||a?.defaultModel||{};return{templateId:String(a?.template_id||a?.templateID||a?.id||"").trim(),displayName:String(a?.display_name||a?.displayName||a?.name||"").trim(),avatarUrl:String(a?.avatar_url||a?.avatarUrl||"").trim(),role:String(a?.role||"worker").trim()||"worker",systemPrompt:String(a?.system_prompt||a?.systemPrompt||"").trim(),modelProvider:String(t?.provider_id||t?.providerId||"").trim(),modelId:String(t?.model_id||t?.modelId||"").trim()}}function up(a){const t={templateID:a.templateId.trim(),display_name:a.displayName.trim()||void 0,avatar_url:a.avatarUrl.trim()||void 0,role:a.role,system_prompt:a.systemPrompt.trim()||void 0,skills:[],default_budget:{},capabilities:{}};return a.modelProvider.trim()&&a.modelId.trim()&&(t.default_model={provider_id:a.modelProvider.trim(),model_id:a.modelId.trim()}),t}function si({client:a,toast:t}){const n=ca(),r=a?.agentTeams,s=Rt(null),[c,d]=w(or),[u,p]=w(null),N=Rt(null),E=V({queryKey:["teams","templates"],queryFn:()=>r?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:8e3}),x=V({queryKey:["teams","instances"],queryFn:()=>r?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),A=V({queryKey:["teams","approvals"],queryFn:()=>r?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),O=ke({mutationFn:async()=>{if(!c.templateId.trim())throw new Error("Template ID is required.");return u?r?.updateTemplate?.(u,{display_name:c.displayName.trim()||void 0,avatar_url:c.avatarUrl.trim()||void 0,role:c.role,system_prompt:c.systemPrompt.trim()||void 0,default_model:c.modelProvider.trim()&&c.modelId.trim()?{provider_id:c.modelProvider.trim(),model_id:c.modelId.trim()}:void 0}):r?.createTemplate?.({template:up(c)})},onSuccess:async()=>{t("ok",u?"Template updated.":"Template created."),d(or),p(null),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),_=ke({mutationFn:y=>r?.deleteTemplate?.(y),onSuccess:async()=>{t("ok","Template deleted."),u&&(p(null),d(or)),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),z=ke({mutationFn:({requestId:y,decision:v})=>v==="approve"?r?.approveSpawn?.(y):r?.denySpawn?.(y),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["teams"]})},onError:y=>t("err",y instanceof Error?y.message:String(y))}),P=F(()=>Ur(E.data,"templates").map(dp).filter(y=>y.templateId),[E.data]),Q=Ur(x.data,"instances"),B=Ur(A.data,"spawnApprovals"),ne=!!(u||c.templateId||c.displayName||c.systemPrompt),I=c.displayName.trim()||c.templateId.trim()||"New Agent",C=I.slice(0,1).toUpperCase()||"A",H=lp[c.role],M=c.avatarUrl.trim();fe(()=>{const y=s.current;y&&xa(y)},[P.length,Q.length,B.length,c.role,c.templateId,c.displayName,c.avatarUrl,c.modelProvider,c.modelId,c.systemPrompt,u,O.isPending,_.isPending,z.isPending]);const xe=y=>{if(!y)return;if(y.size>10*1024*1024){t("err","Avatar image is too large (max 10 MB).");return}const v=new FileReader;v.onload=()=>{const j=typeof v.result=="string"?v.result:"";if(!j){t("err","Failed to read avatar image.");return}d(he=>({...he,avatarUrl:j}))},v.onerror=()=>t("err","Failed to read avatar image."),v.readAsDataURL(y)};return e("div",{ref:s,className:"grid gap-4",children:[e(Yt,{title:"Agent Standup",subtitle:"Compose scheduled standups from the same saved agents you manage here",children:e(op,{client:a,toast:t})}),e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(Yt,{title:"Agents",subtitle:"Create reusable agent personalities, prompts, and default models for automation workflows",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-cyan-300",children:"Reusable Personalities"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses."})]}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"template-id",value:c.templateId,disabled:!!u,onInput:y=>d(v=>({...v,templateId:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Display name",value:c.displayName,onInput:y=>d(v=>({...v,displayName:y.target.value}))}),e("select",{className:"tcp-input",value:c.role,onInput:y=>d(v=>({...v,role:y.target.value})),children:ri.map(y=>e("option",{value:y,children:y},y))}),e("input",{className:"tcp-input",placeholder:"Avatar URL or upload (optional)",value:c.avatarUrl,onInput:y=>d(v=>({...v,avatarUrl:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model provider (optional)",value:c.modelProvider,onInput:y=>d(v=>({...v,modelProvider:y.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model ID (optional)",value:c.modelId,onInput:y=>d(v=>({...v,modelId:y.target.value}))})]}),e("div",{className:"grid gap-3 lg:grid-cols-[1.15fr_0.85fr]",children:[e("div",{className:"rounded-2xl border border-slate-800/80 bg-slate-950/40 px-4 py-3",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Prompt Guidance"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Write the lasting perspective for this agent, not a one-off task. Good prompts describe ownership and judgment: frontend lead, backend lead, product ops, incident watcher."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:cp.map(y=>e("button",{type:"button",className:"tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs",onClick:()=>d(v=>({...v,systemPrompt:y})),children:"Use Example"},y))})]}),e("div",{className:"rounded-[28px] border border-slate-800/80 bg-[radial-gradient(circle_at_top,_rgba(34,211,238,0.18),_transparent_45%),linear-gradient(180deg,rgba(15,23,42,0.9),rgba(2,6,23,0.96))] p-5",children:[e("div",{className:"flex items-start justify-between gap-4",children:[e("div",{className:"flex items-start gap-4",children:[e("div",{className:"flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-cyan-400/30 bg-cyan-400/10 text-lg font-semibold text-cyan-100",children:M?e("img",{src:M,alt:I,className:"h-full w-full object-cover"}):C}),e("div",{className:"min-w-0",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-white",children:I}),e("span",{className:"tcp-badge-info",children:c.role})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:c.templateId.trim()||"template-id"}),e("div",{className:"mt-2 text-sm text-slate-300",children:H})]})]}),e("div",{className:"flex items-center gap-2",children:[e("button",{type:"button",className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>N.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{type:"button",className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>d(y=>({...y,avatarUrl:""})),children:e("i",{"data-lucide":"trash-2"})})]})]}),e("div",{className:"mt-3 text-xs text-slate-400",children:"Upload an image like Settings Identity preview, or paste a direct avatar URL."}),e("input",{ref:N,type:"file",accept:"image/*",className:"hidden",onChange:y=>{xe(y.target.files?.[0]||null),y.target.value=""}}),e("div",{className:"mt-4 rounded-2xl border border-slate-800/70 bg-black/20 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Personality Preview"}),e("div",{className:"mt-2 whitespace-pre-wrap text-sm leading-6 text-slate-200",children:c.systemPrompt.trim()||"This agent will respond from the persistent personality you define here across workflows and standups."})]}),(c.modelProvider.trim()||c.modelId.trim())&&e("div",{className:"mt-3 text-xs text-cyan-200",children:["Default model: ",c.modelProvider.trim()||"provider","/",c.modelId.trim()||"model"]})]})]}),e("textarea",{className:"tcp-input min-h-[140px]",placeholder:"Persistent system prompt",value:c.systemPrompt,onInput:y=>d(v=>({...v,systemPrompt:y.target.value}))}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:O.isPending,onClick:()=>O.mutate(),children:[e("i",{"data-lucide":"save"}),u?"Update Agent":"Create Agent"]}),ne&&e("button",{type:"button",className:"tcp-btn",onClick:()=>{p(null),d(or)},children:[e("i",{"data-lucide":"rotate-ccw"}),"Reset"]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Saved Agents"}),e("div",{className:"tcp-subtle text-xs",children:[P.length," saved"]})]}),P.length?P.map(y=>e("div",{className:"tcp-list-item",children:e("div",{className:"flex items-start justify-between gap-3",children:[e("div",{className:"min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[e("strong",{children:y.displayName||y.templateId}),e("span",{className:"tcp-badge-info",children:y.role}),y.modelProvider&&y.modelId?e("span",{className:"tcp-badge-ok",children:[y.modelProvider,"/",y.modelId]}):null]}),e("div",{className:"tcp-subtle text-xs",children:y.templateId}),y.systemPrompt?e("div",{className:"mt-2 line-clamp-4 text-xs text-slate-300",children:y.systemPrompt}):e("div",{className:"mt-2 text-xs text-slate-500",children:"No persistent prompt set yet."})]}),e("div",{className:"flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>{p(y.templateId),d({templateId:y.templateId,displayName:y.displayName,avatarUrl:y.avatarUrl,role:ri.includes(y.role)?y.role:"worker",systemPrompt:y.systemPrompt,modelProvider:y.modelProvider,modelId:y.modelId})},children:[e("i",{"data-lucide":"pencil"}),"Edit"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>_.mutate(y.templateId),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]})},y.templateId)):e(je,{title:"No agents yet",text:"Create your first saved personality here, then reuse it across automation workflows and standups."})]})]})}),e(Yt,{title:"Team Instances",subtitle:"Running collaborative agent instances",children:e("div",{className:"grid gap-2",children:Q.length?Q.map((y,v)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(y?.template_id||y?.templateID||y?.instance_id||"Instance")}),e("span",{className:"tcp-badge-info",children:String(y?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs",children:["mission: ",String(y?.mission_id||y?.missionID||"n/a")]})]},String(y?.instance_id||y?.id||v))):e(je,{text:"No team instances found."})})}),e(Yt,{title:"Spawn Approvals",subtitle:"Pending team approval requests",children:e("div",{className:"grid gap-2",children:B.length?B.map((y,v)=>{const j=String(y?.approval_id||y?.request_id||y?.id||`request-${v}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:String(y?.reason||y?.title||j)}),e("div",{className:"tcp-subtle text-xs",children:j}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>z.mutate({requestId:j,decision:"approve"}),children:[e("i",{"data-lucide":"badge-check"}),"Approve"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>z.mutate({requestId:j,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},j)}):e(je,{text:"No pending approvals."})})})]})]})}function lr(a){return a?.type||a?.event||"event"}function ii(a){const t=String(a||"").trim().toLowerCase();return["server.connected","engine.lifecycle.ready","engine.heartbeat","engine.lifecycle.heartbeat"].includes(t)}function oi(a){return String(a?.type||a?.event||"").trim()==="context.run.stream"&&String(a?.run_id||a?.runId||"").trim().startsWith("workflow-")}function mp({client:a,toast:t,navigate:n}){const[r,s]=w([]),[c,d]=w(""),[u,p]=w("all"),[N,E]=w(!0),[x,A]=w(null),O=F(()=>!x||!oi(x.data)?"":String(x.data?.run_id||x.data?.runId||"").trim(),[x]),_=V({queryKey:["feed","workflow-context-run",O],enabled:!!O,queryFn:()=>Xt(`/api/engine/context/runs/${encodeURIComponent(O)}`).catch(()=>({run:null}))}),z=V({queryKey:["feed","workflow-context-blackboard",O],enabled:!!O,queryFn:()=>Xt(`/api/engine/context/runs/${encodeURIComponent(O)}/blackboard`).catch(()=>({blackboard:null}))});en("/api/global/event",I=>{try{const C=JSON.parse(I.data);s(H=>[...H.slice(-299),{at:Date.now(),data:C}])}catch{}},{enabled:!0});const P=F(()=>{const I=new Map;for(const C of r){const H=lr(C.data);N&&ii(H)||I.set(H,(I.get(H)||0)+1)}return[...I.entries()].sort((C,H)=>H[1]-C[1])},[r,N]),Q=F(()=>{const I=c.trim().toLowerCase();return r.filter(C=>{const H=lr(C.data);return N&&ii(H)||u!=="all"&&H!==u?!1:I?`${H} ${JSON.stringify(C.data||{})}`.toLowerCase().includes(I):!0}).slice(-240).reverse()},[r,c,u,N]);async function B(I){try{const C=await Xt("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:I,source:{kind:"control_panel_feed",event:"pack.detected"}})});t("ok",`Installed ${C?.installed?.name||"pack"}`)}catch(C){t("err",C instanceof Error?C.message:String(C))}}async function ne(I){try{const C=await Xt("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:String(I?.properties?.attachment_id||I?.attachment_id||""),path:String(I?.properties?.path||I?.path||""),connector:String(I?.properties?.connector||I?.connector||"")||void 0,channel_id:String(I?.properties?.channel_id||I?.channel_id||"")||void 0,sender_id:String(I?.properties?.sender_id||I?.sender_id||"")||void 0})});t("ok",`Installed ${C?.installed?.name||"pack"}`)}catch(C){t("err",C instanceof Error?C.message:String(C))}}return e(vn,{className:"grid gap-4",children:[e(ot,{title:"Live feed",subtitle:"Filter events and inspect raw payload details.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e("span",{className:"tcp-badge-info",children:[r.length," buffered"]}),e("span",{className:"tcp-badge tcp-badge-ghost",children:u==="all"?"All event types":u}),e("span",{className:N?"tcp-badge-ok":"tcp-badge-info",children:N?"noise hidden":"noise visible"}),e("button",{className:"tcp-btn",onClick:()=>s([]),children:[e("i",{"data-lucide":"trash-2"}),"Clear feed"]}),e("button",{className:"tcp-btn",onClick:()=>n("packs-detail"),children:[e("i",{"data-lucide":"package"}),"Pack library"]})]}),children:[e(wa,{className:"mb-3",children:[e("input",{className:"tcp-input min-w-[220px] flex-1",value:c,onInput:I=>d(I.target.value),placeholder:"Filter by type or payload"}),e(Ar,{active:u==="all",onClick:()=>p("all"),children:[e("i",{"data-lucide":"list"}),"All"]}),e(Ar,{active:N,onClick:()=>E(I=>!I),children:[e("i",{"data-lucide":N?"filter":"filter-x"}),N?"Hide noise":"Show noise"]}),P.slice(0,8).map(([I,C])=>e(Ar,{active:u===I,onClick:()=>p(I),children:[e("i",{"data-lucide":"activity"}),I," (",C,")"]},I))]}),e("div",{className:"grid max-h-[68vh] gap-2 overflow-auto rounded-2xl border border-slate-700/60 bg-black/20 p-2",children:Q.length?Q.map((I,C)=>{const H=lr(I.data),M=String(H).startsWith("pack."),xe=oi(I.data),y=String(I.data?.properties?.path||I.data?.path||""),v=String(I.data?.properties?.attachment_id||I.data?.attachment_id||"");return e("article",{className:"tcp-list-item cursor-pointer",onClick:()=>A(I),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:H}),e("div",{className:"flex items-center gap-2",children:[xe?e("span",{className:"tcp-badge-warn",children:"workflow context"}):null,e("span",{className:"tcp-badge-info",children:new Date(I.at).toLocaleTimeString()})]})]}),e("p",{className:"tcp-subtle mt-1 text-xs",children:xe?`run: ${String(I.data?.run_id||I.data?.runId||"n/a")}`:`session: ${String(I.data?.sessionID||I.data?.sessionId||"n/a")}`}),xe?e("p",{className:"tcp-subtle mt-1 text-xs",children:["kind: ",String(I.data?.kind||"context_run_event")," · seq:"," ",String(I.data?.seq||"-")]}):null,M?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:j=>{j.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open pack library"]}),y?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:j=>{j.stopPropagation(),B(y)},children:[e("i",{"data-lucide":"download"}),"Install from path"]}):null,y&&v?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:j=>{j.stopPropagation(),ne(I.data)},children:[e("i",{"data-lucide":"paperclip"}),"Install attachment"]}):null]}):null,xe?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:j=>{j.stopPropagation(),n("orchestrator")},children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:j=>{j.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open workflow lab"]})]}):null]},`${I.at}-${C}`)}):e(je,{text:"No events have arrived yet."})})]}),e(br,{open:!!x,onClose:()=>A(null),title:x?lr(x.data):"Event",children:x?e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Captured at"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:new Date(x.at).toLocaleString()})]}),O?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(_.data?.run?.objective||O)}),e("span",{className:"tcp-badge-info",children:String(_.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(z.data?.blackboard?.tasks)?z.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(z.data?.blackboard?.artifacts)?z.data.blackboard.artifacts.length:0]})]}):null,e("pre",{className:"tcp-code",children:aa(x.data)}),O?e("pre",{className:"tcp-code",children:aa({run:_.data?.run||null,blackboard:z.data?.blackboard||null})}):null]}):null})]})}function pp({theme:a}){const t=a?.cssVars?.["--color-background"]||"#000000",n=a?.cssVars?.["--color-surface"]||"#111111",r=a?.cssVars?.["--color-primary"]||"#ffffff",s=a?.cssVars?.["--color-secondary"]||"#ffffff";return e("div",{className:"flex items-center gap-2",children:[e("span",{className:"tcp-theme-swatch",style:{background:t},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:n},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:r},"aria-hidden":"true"}),e("span",{className:"tcp-theme-swatch",style:{background:s},"aria-hidden":"true"})]})}function hp({themes:a,themeId:t,onChange:n}){return e("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-2",children:a.map(r=>{const s=r.id===t;return e(Re.button,{type:"button",layout:!0,onClick:()=>n(r.id),className:`tcp-theme-tile ${s?"active":""}`,whileHover:{y:-2},whileTap:{scale:.985},transition:Ra.spring.gentle,children:[e("div",{className:"tcp-theme-tile-top",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-theme-tile-title",children:r.name}),e("p",{className:"tcp-subtle mt-1 text-xs",children:r.description})]}),e(pp,{theme:r})]}),e("div",{className:"tcp-theme-preview",children:e("div",{className:"tcp-theme-preview-bg",style:{background:r.cssVars["--color-background"]||"#000"},children:e("div",{className:"tcp-theme-preview-card",style:{background:r.cssVars["--color-surface"]||"#111",borderColor:r.cssVars["--color-border"]||"rgba(255,255,255,0.1)"},children:[e("div",{className:"tcp-theme-preview-line short",style:{background:r.cssVars["--color-text"]||"#fff"}}),e("div",{className:"tcp-theme-preview-line",style:{background:r.cssVars["--color-text-muted"]||"#aaa"}}),e("div",{className:"tcp-theme-preview-pill",style:{background:r.cssVars["--color-primary"]||"#fff"}})]})})}),e(Mt,{initial:!1,children:s?e(Re.span,{className:"tcp-theme-active",initial:{opacity:0,scale:.86},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.86},transition:Ra.spring.snappy,children:[e("i",{"data-lucide":"badge-check"}),"Active"]}):null})]},r.id)})})}const gp=new Set(["openai","openrouter","anthropic","ollama","groq","mistral","together","azure","bedrock","vertex","copilot","cohere"]),fp=[{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"]}],bp=["websearch","webfetch","webfetch_html","memory_search","memory_store","memory_list"];function _r(a){try{return new URL(a)}catch{return null}}function Vr(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"mcp-server"}function li(a){const t=_r(a);if(!t)return"";const n=String(t.hostname||"").toLowerCase();if(!n)return"";if(n.endsWith("composio.dev"))return"composio";const r=n.split(".").filter(Boolean);if(!r.length)return"";const s=["backend","api","mcp","www"].includes(r[0])&&r[1]||r[0];return Vr(s)}function no(a){const t=_r(a);return t?String(t.hostname||"").toLowerCase().endsWith("composio.dev"):!1}function un(a){const t=_r(a);if(!t)return!1;const n=String(t.hostname||"").toLowerCase();return n==="api.githubcopilot.com"||n.endsWith(".githubcopilot.com")}function vp(a){return a.map(t=>({key:String(t?.key||"").trim(),value:String(t?.value||"").trim()}))}function yp(a,t){const n={...a};for(const r of vp(t))!r.key||!r.value||(n[r.key]=r.value);return n}function wp({authMode:a,token:t,customHeader:n,transport:r}){const s=String(t||"").trim();if(!s||a==="none")return{};if(a==="custom"){const d=String(n||"").trim();if(!d)throw new Error("Custom header name is required.");return{[d]:s}}return a==="x-api-key"?{"x-api-key":s}:a==="bearer"?{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}:no(r)?{"x-api-key":s}:{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}}function xp(a,t,n,r){return!String(t||"").trim()||a==="none"?"No auth header will be sent.":a==="custom"?n?`Header preview: ${n}: <token>`:"Set a custom header name.":a==="x-api-key"?"Header preview: x-api-key: <token>":a==="bearer"?"Header preview: Authorization: Bearer <token>":no(r)?"Auto mode: selected x-api-key for this endpoint":"Auto mode: using Authorization Bearer token"}function Br(a,t=""){if(!a||typeof a!="object")return null;const n=a,r=String(n.name||t||"").trim();return r?{name:r,transport:String(n.transport||"").trim(),connected:!!n.connected,enabled:n.enabled!==!1,lastError:String(n.last_error||n.lastError||"").trim(),headers:n.headers&&typeof n.headers=="object"?n.headers:{},toolCache:Array.isArray(n.tool_cache||n.toolCache)?n.tool_cache||n.toolCache:[]}:null}function kp(a){return Array.isArray(a)?a.map(t=>Br(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):!a||typeof a!="object"?[]:Array.isArray(a.servers)?a.servers.map(t=>Br(t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name)):Object.entries(a).map(([t,n])=>Br(n&&typeof n=="object"?n:{transport:String(n||"")},t)).filter(t=>!!t).sort((t,n)=>t.name.localeCompare(n.name))}function Np(a){return(Array.isArray(a)?a:Array.isArray(a?.tools)?a.tools:[]).map(n=>typeof n=="string"?n:!n||typeof n!="object"?"":String(n.namespaced_name||n.namespacedName||n.id||n.tool_name||n.toolName||"").trim()).filter(Boolean)}function _p(a){const t=a&&typeof a=="object"?a:{},n=Array.isArray(t.servers)?t.servers:[];return{generatedAt:String(t.generated_at||"").trim(),count:Number.isFinite(Number(t.count))?Number(t.count):n.length,servers:n.map(r=>!r||typeof r!="object"?null:{slug:String(r.slug||"").trim(),name:String(r.name||r.slug||"").trim(),description:String(r.description||"").trim(),transportUrl:String(r.transport_url||"").trim(),serverConfigName:String(r.server_config_name||r.slug||"").trim(),documentationUrl:String(r.documentation_url||"").trim(),directoryUrl:String(r.directory_url||"").trim(),toolCount:Number.isFinite(Number(r.tool_count))?Number(r.tool_count):0,requiresAuth:r.requires_auth!==!1,requiresSetup:!!r.requires_setup}).filter(r=>!!r&&!!r.slug&&!!r.transportUrl).sort((r,s)=>r.name.localeCompare(s.name))}}function Fr(a,t){const n=t&&typeof t=="object"?t:{};return{botToken:"",allowedUsers:Array.isArray(n.allowed_users)?n.allowed_users.join(", "):"",mentionOnly:n.mention_only!==!1&&a==="discord"?!0:!!n.mention_only,guildId:String(n.guild_id||"").trim(),channelId:String(n.channel_id||"").trim(),styleProfile:String(n.style_profile||"default").trim()||"default",securityProfile:String(n.security_profile||"operator").trim()||"operator"}}function ci(){return{enabled_tools:[],disabled_tools:[],enabled_mcp_servers:[]}}function gn(a){return Array.from(new Set(a.map(t=>t.trim()).filter(Boolean)))}function di(a){const t=a&&typeof a=="object"?a:{};return{enabled_tools:Array.isArray(t.enabled_tools)?gn(t.enabled_tools.map(n=>String(n))):[],disabled_tools:Array.isArray(t.disabled_tools)?gn(t.disabled_tools.map(n=>String(n))):[],enabled_mcp_servers:Array.isArray(t.enabled_mcp_servers)?gn(t.enabled_mcp_servers.map(n=>String(n))):[]}}function Sp(a,t){return a.disabled_tools.includes(t)?!1:a.enabled_tools.length===0||a.enabled_tools.includes(t)}function Ip(a,t,n){const r=a.disabled_tools.filter(c=>c!==t),s=a.enabled_tools.length>0?[...a.enabled_tools]:[];return n?{...a,disabled_tools:r,enabled_tools:s.length>0?gn([...s,t]):[]}:{...a,disabled_tools:gn([...r,t]),enabled_tools:s.length>0?s.filter(c=>c!==t):s}}function Cp(a,t,n){const r=a.enabled_mcp_servers.filter(s=>s!==t);return{...a,enabled_mcp_servers:n?gn([...r,t]):r}}function ro(a,t){return a!=="public_demo"?!0:bp.includes(t)}function Ap(a,t,n){return ro(n,t)&&Sp(a,t)}function Pp(a){const t=String(a||"").split(",").map(n=>n.trim()).filter(Boolean);return t.length?t:["*"]}function Tp(a,t){const n=String(a?.catalog_source||"").trim().toLowerCase();return n==="remote"&&t>0?{tone:"ok",text:`${t} models`}:n==="config"&&t>0?{tone:"info",text:"configured models"}:{tone:"warn",text:"manual entry"}}function Rp(a,t){const n=String(a?.catalog_message||"").trim();return n||`Default model: ${t||"none"}`}function ui({client:a,api:t,toast:n,navigate:r,currentRoute:s,identity:c,themes:d,setTheme:u,themeId:p,refreshProviderStatus:N,refreshIdentityStatus:E}){const x=ca(),A=Rt(null),[O,_]=w({}),[z,P]=w(String(c?.botName||"Tandem")),[Q,B]=w(String(c?.botAvatarUrl||"")),[ne,I]=w("Control Center"),[C,H]=w("providers"),[M,xe]=w("auto"),[y,v]=w(""),[j,he]=w(""),[ee,qe]=w("10000"),[$e,Le]=w(""),[re,me]=w(""),[q,ge]=w(!1),[Pe,Te]=w(!1),[se,Oe]=w(!1),[Me,He]=w("custom"),[Y,Ze]=w(""),[ae,Ae]=w(""),[St,oe]=w(""),[W,lt]=w(!0),[xt,rt]=w({}),[Et,Fe]=w({}),[Bt,At]=w(!1),[$t,We]=w(""),[ze,tt]=w(""),[be,Se]=w("none"),[Ve,ce]=w(""),[dt,S]=w(""),[G,ue]=w(""),[Ke,l]=w([]),[b,T]=w(!0),[R,$]=w(""),[Ye,Xe]=w("manual"),[Ot,Ft]=w(""),[Ie,Pt]=w(!1),[bt,te]=w(!1),[Ne,h]=w(""),[U,J]=w(""),[L,X]=w(""),[ye,Ue]=w("auto"),[st,vt]=w(""),[It,et]=w(""),[yt,Lt]=w(!0),[Qt,Ct]=w(!1),[Ht,kt]=w(!0),[Ge,da]=w(!1),[Ce,we]=w(""),[ut,Qe]=w(""),qt=Rt(null),ia=async()=>{const o=a?.identity;return o?.get?o.get():t("/api/engine/config/identity",{method:"GET"})},ba=async o=>{const k=a?.identity;return k?.patch?k.patch(o):t("/api/engine/config/identity",{method:"PATCH",body:JSON.stringify(o)})},Kt=V({queryKey:["settings","identity","config"],queryFn:()=>ia().catch(()=>({identity:{}}))});fe(()=>{const o=Kt.data?.identity?.bot||{},k=o?.aliases||{},de=String(o?.canonicalName||o?.canonical_name||c?.botName||"Tandem").trim(),Ee=String(o?.avatarUrl||o?.avatar_url||c?.botAvatarUrl||"").trim(),ct=String(k?.controlPanel||k?.control_panel||"").trim();P(de||"Tandem"),B(Ee),I(ct||"Control Center")},[c?.botAvatarUrl,c?.botName,Kt.data]),fe(()=>{s==="mcp"&&H("mcp"),s==="channels"&&H("channels"),s==="bug-monitor"&&H("bug_monitor")},[s]);const Gt=V({queryKey:["settings","providers","catalog"],queryFn:()=>a.providers.catalog().catch(()=>({all:[],connected:[]}))}),mt=V({queryKey:["settings","providers","config"],queryFn:()=>a.providers.config().catch(()=>({default:"",providers:{}}))}),ua=F(()=>mt.data?.providers||{},[mt.data?.providers]),na=F(()=>Object.entries(ua).filter(([o])=>{const k=o.trim().toLowerCase();return k&&!gp.has(k)}).map(([o,k])=>({id:o,url:String(k?.url||"").trim(),model:String(k?.default_model||k?.defaultModel||"").trim(),isDefault:String(mt.data?.default||"").trim().toLowerCase()===o.trim().toLowerCase()})),[ua,mt.data?.default]),Nt=V({queryKey:["settings","search","config"],queryFn:()=>t("/api/system/search-settings",{method:"GET"}).catch(()=>null)});fe(()=>{const o=Nt.data?.settings||null;o&&(xe(String(o.backend||"auto").trim()||"auto"),v(String(o.tandem_url||"").trim()),he(String(o.searxng_url||"").trim()),qe(String(o.timeout_ms||1e4)))},[Nt.data]);const Je=V({queryKey:["settings","browser","status"],queryFn:()=>t("/api/engine/browser/status",{method:"GET"}).catch(()=>null),refetchInterval:3e4}),[f,K]=w(null),pe=ke({mutationFn:()=>t("/api/engine/browser/install",{method:"POST"}),onSuccess:async()=>{n("ok","Browser sidecar installed on the engine host."),await Je.refetch()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),De=ke({mutationFn:()=>t("/api/engine/browser/smoke-test",{method:"POST",body:JSON.stringify({url:"https://example.com"})}),onSuccess:async o=>{K(o),n("ok","Browser smoke test passed."),await Je.refetch()},onError:o=>{K(null),n("err",o instanceof Error?o.message:String(o))}}),Be=V({queryKey:["settings","mcp","servers"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:1e4}),it=V({queryKey:["settings","mcp","tools"],queryFn:()=>a.mcp.listTools().catch(()=>[]),refetchInterval:15e3}),_t=V({queryKey:["settings","mcp","catalog"],queryFn:()=>t("/api/engine/mcp/catalog",{method:"GET"}).catch(()=>null),refetchInterval:6e4}),zt=V({queryKey:["settings","bug-monitor","config"],queryFn:()=>t("/api/engine/config/bug-monitor",{method:"GET"}).catch(()=>({bug_monitor:{}}))}),oa=V({queryKey:["settings","bug-monitor","status"],queryFn:()=>t("/api/engine/bug-monitor/status",{method:"GET"}).catch(()=>({status:{}})),refetchInterval:1e4}),ka=V({queryKey:["settings","bug-monitor","drafts"],queryFn:()=>t("/api/engine/bug-monitor/drafts?limit=10",{method:"GET"}).catch(()=>({drafts:[]})),refetchInterval:15e3}),Zt=V({queryKey:["settings","bug-monitor","incidents"],queryFn:()=>t("/api/engine/bug-monitor/incidents?limit=10",{method:"GET"}).catch(()=>({incidents:[]})),refetchInterval:1e4}),va=V({queryKey:["settings","bug-monitor","posts"],queryFn:()=>t("/api/engine/bug-monitor/posts?limit=10",{method:"GET"}).catch(()=>({posts:[]})),refetchInterval:15e3}),Ma=V({queryKey:["settings","bug-monitor","workspace-browser",Ce],enabled:Ge&&!!Ce,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(Ce)}`,{method:"GET"})}),Ia=V({queryKey:["settings","channels","config"],queryFn:()=>a.channels.config().catch(()=>({})),refetchInterval:15e3}),wn=V({queryKey:["settings","channels","status"],queryFn:()=>a.channels.status().catch(()=>({})),refetchInterval:6e3}),zn=V({queryKey:["settings","channels","tool-preferences"],queryFn:async()=>{const o=await Promise.all(["telegram","discord","slack"].map(async k=>[k,di(await t(`/api/engine/channels/${k}/tool-preferences`,{method:"GET"}).catch(()=>ci()))]));return Object.fromEntries(o)},refetchInterval:15e3}),Jn=ke({mutationFn:async({providerId:o,modelId:k})=>a.providers.setDefaults(o,k),onSuccess:async()=>{n("ok","Updated provider defaults."),await Promise.all([x.invalidateQueries({queryKey:["settings","providers"]}),N()])},onError:o=>n("err",o instanceof Error?o.message:String(o))}),pa=ke({mutationFn:async({providerId:o,url:k,modelId:de,apiKey:Ee,makeDefault:ct})=>{const Tt=o.trim().toLowerCase(),Wt=k.trim(),sa=de.trim();if(!Tt)throw new Error("Custom provider ID is required.");if(!Wt)throw new Error("Custom provider URL is required.");await t("/api/engine/config",{method:"PATCH",body:JSON.stringify({...ct?{default_provider:Tt}:{},providers:{[Tt]:{url:Wt,...sa?{default_model:sa}:{}}}})}),Ee.trim()&&await a.providers.setApiKey(Tt,Ee.trim())},onSuccess:async()=>{n("ok","Custom provider saved."),oe(""),await Promise.all([x.invalidateQueries({queryKey:["settings","providers"]}),N()])},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Qa=ke({mutationFn:async()=>t("/api/engine/config/bug-monitor",{method:"PATCH",body:JSON.stringify({bug_monitor:{enabled:Ie,paused:bt,workspace_root:String(Ne||"").trim()||null,repo:String(U||"").trim()||null,mcp_server:String(L||"").trim()||null,provider_preference:String(ye||"auto").trim(),model_policy:st&&It?{default_model:{provider_id:st,model_id:It}}:null,auto_create_new_issues:yt,require_approval_for_new_issues:Qt,auto_comment_on_matched_open_issues:Ht,label_mode:"reporter_only"}})}),onSuccess:async()=>{n("ok","Bug Monitor settings saved."),await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})])},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),qa=ke({mutationFn:async()=>t("/api/engine/capabilities/bindings/refresh-builtins",{method:"POST"}),onSuccess:async()=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]}),x.invalidateQueries({queryKey:["settings","mcp"]})]),n("ok","Capability bindings refreshed from built-ins.")},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),$a=ke({mutationFn:async({draftId:o,decision:k})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/${k}`,{method:"POST",body:JSON.stringify({reason:`${k}d from control panel settings`})}),onSuccess:async(o,k)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor draft ${k.decision==="approve"?"approved":"denied"}.`)},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),an=ke({mutationFn:async({draftId:o})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/triage-run`,{method:"POST"}),onSuccess:async o=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",o?.deduped?`Bug Monitor triage run already exists: ${o?.run?.run_id||"unknown"}`:`Bug Monitor triage run created: ${o?.run?.run_id||"unknown"}`)},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),Ha=ke({mutationFn:async({action:o})=>t(`/api/engine/bug-monitor/${o}`,{method:"POST"}),onSuccess:async(o,k)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor ${k.action==="pause"?"paused":"resumed"}.`)},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),nn=ke({mutationFn:async({incidentId:o})=>t(`/api/engine/bug-monitor/incidents/${encodeURIComponent(o)}/replay`,{method:"POST"}),onSuccess:async o=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",o?.deduped?`Bug Monitor triage run already exists: ${o?.run?.run_id||"unknown"}`:`Bug Monitor replay queued triage: ${o?.run?.run_id||"unknown"}`)},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),rn=ke({mutationFn:async({draftId:o})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/publish`,{method:"POST"}),onSuccess:async o=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",o?.action==="comment_issue"?`Bug Monitor commented on issue #${o?.draft?.issue_number||"unknown"}.`:`Bug Monitor published issue #${o?.draft?.issue_number||"unknown"}.`)},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),Qn=ke({mutationFn:async({draftId:o})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/recheck-match`,{method:"POST"}),onSuccess:async o=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`GitHub match result: ${String(o?.action||"rechecked").replaceAll("_"," ")}.`)},onError:o=>{const k=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",k)}}),Hn=ke({mutationFn:({providerId:o,apiKey:k})=>a.providers.setApiKey(o,k),onSuccess:async()=>{n("ok","API key updated."),await N()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),ea=ke({mutationFn:async o=>t("/api/system/search-settings",{method:"PATCH",body:JSON.stringify(o)}),onSuccess:async o=>{Le(""),me(""),await x.invalidateQueries({queryKey:["settings","search"]}),n("ok",o?.restart_required?"Search settings saved. Restart tandem-engine to apply them.":"Search settings saved.")},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Gn=ke({mutationFn:async()=>{const k=(Kt.data?.identity?.bot||{})?.aliases||{},de=String(z||"").trim();if(!de)throw new Error("Bot name is required.");const Ee=String(Q||"").trim(),ct=String(ne||"").trim();return ba({identity:{bot:{canonical_name:de,avatar_url:Ee||null,aliases:{...k,control_panel:ct||void 0}}}})},onSuccess:async()=>{n("ok","Identity updated."),await Promise.all([x.invalidateQueries({queryKey:["settings","identity"]}),E()])},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Ga=ft(async()=>Promise.all([x.invalidateQueries({queryKey:["settings","channels"]}),x.invalidateQueries({queryKey:["settings","channels","tool-preferences"]})]),[x]),Oa=ke({mutationFn:async({channel:o,payload:k})=>"reset"in k?t(`/api/engine/channels/${o}/tool-preferences`,{method:"PUT",body:JSON.stringify({reset:!0})}):t(`/api/engine/channels/${o}/tool-preferences`,{method:"PUT",body:JSON.stringify(k)}),onSuccess:async(o,k)=>{await x.invalidateQueries({queryKey:["settings","channels","tool-preferences"]}),n("ok",`Saved ${k.channel} channel tool scope.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),xn=ke({mutationFn:async o=>{const k=xt[o];if(!k)throw new Error(`No draft found for ${o}.`);const de={allowed_users:Pp(k.allowedUsers),mention_only:!!k.mentionOnly,security_profile:String(k.securityProfile||"operator").trim()||"operator"},Ee=String(k.botToken||"").trim();if(Ee&&(de.bot_token=Ee),o==="telegram"&&(de.style_profile=String(k.styleProfile||"default").trim()||"default"),o==="discord"&&(de.guild_id=String(k.guildId||"").trim()),o==="slack"){const ct=String(k.channelId||"").trim();if(!ct&&!Ia.data?.slack?.channel_id)throw new Error("Slack channel ID is required.");ct&&(de.channel_id=ct)}return a.channels.put(o,de)},onSuccess:async(o,k)=>{n("ok",`Saved ${k} channel settings.`),Fe(de=>({...de,[k]:null})),rt(de=>({...de,[k]:{...de[k],botToken:""}})),await Ga()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),kn=ke({mutationFn:async o=>a.channels.delete(o),onSuccess:async(o,k)=>{n("ok",`Removed ${k} channel settings.`),Fe(de=>({...de,[k]:null})),rt(de=>({...de,[k]:Fr(k,null)})),await Ga()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Nn=ke({mutationFn:async o=>{const k=xt[o],de={bot_token:String(k?.botToken||"").trim()||void 0};return a.channels.verify(o,de)},onSuccess:(o,k)=>{Fe(de=>({...de,[k]:o})),n("ok",`${k} verification complete.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Ea=ft(async()=>x.invalidateQueries({queryKey:["settings","mcp"]}),[x]),i=ke({mutationFn:async({action:o,server:k})=>{if(!k)throw new Error("No MCP server selected.");if(o==="connect")return a.mcp.connect(k.name);if(o==="disconnect")return a.mcp.disconnect(k.name);if(o==="refresh")return a.mcp.refresh(k.name);if(o==="toggle-enabled")return a.mcp.setEnabled(k.name,!k.enabled);if(o==="delete")return t(`/api/engine/mcp/${encodeURIComponent(k.name)}`,{method:"DELETE"});throw new Error(`Unknown action: ${o}`)},onSuccess:async(o,k)=>{await Ea(),k.action==="connect"&&n("ok",`Connected ${k.server?.name}.`),k.action==="disconnect"&&n("ok",`Disconnected ${k.server?.name}.`),k.action==="refresh"&&n("ok",`Refreshed ${k.server?.name}.`),k.action==="toggle-enabled"&&n("ok",`${k.server?.enabled?"Disabled":"Enabled"} ${k.server?.name}.`),k.action==="delete"&&n("ok",`Deleted ${k.server?.name}.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),m=ke({mutationFn:async()=>{const o=String(ze||"").trim(),k=li(o),de=Vr($t||k);if(!o)throw new Error("Transport URL is required.");if(!_r(o)&&!o.startsWith("stdio:"))throw new Error("Transport must be a valid URL or stdio:* transport.");const Ee=wp({authMode:be,token:Ve,customHeader:dt,transport:o}),ct=yp(Ee,Ke),Tt=String(G||"").trim();un(o)&&Tt&&(ct["X-MCP-Toolsets"]=Tt);const Wt={name:de,transport:o,enabled:!0};Object.keys(ct).length&&(Wt.headers=ct);const sa=String(R||"").trim();if(sa&&sa!==de&&await t(`/api/engine/mcp/${encodeURIComponent(sa)}`,{method:"DELETE"}).catch(()=>null),await a.mcp.add(Wt),b&&!(await a.mcp.connect(Wt.name))?.ok)throw new Error(`Added "${Wt.name}" but connect failed.`);return Wt.name},onSuccess:async o=>{await Ea(),At(!1),We(""),tt(""),Se("none"),ce(""),S(""),ue(""),l([]),T(!0),$(""),n("ok",`Saved MCP "${o}".`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),D=o=>{if(!o)return;if(o.size>10*1024*1024){n("err","Avatar image is too large (max 10 MB).");return}const k=new FileReader;k.onload=()=>{const de=typeof k.result=="string"?k.result:"";if(!de){n("err","Failed to read avatar image.");return}B(de)},k.onerror=()=>n("err","Failed to read avatar image."),k.readAsDataURL(o)},Z=Array.isArray(Gt.data?.all)?Gt.data.all:[];fe(()=>{const o=na.find(k=>k.isDefault)||na[0];o&&(He(k=>k.trim()&&k.trim().toLowerCase()!=="custom"?k:o.id),Ze(k=>k.trim()?k:o.url),Ae(k=>k.trim()?k:o.model),lt(String(mt.data?.default||"").trim().toLowerCase()===o.id.trim().toLowerCase()))},[na,mt.data?.default]);const le=F(()=>kp(Be.data),[Be.data]),nt=F(()=>Np(it.data),[it.data]),Dt=F(()=>_p(_t.data?.catalog||_t.data||null),[_t.data]),Na=F(()=>new Set(le.map(o=>o.name.toLowerCase())),[le]),_a=F(()=>{const o=String(Ot||"").trim().toLowerCase();return Dt.servers.filter(k=>o?k.name.toLowerCase().includes(o)||k.slug.toLowerCase().includes(o)||k.transportUrl.toLowerCase().includes(o):!0).slice(0,36)},[Dt.servers,Ot]),ha=le.filter(o=>o.connected).length,_e=F(()=>oa.data?.status||{},[oa.data]),ra=F(()=>Array.isArray(ka.data?.drafts)?ka.data.drafts||[]:[],[ka.data]),Ca=F(()=>Array.isArray(Zt.data?.incidents)?Zt.data.incidents||[]:[],[Zt.data]),sn=F(()=>Array.isArray(va.data?.posts)?va.data.posts||[]:[],[va.data]),Sa=F(()=>le.find(o=>o.name.toLowerCase()===String(L||"").trim().toLowerCase())||null,[L,le]),jt=F(()=>Z.find(o=>String(o?.id||"").toLowerCase()===String(st||"").trim().toLowerCase())||null,[st,Z]),_n=F(()=>{const o=jt&&typeof jt=="object"?jt.models||{}:{};return Object.keys(o).sort((k,de)=>k.localeCompare(de))},[jt]),on=Array.isArray(Je.data?.blocking_issues)?Je.data?.blocking_issues||[]:[],Sn=Array.isArray(Je.data?.recommendations)?Je.data?.recommendations||[]:[],Vn=Array.isArray(Je.data?.install_hints)?Je.data?.install_hints||[]:[],In=["telegram","discord","slack"],Sr=In.filter(o=>!!wn.data?.[o]?.connected).length,Ir=Array.isArray(Ma.data?.directories)?Ma.data.directories:[],Yn=String(ut||"").trim().toLowerCase(),hs=F(()=>Yn?Ir.filter(o=>String(o?.name||o?.path||"").trim().toLowerCase().includes(Yn)):Ir,[Ir,Yn]),Cr=String(Ma.data?.parent||"").trim(),Xn=String(Ma.data?.dir||Ce||"").trim();fe(()=>{const o=zt.data?.bug_monitor&&typeof zt.data?.bug_monitor=="object"?zt.data.bug_monitor:{};Pt(!!o.enabled),te(!!o.paused),h(String(o.workspace_root||"").trim()),J(String(o.repo||"").trim()),X(String(o.mcp_server||"").trim()),Ue(String(o.provider_preference||"auto").trim()||"auto"),vt(String(o.model_policy?.default_model?.provider_id||"").trim()),et(String(o.model_policy?.default_model?.model_id||"").trim()),Lt(o.auto_create_new_issues!==!1),Ct(!!o.require_approval_for_new_issues),kt(o.auto_comment_on_matched_open_issues!==!1)},[zt.data]),fe(()=>{const o=Ia.data&&typeof Ia.data=="object"?Ia.data:{};rt(k=>{const de={...k};for(const Ee of In)de[Ee]||(de[Ee]=Fr(Ee,o[Ee]));return de})},[Ia.data]);const gs=(o,k)=>{const de=String(k||"").trim();de&&Jn.mutate({providerId:o,modelId:de})},Zn=o=>{if(o){Xe("manual");const k=o.headers&&typeof o.headers=="object"?o.headers:{},de=Object.keys(k),Ee=de.find(gt=>String(gt).toLowerCase()==="authorization"),ct=de.find(gt=>String(gt).toLowerCase()==="x-api-key"),Tt=de.find(gt=>String(gt).toLowerCase()==="x-mcp-toolsets"),Wt=de.filter(gt=>![Ee,ct,Tt].filter(Boolean).map(Aa=>String(Aa).toLowerCase()).includes(String(gt).toLowerCase()));let sa="none",pt="",ht="";ct?(sa="x-api-key",ht=String(k[ct]||"").trim()):Ee?(sa="bearer",ht=String(k[Ee]||"").replace(/^bearer\s+/i,"").trim()):Wt.length===1&&(sa="custom",pt=Wt[0],ht=String(k[Wt[0]]||"").trim()),$(o.name),We(o.name),tt(o.transport||""),T(o.connected||!1),ue(Tt?String(k[Tt]||"").trim():un(o.transport||"")?"default":""),Se(sa),S(pt),ce(ht);const Da=new Set([Ee,ct,Tt,sa==="custom"?pt:""].filter(Boolean).map(gt=>String(gt).toLowerCase()));l(de.filter(gt=>!Da.has(String(gt).toLowerCase())).map(gt=>({key:gt,value:String(k[gt]||"").trim()})))}else Xe("catalog"),$(""),We(""),tt(""),Se("none"),S(""),ce(""),ue(""),l([]),T(!0);At(!0)},fs=async()=>{const o=await t("/api/engine/bug-monitor/debug",{method:"GET"});await navigator.clipboard.writeText(JSON.stringify(o,null,2)),n("ok","Bug Monitor debug payload copied.")},bs=[{id:"providers",label:"Providers",icon:"cpu"},{id:"search",label:"Web Search",icon:"globe"},{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"}],oo=F(()=>xp(be,Ve,dt,ze),[be,dt,Ve,ze]),lo=F(()=>un(ze),[ze]);return fe(()=>{const o=A.current;o?xa(o):xa()},[C,Ie,bt,Ne,L,_e.readiness?.runtime_ready,_e.runtime?.monitoring_active,_e.runtime?.paused,_e.runtime?.pending_incidents,_e.pending_drafts,ra.length,Ca.length,qa.isPending,Ha.isPending,$a.isPending,nn.isPending,an.isPending,Qa.isPending,i.isPending,ea.isPending]),e(vn,{className:"grid gap-4",children:e("div",{ref:A,className:"grid gap-4",children:[e("div",{className:"tcp-settings-tabs",children:bs.map(o=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${C===o.id?"active":""}`,onClick:()=>H(o.id),children:[e("i",{"data-lucide":o.icon}),o.label]},o.id))}),e(En,{main:e(Tc,{className:"grid gap-4",children:[C==="providers"?e(ot,{title:"Provider defaults",subtitle:"Provider catalog, model selection, and API key entry.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(ve,{tone:String(mt.data?.default||"").trim()?"ok":"warn",children:["Default: ",String(mt.data?.default||"none")]}),e(ve,{tone:"info",children:[String(Gt.data?.connected?.length||0)," connected"]}),e("button",{className:"tcp-btn",onClick:()=>N().then(()=>n("ok","Provider status refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh provider"]})]}),children:e("div",{className:"grid gap-3",children:[e("div",{className:"tcp-list-item grid gap-3",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium",children:"Custom OpenAI-compatible provider"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:"Add providers like MiniMax by ID, base URL, default model, and API key."})]}),e(ve,{tone:na.length?"ok":"info",children:[na.length," configured"]})]}),e("form",{className:"grid gap-3",onSubmit:o=>{o.preventDefault(),pa.mutate({providerId:Me,url:Y,modelId:ae,apiKey:St,makeDefault:W})},children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Provider ID"}),e("input",{className:"tcp-input",value:Me,onInput:o=>He(o.target.value),placeholder:"custom"})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Default model"}),e("input",{className:"tcp-input",value:ae,onInput:o=>Ae(o.target.value),placeholder:"MiniMax-M2"})]})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Base URL"}),e("input",{className:"tcp-input",value:Y,onInput:o=>Ze(o.target.value),placeholder:"https://api.minimax.io/v1"})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"API key"}),e("input",{className:"tcp-input",type:"password",value:St,onInput:o=>oe(o.target.value),placeholder:"Optional. Leave blank to keep the existing key."})]}),e("label",{className:"inline-flex items-center gap-2 text-sm text-slate-200",children:[e("input",{type:"checkbox",className:"accent-slate-400",checked:W,onChange:o=>lt(o.target.checked)}),"Make this the default provider"]}),e("div",{className:"flex flex-wrap justify-end gap-2",children:e("button",{className:"tcp-btn-primary",type:"submit",disabled:pa.isPending,children:[e("i",{"data-lucide":"plus"}),"Save custom provider"]})})]}),na.length?e("div",{className:"grid gap-2",children:na.map(o=>e("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:[e("div",{className:"min-w-0",children:[e("div",{className:"font-medium",children:o.id}),e("div",{className:"tcp-subtle break-all text-xs",children:o.url||"No URL configured"}),e("div",{className:"tcp-subtle text-xs",children:["Model: ",o.model||"not set"]})]}),e("div",{className:"flex flex-wrap gap-2",children:[o.isDefault?e(ve,{tone:"ok",children:"default"}):null,e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{He(o.id),Ze(o.url),Ae(o.model),lt(o.isDefault),Oe(!0)},children:[e("i",{"data-lucide":"square-pen"}),"Edit"]})]})]},o.id))}):null]}),e("button",{type:"button",className:"tcp-list-item text-left",onClick:()=>Oe(o=>!o),"aria-expanded":se,children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium inline-flex items-center gap-2",children:[e("i",{"data-lucide":se?"chevron-down":"chevron-right"}),e("span",{children:se?"Hide provider catalog":"Show provider catalog"})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Z.length," providers available for configuration. Expand to change models and API keys."]})]}),e(ve,{tone:"info",children:[String(Gt.data?.connected?.length||0)," connected"]})]})}),e(Mt,{initial:!1,children:se?e(Re.div,{className:"grid gap-3",initial:{opacity:0,y:-8},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},children:Z.length?Z.map(o=>{const k=String(o?.id||""),de=Object.keys(o?.models||{}),Ee=String(mt.data?.providers?.[k]?.default_model||de[0]||""),ct=String(O[k]??Ee).trim(),Tt=ct.toLowerCase(),Wt=de.filter(gt=>Tt?gt.toLowerCase().includes(Tt):!0).slice(0,80),sa=Tp(o,de.length),pt=Rp(o,Ee),ht=_i[k]||null,Da=String(ht?.keyUrl||"").trim();return e(Re.details,{layout:!0,className:"tcp-list-item",children:[e("summary",{className:"cursor-pointer list-none",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium",children:k}),e("div",{className:"tcp-subtle text-xs",children:pt})]}),e(ve,{tone:sa.tone,children:sa.text})]})}),e("div",{className:"mt-3 grid gap-3",children:[Da?e("div",{className:"flex justify-end",children:e("a",{className:"tcp-btn h-8 px-3 text-xs",href:Da,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Get API key"]})}):null,e("form",{className:"grid gap-2",onSubmit:gt=>{gt.preventDefault(),gs(k,ct)},children:[e("div",{className:"flex gap-2",children:[e("input",{className:"tcp-input",value:ct,placeholder:`Type model id for ${k}`,onInput:gt=>_(Aa=>({...Aa,[k]:gt.target.value}))}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"badge-check"}),"Apply"]})]}),e("div",{className:"max-h-48 overflow-auto rounded-xl border border-slate-700/60 bg-slate-900/20 p-1",children:Wt.length?Wt.map(gt=>e("button",{type:"button",className:`block w-full rounded-lg px-2 py-1.5 text-left text-sm hover:bg-slate-700/30 ${gt===Ee?"bg-slate-700/40":""}`,onClick:()=>{_(Aa=>({...Aa,[k]:gt})),gs(k,gt)},children:gt},gt)):e("div",{className:"tcp-subtle px-2 py-1 text-xs",children:de.length?"No matching models.":"No live catalog available. Type a model ID manually."})})]}),e("form",{onSubmit:gt=>{gt.preventDefault();const Aa=gt.currentTarget.elements.namedItem("apiKey"),vs=String(Aa?.value||"").trim();vs&&(Hn.mutate({providerId:k,apiKey:vs}),Aa.value="")},className:"flex gap-2",children:[e("input",{name:"apiKey",className:"tcp-input",placeholder:String(ht?.placeholder||`Set ${k} API key`)}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"save"}),"Save"]})]})]})]},k)}):e(je,{text:"No providers were detected from the engine catalog."})}):null})]})}):null,C==="search"?e(ot,{title:"Web Search",subtitle:"Configure the engine's `websearch` backend and provider keys.",actions:e(wa,{children:[e(ve,{tone:Nt.data?.settings?.has_brave_key?"ok":"warn",children:["Brave"," ",Nt.data?.settings?.has_brave_key?"configured":"missing"]}),e(ve,{tone:Nt.data?.settings?.has_exa_key?"ok":"warn",children:["Exa"," ",Nt.data?.settings?.has_exa_key?"configured":"missing"]}),e("button",{className:"tcp-btn-primary",onClick:()=>ea.mutate({backend:M,tandem_url:y,searxng_url:j,timeout_ms:Number.parseInt(ee||"10000",10),brave_api_key:$e.trim()||void 0,exa_api_key:re.trim()||void 0}),disabled:!Nt.data?.available||ea.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:Nt.data?.available?e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4 text-sm",children:[e("div",{className:"font-medium",children:"Engine env file"}),e("div",{className:"tcp-subtle mt-1 break-all",children:Nt.data?.managed_env_path||"/etc/tandem/engine.env"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:Nt.data?.restart_hint||"Restart tandem-engine after saving search settings."})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Backend"}),e("select",{className:"tcp-select",value:M,onChange:o=>xe(o.target.value),children:[e("option",{value:"auto",children:"Auto failover"}),e("option",{value:"brave",children:"Brave Search"}),e("option",{value:"exa",children:"Exa"}),e("option",{value:"searxng",children:"SearxNG"}),e("option",{value:"tandem",children:"Tandem hosted search"}),e("option",{value:"none",children:"Disable websearch"})]})]}),e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Timeout (ms)"}),e("input",{className:"tcp-input",type:"number",min:1e3,max:12e4,value:ee,onInput:o=>qe(o.target.value)})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"Tandem search URL"}),e("input",{className:"tcp-input",placeholder:"https://search.tandem.frumu.ai",value:y,onInput:o=>v(o.target.value)})]}),e("label",{className:"grid gap-1 text-sm",children:[e("span",{className:"tcp-subtle text-xs uppercase tracking-[0.18em]",children:"SearxNG URL"}),e("input",{className:"tcp-input",placeholder:"http://127.0.0.1:8080",value:j,onInput:o=>he(o.target.value)})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Brave Search key"}),e(ve,{tone:Nt.data?.settings?.has_brave_key?"ok":"warn",children:Nt.data?.settings?.has_brave_key?"Saved":"Missing"})]}),e("input",{className:"tcp-input",type:"password",placeholder:"Paste Brave Search key",value:$e,onInput:o=>Le(o.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>ea.mutate({backend:M,tandem_url:y,searxng_url:j,timeout_ms:Number.parseInt(ee||"10000",10),brave_api_key:$e.trim()||void 0}),disabled:!$e.trim()||ea.isPending,children:"Save Brave Key"}),Nt.data?.settings?.has_brave_key?e("button",{className:"tcp-btn",onClick:()=>ea.mutate({backend:M,tandem_url:y,searxng_url:j,timeout_ms:Number.parseInt(ee||"10000",10),clear_brave_key:!0}),disabled:ea.isPending,children:"Remove"}):null]})]}),e("div",{className:"grid gap-2 rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:"Exa key"}),e(ve,{tone:Nt.data?.settings?.has_exa_key?"ok":"warn",children:Nt.data?.settings?.has_exa_key?"Saved":"Missing"})]}),e("input",{className:"tcp-input",type:"password",placeholder:"Paste Exa API key",value:re,onInput:o=>me(o.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>ea.mutate({backend:M,tandem_url:y,searxng_url:j,timeout_ms:Number.parseInt(ee||"10000",10),exa_api_key:re.trim()||void 0}),disabled:!re.trim()||ea.isPending,children:"Save Exa Key"}),Nt.data?.settings?.has_exa_key?e("button",{className:"tcp-btn",onClick:()=>ea.mutate({backend:M,tandem_url:y,searxng_url:j,timeout_ms:Number.parseInt(ee||"10000",10),clear_exa_key:!0}),disabled:ea.isPending,children:"Remove"}):null]})]})]}),e("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."})]}):e(je,{text:Nt.data?.reason||"Search settings are only editable here when the panel points at a local engine host."})}):null,C==="identity"?e(ot,{title:"Identity preview",subtitle:"Live preview of how the assistant appears across the panel.",actions:e(wa,{children:[e("button",{className:"tcp-btn",onClick:()=>E().then(()=>n("ok","Identity refreshed.")),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh identity"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Gn.mutate(),disabled:Gn.isPending,children:[e("i",{"data-lucide":"save"}),"Save"]})]}),children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-slate-700/60 bg-slate-950/25 p-4",children:e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"inline-flex items-center gap-3",children:[e("span",{className:"tcp-brand-avatar inline-grid h-12 w-12 rounded-xl",children:Q?e("img",{src:Q,alt:z||"Bot",className:"block h-full w-full object-cover"}):e("i",{"data-lucide":"cpu"})}),e("div",{children:[e("div",{className:"font-semibold",children:z||"Tandem"}),e("div",{className:"tcp-subtle text-xs",children:ne||"Control Center"})]})]}),e(wa,{children:[e("button",{className:"tcp-icon-btn",title:"Upload avatar","aria-label":"Upload avatar",onClick:()=>qt.current?.click(),children:e("i",{"data-lucide":"pencil"})}),e("button",{className:"tcp-icon-btn",title:"Clear avatar","aria-label":"Clear avatar",onClick:()=>B(""),children:e("i",{"data-lucide":"trash-2"})})]})]})}),e("input",{className:"tcp-input",value:z,onInput:o=>P(o.target.value),placeholder:"Bot name"}),e("input",{className:"tcp-input",value:ne,onInput:o=>I(o.target.value),placeholder:"Control panel alias"}),e("input",{className:"tcp-input",value:Q,onInput:o=>B(o.target.value),placeholder:"Avatar URL or data URL"}),e("input",{ref:qt,type:"file",accept:"image/*",className:"hidden",onChange:o=>D(o.target.files?.[0]||null)})]})}):null,C==="theme"?e(ot,{title:"Theme studio",subtitle:"Preview tiles with richer feedback and immediate switching.",children:e(hp,{themes:d,themeId:p,onChange:u})}):null,C==="channels"?e(ot,{title:"Channel connections",subtitle:"Telegram, Discord, and Slack delivery setup and live listener status.",actions:e(wa,{children:[e(ve,{tone:Sr?"ok":"warn",children:[Sr,"/",In.length," connected"]}),e("button",{className:"tcp-btn",onClick:()=>{Ga()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh channels"]})]}),children:e("div",{className:"grid gap-3",children:In.map(o=>{const k=Ia.data?.[o]||{},de=wn.data?.[o]||{},Ee=xt[o]||Fr(o,k),ct=Et[o],Tt=di(zn.data?.[o]||ci()),Wt=Ee.securityProfile==="public_demo",sa=!!k?.has_token||!!(Array.isArray(k?.allowed_users)&&k.allowed_users.length)||!!String(k?.guild_id||"").trim()||!!String(k?.channel_id||"").trim();return e("div",{className:"tcp-list-item grid gap-3",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-semibold capitalize",children:o}),e("div",{className:"tcp-subtle text-xs",children:o==="telegram"?"Bot token, allowed users, and style profile.":o==="discord"?"Bot token, allowed users, mention policy, and guild targeting.":"Bot token, allowed users, mention policy, and default channel."})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(ve,{tone:de.connected?"ok":"warn",children:de.connected?"Connected":de.enabled?"Configured":"Disconnected"}),e(ve,{tone:k.has_token?"info":"warn",children:k.has_token?"Token saved":"No token"})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("input",{className:"tcp-input",type:"password",placeholder:k.has_token?String(k.token_masked||"********"):`Paste ${o} bot token`,value:Ee.botToken,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,botToken:pt.target.value}}))}),k.has_token&&!Ee.botToken?e("div",{className:"tcp-subtle text-xs",children:"Token is already stored. Enter a new token only if you want to replace it."}):null,e("input",{className:"tcp-input",placeholder:"Allowed users (comma separated)",value:Ee.allowedUsers,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,allowedUsers:pt.target.value}}))})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("select",{className:"tcp-input",value:Ee.securityProfile,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,securityProfile:pt.target.value}})),children:[e("option",{value:"operator",children:"Operator"}),e("option",{value:"trusted_team",children:"Trusted team"}),e("option",{value:"public_demo",children:"Public demo"})]}),o==="telegram"?e("input",{className:"tcp-input",placeholder:"Style profile",value:Ee.styleProfile,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,styleProfile:pt.target.value}}))}):null,o==="discord"?e("input",{className:"tcp-input",placeholder:"Guild ID (optional)",value:Ee.guildId,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,guildId:pt.target.value}}))}):null,o==="slack"?e("input",{className:"tcp-input",placeholder:"Default channel ID",value:Ee.channelId,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,channelId:pt.target.value}}))}):null,e("label",{className:"inline-flex items-center gap-2 rounded-xl border border-slate-700/60 bg-slate-900/20 px-3 py-2 text-sm",children:[e("input",{type:"checkbox",checked:Ee.mentionOnly,onChange:pt=>rt(ht=>({...ht,[o]:{...Ee,mentionOnly:pt.target.checked}}))}),"Mention only"]})]}),Ee.securityProfile==="public_demo"?e("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,e("div",{className:"tcp-subtle text-xs",children:["Active sessions: ",Number(de.active_sessions||0),de.last_error?` · Last error: ${de.last_error}`:""]}),ct?.hints?.length?e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3 text-xs",children:[e("div",{className:"mb-1 font-medium",children:"Verification hints"}),e("div",{className:"grid gap-1",children:ct.hints.map((pt,ht)=>e("div",{className:"tcp-subtle",children:pt},`${o}-hint-${ht}`))})]}):null,e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-3 flex flex-wrap items-start justify-between gap-3",children:[e("div",{children:[e("div",{className:"font-medium",children:"Channel tool scope"}),e("div",{className:"tcp-subtle text-xs",children:["Built-in tools and MCP servers available to ",o," sessions."]}),Tt.enabled_tools.length>0?e("div",{className:"mt-1 text-xs text-amber-300",children:"Explicit built-in allowlist is active for this channel."}):null,Wt?e("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]}),e("button",{className:"tcp-btn",disabled:Oa.isPending,onClick:()=>Oa.mutate({channel:o,payload:{reset:!0}}),children:"Reset scope"})]}),e("div",{className:"grid gap-3",children:[fp.map(pt=>e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-[11px] uppercase tracking-[0.24em]",children:pt.label}),e("div",{className:"grid gap-2 md:grid-cols-2",children:pt.tools.map(ht=>{const Da=ro(Ee.securityProfile,ht),gt=Ap(Tt,ht,Ee.securityProfile);return e("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:[e("div",{className:"flex flex-col",children:[e("span",{className:"font-mono text-xs",children:ht}),Da?null:e("span",{className:"tcp-subtle text-[11px]",children:"Disabled by security profile"})]}),e("input",{type:"checkbox",checked:gt,disabled:Oa.isPending||!Da,onChange:Aa=>Oa.mutate({channel:o,payload:Ip(Tt,ht,Aa.currentTarget.checked)})})]},`${o}-${ht}`)})})]},`${o}-${pt.label}`)),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-subtle text-[11px] uppercase tracking-[0.24em]",children:"MCP servers"}),le.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:le.map(pt=>{const ht=!Wt&&Tt.enabled_mcp_servers.includes(pt.name);return e("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:[e("div",{className:"flex flex-col",children:[e("span",{className:"font-mono text-xs",children:pt.name}),Wt?e("span",{className:"tcp-subtle text-[11px]",children:"Disabled by security profile"}):null]}),e("input",{type:"checkbox",checked:ht,disabled:Oa.isPending||Wt,onChange:Da=>Oa.mutate({channel:o,payload:Cp(Tt,pt.name,Da.currentTarget.checked)})})]},`${o}-mcp-${pt.name}`)})}):e("div",{className:"tcp-subtle text-xs",children:Wt?"MCP servers stay disabled in public demo mode.":"No MCP servers configured yet."})]})]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:xn.isPending,onClick:()=>xn.mutate(o),children:[e("i",{"data-lucide":"save"}),"Save"]}),o==="discord"?e("button",{className:"tcp-btn",disabled:Nn.isPending,onClick:()=>Nn.mutate("discord"),children:[e("i",{"data-lucide":"shield-check"}),"Verify"]}):null,e("button",{className:"tcp-btn-danger",disabled:kn.isPending||!sa,onClick:()=>kn.mutate(o),children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},o)})})}):null,C==="mcp"?e(ot,{title:"MCP connections",subtitle:"Configured MCP servers, connection state, and discovered tool coverage.",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(ve,{tone:ha?"ok":"warn",children:[ha,"/",le.length," connected"]}),e(ve,{tone:"info",children:[nt.length," tools"]}),e("button",{className:"tcp-btn-primary",onClick:()=>Zn(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]}),e("button",{className:"tcp-btn",onClick:()=>{Ea()},children:[e("i",{"data-lucide":"refresh-cw"}),"Reload"]})]}),children:e("div",{className:"grid gap-3",children:[le.length?le.map(o=>{const k=Object.keys(o.headers||{}).filter(Boolean),de=Array.isArray(o.toolCache)?o.toolCache.length:0;return e("div",{className:"tcp-list-item grid gap-2",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:o.name}),e("div",{className:"tcp-subtle text-sm",children:o.transport||"No transport set"})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(ve,{tone:o.connected?"ok":"warn",children:o.connected?"Connected":"Disconnected"}),e(ve,{tone:o.enabled?"info":"warn",children:o.enabled?"Enabled":"Disabled"}),e(ve,{tone:"info",children:[de," tools"]})]})]}),o.lastError?e("div",{className:"rounded-xl border border-rose-700/60 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:o.lastError}):null,e("div",{className:"tcp-subtle text-xs",children:k.length?`Auth headers: ${k.join(", ")}`:"No stored auth headers."}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>Zn(o),children:"Edit"}),e("button",{className:"tcp-btn",disabled:i.isPending,onClick:()=>i.mutate({action:o.connected?"disconnect":"connect",server:o}),children:o.connected?"Disconnect":"Connect"}),e("button",{className:"tcp-btn",disabled:i.isPending,onClick:()=>i.mutate({action:"refresh",server:o}),children:"Refresh"}),e("button",{className:"tcp-btn",disabled:i.isPending,onClick:()=>i.mutate({action:"toggle-enabled",server:o}),children:o.enabled?"Disable":"Enable"}),e("button",{className:"tcp-btn-danger",disabled:i.isPending,onClick:()=>i.mutate({action:"delete",server:o}),children:"Delete"})]})]},o.name)}):e("div",{className:"grid gap-3",children:[e(je,{text:"No MCP servers configured."}),e("div",{className:"flex justify-start",children:e("button",{className:"tcp-btn-primary",onClick:()=>Zn(),children:[e("i",{"data-lucide":"plus"}),"Add MCP server"]})})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Discovered tools"}),e("pre",{className:"tcp-code max-h-56 overflow-auto whitespace-pre-wrap break-words",children:nt.length?nt.slice(0,250).join(`
|
|
2459
|
+
`):"No MCP tools discovered yet. Connect a server first."})]})]})}):null,C==="bug_monitor"?e(ot,{title:"Bug monitor",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(ve,{tone:_e.runtime?.monitoring_active?_e.readiness?.publish_ready?"ok":"info":_e.readiness?.ingest_ready?"info":"warn",children:_e.runtime?.monitoring_active?_e.readiness?.publish_ready?"Monitoring":"Watching locally":_e.readiness?.ingest_ready?"Ready":"Not ready"}),bt||_e.runtime?.paused?e(ve,{tone:"warn",children:"Paused"}):null,e(ve,{tone:"info",children:[Number(_e.runtime?.pending_incidents||0)," incidents"]}),e(ve,{tone:"info",children:[Number(_e.pending_drafts||0)," pending drafts"]}),e(ve,{tone:"info",children:[Number(_e.pending_posts||0)," post attempts"]}),e("button",{className:"tcp-icon-btn",title:"Reload status","aria-label":"Reload status",onClick:()=>Promise.all([oa.refetch(),ka.refetch(),Zt.refetch(),va.refetch()]).then(()=>n("ok","Bug Monitor status refreshed.")),children:e("i",{"data-lucide":"refresh-cw"})}),e("button",{className:"tcp-icon-btn",title:bt||_e.runtime?.paused?"Resume monitoring":"Pause monitoring","aria-label":bt||_e.runtime?.paused?"Resume monitoring":"Pause monitoring",disabled:Ha.isPending,onClick:()=>Ha.mutate({action:bt||_e.runtime?.paused?"resume":"pause"}),children:e("i",{"data-lucide":bt||_e.runtime?.paused?"play":"pause"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:qa.isPending,onClick:()=>qa.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{fs()},children:e("i",{"data-lucide":"copy"})}),e("button",{className:"tcp-icon-btn",title:"Open GitHub MCP guide","aria-label":"Open GitHub MCP guide",onClick:()=>Te(!0),children:e("i",{"data-lucide":"book-open"})})]}),children:e("div",{className:"grid gap-4",children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Reporter state"}),e("button",{type:"button",className:`tcp-list-item text-left ${Ie?"ring-1 ring-emerald-400/40":""}`,onClick:()=>Pt(o=>!o),children:[e("div",{className:"font-medium",children:Ie?bt?"Paused":"Enabled":"Disabled"}),e("div",{className:"tcp-subtle text-xs",children:Ie?bt?"Monitoring is paused. Resume to process new failures.":"Failure events can be analyzed once readiness is green.":"No reporter work will execute."})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Local directory"}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr_auto]",children:[e("button",{className:"tcp-btn",type:"button",onClick:()=>{const o=String(Ne||"/").trim();we(o||"/"),Qe(""),da(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,value:Ne,placeholder:"No local directory selected. Use Browse."}),e("button",{className:"tcp-btn",type:"button",onClick:()=>h(""),disabled:!Ne,children:[e("i",{"data-lucide":"x"}),"Clear"]})]}),e("div",{className:"tcp-subtle text-xs",children:Ne?`Reporter analysis root: ${Ne}`:"Defaults to the engine workspace root if not set."})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Target repo"}),e("input",{className:"tcp-input",value:U,onChange:o=>J(o.target.value),placeholder:"owner/repo"})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"MCP server"}),e("select",{className:"tcp-input",value:L,onChange:o=>X(o.target.value),children:[e("option",{value:"",children:"Select an MCP server"}),le.map(o=>e("option",{value:o.name,children:o.name},o.name))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider preference"}),e("select",{className:"tcp-input",value:ye,onChange:o=>Ue(o.target.value),children:[e("option",{value:"auto",children:"Auto"}),e("option",{value:"official_github",children:"Official GitHub"}),e("option",{value:"composio",children:"Composio"}),e("option",{value:"arcade",children:"Arcade"})]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Provider"}),e("select",{className:"tcp-input",value:st,onChange:o=>{const k=o.target.value;vt(k),et("")},children:[e("option",{value:"",children:"Select a provider"}),Z.map(o=>e("option",{value:String(o?.id||""),children:String(o?.id||"")},String(o?.id||"")))]})]}),e("label",{className:"grid gap-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"Model"}),e("input",{className:"tcp-input",value:It,onChange:o=>et(o.target.value),list:"bug-monitor-models",disabled:!st,placeholder:st?"Type or paste a model id":"Choose a provider first",spellCheck:!1}),e("datalist",{id:"bug-monitor-models",children:_n.map(o=>e("option",{value:o},o))}),e("div",{className:"tcp-subtle text-xs",children:st?_n.length?`${_n.length} suggested models from provider catalog`:"No provider catalog models available. Manual model ids are allowed.":"Select a provider to load model suggestions."})]}),e("div",{className:"grid gap-2 md:col-span-2",children:[e("span",{className:"text-xs uppercase tracking-[0.24em] tcp-subtle",children:"GitHub posting"}),e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("button",{type:"button",className:`tcp-list-item text-left ${yt&&!Qt?"ring-1 ring-emerald-400/40":""}`,onClick:()=>{Lt(o=>!o),Qt&&yt&&Ct(!1)},children:[e("div",{className:"font-medium",children:"Auto-create new issues"}),e("div",{className:"tcp-subtle text-xs",children:yt?"New drafts post to GitHub automatically.":"New drafts stay internal until published manually."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${Qt?"ring-1 ring-amber-400/40":""}`,onClick:()=>{Ct(o=>{const k=!o;return k&&Lt(!1),k})},children:[e("div",{className:"font-medium",children:"Require approval"}),e("div",{className:"tcp-subtle text-xs",children:Qt?"New drafts wait for a manual publish click.":"Approval gate disabled."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${Ht?"ring-1 ring-sky-400/40":""}`,onClick:()=>kt(o=>!o),children:[e("div",{className:"font-medium",children:"Auto-comment matches"}),e("div",{className:"tcp-subtle text-xs",children:Ht?"Open matching GitHub issues receive new evidence comments.":"Matching issues are detected but not updated automatically."})]})]})]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:Qa.isPending,title:"Save Bug Monitor settings","aria-label":"Save Bug Monitor settings",onClick:()=>Qa.mutate(),children:[e("i",{"data-lucide":"save"}),Qa.isPending?"Saving...":null]}),e("button",{className:"tcp-icon-btn",title:"Add MCP server","aria-label":"Add MCP server",onClick:()=>Zn(),children:e("i",{"data-lucide":"plus"})}),e("button",{className:"tcp-icon-btn",title:"Open setup guide","aria-label":"Open setup guide",onClick:()=>Te(!0),children:e("i",{"data-lucide":"external-link"})}),e("button",{className:"tcp-icon-btn",title:"Refresh capability bindings","aria-label":"Refresh capability bindings",disabled:qa.isPending,onClick:()=>qa.mutate(),children:e("i",{"data-lucide":"rotate-cw"})}),e("button",{className:"tcp-icon-btn",title:"Copy debug payload","aria-label":"Copy debug payload",onClick:()=>{fs()},children:e("i",{"data-lucide":"copy"})}),Sa?e("button",{className:"tcp-icon-btn",title:Sa.connected?"Refresh selected MCP":"Connect selected MCP","aria-label":Sa.connected?"Refresh selected MCP":"Connect selected MCP",disabled:i.isPending,onClick:()=>i.mutate({action:Sa.connected?"refresh":"connect",server:Sa}),children:e("i",{"data-lucide":Sa.connected?"refresh-cw":"plug-zap"})}):null]}),e("div",{className:"grid gap-3 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Readiness"}),e("div",{className:"mt-1 text-sm",children:_e.runtime?.monitoring_active?_e.readiness?.publish_ready?"Monitoring":"Watching locally":_e.runtime?.paused||bt?"Paused":_e.readiness?.ingest_ready?"Ready":"Blocked"}),e("div",{className:"tcp-subtle text-xs",children:_e.runtime?.last_runtime_error||_e.last_error||"No blocking issue reported."}),!_e.readiness?.publish_ready&&Array.isArray(_e.missing_required_capabilities)&&_e.missing_required_capabilities.length?e("div",{className:"tcp-subtle mt-2 text-xs",children:["Missing: ",_e.missing_required_capabilities.join(", ")]}):null]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Selected MCP"}),e("div",{className:"mt-1 text-sm",children:Sa?.name||"None selected"}),e("div",{className:"tcp-subtle text-xs",children:Sa?Sa.connected?"Connected":"Disconnected":"No server selected"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Bindings: ",_e.binding_source_version||"unknown version",_e.bindings_last_merged_at_ms?` · merged ${new Date(_e.bindings_last_merged_at_ms).toLocaleString()}`:""]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Local directory:"," ",Ne||String(_e.config?.workspace_root||"").trim()||"engine workspace root"]}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last event:"," ",String(_e.runtime?.last_incident_event_type||"").trim()||"No incidents processed yet"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Model route"}),e("div",{className:"mt-1 break-all text-sm",children:_e.selected_model?.provider_id&&_e.selected_model?.model_id?`${_e.selected_model.provider_id} / ${_e.selected_model.model_id}`:"No dedicated model selected"}),e("div",{className:"tcp-subtle text-xs",children:_e.readiness?.selected_model_ready?"Available":"Fail-closed when unavailable"}),e("div",{className:"tcp-subtle mt-2 text-xs",children:["Last processed:"," ",_e.runtime?.last_processed_at_ms?new Date(Number(_e.runtime.last_processed_at_ms)).toLocaleString():"Not processed yet"]})]})]}),e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Capability readiness"}),e("div",{className:"tcp-subtle mt-2 grid gap-1 text-xs",children:[e("div",{children:["github.list_issues:"," ",_e.required_capabilities?.github_list_issues?"ready":"missing"]}),e("div",{children:["github.get_issue:"," ",_e.required_capabilities?.github_get_issue?"ready":"missing"]}),e("div",{children:["github.create_issue:"," ",_e.required_capabilities?.github_create_issue?"ready":"missing"]}),e("div",{children:["github.comment_on_issue:"," ",_e.required_capabilities?.github_comment_on_issue?"ready":"missing"]})]}),Array.isArray(_e.resolved_capabilities)&&_e.resolved_capabilities.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:_e.resolved_capabilities.map((o,k)=>e("div",{children:[String(o.capability_id||"unknown"),":"," ",String(o.tool_name||"unresolved")]},`${o.capability_id||"cap"}-${k}`))}):null,Array.isArray(_e.selected_server_binding_candidates)&&_e.selected_server_binding_candidates.length?e("div",{className:"tcp-subtle mt-3 grid gap-1 text-xs",children:_e.selected_server_binding_candidates.map((o,k)=>e("div",{children:[String(o.capability_id||"unknown"),":"," ",String(o.binding_tool_name||"unknown"),o.matched?" · matched":" · candidate"]},`${o.capability_id||"candidate"}-${k}`))}):null,Array.isArray(_e.discovered_mcp_tools)&&_e.discovered_mcp_tools.length?e("div",{className:"mt-3",children:[e("div",{className:"tcp-subtle text-xs font-medium",children:"Discovered MCP tools"}),e("pre",{className:"tcp-code mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words text-xs",children:_e.discovered_mcp_tools.join(`
|
|
2460
|
+
`)})]}):e("div",{className:"tcp-subtle mt-3 text-xs",children:"No MCP tools were discovered for the selected server."})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Posting policy"}),e("div",{className:"tcp-subtle mt-2 grid gap-1 text-xs",children:[e("div",{children:["New issues:"," ",Qt?"Manual publish":yt?"Auto-create":"Internal draft only"]}),e("div",{children:["Matched open issues:"," ",Ht?"Auto-comment":"Detect only"]}),e("div",{children:"Dedupe: Fingerprint marker + label"}),e("div",{children:"Labels: bug-monitor"}),e("div",{children:"Workspace write tools: Disabled"}),e("div",{children:"Model fallback: Fail closed"})]})]})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent incidents"}),Ca.length?e("div",{className:"grid gap-2",children:Ca.map(o=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:o.title||o.event_type}),e(ve,{tone:o.last_error?"warn":"info",children:o.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[o.event_type," · seen"," ",Number(o.occurrence_count||0),"x"," · ",o.updated_at_ms?new Date(o.updated_at_ms).toLocaleString():"time unavailable"]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:o.workspace_root||"engine workspace root"}),o.last_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.last_error}):null,o.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.detail}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-icon-btn",title:"Replay triage for this incident","aria-label":"Replay triage for this incident",disabled:nn.isPending,onClick:()=>nn.mutate({incidentId:o.incident_id}),children:e("i",{"data-lucide":"rotate-cw"})}),o.triage_run_id?e("span",{className:"tcp-subtle text-xs",children:["triage run: ",o.triage_run_id]}):null,o.draft_id?e("span",{className:"tcp-subtle text-xs",children:["draft: ",o.draft_id]}):null]})]},o.incident_id))}):e(je,{text:"No Bug Monitor incidents yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent reporter drafts"}),ra.length?e("div",{className:"grid gap-2",children:ra.map(o=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:o.title||o.fingerprint}),e(ve,{tone:o.status==="approval_required"?"warn":"info",children:o.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[o.repo," ·"," ",o.issue_number?`issue #${o.issue_number}`:"draft only"," ","·"," ",o.created_at_ms?new Date(o.created_at_ms).toLocaleString():"time unavailable"]}),o.github_status?e("div",{className:"tcp-subtle mt-1 text-xs",children:["GitHub: ",o.github_status,o.matched_issue_number?` · matched #${o.matched_issue_number}${o.matched_issue_state?` (${o.matched_issue_state})`:""}`:""]}):null,o.detail?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.detail}):null,o.last_post_error?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.last_post_error}):null,o.triage_run_id?e("div",{className:"tcp-subtle mt-2 text-xs",children:["triage run: ",o.triage_run_id]}):null,o.status==="approval_required"?e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn-primary",disabled:$a.isPending,title:"Approve draft","aria-label":"Approve draft",onClick:()=>$a.mutate({draftId:o.draft_id,decision:"approve"}),children:[e("i",{"data-lucide":"check"}),$a.isPending?"Updating...":null]}),e("button",{className:"tcp-icon-btn",title:"Deny draft","aria-label":"Deny draft",disabled:$a.isPending,onClick:()=>$a.mutate({draftId:o.draft_id,decision:"deny"}),children:e("i",{"data-lucide":"x"})})]}):null,o.issue_number?null:e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{className:"tcp-icon-btn",title:"Publish this draft to GitHub now","aria-label":"Publish this draft to GitHub now",disabled:rn.isPending,onClick:()=>rn.mutate({draftId:o.draft_id}),children:e("i",{"data-lucide":"bug-play"})}),e("button",{className:"tcp-icon-btn",title:"Recheck GitHub for an existing matching issue","aria-label":"Recheck GitHub for an existing matching issue",disabled:Qn.isPending,onClick:()=>Qn.mutate({draftId:o.draft_id}),children:e("i",{"data-lucide":"refresh-cw"})})]}),(o.github_issue_url||o.github_comment_url)&&e("div",{className:"mt-3 flex flex-wrap gap-2 text-xs",children:[o.github_issue_url?e("a",{className:"tcp-btn",href:o.github_issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,o.github_comment_url?e("a",{className:"tcp-btn",href:o.github_comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]}),(o.status==="draft_ready"||o.status==="triage_queued")&&!o.triage_run_id?e("div",{className:"mt-3 flex flex-wrap gap-2",children:e("button",{className:"tcp-icon-btn",title:"Create triage run","aria-label":"Create triage run",disabled:an.isPending,onClick:()=>an.mutate({draftId:o.draft_id}),children:e("i",{"data-lucide":"sparkles"})})}):null]},o.draft_id))}):e(je,{text:"No Bug Monitor drafts yet."})]}),e("div",{className:"rounded-xl border border-slate-700/60 bg-slate-900/20 p-3",children:[e("div",{className:"mb-2 font-medium",children:"Recent GitHub posts"}),sn.length?e("div",{className:"grid gap-2",children:sn.map(o=>e("div",{className:"tcp-list-item",children:[e("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:o.operation}),e(ve,{tone:o.status==="posted"?"ok":"warn",children:o.status})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[o.repo,o.issue_number?` · issue #${o.issue_number}`:"",o.updated_at_ms?` · ${new Date(o.updated_at_ms).toLocaleString()}`:""]}),o.error?e("div",{className:"tcp-subtle mt-1 text-xs",children:o.error}):null,e("div",{className:"mt-3 flex flex-wrap gap-2",children:[o.issue_url?e("a",{className:"tcp-btn",href:o.issue_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Open issue"]}):null,o.comment_url?e("a",{className:"tcp-btn",href:o.comment_url,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"message-square"}),"Open comment"]}):null]})]},o.post_id))}):e(je,{text:"No GitHub post attempts yet."})]})]})}):null,C==="browser"?e(ot,{title:"Browser readiness",subtitle:"Operational browser status, diagnostics, and recovery actions.",actions:e(wa,{children:[e("button",{className:"tcp-btn",onClick:()=>{Je.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[e("i",{"data-lucide":"download"}),pe.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>De.mutate(),disabled:De.isPending,children:[e("i",{"data-lucide":"globe"}),De.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>ge(!0),children:[e("i",{"data-lucide":"activity"}),"Diagnostics"]})]}),children:[e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Status"}),e("div",{className:"mt-1 text-sm",children:Je.data?Je.data.runnable?"Ready":Je.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",Je.data?.headless_default?"yes":"no"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Sidecar"}),e("div",{className:"mt-1 break-all text-sm",children:Je.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Je.data?.sidecar?.version||"No version detected"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Browser"}),e("div",{className:"mt-1 break-all text-sm",children:Je.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Je.data?.browser?.version||Je.data?.browser?.channel||"No version detected"})]})]}),on.length?e("div",{className:"mt-3 grid gap-2",children:on.map((o,k)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:o.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:o.message||"Unknown browser issue."})]},`${o.code||"issue"}-${k}`))}):null,f?e("div",{className:"mt-3 rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:[e("div",{className:"font-medium",children:["Smoke test passed",f.title?`: ${f.title}`:""]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:f.final_url||f.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",f.load_state||"unknown"," · elements:"," ",String(f.element_count??0)," · closed:"," ",f.closed?"yes":"no"]}),f.excerpt?e("pre",{className:"tcp-code mt-2 max-h-32 overflow-auto whitespace-pre-wrap break-words",children:f.excerpt}):null]}):null]}):null]}),aside:e("div",{className:"grid gap-4",children:[e(ot,{title:"Readiness snapshot",subtitle:"High-signal operational summary for this configuration state.",children:e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Connected providers"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[String(Gt.data?.connected?.length||0)," connected, default"," ",String(mt.data?.default||"none")]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Browser automation"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:Je.data?Je.data.runnable?"Ready":Je.data.enabled?"Enabled but blocked":"Disabled":"Unknown"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Theme"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:d.find(o=>o.id===p)?.name||p})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"MCP"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[ha," connected, ",nt.length," discovered tools"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Bug monitor"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[_e.readiness?.runtime_ready?"Ready":Ie?"Enabled but blocked":"Disabled"," · ",Number(_e.pending_drafts||0)," pending drafts"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:"Channels"}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Sr," connected, ",In.length," available"]})]})]})}),e(ot,{title:"Quick access",subtitle:"Jump straight to the section you need.",children:e("div",{className:"grid gap-2",children:bs.map(o=>e("button",{className:"tcp-list-item flex items-center justify-between text-left",onClick:()=>H(o.id),children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":o.icon}),o.label]}),C===o.id?e(ve,{tone:"ok",children:"open"}):null]},o.id))})})]})}),e(br,{open:Pe,onClose:()=>Te(!1),title:"Official GitHub MCP guide",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Recommended for Bug Monitor: use the official GitHub MCP endpoint instead of a third-party wrapper when you want stable issue read/write operations."}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Transport URL"}),e("div",{className:"mt-1 break-all text-sm",children:"https://api.githubcopilot.com/mcp/"}),e("div",{className:"tcp-subtle text-xs",children:"Use this as the MCP server transport in Tandem Settings."})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Auth mode"}),e("div",{className:"mt-1 text-sm",children:"Authorization Bearer"}),e("div",{className:"tcp-subtle text-xs",children:"Paste a GitHub token in the MCP server dialog and use bearer auth."})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommended setup"}),e("div",{className:"tcp-list-item text-sm",children:["1. Open `Add MCP server`.",e("br",{}),"2. Name it `github` or another stable name.",e("br",{}),"3. Set transport to `https://api.githubcopilot.com/mcp/`.",e("br",{}),"4. Set auth mode to `Authorization Bearer`.",e("br",{}),"5. Paste a GitHub Personal Access Token.",e("br",{}),"6. Save, connect, then select that MCP server in Bug Monitor settings."]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Token guidance"}),e("div",{className:"tcp-list-item text-sm",children:"For failure reporting, the token needs issue read/write access on the target repository so the runtime can create issues and add comments."})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Direct links"}),e("div",{className:"flex flex-wrap gap-2",children:[e("a",{className:"tcp-btn",href:"https://github.com/github/github-mcp-server?tab=readme-ov-file",target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"GitHub MCP README"]}),e("a",{className:"tcp-btn",href:"https://docs.github.com/en/copilot/how-tos/provide-context/use-mcp/use-the-github-mcp-server",target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"GitHub Docs"]})]})]}),e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Issue tools to expect"}),e("div",{className:"tcp-list-item text-sm",children:"The reporter should be able to resolve issue-list, issue-read, issue-create, and issue-comment operations from the selected GitHub MCP server. If readiness still fails, compare the discovered MCP tools shown in Settings against those issue operations."})]})]})}),e(Mt,{children:Ge?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close Bug Monitor workspace dialog",onClick:()=>{da(!1),Qe("")}}),e(Re.div,{className:"tcp-confirm-dialog max-w-2xl",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Select Bug Monitor Directory"}),e("p",{className:"tcp-confirm-message",children:["Current: ",Xn||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>{Cr&&we(Cr)},disabled:!Cr,children:[e("i",{"data-lucide":"arrow-up-circle"}),"Up"]}),e("button",{className:"tcp-btn-primary",onClick:()=>{Xn&&(h(Xn),da(!1),Qe(""),n("ok",`Bug Monitor directory selected: ${Xn}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{da(!1),Qe("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ut,onInput:o=>Qe(o.target.value)})}),e("div",{className:"max-h-[360px] overflow-auto rounded-lg border border-slate-700/60 bg-slate-900/20 p-2",children:hs.length?hs.map(o=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>we(String(o?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(o?.name||o?.path||"")]},String(o?.path||o?.name))):e(je,{text:Yn?"No folders match your search.":"No subdirectories in this folder."})})]})]}):null}),e(br,{open:q,onClose:()=>ge(!1),title:"Browser diagnostics",children:e("div",{className:"grid gap-3",children:[e("div",{className:"grid gap-2 md:grid-cols-3",children:[e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Status"}),e("div",{className:"mt-1 text-sm",children:Je.data?Je.data.runnable?"Ready":Je.data.enabled?"Blocked":"Disabled":"Unknown"}),e("div",{className:"tcp-subtle text-xs",children:["Headless default: ",Je.data?.headless_default?"yes":"no"]})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Sidecar"}),e("div",{className:"mt-1 break-all text-sm",children:Je.data?.sidecar?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Je.data?.sidecar?.version||"No version detected"})]}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:"Browser"}),e("div",{className:"mt-1 break-all text-sm",children:Je.data?.browser?.path||"Not found"}),e("div",{className:"tcp-subtle text-xs",children:Je.data?.browser?.version||Je.data?.browser?.channel||"No version detected"})]})]}),e(wa,{children:[e("button",{className:"tcp-btn",onClick:()=>{Je.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh browser status"]}),e("button",{className:"tcp-btn",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[e("i",{"data-lucide":"download"}),pe.isPending?"Installing sidecar...":"Install sidecar"]}),e("button",{className:"tcp-btn",onClick:()=>De.mutate(),disabled:De.isPending,children:[e("i",{"data-lucide":"globe"}),De.isPending?"Running smoke test...":"Run smoke test"]}),e("button",{className:"tcp-btn",onClick:()=>t("/api/engine/browser/status",{method:"GET"}).then(()=>n("ok","Browser diagnostics refreshed.")).catch(o=>n("err",o instanceof Error?o.message:String(o))),children:[e("i",{"data-lucide":"activity"}),"Re-run diagnostics"]})]}),Je.isLoading?e(je,{text:"Loading browser diagnostics..."}):Je.data?e(la,{children:[on.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Blocking issues"}),on.map((o,k)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:o.code||"browser_issue"}),e("div",{className:"tcp-subtle text-xs",children:o.message||"Unknown browser issue."})]},`${o.code||"issue"}-${k}`))]}):e("div",{className:"rounded-xl border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm",children:"Browser automation is ready on this machine."}),f?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Latest smoke test"}),e("div",{className:"tcp-list-item",children:[e("div",{className:"text-sm font-medium",children:f.title||"Smoke test"}),e("div",{className:"tcp-subtle text-xs",children:f.final_url||f.url||"No URL returned"}),e("div",{className:"tcp-subtle text-xs",children:["Load state: ",f.load_state||"unknown"," · elements:"," ",String(f.element_count??0)," · closed:"," ",f.closed?"yes":"no"]}),f.excerpt?e("pre",{className:"tcp-code mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words",children:f.excerpt}):null]})]}):null,Sn.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommendations"}),Sn.map((o,k)=>e("div",{className:"tcp-list-item text-sm",children:o},`browser-recommendation-${k}`))]}):null,Vn.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Install hints"}),Vn.map((o,k)=>e("div",{className:"tcp-list-item text-sm",children:o},`browser-install-hint-${k}`))]}):null,Je.data?.last_error?e("div",{className:"tcp-subtle rounded-lg border border-slate-700/60 bg-slate-900/20 p-3 text-xs",children:["Last error: ",Je.data.last_error]}):null]}):e(je,{text:"Browser diagnostics are unavailable."})]})}),e(Mt,{children:Bt?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:[e("button",{type:"button",className:"tcp-confirm-backdrop","aria-label":"Close MCP server dialog",onClick:()=>At(!1)}),e(Re.div,{className:"tcp-confirm-dialog tcp-verification-modal",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e("div",{children:[e("h3",{className:"tcp-confirm-title",children:R?"Edit MCP Server":"Add MCP Server"}),e("p",{className:"tcp-confirm-message",children:"Configure transport and auth without leaving Settings."})]}),e("button",{type:"button",className:"tcp-btn h-8 px-2",onClick:()=>At(!1),children:e("i",{"data-lucide":"x"})})]}),e("form",{className:"flex min-h-0 flex-1 flex-col gap-3 overflow-hidden",onSubmit:o=>{o.preventDefault(),m.mutate()},children:[e("div",{className:"tcp-settings-tabs",children:[e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${Ye==="catalog"?"active":""}`,onClick:()=>Xe("catalog"),children:[e("i",{"data-lucide":"blocks"}),"Built-in packs"]}),e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${Ye==="manual"?"active":""}`,onClick:()=>Xe("manual"),children:[e("i",{"data-lucide":"square-pen"}),"Manual"]})]}),Ye==="catalog"?e("div",{className:"grid min-h-0 flex-1 content-start gap-3 overflow-hidden",children:[e("div",{className:"flex items-center justify-between gap-3",children:[e("div",{className:"tcp-subtle text-sm",children:Dt.generatedAt?`Built-in MCP packs · generated ${Dt.generatedAt}`:"Built-in MCP packs"}),e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{_t.refetch()},children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("input",{className:"tcp-input",value:Ot,onInput:o=>Ft(o.target.value),placeholder:"Search built-in MCP packs"}),e("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:_a.length?_a.map(o=>{const k=Na.has(String(o.serverConfigName||o.slug||"").toLowerCase());return e("div",{className:"tcp-list-item grid h-full min-h-[8.5rem] content-start gap-2",children:[e("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e("div",{children:[e("div",{className:"font-semibold",children:o.name}),e("div",{className:"tcp-subtle text-xs",children:[o.slug,o.requiresSetup?" · setup required":""]})]}),e("div",{className:"flex flex-wrap gap-2",children:[e(ve,{tone:"info",children:[o.toolCount," tools"]}),e(ve,{tone:o.requiresAuth?"warn":"ok",children:o.requiresAuth?"Auth":"Authless"})]})]}),e("div",{className:"tcp-subtle line-clamp-2 text-xs",children:o.description||o.transportUrl}),e("div",{className:"tcp-subtle break-all text-xs",children:o.transportUrl}),e("div",{className:"mt-auto flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>{const de=o.transportUrl,Ee=Vr(o.serverConfigName||o.slug||o.name);We(Ee),tt(de),Se(Ee==="github"||un(de)?"bearer":"none"),ue(Ee==="github"||un(de)?"default":""),l([]),Xe("manual"),n("ok",`Loaded ${o.name}. Review and save when ready.`)},children:"Use pack"}),o.documentationUrl?e("a",{className:"tcp-btn h-8 px-3 text-xs",href:o.documentationUrl,target:"_blank",rel:"noreferrer",children:[e("i",{"data-lucide":"external-link"}),"Docs"]}):null,k?e(ve,{tone:"ok",children:"added"}):null]})]},o.slug)}):e(je,{text:"No built-in MCP packs match this search."})})]}):e(la,{children:[e("div",{className:"grid gap-3 md:grid-cols-2",children:[e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Name"}),e("input",{className:"tcp-input",value:$t,onInput:o=>We(o.target.value),placeholder:"mcp-server"})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Auth mode"}),e("select",{className:"tcp-select",value:be,onChange:o=>Se(o.target.value),children:[e("option",{value:"none",children:"No Auth Header"}),e("option",{value:"auto",children:"Auto"}),e("option",{value:"x-api-key",children:"x-api-key"}),e("option",{value:"bearer",children:"Authorization Bearer"}),e("option",{value:"custom",children:"Custom Header"})]})]})]}),e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Transport URL"}),e("input",{className:"tcp-input",value:ze,onInput:o=>{const k=o.target.value;if(tt(k),un(k)&&!String(G||"").trim()&&ue("default"),!String($t||"").trim()||$t==="mcp-server"){const de=li(k);de&&We(de)}},placeholder:"https://example.com/mcp"})]}),be==="custom"?e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Custom header name"}),e("input",{className:"tcp-input",value:dt,onInput:o=>S(o.target.value),placeholder:"X-My-Token"})]}):null,e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"Token"}),e("input",{className:"tcp-input",type:"password",value:Ve,onInput:o=>ce(o.target.value),placeholder:"token"}),e("div",{className:"tcp-subtle text-xs",children:oo})]}),lo?e("div",{className:"grid gap-2",children:[e("label",{className:"text-sm font-medium",children:"GitHub toolsets"}),e("input",{className:"tcp-input",value:G,onInput:o=>ue(o.target.value),placeholder:"default,projects"}),e("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,e("div",{className:"grid gap-2",children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("label",{className:"text-sm font-medium",children:"Additional headers"}),e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>l(o=>[...o,{key:"",value:""}]),children:[e("i",{"data-lucide":"plus"}),"Add header"]})]}),Ke.length?e("div",{className:"grid gap-2",children:Ke.map((o,k)=>e("div",{className:"grid gap-2 md:grid-cols-[1fr_1fr_auto]",children:[e("input",{className:"tcp-input",value:o.key,onInput:de=>l(Ee=>Ee.map((ct,Tt)=>Tt===k?{...ct,key:de.target.value}:ct)),placeholder:"Header name"}),e("input",{className:"tcp-input",value:o.value,onInput:de=>l(Ee=>Ee.map((ct,Tt)=>Tt===k?{...ct,value:de.target.value}:ct)),placeholder:"Header value"}),e("button",{type:"button",className:"tcp-btn",onClick:()=>l(de=>de.filter((Ee,ct)=>ct!==k)),children:"Remove"})]},`mcp-header-${k}`))}):e("div",{className:"tcp-subtle text-xs",children:"Add arbitrary request headers such as `X-MCP-Insiders` or vendor feature flags."})]}),e("label",{className:"inline-flex items-center gap-2 text-sm text-slate-200",children:[e("input",{type:"checkbox",className:"accent-slate-400",checked:b,onChange:o=>T(o.target.checked)}),"Connect after save"]})]}),e("div",{className:"tcp-confirm-actions mt-2",children:[e("button",{type:"button",className:"tcp-btn",onClick:()=>At(!1),children:"Cancel"}),e("button",{type:"submit",className:"tcp-btn-primary",disabled:m.isPending,children:[e("i",{"data-lucide":"save"}),"Save MCP server"]})]})]})]})]}):null})]})})}function Mp({routeId:a,pageProps:t}){switch(Zr(a)){case"chat":return e(wd,{...t});case"studio":return e(vu,{...t});case"automations":case"packs":case"teams":return e(Sm,{...t});case"coding":return e(qm,{...t});case"agents":return e(si,{...t});case"channels":return e($m,{...t});case"mcp":return e(ui,{...t});case"packs-detail":return e(Dm,{...t});case"orchestrator":return e(Ym,{...t});case"files":return e(Zm,{...t});case"memory":return e(tp,{...t});case"teams-detail":return e(si,{...t});case"feed":return e(mp,{...t});case"settings":return e(ui,{...t});default:return e(Jc,{...t})}}const qp={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."},studio:{title:"Studio",subtitle:"Template-first workflow builder with reusable role prompts and visual stages."},automations:{title:"Automations",subtitle:"Templates, routines, approvals, and execution history."},coding:{title:"Coding Workflows",subtitle:"Internal Kanban, manual task launchers, and MCP-aware coding runs."},agents:{title:"Agents",subtitle:"Persistent personalities, default models, and prompts reused across automation workflows."},orchestrator:{title:"Orchestrator",subtitle:"Plan-driven task execution with workspace visibility and approvals."},memory:{title:"Memory",subtitle:"Searchable memory records and operational context snapshots."},feed:{title:"Live Feed",subtitle:"Global event stream with pack-aware actions and debugging detail."},settings:{title:"Settings",subtitle:"Provider defaults, identity, themes, and runtime diagnostics."},mcp:{title:"MCP",subtitle:"Catalog, readiness, and generated integration details."},files:{title:"Files",subtitle:"Uploaded assets and workspace-adjacent file management."},"packs-detail":{title:"Packs",subtitle:"Starter packs, installation paths, and detected attachments."},"teams-detail":{title:"Teams",subtitle:"Team instances, approvals, and shared execution state."}};function $p({identity:a,currentRoute:t,providerLocked:n,navRoutes:r,onNavigate:s,onPaletteOpen:c,onThemeCycle:d,onLogout:u,statusBar:p,routeKey:N,children:E,providerGate:x}){const[A,O]=w(!1),[_,z]=w(!1),P=String(a.botAvatarUrl||"").trim(),Q=wi();fe(()=>{O(!1)},[t]),fe(()=>{try{xa()}catch{}},[t,A,p.bugMonitor?.enabled,p.bugMonitor?.monitoringActive,p.bugMonitor?.paused,p.bugMonitor?.pendingIncidents,p.bugMonitor?.blocked]),fe(()=>{z(!1)},[P]);const B=qp[t]||{title:String(r.find(([y])=>y===t)?.[1]||"Control Panel"),subtitle:"Desktop-inspired operations UI for Tandem."},ne=F(()=>r.find(([y])=>y===t)||r[0],[t,r]),I=F(()=>{const y=p.bugMonitor;return y?.enabled?y.blocked?{toneClass:"blocked",label:"Bug Monitor blocked",shortLabel:"Blocked"}:y.paused?{toneClass:"paused",label:"Bug Monitor paused",shortLabel:"Paused"}:y.pendingIncidents>0?{toneClass:"incidents",label:`Bug Monitor incidents: ${y.pendingIncidents}`,shortLabel:`${y.pendingIncidents} incident${y.pendingIncidents===1?"":"s"}`}:y.monitoringActive?{toneClass:"watching",label:"Bug Monitor watching",shortLabel:"Watching"}:{toneClass:"ready",label:"Bug Monitor ready",shortLabel:"Ready"}:null},[p.bugMonitor]),C=()=>P&&!_?e("img",{src:P,alt:a.botName,className:"block h-full w-full object-cover",onError:()=>z(!0)}):e("span",{className:"text-sm font-semibold uppercase",children:String(a.botName||"T").trim().slice(0,1)||"T"}),H=()=>r.map(([y,v,j])=>{const he=t===y,ee=n&&y!=="settings";return e("button",{type:"button",title:v,disabled:ee,className:`tcp-rail-icon ${he?"active":""} ${ee?"locked":""}`,onClick:()=>s(y),children:[he?e(Re.span,{layoutId:"tcp-icon-indicator",className:"tcp-rail-icon-indicator"}):null,e("i",{"data-lucide":j})]},y)}),M=(y=!1)=>r.map(([v,j,he])=>{const ee=t===v,qe=n&&v!=="settings";return e("button",{type:"button",disabled:qe,className:`tcp-context-link ${ee?"active":""} ${qe?"locked":""}`,onClick:()=>{s(v),y&&O(!1)},children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":he}),e("span",{children:j})]}),ee?e("span",{className:"tcp-context-link-dot"}):null]},v)}),xe=(y=!1)=>e(la,{children:[y?e("div",{className:"tcp-context-hero",children:[e(fr,{className:"tcp-context-hero-glow"}),e("div",{className:"relative z-10 flex items-center gap-3",children:[e("div",{className:"tcp-brand-avatar h-11 w-11",children:C()}),e("div",{className:"min-w-0",children:[e("div",{className:"truncate text-sm font-semibold",children:a.controlPanelName||`${a.botName} Control Panel`}),e("div",{className:"tcp-subtle text-xs",children:"Workspace navigation and system status"})]})]})]}):null,e("div",{className:`tcp-context-section ${y?"":"xl:hidden"}`.trim(),children:[e("div",{className:"tcp-context-section-label",children:"Navigation"}),e("nav",{className:"grid gap-1",children:M(y)})]}),y?e("div",{className:"tcp-context-section",children:[e("div",{className:"tcp-context-section-label",children:"System"}),e("div",{className:"grid gap-2",children:[e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Engine"}),p.engineHealthy?e(ya,{tone:"ok",text:"healthy"}):e(ya,{tone:"warn",text:"checking"})]}),e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Provider"}),e("span",{className:p.providerBadge,children:p.providerText})]}),e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Active runs"}),p.activeRuns>0?e(ya,{tone:"live",text:String(p.activeRuns)}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"idle"})]}),I?e("div",{className:"tcp-context-stat",children:[e("span",{className:"tcp-subtle text-xs",children:"Bug Monitor"}),e("button",{type:"button",className:`tcp-bug-monitor-pill ${I.toneClass}`,title:p.bugMonitor?.lastError?`${I.label}: ${p.bugMonitor.lastError}`:I.label,onClick:()=>{s("bug-monitor"),y&&O(!1)},children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:I.shortLabel})]})]}):null]})]}):null,e("div",{className:"tcp-context-section mt-auto",children:[e("div",{className:"tcp-context-section-label",children:"Actions"}),e("div",{className:"grid gap-2",children:[e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{c(),y&&O(!1)},children:[e("i",{"data-lucide":"search"}),"Command palette"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{d(),y&&O(!1)},children:[e("i",{"data-lucide":"paint-bucket"}),"Cycle theme"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{u(),y&&O(!1)},children:[e("i",{"data-lucide":"log-out"}),"Logout"]})]})]})]});return e("div",{className:`tcp-shell ${t==="chat"?"tcp-shell-chat":""}`.trim(),children:[e(fr,{className:"tcp-shell-background",children:[e("div",{className:"tcp-shell-glow tcp-shell-glow-a"}),e("div",{className:"tcp-shell-glow tcp-shell-glow-b"})]}),e("aside",{className:"tcp-icon-rail hidden xl:flex",children:[e("button",{type:"button",className:"tcp-rail-brand",onClick:()=>s("dashboard"),children:e("div",{className:"tcp-brand-avatar h-10 w-10",children:C()})}),e("nav",{className:"tcp-rail-nav",children:H()}),e("div",{className:"tcp-rail-footer",children:[e(qn,{title:"Command palette",onClick:c,children:e("i",{"data-lucide":"search"})}),e(qn,{title:"Cycle theme",onClick:d,children:e("i",{"data-lucide":"paint-bucket"})}),e(qn,{title:"Logout",onClick:u,children:e("i",{"data-lucide":"log-out"})}),e("div",{className:"mt-2 flex justify-center",children:p.engineHealthy?e(ya,{tone:"ok"}):e(ya,{tone:"warn"})})]})]}),e("aside",{className:"tcp-context-rail hidden lg:flex xl:hidden",children:xe(!1)}),e("main",{className:`tcp-main-shell ${t==="chat"?"tcp-main-shell-fill":""}`.trim(),children:[e("section",{className:"tcp-mobile-topbar lg:hidden",children:[e("button",{type:"button",className:"tcp-btn h-10 px-3",onClick:()=>O(!0),children:[e("i",{"data-lucide":"menu"}),"Menu"]}),e("div",{className:"min-w-0 flex-1",children:[e("div",{className:"truncate text-sm font-semibold",children:B.title}),e("div",{className:"tcp-subtle truncate text-xs",children:ne?.[1]||B.subtitle})]}),I?e("button",{type:"button",className:`tcp-bug-monitor-pill ${I.toneClass}`,title:p.bugMonitor?.lastError?`${I.label}: ${p.bugMonitor.lastError}`:I.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"})]}):null,p.activeRuns>0?e(ya,{tone:"live",text:String(p.activeRuns)}):null]}),e("section",{className:"tcp-topbar",children:[e("div",{className:"min-w-0",children:[e("div",{className:"tcp-page-eyebrow",children:"Tandem Control"}),e("h1",{className:"tcp-main-title",children:B.title}),e("p",{className:"tcp-subtle mt-1 max-w-2xl",children:B.subtitle})]}),e("div",{className:"tcp-topbar-status",children:[I?e("button",{type:"button",className:`tcp-bug-monitor-pill ${I.toneClass}`,title:p.bugMonitor?.lastError?`${I.label}: ${p.bugMonitor.lastError}`:I.label,onClick:()=>s("bug-monitor"),children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:I.shortLabel})]}):null,e("span",{className:p.providerBadge,children:p.providerText}),p.engineHealthy?e(ya,{tone:"ok",text:"Engine healthy"}):e(ya,{tone:"warn",text:"Checking engine"}),p.activeRuns>0?e(ya,{tone:"live",text:`${p.activeRuns} run`}):e("span",{className:"tcp-badge tcp-badge-ghost",children:"No active runs"})]})]}),e(Mt,{mode:"wait",children:e(Re.section,{className:`tcp-main-content ${t==="chat"?"tcp-main-content-fill":""}`.trim(),initial:Q?!1:{opacity:0,y:18},animate:Q?void 0:{opacity:1,y:0},exit:Q?void 0:{opacity:0,y:-14},transition:Q?void 0:{duration:Ra.duration.normal,ease:Ra.easing.standard},children:E},N)})]}),e(Mt,{children:A?e(Re.div,{className:"tcp-mobile-drawer lg:hidden",initial:Q?!1:{opacity:0},animate:Q?void 0:{opacity:1},exit:Q?void 0:{opacity:0},children:[e("button",{type:"button",className:"tcp-mobile-drawer-backdrop","aria-label":"Close navigation",onClick:()=>O(!1)}),e(Re.aside,{className:"tcp-mobile-drawer-panel",initial:Q?!1:{x:"-100%"},animate:Q?void 0:{x:0},exit:Q?void 0:{x:"-100%"},transition:Q?void 0:Ra.spring.drawer,children:[e("div",{className:"mb-3 flex items-center justify-between",children:[e("div",{children:[e("div",{className:"text-sm font-semibold",children:a.botName}),e("div",{className:"tcp-subtle text-xs",children:B.title})]}),e(qn,{title:"Close",onClick:()=>O(!1),children:e("i",{"data-lucide":"x"})})]}),xe(!0)]})]}):null}),e(Mt,{children:x||null})]})}function so(a){const t=String(a||"").trim().toLowerCase();return!!t&&t!=="ollama"&&t!=="local"}function Op(a,t){const n=String(t||"").trim().toLowerCase();if(!n||!a||typeof a!="object")return!1;const r=s=>!s||typeof s!="object"?!1:s.has_key===!0||s.hasKey===!0||s.configured===!0&&!so(n);return r(a[n])||r(a.providers?.[n])}function Ep(a,t,n){const r=String(a?.default||a?.selected_model?.provider_id||"").trim(),s=a?.providers?.[r]||{},c=String(s.default_model||s.defaultModel||a?.selected_model?.model_id||"").trim(),d=Array.isArray(t?.connected)?t.connected:[],u=new Set(d.map(E=>String(E||"").trim().toLowerCase())),p=Op(n,r),N=!!r&&!!c&&u.has(r.toLowerCase())&&(!so(r)||p);return{ready:N,defaultProvider:r,defaultModel:c,connected:[...u],error:"",needsOnboarding:!N}}const ps="tandem_control_panel_token";function mi(){try{return localStorage.getItem(ps)||""}catch{return""}}function Dp(a){try{localStorage.setItem(ps,a)}catch{}}function jp(){try{localStorage.removeItem(ps)}catch{}}function Up(a,t){return V({queryKey:["provider","status"],enabled:t&&!!a,refetchInterval:t?15e3:!1,queryFn:async()=>{if(!a)return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:"",needsOnboarding:!1};try{const[n,r,s]=await Promise.all([a.providers.config(),a.providers.catalog(),a.providers.authStatus().catch(()=>({}))]);return Ep(n,r,s)}catch(n){return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:n instanceof Error?n.message:String(n),needsOnboarding:!0}}}})}function Bp(a,t){return V({queryKey:["identity"],enabled:t&&!!a,refetchInterval:t?3e4:!1,queryFn:async()=>{if(!a)return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"};try{const r=(await Xt("/api/engine/config/identity",{method:"GET"}))?.identity||{},s=String(r?.bot?.canonical_name||r?.bot?.canonicalName||"").trim(),c=r?.bot?.aliases||{},d=String(r?.bot?.avatar_url||r?.bot?.avatarUrl||"").trim(),u=String(c?.control_panel||c?.controlPanel||"").trim(),p=s||"Tandem";return{botName:p,botAvatarUrl:d,controlPanelName:u||`${p} Control Panel`}}catch{return{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"}}}})}function Fp(a){return V({queryKey:["bug-monitor","status"],enabled:a,refetchInterval:a?1e4:!1,queryFn:async()=>{try{return await Xt("/api/engine/bug-monitor/status",{method:"GET"})}catch{return null}}})}function Lp(){const a=ca(),{toast:t}=Wc(),{route:n,navigate:r}=Lc(),[s,c]=w(Ic()),[d,u]=w(!1),[p,N]=w(!1),E=Rt(!1);fe(()=>{Cc(s)},[s]);const A=V({queryKey:["auth","me"],retry:!1,refetchInterval:3e4,queryFn:()=>Xt("/api/auth/me",{method:"GET"})}).isSuccess;fe(()=>{try{xa()}catch{}},[A,n]);const O=F(()=>A?new tc({baseUrl:"/api/engine",token:"session"}):null,[A]),_=Up(O,A),z=Bp(O,A),P=Bi(A),Q=Wd(A),B=Fp(A),ne=ke({mutationFn:async({token:Me})=>{await Xt("/api/auth/login",{method:"POST",body:JSON.stringify({token:Me})})},onSuccess:(Me,He)=>{He.remember?Dp(He.token):jp(),a.invalidateQueries({queryKey:["auth","me"]}),t("ok","Signed in."),r("dashboard")},onError:Me=>{t("err",Me instanceof Error?Me.message:String(Me))}});fe(()=>{if(A||ne.isPending||E.current)return;const Me=mi().trim();if(!Me){E.current=!0;return}E.current=!0,ne.mutate({token:Me,remember:!0})},[A,ne]);const I=ft(async()=>{await Xt("/api/auth/logout",{method:"POST"}).catch(()=>{}),a.removeQueries({queryKey:["auth"]}),a.removeQueries({queryKey:["provider"]}),a.removeQueries({queryKey:["identity"]}),a.invalidateQueries({queryKey:["auth","me"]}),t("info","Logged out.")},[a,t]),C=F(()=>new Set(["chat","studio","agents","orchestrator","teams"]),[]),H=!!_.data?.needsOnboarding,M=A&&H;fe(()=>{if(!M){N(!1);return}C.has(n)&&(r("settings"),p||(N(!0),t("info","Set provider + default model first to unlock the control panel.")))},[C,r,p,M,n,t]);const xe=M&&C.has(n)?"settings":n,y=ft(async()=>{await a.invalidateQueries({queryKey:["provider","status"]})},[a]),v=ft(async()=>{await a.invalidateQueries({queryKey:["identity"]})},[a]),j=ft(Me=>{const He=Ac(Me);return c(He.id),He},[c]),he=z.data||{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"},ee={client:O,api:Xt,toast:t,navigate:r,currentRoute:xe,providerStatus:{ready:!!_.data?.ready,defaultProvider:_.data?.defaultProvider||"",defaultModel:_.data?.defaultModel||"",connected:_.data?.connected||[],error:_.data?.error||"",needsOnboarding:!!_.data?.needsOnboarding},identity:he,refreshProviderStatus:y,refreshIdentityStatus:v,providerHints:_i,themes:mn,setTheme:j,themeId:s},qe=F(()=>{const Me=Si.map(([Y,Ze])=>({id:`route:${Y}`,label:`Go to ${Ze}`,group:"Routes",onSelect:()=>r(Y)})),He=[{id:"action:new-chat",label:"New chat session",group:"Actions",onSelect:()=>{window.dispatchEvent(new CustomEvent("tcp:new-chat")),r("chat")}},{id:"action:start-engine-check",label:"Check engine health",group:"Actions",onSelect:async()=>{try{const Y=await Xt("/api/system/health"),Ze=Y?.engine?.ready||Y?.engine?.healthy?"healthy":"unhealthy";t("info",`Engine ${Ze}: ${Y?.engineUrl||"n/a"}`)}catch(Y){t("err",Y instanceof Error?Y.message:String(Y))}}},{id:"action:open-settings",label:"Open provider settings",group:"Actions",onSelect:()=>r("settings")},{id:"action:open-orchestrator",label:"Open orchestrator",group:"Actions",onSelect:()=>r("orchestrator")}];return[...Me,...He]},[r,t]);if(Oc(()=>u(Me=>!Me)),!A)return e($c,{loginMutation:ne,savedToken:mi(),controlPanelName:he.controlPanelName,onCheckEngine:async()=>{const Me=await Xt("/api/system/health");return`Engine check: ${Me?.engine?.ready||Me?.engine?.healthy?"healthy":"unhealthy"} at ${Me?.engineUrl||"n/a"}`}});const $e=_.data?.ready?"tcp-badge-ok":"tcp-badge-warn",Le=_.data?.ready?`${_.data?.defaultProvider||"none"}/${_.data?.defaultModel||"none"}`:"provider setup required",re=B.data||null,me=!!re?.config?.enabled,q=Number(re?.runtime?.pending_incidents||0),ge=!!re?.runtime?.monitoring_active,Pe=!!re?.runtime?.paused,Te=!!re?.readiness?.ingest_ready,se=!!re?.readiness?.publish_ready,Oe=String(re?.runtime?.last_runtime_error||re?.last_error||"").trim();return e(la,{children:[e($p,{identity:he,currentRoute:xe,providerLocked:M,navRoutes:jc,onNavigate:r,onPaletteOpen:()=>u(!0),onThemeCycle:()=>j(Sc(s)),onLogout:I,statusBar:{engineHealthy:!!(P.data?.engine?.ready||P.data?.engine?.healthy),providerBadge:$e,providerText:Le,activeRuns:["planning","awaiting_approval","running"].includes(String(Q.data?.status||"").toLowerCase())?1:0,bugMonitor:me?{enabled:!0,monitoringActive:ge,paused:Pe,pendingIncidents:q,blocked:!Te,lastError:ge&&!se&&Oe?`Watching locally only. ${Oe}`:Oe}:null},routeKey:xe,providerGate:M&&xe!=="settings"?e(Re.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e(Re.div,{className:"tcp-confirm-dialog",initial:{opacity:0,y:8,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:6,scale:.98},children:[e("h3",{className:"tcp-confirm-title",children:"Provider Setup Required"}),e("p",{className:"tcp-confirm-message",children:"Configure provider and default model in Settings to unlock all sections."}),e("div",{className:"tcp-confirm-actions",children:e("button",{className:"tcp-btn-primary",onClick:()=>r("settings"),children:"Open Settings"})})]})}):null,children:e(Mp,{routeId:xe,pageProps:ee})}),e(Ec,{open:d,onClose:()=>u(!1),actions:qe})]})}function Kp(){return e(Kc,{children:e(Lp,{})})}const Wp=new El({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),io=document.getElementById("app");if(!io)throw new Error("Missing #app host");po(io).render(e(ho,{children:e(fo,{client:Wp,children:e(Kp,{})})}));
|