@frumu/tandem-panel 0.4.13 → 0.4.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +17 -0
- package/bin/setup.js +29 -1
- package/dist/assets/index-DAtDe1Vc.js +2460 -0
- package/dist/assets/{index-DJVNgAiY.css → index-DzX1-UXX.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/server/routes/capabilities.js +159 -0
- package/server/routes/swarm.js +18 -1
- package/dist/assets/index-xmcHHgpI.js +0 -2460
|
@@ -0,0 +1,2460 @@
|
|
|
1
|
+
import{u as e,d as y,A as Rt,y as fe,T as B,q as ft,R as mo,x as po,k as la,h as ho,e as go,f as fo}from"./preact-vendor-jo0muZ28.js";import{u as V,a as ca,b as ke,c as bo,Q as vo}from"./react-query-wD0mx2Xi.js";import{c as ie,o as Ut,d as vn,r as Xr,e as yn,f as fa,g as Ja,h as yo,W as wo,U as xo,C as ko,X as No,T as _o,j as So,S as Io,k as Co,l as Ao,m as Po,p as To,q as Ro,t as Mo,u as qo,v as $o,w as Oo,x as Eo,y as Do,z as jo,R as Uo,A as Bo,B as Fo,P as Lo,D as Ko,E as Wo,F as zo,G as Jo,H as Qo,I as Ho,J as Go,N as Vo,K as Yo,L as Xo,O as Zo,V as el,Y as tl,Z as al,_ as nl,$ as rl,a0 as sl,a1 as il,a2 as ol,a3 as ll,a4 as cl,a5 as dl,a6 as ul,a7 as ml,a8 as pl,a9 as hl,aa as gl,ab as fl,ac as bl,ad as vl,ae as yl,af as wl,ag as xl,ah as kl,ai as Nl,aj as _l,ak as Sl,al as Il,am as Cl,an as Al,ao as Pl,ap as Tl,aq as Rl,ar as Ml,as as ql,at as $l,au as Ol,av as El,aw as Dl,ax as wr,ay as jl}from"./vendor-BB3fzNns.js";import{m as Me,A as Mt,u as gi}from"./motion-BCvrfAt1.js";import{g as fi,p as Ul}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 Bl 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 xs=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);vn().transform(a=>a);Xr(ie(),vn()).transform(a=>a);const Fl=Ut({ready:yn().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:yn().optional()}).passthrough().transform(a=>({...a,createdAtMs:a.created_at_ms??a.createdAtMs??0,workspaceRoot:a.workspace_root??a.workspaceRoot})),ks=Ut({sessions:Ja(cr).optional().default([]),count:fa().optional().default(0)}).passthrough(),Ll=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}),bi=Ut({ok:yn().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})),vi=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})),Ns=Ut({ok:yn().default(!0),rev:fa().optional()}).passthrough(),yi=Ut({key:ie(),value:vn(),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})),Kl=Ut({items:Ja(yi).optional().default([]),count:fa().optional().default(0)}).passthrough(),Wl=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})),zl=Ut({items:Ja(Wl).optional().default([]),count:fa().optional().default(0)}).passthrough(),Jl=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})),Ql=Ut({results:Ja(Jl).optional().default([]),count:fa().optional().default(0)}).passthrough(),wi=Ut({id:ie(),uri:ie(),parent_uri:ie().optional(),node_type:ie(),created_at:ie(),updated_at:ie(),metadata:Xr(ie(),vn()).optional()}).passthrough(),Hl=Ut({l0_preview:ie().optional(),l1_preview:ie().optional(),has_l2:yn()}).passthrough(),Gl=Ut({node:wi,children:Ja(vn()).optional().default([]),layer_summary:Hl.optional()}).passthrough(),Vl=Ut({node:wi.optional()}).passthrough(),Yl=Ut({tree:Ja(Gl).optional().default([])}).passthrough(),Xl=Ut({ok:yn(),distillation_id:ie().optional(),session_id:ie().optional(),facts_extracted:fa().optional()}).passthrough(),Zl=Ut({type:ie(),properties:Xr(ie(),vn()).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 Bl(n,r,s.error.issues,c)}return s.data}function ec(a){const t=a.trim();if(!t||t===": keep-alive"||t.startsWith(":"))return null;try{const n=JSON.parse(t),r=Zl.safeParse(n);return r.success?r.data:null}catch{return null}}async function*an(a,t,n){const r=n?.connectTimeoutMs??3e4,s=new AbortController,c=setTimeout(()=>s.abort(),r),d=n?.signal?tc([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 D="";try{for(;;){const{done:x,value:M}=await N.read();if(x)break;D+=p.decode(M,{stream:!0});const E=D.split(`
|
|
2
|
+
`);D=E.pop()??"";let S="";for(const W of E)if(W.startsWith("data:"))S+=W.slice(5).trimStart();else if(W===""&&S){const I=ec(S);I&&(yield I),S=""}}}finally{N.releaseLock()}}function tc(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,ac=a=>{try{const t=xs.parse(a);if(t)return t}catch{const t=a.run||null;if(t)try{const n=xs.parse(t);if(n)return n}catch{}}throw new Error("Run ID missing in engine response")};class nc{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 oc(this.baseUrl,this.token,this.timeoutMs,n),this.permissions=new lc(n),this.questions=new cc(n),this.providers=new dc(n),this.identity=new uc(n),this.channels=new mc(n),this.mcp=new pc(n,this._requestText.bind(this));const r=()=>this.token;this.routines=new wc(this.baseUrl,r,n),this.automations=new kc(this.baseUrl,r,n),this.automationsV2=new Nc(this.baseUrl,r,n),this.optimizations=new _c(n),this.workflowPlans=new xc(n),this.memory=new hc(n),this.skills=new gc(n),this.packs=new fc(n),this.capabilities=new bc(n),this.resources=new vc(this.baseUrl,r,n),this.browser=new rc(n),this.workflows=new sc(this.baseUrl,r,n),this.bugMonitor=new ic(n),this.coder=new yc(n),this.agentTeams=new Sc(n),this.missions=new Ic(n)}setToken(t){this.token=t,this.sessions.setToken(t)}async health(){const t=await this._request("/global/health");return Jt(Fl,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 an(c,this.token,r)}globalStream(t){const n=`${this.baseUrl}/global/event`;return an(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 rc{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 sc{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 an(`${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 ic{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 oc{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(ks,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(Ll,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 M=(await N.json().catch(()=>({}))).activeRun,E=ma(M?.runID)||ma(M?.runId)||ma(M?.run_id);if(E)return{runId:E}}if(!N.ok){const x=await N.text().catch(()=>"");throw new Error(`promptAsyncParts failed (${N.status}): ${x}`)}const D=await N.json();return{runId:ac(D)}}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(ks,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 lc{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 cc{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 dc{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 uc{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 mc{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 pc{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 hc{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(Ql,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(zl,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(Vl,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(Yl,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(Xl,r,"/memory/context/distill",200)}}class gc{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 fc{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 bc{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 vc{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(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 Jt(yi,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(Ns,s,`/resource/${t}`,200)}async patchKey(t,n){const r=await this.req(`/resource/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)});return Jt(Ns,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 an(`${this.baseUrl}/resource/events${r}`,this.getToken())}}class yc{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 wc{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(bi,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(vi,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 an(`${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 xc{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 kc{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(bi,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(vi,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 an(`${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 Nc{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 an(`${this.baseUrl}/automations/v2/events${c}`,this.getToken(),{signal:t?.signal})}}class _c{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 Sc{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 Ic{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",hn=[{id:"charcoal_fire",name:"Charcoal & Fire",description:"Deep charcoal surfaces with solar-yellow power accents and crimson security cues.",cssVars:{"--color-background":"#121212","--color-surface":"#141414","--color-surface-elevated":"#1a1a1a","--color-border":"rgba(245, 245, 245, 0.10)","--color-border-subtle":"rgba(245, 245, 245, 0.06)","--color-primary":"#F59E0B","--color-primary-hover":"#D97706","--color-primary-muted":"#B45309","--color-secondary":"#EF4444","--color-secondary-hover":"#DC2626","--color-success":"#10B981","--color-warning":"#F59E0B","--color-error":"#EF4444","--color-text":"#F5F5F5","--color-text-muted":"rgba(245, 245, 245, 0.70)","--color-text-subtle":"rgba(245, 245, 245, 0.50)","--color-glass":"rgba(255, 255, 255, 0.03)","--color-glass-border":"rgba(255, 255, 255, 0.08)","--font-sans":'"Manrope", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(245, 158, 11, 0.16)","--tcp-glow-b":"rgba(239, 68, 68, 0.12)"}},{id:"electric_blue",name:"Electric Blue",description:"The original Tandem look: electric-blue primary with purple secondary.",cssVars:{"--color-background":"#0a0a0f","--color-surface":"#12121a","--color-surface-elevated":"#1a1a24","--color-border":"#2a2a3a","--color-border-subtle":"#1f1f2e","--color-primary":"#3b82f6","--color-primary-hover":"#2563eb","--color-primary-muted":"#1d4ed8","--color-secondary":"#8b5cf6","--color-secondary-hover":"#7c3aed","--color-success":"#10b981","--color-warning":"#f59e0b","--color-error":"#ef4444","--color-text":"#f8fafc","--color-text-muted":"#94a3b8","--color-text-subtle":"#64748b","--color-glass":"rgba(18, 18, 26, 0.8)","--color-glass-border":"rgba(255, 255, 255, 0.1)","--font-sans":'"Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(59, 130, 246, 0.16)","--tcp-glow-b":"rgba(139, 92, 246, 0.12)"}},{id:"emerald_night",name:"Emerald Night",description:"Dark glass with emerald primary and cyan secondary highlights.",cssVars:{"--color-background":"#0b1010","--color-surface":"#0f1616","--color-surface-elevated":"#142020","--color-border":"rgba(226, 232, 240, 0.12)","--color-border-subtle":"rgba(226, 232, 240, 0.08)","--color-primary":"#10B981","--color-primary-hover":"#059669","--color-primary-muted":"#047857","--color-secondary":"#22D3EE","--color-secondary-hover":"#06B6D4","--color-success":"#22C55E","--color-warning":"#F59E0B","--color-error":"#EF4444","--color-text":"#F1F5F9","--color-text-muted":"rgba(241, 245, 249, 0.72)","--color-text-subtle":"rgba(241, 245, 249, 0.52)","--color-glass":"rgba(15, 22, 22, 0.75)","--color-glass-border":"rgba(255, 255, 255, 0.10)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(16, 185, 129, 0.16)","--tcp-glow-b":"rgba(34, 211, 238, 0.12)"}},{id:"hello_bunny",name:"Hello Bunny",description:"Soft pink glass with berry accents and a cozy, playful vibe.",cssVars:{"--color-background":"#140A12","--color-surface":"#1C0E1A","--color-surface-elevated":"#251022","--color-border":"rgba(255, 228, 242, 0.12)","--color-border-subtle":"rgba(255, 228, 242, 0.08)","--color-primary":"#FB7185","--color-primary-hover":"#F43F5E","--color-primary-muted":"#E11D48","--color-secondary":"#C084FC","--color-secondary-hover":"#A855F7","--color-success":"#34D399","--color-warning":"#FBBF24","--color-error":"#FB7185","--color-text":"#FFEAF4","--color-text-muted":"rgba(255, 234, 244, 0.74)","--color-text-subtle":"rgba(255, 234, 244, 0.52)","--color-glass":"rgba(255, 255, 255, 0.04)","--color-glass-border":"rgba(255, 228, 242, 0.10)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(251, 113, 133, 0.16)","--tcp-glow-b":"rgba(192, 132, 252, 0.12)"}},{id:"porcelain",name:"Porcelain",description:"Plain, bright whites with soft pastel accents and glassy structure.",cssVars:{"--color-background":"#F8FAFC","--color-surface":"#FFFFFF","--color-surface-elevated":"#F1F5F9","--color-border":"rgba(15, 23, 42, 0.12)","--color-border-subtle":"rgba(15, 23, 42, 0.08)","--color-primary":"#6366F1","--color-primary-hover":"#4F46E5","--color-primary-muted":"#4338CA","--color-secondary":"#F472B6","--color-secondary-hover":"#EC4899","--color-success":"#10B981","--color-warning":"#F59E0B","--color-error":"#EF4444","--color-text":"#0F172A","--color-text-muted":"rgba(15, 23, 42, 0.70)","--color-text-subtle":"rgba(15, 23, 42, 0.50)","--color-glass":"rgba(255, 255, 255, 0.72)","--color-glass-border":"rgba(15, 23, 42, 0.10)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(99, 102, 241, 0.13)","--tcp-glow-b":"rgba(244, 114, 182, 0.11)"}},{id:"neon_riot",name:"Neon Riot",description:"Electric cyan and magenta over deep space surfaces.",cssVars:{"--color-background":"#050014","--color-surface":"#0B0720","--color-surface-elevated":"#140A3A","--color-border":"rgba(248, 250, 252, 0.16)","--color-border-subtle":"rgba(248, 250, 252, 0.10)","--color-primary":"#00E5FF","--color-primary-hover":"#00B8D4","--color-primary-muted":"#00838F","--color-secondary":"#FF3DF5","--color-secondary-hover":"#D500F9","--color-success":"#22C55E","--color-warning":"#FBBF24","--color-error":"#FB7185","--color-text":"#F8FAFC","--color-text-muted":"rgba(248, 250, 252, 0.72)","--color-text-subtle":"rgba(248, 250, 252, 0.52)","--color-glass":"rgba(5, 0, 20, 0.55)","--color-glass-border":"rgba(255, 255, 255, 0.14)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(0, 229, 255, 0.20)","--tcp-glow-b":"rgba(255, 61, 245, 0.14)"}},{id:"cosmic_glass",name:"Cosmic Glass",description:"Transparent nebula glass panels with deep-space glow.",cssVars:{"--color-background":"#03020F","--color-surface":"rgba(9, 6, 28, 0.72)","--color-surface-elevated":"rgba(18, 12, 40, 0.82)","--color-border":"rgba(120, 105, 255, 0.22)","--color-border-subtle":"rgba(120, 105, 255, 0.12)","--color-primary":"#7C5CFF","--color-primary-hover":"#6A40FF","--color-primary-muted":"#4C2ED8","--color-secondary":"#FF7AD9","--color-secondary-hover":"#FF4FC3","--color-success":"#3BE4C0","--color-warning":"#F9D86B","--color-error":"#FF5C7A","--color-text":"#F3F0FF","--color-text-muted":"rgba(243, 240, 255, 0.74)","--color-text-subtle":"rgba(243, 240, 255, 0.52)","--color-glass":"rgba(14, 10, 40, 0.48)","--color-glass-border":"rgba(255, 255, 255, 0.16)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(124, 92, 255, 0.20)","--tcp-glow-b":"rgba(255, 122, 217, 0.14)"}},{id:"pink_pony",name:"Pink Pony",description:"Candy pinks and dreamy pastels with brighter glass accents.",cssVars:{"--color-background":"#240818","--color-surface":"rgba(56, 12, 38, 0.94)","--color-surface-elevated":"rgba(72, 16, 48, 0.96)","--color-border":"rgba(255, 184, 217, 0.36)","--color-border-subtle":"rgba(255, 184, 217, 0.22)","--color-primary":"#FF5FB1","--color-primary-hover":"#FF3B9A","--color-primary-muted":"#D91E7D","--color-secondary":"#FFB8E6","--color-secondary-hover":"#FF98D8","--color-success":"#58E5C1","--color-warning":"#FFD166","--color-error":"#FF5C8A","--color-text":"#FFF7FC","--color-text-muted":"rgba(255, 247, 252, 0.86)","--color-text-subtle":"rgba(255, 247, 252, 0.68)","--color-glass":"rgba(74, 17, 50, 0.78)","--color-glass-border":"rgba(255, 220, 238, 0.30)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(255, 95, 177, 0.20)","--tcp-glow-b":"rgba(255, 184, 230, 0.14)"}},{id:"zen_dusk",name:"Zen Dusk",description:"Muted green dusk tones for calmer long-session work.",cssVars:{"--color-background":"#0B1110","--color-surface":"#101716","--color-surface-elevated":"#141D1C","--color-border":"rgba(226, 232, 240, 0.12)","--color-border-subtle":"rgba(226, 232, 240, 0.06)","--color-primary":"#7CC8A4","--color-primary-hover":"#6AB690","--color-primary-muted":"#559B7B","--color-secondary":"#9FB8B0","--color-secondary-hover":"#8AA59C","--color-success":"#5EC79B","--color-warning":"#E6C17B","--color-error":"#E38B8B","--color-text":"#E6EFEA","--color-text-muted":"rgba(230, 239, 234, 0.72)","--color-text-subtle":"rgba(230, 239, 234, 0.50)","--color-glass":"rgba(20, 28, 26, 0.72)","--color-glass-border":"rgba(255, 255, 255, 0.08)","--font-sans":'"Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-display":'"Rubik", "Geist Sans", "Inter", system-ui, -apple-system, sans-serif',"--font-mono":'"Geist Mono", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace',"--tcp-glow-a":"rgba(124, 200, 164, 0.16)","--tcp-glow-b":"rgba(159, 184, 176, 0.12)"}}],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 Zr(a){let t=String(a||"").trim()||gr;return t==="web_control"&&(t=gr),hn.find(n=>n.id===t)||hn[0]}function Cc(a){const t=Zr(a).id,n=hn.findIndex(r=>r.id===t);return n<0?gr:hn[(n+1)%hn.length].id}function xi(a,t=typeof document<"u"?document.documentElement:null){const n=Zr(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 ki(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}const Ni="tandem.themeId";function Ac(){try{const a=localStorage.getItem(Ni);return Zr(a).id}catch{return gr}}function Pc(a){return xi(a)}function Tc(a){const t=xi(a);try{localStorage.setItem(Ni,t.id)}catch{}return t}function Ln(){const[a,t]=y(()=>ki());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 Rc(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 nn({className:a="",children:t}){const n=Ln();return e(Me.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 Mc({className:a="",children:t}){const n=Ln();return e(Me.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 _i({className:a="",children:t,as:n="div"}){const r=Ln(),s=n==="section"?Me.section:n==="article"?Me.article:Me.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 qc({value:a,format:t=r=>String(r),className:n=""}){const r=Ln(),[s,c]=y(()=>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 D=performance.now();let x=0;const M=E=>{const S=Rc((E-D)/420,0,1),W=1-Math.pow(1-S,3),I=p+N*W;c(I),S<1?x=window.requestAnimationFrame(M):d.current=u};return x=window.requestAnimationFrame(M),()=>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 $n({className:a="",title:t,children:n,...r}){return e("button",{type:"button",title:t,className:`tcp-icon-btn ${a}`.trim(),...r,children:n})}function ye({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(_i,{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 $c({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 Oc({eyebrow:a,title:t,subtitle:n,badges:r,actions:s,className:c=""}){return e(_i,{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 Dn({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(Me.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(Me.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($n,{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 Ec({loginMutation:a,savedToken:t,onCheckEngine:n,controlPanelName:r}){const[s,c]=y(t),[d,u]=y(!0),[p,N]=y(""),[D,x]=y(!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:M=>{if(M.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:M=>c(M.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:M=>u(M.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 M=await n();x(!0),N(M)}catch(M){x(!1),N(M instanceof Error?M.message:String(M))}},children:[e("i",{"data-lucide":"activity"}),"Check engine"]})]}),e("div",{className:`min-h-[1.2rem] text-sm ${D?"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:D?"ok":"warn",text:D?"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 Dc(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 jc({open:a,onClose:t,actions:n}){const[r,s]=y("");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=B(()=>{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(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,children:e(Me.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 Si=[["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"]],Uc=Si.filter(([a])=>["dashboard","chat","studio","automations","coding","agents","orchestrator","memory","feed","settings"].includes(a)),Ii={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"}},Ci=Si,Bc=Uc,Fc=new Map([["packs","automations"],["teams","automations"],["swarm","orchestrator"],["failure-reporter","bug-monitor"]]),Lc=new Set(Ci.map(([a])=>a));function es(a,t="dashboard"){const n=Fc.get(String(a||"").trim());return n||(Lc.has(a)?a:t)}function _s(a="dashboard"){const t=(window.location.hash||`#/${a}`).replace(/^#\//,"");return es(t.split("?")[0].split("/")[0].trim(),a)}function Kc(a){window.location.hash=`#/${a}`}function Wc(){const[a,t]=y(()=>_s());fe(()=>{const r=()=>t(_s());return window.addEventListener("hashchange",r),()=>window.removeEventListener("hashchange",r)},[]);const n=ft(r=>{const s=es(r);if(window.location.hash!==`#/${s}`){Kc(s);return}t(s)},[]);return{route:a,navigate:n}}const Ai=mo({toast:()=>{}});function zc({children:a}){const[t,n]=y([]),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=B(()=>({toast:r}),[r]);return e(Ai.Provider,{value:s,children:[a,e("div",{className:"toasts","aria-live":"polite","aria-atomic":"true",children:e(Mt,{children:t.map(c=>e(Me.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 Jc(){return po(Ai)}function Xt({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($c,{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 Qc(a){return new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1}).format(Number(a||0))}function Hc(a){const{api:t,client:n,navigate:r,providerStatus:s}=a,[c,d]=y(""),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}),D=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}),M=V({queryKey:["dashboard","workflow-context-runs"],queryFn:()=>t("/api/engine/context/runs?limit=12").catch(()=>({runs:[]})),refetchInterval:6e3}),E=V({queryKey:["dashboard","workflow-context-run",c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}`).catch(()=>({run:null}))}),S=V({queryKey:["dashboard","workflow-context-blackboard",c],enabled:!!c,queryFn:()=>t(`/api/engine/context/runs/${encodeURIComponent(c)}/blackboard`).catch(()=>({blackboard:null}))}),W=Pr(N.data,"sessions"),I=Pr(D.data,"routines"),Q=Pr(M.data,"runs").filter(A=>u.has(String(A?.run_type||"").trim().toLowerCase())),ee=!!(p.data?.engine?.ready||p.data?.engine?.healthy),ce=String(x.data?.status||"unknown"),C=["planning","awaiting_approval","running","executing"].includes(ce.toLowerCase()),P=Q.filter(A=>["queued","planning","running","awaiting_approval"].includes(String(A?.status||"").trim().toLowerCase())),O=B(()=>[{label:"Recent sessions",value:W.length,tone:"info",helper:"Latest active conversation surfaces"},{label:"Automations",value:I.length,tone:"ok",helper:"Configured routines and schedules"},{label:"Swarm status",value:C?1:0,tone:C?"warn":"ghost",helper:ce},{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:P.length?"warn":"info",helper:P.length?`${P.length} active`:"Workflow + triage visibility"}],[P.length,s.defaultModel,s.ready,I.length,W.length,C,ce,Q.length]);return e(nn,{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(ye,{tone:ee?"ok":"warn",children:ee?"Engine healthy":"Engine checking"}),e(ye,{tone:s.ready?"ok":"warn",children:s.ready?s.defaultProvider:"Provider setup required"}),C?e(ya,{tone:"live",text:`Swarm ${ce}`}):e(ye,{tone:"ghost",children:["Swarm ",ce]})]})]}),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:O.map(A=>e("div",{children:[e("div",{className:"flex items-start justify-between gap-3",children:[e("span",{className:"dashboard-kpi-label",children:A.label}),e(ye,{tone:A.tone,children:A.helper})]}),e("strong",{children:e(qc,{value:A.value,format:Qc})})]},A.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:ee?"100%":"45%"})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:"dashboard-bar-fill completed",style:{width:ee?"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:[I.length," routines"]})]}),e("div",{className:"dashboard-bar-track",children:e("span",{className:`dashboard-bar-fill ${I.length?"scheduled":"manual"}`,style:{width:`${Math.min(100,Math.max(12,I.length*12))}%`}})})]})]})]})]}),e(Dn,{main:e(ot,{title:"Recent sessions",subtitle:"Latest conversations, ready to reopen.",children:e("div",{className:"grid gap-2",children:W.length?W.map(A=>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(A.title||A.id||"Session")]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(A.id||A.session_id||"")})]},String(A.id||A.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(ye,{tone:P.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(A=>e("button",{className:"tcp-list-item text-left",onClick:()=>d(String(A?.run_id||"").trim()),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("div",{className:"font-medium",children:String(A?.objective||A?.run_id||"Context run")}),e("div",{className:"flex flex-wrap items-center gap-2",children:[e(ye,{tone:"ghost",children:String(A?.run_type||"context")}),e(ye,{tone:["failed","cancelled"].includes(String(A?.status||"").toLowerCase())?"err":["running","queued","planning"].includes(String(A?.status||"").toLowerCase())?"warn":"ok",children:String(A?.status||"unknown")})]})]}),e("div",{className:"tcp-subtle text-xs",children:String(A?.run_id||"")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:[Array.isArray(A?.tasks)?A.tasks.length:0," tasks ·"," ",Array.isArray(A?.steps)?A.steps.length:0," steps"]})]},String(A?.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(ye,{tone:"info",children:[I.length," loaded"]}),e("button",{className:"tcp-btn",onClick:()=>r("automations"),children:[e("i",{"data-lucide":"bot"}),"Manage"]})]}),e("div",{className:"grid gap-2",children:I.length?I.slice(0,4).map(A=>e("div",{className:"tcp-list-item",children:[e("div",{className:"font-medium",children:String(A.name||A.id||"Routine")}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(A.schedule||A.status||"manual")})]},String(A.id||A.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: ",ce]})]}),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(E.data?.run?.objective||c)}),e(ye,{tone:"info",children:String(E.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["type: ",String(E.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(S.data?.blackboard?.tasks)?S.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(S.data?.blackboard?.artifacts)?S.data.blackboard.artifacts.length:0]})]}),e("pre",{className:"tcp-code",children:aa({run:E.data?.run||null,blackboard:S.data?.blackboard||null})})]}):null})]})}const Gc={Activity:Dl,Archive:El,ArrowLeftToLine:Ol,ArrowUpCircle:$l,BadgeCheck:ql,Binary:Ml,Bug:Rl,BugPlay:Tl,Bot:Pl,BookOpen:Al,Check:Cl,ChevronDown:Il,ChevronRight:Sl,ClipboardList:_l,Clock:Nl,Clock3:kl,Copy:xl,CopyPlus:wl,Code:yl,ExternalLink:vl,Cpu:bl,Database:fl,Download:gl,FileUp:hl,Filter:pl,FilterX:ml,FlaskConical:ul,FolderOpen:dl,History:cl,Home:ll,Info:ol,KeyRound:il,Link:sl,LoaderCircle:rl,List:nl,LogOut:al,MessageCircle:tl,MessageSquare:el,MessagesSquare:Zo,Menu:Xo,MonitorCog:Yo,Network:Vo,Paperclip:Go,Package:Ho,PaintBucket:Qo,Pencil:Jo,Play:zo,PlugZap:Wo,Plus:Ko,Pause:Lo,Radio:Fo,RefreshCw:Bo,RotateCw:Uo,Save:jo,Search:Do,Send:Eo,Settings:Oo,Settings2:$o,ShieldAlert:qo,ShieldCheck:Mo,SlidersHorizontal:Ro,Sparkles:To,Siren:Po,Share2:Ao,Shield:Co,Square:Io,Trash2:So,TriangleAlert:_o,X:No,XCircle:ko,Users:xo,Workflow:wo},Lr=new Set;let Kr=0;function Vc(){Kr=0;const a=[...Lr];Lr.clear();for(const t of a)yo({icons:Gc,attrs:{width:"16",height:"16","stroke-width":"1.8"},...t?{root:t}:{}})}function xa(a){Lr.add(a||null),!Kr&&(Kr=window.requestAnimationFrame(Vc))}fi.setOptions({gfm:!0,breaks:!0});function gn(a){const t=String(a||""),n=fi.parse(t,{async:!1});return Ul.sanitize(n)}const Wr="tcp.chat.session";function Pi(a){return String(a?.id||a?.session_id||a?.sessionID||"").trim()}function Yc(a){const t=String(a?.title||a?.name||"").trim();if(t)return t;const n=Pi(a);return n?`Session ${n.slice(0,8)}`:"Session"}function Xc(a){return Array.isArray(a)?a:Array.isArray(a?.sessions)?a.sessions:[]}function Zc(a){return String(a?.title||"").trim().toLowerCase().startsWith("__provider_test__")}function Ss(a){return Xc(a).filter(t=>!Zc(t)).map(t=>({id:Pi(t),title:Yc(t),raw:t})).filter(t=>!!t.id)}async function ed(a,t){try{const n=await a.sessions.list({pageSize:50}),r=Ss(n);if(r.length>0)return r}catch{}try{const n=await t("/api/engine/session?page_size=50",{method:"GET"});return Ss(n)}catch{return[]}}function Is(){try{return localStorage.getItem(Wr)||""}catch{return""}}function td(a){try{a?localStorage.setItem(Wr,a):localStorage.removeItem(Wr)}catch{}}function ad(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 nd(a){return String(a?.info?.role||a?.role||a?.message_role||a?.type||a?.author||"assistant").trim().toLowerCase()}function rd(a){const t=ad(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 sd(a,t){return a==="assistant"?t||"Assistant":a==="user"?"User":a==="system"?"System":a||"Assistant"}function id(a,t,n){const r=nd(a),s=rd(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:sd(r,n),text:s,markdown:c}}function Ti(a,t){return(Array.isArray(a)?a:Array.isArray(a?.messages)?a.messages:[]).map((r,s)=>id(r,s,t))}const Cs=new Set(["tool.called","tool_call.started","session.tool_call"]),As=new Set(["tool.result","tool_call.completed","tool_call.failed","session.tool_result"]),od=new Set(["run.complete","run.completed","session.run.finished","session.run.completed"]),ld=new Set(["run.failed","session.run.failed","run.cancelled","run.canceled","session.run.cancelled","session.run.canceled"]);function Ri(a){return String(a||"").trim().replace(/\s+/g," ").replace(/[<>]/g,"")}function dn(a){const t=a||{},n=t.call||t.toolCall||t.part||{};return Ri(t.tool||t.name||t.toolName||t.tool_id||t.toolID||n.tool||n.name||n.toolName||"")}function An(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:Ri(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 Ps(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 cd(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(),D=String(n.version||"").trim(),x=String(n.error||"").trim(),M=[];N&&M.push(N),D&&M.push(D),s&&M.push(s),d&&M.push(d),u&&M.push(`channel=${u}`),p&&M.push(`sender=${p}`);const E=M.join(" · ");return{id:`${r}:${c||s||N||"event"}`,type:r,path:s,attachmentId:c,connector:d,channelId:u,senderId:p,error:x,summary:E||r,at:Date.now()}}const tn=new Map;function Mi(a,t){return`${t?"cred":"anon"}:${a}`}function zr(){for(const a of tn.values())a.closed;tn.size}function dd(a,t=!0){const n=Mi(a,t),r=tn.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,tn.delete(n),zr())},tn.set(n,c),zr(),c}function ts(a,t,n={}){const r=n.withCredentials!==!1,s=Mi(a,r),c=dd(a,r);return c.refs+=1,c.listeners.add(t),typeof n.onError=="function"&&c.errorListeners.add(n.onError),()=>{const d=tn.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(),tn.delete(s),zr()))}}const ud="control-panel",qi="tandem_control_panel_chat_auto_approve_tools",md="tandem.automations.plannerSeed",pd={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 Ts(a=""){const t=String(a).toLowerCase().split(".").pop()||"";return pd[t]||"application/octet-stream"}function hd(a="",t=""){if(!a||!t)return t||"";const n=String(a).replace(/[\\/]+$/,""),r=String(t).replace(/^[\\/]+/,"");return`${n}/${r}`}function gd(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 fd(a){const t=String(a||"").trim();return t!=="server.connected"&&t!=="engine.lifecycle.ready"}function bd(a){return a==="completed"?"chat-tool-chip-ok":a==="failed"?"chat-tool-chip-failed":"chat-tool-chip-running"}function vd(){try{return localStorage.getItem(qi)==="1"}catch{return!1}}function yd(a){try{localStorage.setItem(qi,a?"1":"0")}catch{}}function wd(a){try{const t=String(a?.prompt||a?.goal||"").trim();if(!t)return;sessionStorage.setItem(md,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 xd(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 kd({client:a,api:t,toast:n,providerStatus:r,identity:s,navigate:c}){const d=ca(),u=!!gi(),p=Rt(null),N=Rt(null),D=Rt(null),x=Rt(null),M=Rt(null),E=Rt(!0),S=Rt(null),W=Rt(null),[I,Q]=y([]),[ee,ce]=y(!1),[C,P]=y(Is()),[O,A]=y([]),[ve,z]=y(!1),[k,v]=y(""),[te,H]=y([]),[Pe,$e]=y([]),[Le,re]=y(!1),[pe,q]=y(""),[ge,Te]=y(!1),[Re,se]=y([]),[Oe,qe]=y(new Set),[He,Y]=y([]),[Ze,ne]=y(new Set),[Ae,St]=y([]),[oe,K]=y(new Set),[lt,xt]=y(vd()),[rt,Et]=y(!1),[Fe,Bt]=y([]),[At,$t]=y(null),[We,ze]=y(null),tt=B(()=>I.find(U=>U.id===C)?.title||"Chat",[C,I]);fe(()=>(E.current=!0,()=>{E.current=!1,M.current?.abort(),S.current&&window.clearTimeout(S.current),W.current&&window.clearTimeout(W.current)}),[]),fe(()=>{const h=p.current;h&&xa(h)},[I,te,Pe,Ae,Re,He,O,ee,ge,pe]),fe(()=>{td(C)},[C]),fe(()=>{const h=N.current;h&&(h.style.height="0px",h.style.height=`${Math.min(h.scrollHeight,180)}px`)},[k]),fe(()=>{const h=x.current;h&&(h.scrollTop=h.scrollHeight)},[O,pe,ge]);const be=ft(async()=>{const h=await ed(a,t);E.current&&(Q(h),P(U=>{if(U&&h.some(F=>F.id===U))return U;const J=Is();return J&&h.some(F=>F.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(),F=String(J?.default||"").trim(),X=String(J?.providers?.[F]?.defaultModel||"").trim();if(F&&X)return{providerID:F,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),F=String(J||"").trim();if(!F)throw new Error("Failed to create session.");return P(F),await be(),F},[a.sessions,be,Se]),de=ft(h=>{const U=Ti(h,s.botName||"Assistant");A(U)},[s.botName]),dt=ft(async()=>{if(!C){A([]);return}z(!0);try{const h=await a.sessions.messages(C).catch(()=>({messages:[]}));if(!E.current)return;de(h)}finally{E.current&&z(!1)}},[a.sessions,de,C]),_=ft(()=>{se([]),qe(new Set)},[]),G=ft(()=>{Y([]),ne(new Set)},[]),me=ft((h,U,J="")=>{const F=String(h||"").trim();if(!F)return;let X=!0;J&&(qe(we=>{if(we.has(J))return X=!1,we;const Ue=new Set(we);return Ue.add(J),Ue.size>1e3?new Set([J]):Ue}),!X)||se(we=>[{id:`${F}:${U}:${Date.now()}:${Math.random().toString(36).slice(2,8)}`,tool:F,status:U,at:Date.now()},...we].slice(0,80))},[]),Ke=ft((h,U)=>{const J=cd(h,U);if(!String(J.type).toLowerCase().startsWith("pack."))return;let X=!0;ne(we=>{if(we.has(J.id))return X=!1,we;const Ue=new Set(we);return Ue.add(J.id),Ue.size>400?new Set([J.id]):Ue}),X&&Y(we=>[J,...we].slice(0,80))},[]),l=ft(h=>{Ps(h?.status||"")&&St(U=>{const J=U.findIndex(F=>F.id===h.id);if(J>=0){const F=[...U];return F[J]={...F[J],...h},F}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(F=>er(F)).filter(F=>!!F).filter(F=>Rr(F.sessionId,C)).filter(F=>Ps(F.status));E.current&&St(J.slice(0,80))},[a.permissions,C]),R=ft(async(h,U,J=!1)=>{if(!(!h||oe.has(h))){K(X=>{const we=new Set(X);return we.add(h),we});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{K(X=>{const we=new Set(X);return we.delete(h),we}),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{E.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 F=J||{};return String(F.name||F.id||F.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(E.current){const J=[...new Set(U)].sort((F,X)=>F.localeCompare(X));Bt(J)}}catch{E.current&&Bt([])}},[t,a,Ye]),Ot=ft(h=>new Promise((U,J)=>{const F=`${Date.now()}-${Math.random().toString(16).slice(2)}`;$e(we=>[...we,{id:F,name:h.name,progress:0,error:""}]);const X=new XMLHttpRequest;X.open("POST",`/api/files/upload?dir=${encodeURIComponent(ud)}`),X.withCredentials=!0,X.responseType="json",X.setRequestHeader("x-file-name",encodeURIComponent(h.name)),X.upload.onprogress=we=>{if(!we.lengthComputable)return;const Ue=we.loaded/we.total*100;$e(st=>st.map(vt=>vt.id===F?{...vt,progress:Ue}:vt))},X.onerror=()=>{$e(we=>we.map(Ue=>Ue.id===F?{...Ue,error:"Network error"}:Ue)),window.setTimeout(()=>{$e(we=>we.filter(Ue=>Ue.id!==F))},1200),J(new Error(`Upload failed: ${h.name}`))},X.onload=()=>{const we=X.response||{};if(X.status<200||X.status>=300||we?.ok===!1){const Ue=String(we?.error||`Upload failed (${X.status})`);$e(st=>st.map(vt=>vt.id===F?{...vt,error:Ue}:vt)),window.setTimeout(()=>{$e(st=>st.filter(vt=>vt.id!==F))},1600),J(new Error(Ue));return}$e(Ue=>Ue.filter(st=>st.id!==F)),U(we)},X.send(h)}),[]),Ft=ft(async h=>{const U=[...h||[]];if(!U.length)return;let J=0;for(const F of U)try{const X=await Ot(F);H(we=>[{name:String(X?.name||F.name),path:String(X?.path||F.name),size:Number(X?.size||F.size||0),mime:F.type||Ts(String(X?.name||F.name)),url:String(X?.absPath||hd(X?.root,X?.path)||X?.path||F.name)},...we]),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."),C===h){const U=I.find(J=>J.id!==h)?.id||"";if(U)P(U);else{const J=await Ve();P(J)}}},[a.sessions,Ve,C,I,n]),Pt=ft((h,U)=>{const J=String(h||"").trim();if(!J)return;const F=U>0?`
|
|
5
|
+
|
|
6
|
+
${U} attachment${U===1?"":"s"}`:"";A(X=>[...X,{id:`local-user-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"user",displayRole:"User",text:`${J}${F}`,markdown:!1}])},[]),bt=ft(async()=>{if(Le)return;const h=k.trim(),U=[...te],J=h||(U.length?"Please analyze the attached file(s).":"");if(J){try{const F=await t("/api/engine/setup/understand",{method:"POST",body:JSON.stringify({surface:"control_panel_chat",session_id:C||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:C||"control-panel-chat"}})});if(F.decision!=="pass_through"){const X=xd(F);if(X){ze(X),v("");return}}}catch{}v(""),re(!0),Pt(J,U.length);try{let F=C;if(F||(F=await Ve()),!F)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 we=U.map(Ce=>({type:"file",mime:Ce.mime||Ts(Ce.name||Ce.path),filename:Ce.name||Ce.path||"attachment",url:Ce.url||Ce.path}));we.push({type:"text",text:J});const Ue=async()=>{const Ce=await fetch(`/api/engine/session/${encodeURIComponent(F)}/run`,{method:"GET",credentials:"include"});if(!Ce.ok)return"";const xe=await Ce.json().catch(()=>({}));return xe?.active?.runID||xe?.active?.runId||xe?.active?.run_id||""},st=async()=>{const Ce=await Ue().catch(()=>"");Ce&&await fetch(`/api/engine/session/${encodeURIComponent(F)}/run/${encodeURIComponent(Ce)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),await fetch(`/api/engine/session/${encodeURIComponent(F)}/cancel`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({})}).catch(()=>{});for(let xe=0;xe<50;xe+=1){if(!await Ue().catch(()=>""))return!0;await new Promise(Qe=>window.setTimeout(Qe,200))}return!1},vt=async()=>fetch(`/api/engine/session/${encodeURIComponent(F)}/prompt_async?return=run`,{method:"POST",credentials:"include",headers:{"content-type":"application/json"},body:JSON.stringify({parts:we,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 xe=await It.json().catch(()=>({}));et=xe?.runID||xe?.runId||xe?.run_id||""}else{if(It.status===409)throw new Error("Session is still busy with another run. Retry in a moment.");{const xe=await It.text().catch(()=>"");throw new Error(`prompt_async retry failed (${It.status}): ${xe}`)}}}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&&H([]),q(""),Te(!0);const yt=new AbortController;M.current?.abort(),M.current=yt;let Lt=!1,Ht=!1,Ct="";const Gt=3e4,kt=18e4,Ge=async(Ce,xe)=>{const ut=Date.now();for(;Date.now()-ut<xe;){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=()=>{S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{Ht=!0,Ct="no-events-timeout",yt.abort("no-events-timeout")},Gt)};da(),W.current&&window.clearTimeout(W.current),W.current=window.setTimeout(()=>{Ht=!0,Ct="max-stream-window",yt.abort("max-stream-window")},kt);try{for await(const Ce of a.stream(F,et,{signal:yt.signal})){const xe=Ce;if(fd(xe.type)&&da(),xe.type==="approval.requested"||xe.type==="permission.request"||xe.type==="permission.asked"){const Qe=er(xe.properties||{});Qe&&Rr(Qe.sessionId,F)?(l(Qe),$()):T()}if(xe.type==="approval.resolved"||xe.type==="permission.resolved"||xe.type==="permission.replied"){const Qe=er(xe.properties||{});Qe?.id&&b(Qe.id),T()}String(xe.type||"").toLowerCase().startsWith("pack.")&&Ke(xe.type,xe.properties||{});const ut=Tr(xe);if(!(ut&&ut!==et)){if(xe.type==="session.response"){const Qe=String(xe.properties?.delta||"");if(!Qe)continue;Lt=!0,Te(!1),q(qt=>`${qt}${Qe}`)}if(Cs.has(xe.type)){const Qe=dn(xe.properties)||"tool",qt=An(xe.properties);me(Qe,"started",`${qt||ut||et}:${Qe}:started`)}if(As.has(xe.type)){const Qe=dn(xe.properties)||"tool",qt=An(xe.properties),ia=String(xe.properties?.status||xe.properties?.state||"").toLowerCase(),ba=xe.type==="tool_call.failed"||ia.includes("fail")||ia.includes("error")||!!xe.properties?.error;me(Qe,ba?"failed":"completed",`${qt||ut||et}:${Qe}:${ba?"failed":"completed"}`)}if(xe.type==="message.part.updated"){const Qe=xe.properties?.part||{},qt=String(Qe.type||"").trim().toLowerCase().replace(/_/g,"-"),ia=dn(Qe)||dn(xe.properties),ba=An(Qe),Kt=Qe?.state,Vt=String((Kt&&typeof Kt=="object"?Kt.status:Kt)||Qe.status||"").trim().toLowerCase(),mt=!!Qe.error||!!(Kt&&typeof Kt=="object"&&Kt.error)||Vt.includes("fail")||Vt.includes("error")||Vt.includes("deny")||Vt.includes("reject")||Vt.includes("cancel"),ua=!!Qe.result||!!Qe.output||!!(Kt&&typeof Kt=="object"&&(Kt.output||Kt.result))||Vt.includes("done")||Vt.includes("complete")||Vt.includes("success");if(ia&&(qt==="tool"||qt==="tool-invocation")){const na=mt?"failed":ua?"completed":"started";me(ia,na,`${ba||ut||et}:${ia}:${na}`)}ia&&qt==="tool-result"&&me(ia,mt?"failed":"completed",`${ba||ut||et}:${ia}:${mt?"failed":"completed"}`)}if(ld.has(xe.type))throw new Error(String(xe.properties?.error||"Run failed."));if((xe.type==="session.updated"||xe.type==="session.status")&&String(xe.properties?.status||"").toLowerCase()==="idle"||od.has(xe.type))break}}}catch(Ce){const xe=String(Ce?.message||Ce||"").toLowerCase();if(!(Ht||xe.includes("abort")||xe.includes("terminated")||xe.includes("networkerror")))throw Ce}finally{S.current&&window.clearTimeout(S.current),W.current&&window.clearTimeout(W.current)}if(Ht){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||Te(!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(""),Te(!1),await be(),await d.invalidateQueries({queryKey:["chat"]}).catch(()=>{})}catch(F){const X=Va(F),we=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",we),await dt()}finally{E.current&&(re(!1),Te(!1))}}},[t,Pt,$,a,Ve,k,d,Ke,me,dt,T,be,b,Se,C,Le,n,te,l]);fe(()=>{be(),Xe();const h=async()=>{const J=await Ve().catch(()=>"");J&&P(J),ce(!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(()=>{C&&(M.current?.abort(),ce(!1),_(),G(),T(),dt())},[dt,T,G,_,C]),fe(()=>{C||A([])},[C]),fe(()=>{!C&&I.length===0&&Ve().catch(()=>{})},[Ve,C,I.length]),fe(()=>{yd(lt),lt&&$()},[lt,$]),fe(()=>{const h=window.setInterval(()=>{C&&T()},2500);return()=>window.clearInterval(h)},[T,C]),fe(()=>{const h=ts("/api/global/event",U=>{let J=null;try{J=JSON.parse(String(U.data||"{}"))}catch{return}const F=String(J?.type||"").trim();if(!F)return;const X=J?.properties||{},we=er(X);if(we&&Rr(we.sessionId,C)&&((F==="approval.requested"||F==="permission.request"||F==="permission.asked")&&l(we),(F==="approval.resolved"||F==="permission.resolved"||F==="permission.replied")&&b(we.id)),F.toLowerCase().startsWith("pack.")&&Ke(F,X),Cs.has(F)){const Ue=dn(X)||"tool",st=An(X),vt=Tr(J,"global");me(Ue,"started",`${st||vt}:${Ue}:started`)}if(As.has(F)){const Ue=dn(X)||"tool",st=An(X),vt=Tr(J,"global"),It=String(X?.status||X?.state||"").toLowerCase(),et=F==="tool_call.failed"||It.includes("fail")||!!X?.error;me(Ue,et?"failed":"completed",`${st||vt}:${Ue}:${et?"failed":"completed"}`)}},{withCredentials:!0});return()=>h()},[Ke,me,b,C,l]);const ae=te.length,Ne=!ve&&!O.length&&!ge&&!pe;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(Me.aside,{className:`chat-sessions-panel ${ee?"open":""}`,initial:!1,animate:u?{x:ee?0:"-104%"}:{x:ee?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))),ce(!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:I.map(h=>e(Me.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===C?"active":""}`,title:h.id,onClick:()=>{P(h.id),ce(!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))}),I.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No sessions yet."})]})]}),e(Mt,{children:ee?e(Me.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:()=>ce(!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:()=>ce(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"&&(wd(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:[ve&&!O.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:O.map(h=>{const U=h.role==="assistant"||h.role==="system",J=U?"assistant":"user";return e(Me.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:gn(h.text||"")}}):e("pre",{className:"chat-msg-pre",children:h.text})]},h.id)})}),ge||pe?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&&!pe?e("div",{className:"tcp-thinking","aria-live":"polite",children:[e("span",{children:"Thinking"}),e("i",{}),e("i",{}),e("i",{})]}):null,pe?e("pre",{className:"chat-msg-pre",children:pe}):null]}):null]}),e("div",{className:"chat-composer shrink-0",children:[e("div",{className:`chat-attach-row mb-2 ${ae?"":"hidden"}`,children:[e("span",{className:"tcp-subtle",children:[ae," attached"]}),e("div",{className:"chat-files-line",children:te.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:gd(h.size)}),e("button",{type:"button",className:"chat-file-pill-btn chat-file-pill-btn-danger",title:"Remove from list",onClick:()=>H(J=>J.filter((F,X)=>X!==U)),children:e("i",{"data-lucide":"x"})})]},`${h.path}-${U}`))})]}),Pe.length?e("div",{className:"mb-2 grid gap-1.5",children:Pe.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:D,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:()=>D.current?.click(),children:e("i",{"data-lucide":"paperclip"})}),e("textarea",{ref:N,rows:1,value:k,className:"tcp-input chat-input-with-clip chat-input-modern resize-none",placeholder:"Ask anything... (Enter to send, Shift+Enter newline)",onInput:h=>v(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:()=>{v(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(F=>String(F.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(Me.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:_,children:[e("i",{"data-lucide":"trash-2"}),"Clear"]})]}),e("div",{className:"chat-tools-activity",children:Re.length?Re.slice(0,24).map(h=>e("div",{className:`chat-tool-chip ${bd(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(Me.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(Me.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 wn(a){return a?.checkpoint||{}}function Jr(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function Rs(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 fn(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 $i(a,t=""){return String(a?.properties?.sessionID||a?.sessionID||t||"").trim()}function as(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 ns(a){return as(wn(a),"completed_nodes","completedNodes")}function Oi(a){return String(a?.status||a?.content?.status||"").trim().toLowerCase()}function Ei(a){const t=new Set(as(wn(a),"blocked_nodes","blockedNodes"));for(const{nodeId:n,value:r}of ss(a))Oi(r)==="blocked"&&t.add(n);return Array.from(t)}function Nd(a){const t=new Set;for(const{nodeId:n,value:r}of ss(a)){const s=Oi(r);(s==="verify_failed"||s==="failed")&&t.add(n)}return Array.from(t)}function rs(a){return as(wn(a),"pending_nodes","pendingNodes")}function Ms(a){return ns(a).length}function _d(a){return rs(a).length}function dr(a){return Ei(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")&&Nd(a).length>0?"failed":t||"unknown"}function qs(a){return(Array.isArray(a?.active_session_ids)?a.active_session_ids:Array.isArray(a?.activeSessionIds)?a.activeSessionIds:[]).length}function kr(a){const t=wn(a);return t?.node_outputs||t?.nodeOutputs||{}}function ss(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 Sd(a,t){const n=wn(a),r=String(t||"").trim();return r?Number(n?.node_attempts?.[r]||n?.nodeAttempts?.[r]||0):0}function Id(a,t){const n=Nr(a,t);return String(n?.content?.session_id||n?.content?.sessionId||"").trim()}function Cd(a,t,n){const r=new Set(ns(a)),s=new Set(Ei(a)),c=new Set(rs(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 Ad(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 Pd(a){const t=rs(a),n=String(t[0]||"").trim();return n?n.startsWith("node-")?n:`node-${n}`:""}function Td(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(ns(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(S=>`node-${String(S||"").trim()}`).filter(Boolean):[],N=p.every(S=>r.has(S.replace(/^node-/,""))),D=Cd(a,d,N?[]:p),x=Nr(a,d)||{},M=t===u&&String(a?.status||"").trim().toLowerCase()==="running"?"in_progress":D==="pending"&&N?"runnable":D,E=c?.metadata?.builder||{};return{id:u,title:String(c?.objective||d||"Workflow node"),description:c?.agent_id?`agent: ${c.agent_id}`:"",dependencies:p,state:M,retry_count:Sd(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:Id(a,d),projects_backlog_tasks:!!E?.project_backlog_tasks,backlog_task_id:String(E?.task_id||""),task_kind:String(E?.task_kind||""),repo_root:String(E?.repo_root||""),write_scope:String(E?.write_scope||""),acceptance_criteria:String(E?.acceptance_criteria||""),task_dependencies:String(E?.task_dependencies||""),verification_state:String(E?.verification_state||""),task_owner:String(E?.task_owner||""),verification_command:String(E?.verification_command||""),output_path:String(E?.output_path||"")}});return{currentTaskId:Ad(s,t),taskSource:"checkpoint",tasks:s}}function Di(a){const t=wn(a);return Array.isArray(t?.lifecycle_history)?t.lifecycle_history:Array.isArray(t?.lifecycleHistory)?t.lifecycleHistory:[]}function ji(a){const t=Di(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 is(a){return String(a?.metadata?.node_id||a?.metadata?.nodeId||"").trim()}function Ui(a){const t=is(a);return t?t.startsWith("node-")?t:`node-${t}`:""}function Rd(a,t,n=8){const r=String(t||"").trim();return r?Di(a).filter(s=>is(s)===r).slice(-n).reverse():[]}function Md(a,t,n=8){return Rd(a,t,n).map(r=>({...jd(r),raw:r}))}function qd(a){const t=ji(a);return Ui(t)}function $d(a){const t=Object.values(kr(a)).filter(Boolean);return t.length&&t[t.length-1]||null}function Od(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 os(a){return a?.tool_telemetry||a?.toolTelemetry||null}function Kn(a){return a?.artifact_validation||a?.artifactValidation||null}function Ed(a){const t=Kn(a);return Array.isArray(t?.artifact_candidates)?t.artifact_candidates:[]}function Bi(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 Dd(a){const t=$d(a),n=ji(a),r=Bi(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 jd(a){const t=a?.metadata||{};return{event:String(a?.event||"event").trim()||"event",recordedAtMs:Number(a?.recorded_at_ms||a?.recordedAtMs||0),nodeId:is(a),taskId:Ui(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 Ud(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:Jr(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:Jr(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 Bd(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:fn(n),raw:n})).sort((n,r)=>Number(r.at||0)-Number(n.at||0))}function Fd(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:fn(c),event:c}));return n?[...s,...(Array.isArray(t)?t:[]).map(c=>({id:`context:${String(c?.seq||"")}:${String(c?.event_type||"")}`,source:"context",at:Jr(c?.created_at_ms||c?.timestamp_ms||c?.timestampMs)||Date.now(),event:c}))]:s}function Ld(a,t=""){return(Array.isArray(a)?a:[]).map(n=>{const r=$i(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 Kd(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||fn(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 Wd(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 zd(a,t){const n=os(t),r=Kn(t),s=Bi(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:Ed(t)}}function Fi(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 Qt(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 Li(a=!0){return V({queryKey:["system","health"],queryFn:()=>Qt("/api/system/health"),enabled:a,refetchInterval:a?15e3:!1})}function Jd(a=!0){return V({queryKey:["swarm","status"],queryFn:()=>Qt("/api/swarm/status"),enabled:a,refetchInterval:a?5e3:!1})}function ls(a=!0){return V({queryKey:["system","capabilities"],queryFn:()=>Qt("/api/capabilities"),enabled:a,refetchInterval:a?6e4:!1,staleTime:3e4})}const Qd=`id: competitor-research-pipeline
|
|
8
|
+
order: 2
|
|
9
|
+
name: Competitor Research Pipeline
|
|
10
|
+
icon: radar
|
|
11
|
+
summary: Track competitors, synthesize movements, and brief the team on strategic changes.
|
|
12
|
+
description: A recurring competitor workflow that scans rivals, synthesizes patterns, reviews implications, and prepares a distribution-ready summary.
|
|
13
|
+
suggestedOutputs:
|
|
14
|
+
- competitor-scan.md
|
|
15
|
+
- strategic-summary.md
|
|
16
|
+
agents:
|
|
17
|
+
- agentId: market-discover
|
|
18
|
+
displayName: Market Discover
|
|
19
|
+
role: watcher
|
|
20
|
+
avatarUrl: ""
|
|
21
|
+
templateId: ""
|
|
22
|
+
linkedTemplateId: ""
|
|
23
|
+
skills:
|
|
24
|
+
- analysis
|
|
25
|
+
prompt:
|
|
26
|
+
role: You are a market-source scout.
|
|
27
|
+
mission: Identify the local context, competitor list, and source corpus that should guide the competitor scan before evidence gathering begins.
|
|
28
|
+
inputs: Inspect any local competitor lists, prior scans, strategy docs, changelogs, and source bundles. Return a clear inventory of what should be read next.
|
|
29
|
+
outputContract: Return a structured handoff with \`workspace_inventory_summary\`, \`discovered_paths\`, \`priority_paths\`, and \`skipped_paths_initial\`.
|
|
30
|
+
guardrails: Do not jump to conclusions or write the final competitor scan in this stage.
|
|
31
|
+
modelProvider: ""
|
|
32
|
+
modelId: ""
|
|
33
|
+
toolAllowlist:
|
|
34
|
+
- glob
|
|
35
|
+
- read
|
|
36
|
+
toolDenylist: []
|
|
37
|
+
mcpAllowedServers: []
|
|
38
|
+
- agentId: market-local-sources
|
|
39
|
+
displayName: Market Local Sources
|
|
40
|
+
role: watcher
|
|
41
|
+
avatarUrl: ""
|
|
42
|
+
templateId: ""
|
|
43
|
+
linkedTemplateId: ""
|
|
44
|
+
skills:
|
|
45
|
+
- analysis
|
|
46
|
+
prompt:
|
|
47
|
+
role: You are a local-source analyst for competitor intelligence.
|
|
48
|
+
mission: Read the prioritized local sources and extract the competitor context, prior findings, and product framing that should shape the scan.
|
|
49
|
+
inputs: Use the upstream \`source_inventory\` handoff to choose concrete files to read and capture the facts that later scanning should compare against.
|
|
50
|
+
outputContract: Return a structured handoff with \`read_paths\`, \`reviewed_facts\`, \`files_reviewed\`, \`files_not_reviewed\`, and \`citations_local\`.
|
|
51
|
+
guardrails: Only cite local files that were actually read in this run.
|
|
52
|
+
modelProvider: ""
|
|
53
|
+
modelId: ""
|
|
54
|
+
toolAllowlist:
|
|
55
|
+
- glob
|
|
56
|
+
- read
|
|
57
|
+
toolDenylist: []
|
|
58
|
+
mcpAllowedServers: []
|
|
59
|
+
- agentId: market-external
|
|
60
|
+
displayName: Market External
|
|
61
|
+
role: watcher
|
|
62
|
+
avatarUrl: ""
|
|
63
|
+
templateId: ""
|
|
64
|
+
linkedTemplateId: ""
|
|
65
|
+
skills:
|
|
66
|
+
- websearch
|
|
67
|
+
- trend-analysis
|
|
68
|
+
prompt:
|
|
69
|
+
role: You are an external competitor-research analyst.
|
|
70
|
+
mission: Gather current web evidence about competitor launches, pricing moves, positioning shifts, and customer sentiment.
|
|
71
|
+
inputs: Use the upstream \`source_inventory\` and \`local_source_notes\` handoffs to focus the search and fetch specific sources when snippets are not enough.
|
|
72
|
+
outputContract: Return a structured handoff with \`external_research_mode\`, \`queries_attempted\`, \`sources_reviewed\`, \`citations_external\`, and \`research_limitations\`.
|
|
73
|
+
guardrails: If search is unavailable, record the limitation clearly instead of inventing web evidence.
|
|
74
|
+
modelProvider: ""
|
|
75
|
+
modelId: ""
|
|
76
|
+
toolAllowlist:
|
|
77
|
+
- read
|
|
78
|
+
- websearch
|
|
79
|
+
- webfetch
|
|
80
|
+
- glob
|
|
81
|
+
toolDenylist: []
|
|
82
|
+
mcpAllowedServers: []
|
|
83
|
+
- agentId: market-scan
|
|
84
|
+
displayName: Market Scan
|
|
85
|
+
role: watcher
|
|
86
|
+
avatarUrl: ""
|
|
87
|
+
templateId: ""
|
|
88
|
+
linkedTemplateId: ""
|
|
89
|
+
skills:
|
|
90
|
+
- trend-analysis
|
|
91
|
+
prompt:
|
|
92
|
+
role: You are a competitor intelligence analyst responsible for finding real market changes and separating signal from noise.
|
|
93
|
+
mission: Turn the upstream discovery, local source notes, and external market research into the final competitor scan.
|
|
94
|
+
inputs: Use the upstream \`source_inventory\`, \`local_source_notes\`, and \`external_research\` handoffs as the source of truth for the final scan.
|
|
95
|
+
outputContract: Produce a structured scan with what changed, why it matters, evidence links, confidence level, affected audience or buyer stage, and whether the signal is emerging, confirmed, or low-confidence.
|
|
96
|
+
guardrails: Ignore rumors and recycled noise. Separate evidence from inference, be honest about uncertainty, and do not redo web research in this stage.
|
|
97
|
+
modelProvider: ""
|
|
98
|
+
modelId: ""
|
|
99
|
+
toolAllowlist:
|
|
100
|
+
- read
|
|
101
|
+
- glob
|
|
102
|
+
toolDenylist: []
|
|
103
|
+
mcpAllowedServers: []
|
|
104
|
+
- agentId: synthesist
|
|
105
|
+
displayName: Synthesist
|
|
106
|
+
role: worker
|
|
107
|
+
avatarUrl: ""
|
|
108
|
+
templateId: ""
|
|
109
|
+
linkedTemplateId: ""
|
|
110
|
+
skills:
|
|
111
|
+
- synthesis
|
|
112
|
+
prompt:
|
|
113
|
+
role: You are a strategy synthesist who turns raw competitor monitoring into a useful decision brief.
|
|
114
|
+
mission: Convert the market scan into clear strategic implications, priority calls, and recommended responses for the team.
|
|
115
|
+
inputs: Use the competitor scan, prior strategy context, product positioning, and known customer objections or differentiators.
|
|
116
|
+
outputContract: Produce a summary with key themes, what changed, why it matters, threats, opportunities, confidence levels, and recommended actions ranked by urgency and impact.
|
|
117
|
+
guardrails: Do not overreact to a single data point. Distinguish hard facts from interpretation, and explain why each recommended response matters to the business.
|
|
118
|
+
modelProvider: ""
|
|
119
|
+
modelId: ""
|
|
120
|
+
toolAllowlist:
|
|
121
|
+
- read
|
|
122
|
+
- write
|
|
123
|
+
- glob
|
|
124
|
+
toolDenylist: []
|
|
125
|
+
mcpAllowedServers: []
|
|
126
|
+
- agentId: review
|
|
127
|
+
displayName: Review
|
|
128
|
+
role: reviewer
|
|
129
|
+
avatarUrl: ""
|
|
130
|
+
templateId: ""
|
|
131
|
+
linkedTemplateId: ""
|
|
132
|
+
skills:
|
|
133
|
+
- qa
|
|
134
|
+
prompt:
|
|
135
|
+
role: You are the review editor for competitor intelligence, responsible for evidence quality, honest framing, and practical usefulness.
|
|
136
|
+
mission: Review the strategic summary for unsupported conclusions, weak evidence, and recommendations that do not follow from the data.
|
|
137
|
+
inputs: Use the summary, the raw scan evidence, and any relevant positioning context or review criteria.
|
|
138
|
+
outputContract: Approve or request revisions with exact issues grouped by evidence, interpretation, recommendation quality, and missing context.
|
|
139
|
+
guardrails: Reject unsupported conclusions, misleading framing, and advice that skips over uncertainty. Preserve nuance instead of flattening every insight into a threat.
|
|
140
|
+
modelProvider: ""
|
|
141
|
+
modelId: ""
|
|
142
|
+
toolAllowlist:
|
|
143
|
+
- read
|
|
144
|
+
- write
|
|
145
|
+
- glob
|
|
146
|
+
toolDenylist: []
|
|
147
|
+
mcpAllowedServers: []
|
|
148
|
+
- agentId: briefing
|
|
149
|
+
displayName: Briefing
|
|
150
|
+
role: committer
|
|
151
|
+
avatarUrl: ""
|
|
152
|
+
templateId: ""
|
|
153
|
+
linkedTemplateId: ""
|
|
154
|
+
skills:
|
|
155
|
+
- reporting
|
|
156
|
+
prompt:
|
|
157
|
+
role: You are the internal briefing operator who packages approved competitor intelligence for busy stakeholders.
|
|
158
|
+
mission: Turn the approved summary into a concise update the team can skim quickly and act on.
|
|
159
|
+
inputs: Use the reviewed summary, destination channel guidance, and any audience-specific formatting requirements.
|
|
160
|
+
outputContract: Generate a concise update with headline, TL;DR, the top changes, recommended follow-ups, and any owners or deadlines if the brief implies action.
|
|
161
|
+
guardrails: Keep recommendations grounded in the approved evidence, and do not add new claims while packaging the brief.
|
|
162
|
+
modelProvider: ""
|
|
163
|
+
modelId: ""
|
|
164
|
+
toolAllowlist:
|
|
165
|
+
- read
|
|
166
|
+
- write
|
|
167
|
+
- glob
|
|
168
|
+
toolDenylist: []
|
|
169
|
+
mcpAllowedServers: []
|
|
170
|
+
nodes:
|
|
171
|
+
- nodeId: scan-market-discover
|
|
172
|
+
title: Discover Market Sources
|
|
173
|
+
agentId: market-discover
|
|
174
|
+
objective: Identify the local source corpus and file inventory that should guide the competitor scan.
|
|
175
|
+
dependsOn: []
|
|
176
|
+
inputRefs: []
|
|
177
|
+
stageKind: research_discover
|
|
178
|
+
outputKind: structured_json
|
|
179
|
+
outputPath: ""
|
|
180
|
+
taskKind: ""
|
|
181
|
+
projectBacklogTasks: false
|
|
182
|
+
backlogTaskId: ""
|
|
183
|
+
repoRoot: ""
|
|
184
|
+
writeScope: ""
|
|
185
|
+
acceptanceCriteria: ""
|
|
186
|
+
taskDependencies: ""
|
|
187
|
+
verificationState: ""
|
|
188
|
+
taskOwner: ""
|
|
189
|
+
verificationCommand: ""
|
|
190
|
+
- nodeId: scan-market-local-sources
|
|
191
|
+
title: Read Market Sources
|
|
192
|
+
agentId: market-local-sources
|
|
193
|
+
objective: Read the prioritized local competitor and strategy sources before external scanning.
|
|
194
|
+
dependsOn:
|
|
195
|
+
- scan-market-discover
|
|
196
|
+
inputRefs:
|
|
197
|
+
- fromStepId: scan-market-discover
|
|
198
|
+
alias: source_inventory
|
|
199
|
+
stageKind: research_local_sources
|
|
200
|
+
outputKind: structured_json
|
|
201
|
+
outputPath: ""
|
|
202
|
+
taskKind: ""
|
|
203
|
+
projectBacklogTasks: false
|
|
204
|
+
backlogTaskId: ""
|
|
205
|
+
repoRoot: ""
|
|
206
|
+
writeScope: ""
|
|
207
|
+
acceptanceCriteria: ""
|
|
208
|
+
taskDependencies: ""
|
|
209
|
+
verificationState: ""
|
|
210
|
+
taskOwner: ""
|
|
211
|
+
verificationCommand: ""
|
|
212
|
+
- nodeId: scan-market-external-research
|
|
213
|
+
title: Research Market
|
|
214
|
+
agentId: market-external
|
|
215
|
+
objective: Gather current external competitor evidence guided by the local market context.
|
|
216
|
+
dependsOn:
|
|
217
|
+
- scan-market-discover
|
|
218
|
+
- scan-market-local-sources
|
|
219
|
+
inputRefs:
|
|
220
|
+
- fromStepId: scan-market-discover
|
|
221
|
+
alias: source_inventory
|
|
222
|
+
- fromStepId: scan-market-local-sources
|
|
223
|
+
alias: local_source_notes
|
|
224
|
+
stageKind: research_external_sources
|
|
225
|
+
outputKind: structured_json
|
|
226
|
+
outputPath: ""
|
|
227
|
+
taskKind: ""
|
|
228
|
+
projectBacklogTasks: false
|
|
229
|
+
backlogTaskId: ""
|
|
230
|
+
repoRoot: ""
|
|
231
|
+
writeScope: ""
|
|
232
|
+
acceptanceCriteria: ""
|
|
233
|
+
taskDependencies: ""
|
|
234
|
+
verificationState: ""
|
|
235
|
+
taskOwner: ""
|
|
236
|
+
verificationCommand: ""
|
|
237
|
+
- nodeId: scan-market
|
|
238
|
+
title: Scan Market
|
|
239
|
+
agentId: market-scan
|
|
240
|
+
objective: Synthesize the discovered local and external evidence into the final competitor scan.
|
|
241
|
+
dependsOn:
|
|
242
|
+
- scan-market-discover
|
|
243
|
+
- scan-market-local-sources
|
|
244
|
+
- scan-market-external-research
|
|
245
|
+
inputRefs:
|
|
246
|
+
- fromStepId: scan-market-discover
|
|
247
|
+
alias: source_inventory
|
|
248
|
+
- fromStepId: scan-market-local-sources
|
|
249
|
+
alias: local_source_notes
|
|
250
|
+
- fromStepId: scan-market-external-research
|
|
251
|
+
alias: external_research
|
|
252
|
+
stageKind: research_finalize
|
|
253
|
+
outputKind: scan
|
|
254
|
+
outputPath: ""
|
|
255
|
+
taskKind: ""
|
|
256
|
+
projectBacklogTasks: false
|
|
257
|
+
backlogTaskId: ""
|
|
258
|
+
repoRoot: ""
|
|
259
|
+
writeScope: ""
|
|
260
|
+
acceptanceCriteria: ""
|
|
261
|
+
taskDependencies: ""
|
|
262
|
+
verificationState: ""
|
|
263
|
+
taskOwner: ""
|
|
264
|
+
verificationCommand: ""
|
|
265
|
+
- nodeId: synthesize-signals
|
|
266
|
+
title: Synthesize Signals
|
|
267
|
+
agentId: synthesist
|
|
268
|
+
objective: Turn the raw scan into a strategic competitor summary.
|
|
269
|
+
dependsOn:
|
|
270
|
+
- scan-market
|
|
271
|
+
inputRefs:
|
|
272
|
+
- fromStepId: scan-market
|
|
273
|
+
alias: scan
|
|
274
|
+
outputKind: summary
|
|
275
|
+
outputPath: ""
|
|
276
|
+
taskKind: ""
|
|
277
|
+
projectBacklogTasks: false
|
|
278
|
+
backlogTaskId: ""
|
|
279
|
+
repoRoot: ""
|
|
280
|
+
writeScope: ""
|
|
281
|
+
acceptanceCriteria: ""
|
|
282
|
+
taskDependencies: ""
|
|
283
|
+
verificationState: ""
|
|
284
|
+
taskOwner: ""
|
|
285
|
+
verificationCommand: ""
|
|
286
|
+
- nodeId: review-summary
|
|
287
|
+
title: Review Summary
|
|
288
|
+
agentId: review
|
|
289
|
+
objective: Review the summary for evidence quality and useful recommendations.
|
|
290
|
+
dependsOn:
|
|
291
|
+
- synthesize-signals
|
|
292
|
+
inputRefs:
|
|
293
|
+
- fromStepId: synthesize-signals
|
|
294
|
+
alias: summary
|
|
295
|
+
outputKind: review
|
|
296
|
+
outputPath: ""
|
|
297
|
+
taskKind: ""
|
|
298
|
+
projectBacklogTasks: false
|
|
299
|
+
backlogTaskId: ""
|
|
300
|
+
repoRoot: ""
|
|
301
|
+
writeScope: ""
|
|
302
|
+
acceptanceCriteria: ""
|
|
303
|
+
taskDependencies: ""
|
|
304
|
+
verificationState: ""
|
|
305
|
+
taskOwner: ""
|
|
306
|
+
verificationCommand: ""
|
|
307
|
+
- nodeId: publish-brief
|
|
308
|
+
title: Publish Brief
|
|
309
|
+
agentId: briefing
|
|
310
|
+
objective: Prepare the reviewed summary for internal distribution.
|
|
311
|
+
dependsOn:
|
|
312
|
+
- review-summary
|
|
313
|
+
inputRefs:
|
|
314
|
+
- fromStepId: review-summary
|
|
315
|
+
alias: approved_summary
|
|
316
|
+
outputKind: brief
|
|
317
|
+
outputPath: ""
|
|
318
|
+
taskKind: ""
|
|
319
|
+
projectBacklogTasks: false
|
|
320
|
+
backlogTaskId: ""
|
|
321
|
+
repoRoot: ""
|
|
322
|
+
writeScope: ""
|
|
323
|
+
acceptanceCriteria: ""
|
|
324
|
+
taskDependencies: ""
|
|
325
|
+
verificationState: ""
|
|
326
|
+
taskOwner: ""
|
|
327
|
+
verificationCommand: ""
|
|
328
|
+
`,Hd=`id: marketing-content-pipeline
|
|
329
|
+
order: 0
|
|
330
|
+
name: Marketing Content Pipeline
|
|
331
|
+
icon: megaphone
|
|
332
|
+
summary: Audit the workspace, create a marketing brief, draft copy, review it, and package it for publishing.
|
|
333
|
+
description: A reusable four-stage marketing workflow that starts by inspecting the workspace for product context, source material, and existing assets, then creates a fresh brief, drafts copy, reviews claims and tone, and prepares a publish-ready handoff.
|
|
334
|
+
suggestedOutputs:
|
|
335
|
+
- marketing-brief.md
|
|
336
|
+
- draft-post.md
|
|
337
|
+
- review-notes.md
|
|
338
|
+
- approved-post.md
|
|
339
|
+
- publish-checklist.md
|
|
340
|
+
agents:
|
|
341
|
+
- agentId: research-discover
|
|
342
|
+
displayName: Research Discover
|
|
343
|
+
role: watcher
|
|
344
|
+
avatarUrl: ""
|
|
345
|
+
templateId: ""
|
|
346
|
+
linkedTemplateId: ""
|
|
347
|
+
skills:
|
|
348
|
+
- analysis
|
|
349
|
+
prompt:
|
|
350
|
+
role: You are a workspace source scout for product marketing research.
|
|
351
|
+
mission: Enumerate the workspace, identify the product and marketing source corpus, and decide which files should be reviewed before synthesis begins.
|
|
352
|
+
inputs: Start at the workspace root. Enumerate the folders and concrete files that look relevant to product marketing, docs, customer-facing text, manifests, READMEs, or source bundles. If a curated source index such as \`SOURCES.md\` exists, read it first. Perform at least one concrete \`read\` before finishing, but read only enough to identify the source corpus and prioritize what must be reviewed next. Treat prior generated workflow artifacts as non-authoritative.
|
|
353
|
+
outputContract: Return a structured handoff that includes \`workspace_inventory_summary\`, \`discovered_paths\`, \`priority_paths\`, and \`skipped_paths_initial\` so the next stage can perform concrete file reads. Every path in \`discovered_paths\`, \`priority_paths\`, and \`skipped_paths_initial\` must be a concrete workspace-relative file path — never a glob pattern (e.g. \`*.yaml\`), directory placeholder (e.g. \`tandem-social/\`), or wildcard (e.g. \`tandem/components/*\`).
|
|
354
|
+
guardrails: Do not write the final brief in this stage. Do not invent file contents. Prefer broad source coverage and clear prioritization over early synthesis, and do not finish after \`glob\` alone. Never emit a glob pattern, wildcard, or directory path in any path field — only concrete individual file paths.
|
|
355
|
+
modelProvider: ""
|
|
356
|
+
modelId: ""
|
|
357
|
+
toolAllowlist:
|
|
358
|
+
- glob
|
|
359
|
+
- read
|
|
360
|
+
toolDenylist: []
|
|
361
|
+
mcpAllowedServers: []
|
|
362
|
+
- agentId: research-local-sources
|
|
363
|
+
displayName: Research Local Sources
|
|
364
|
+
role: watcher
|
|
365
|
+
avatarUrl: ""
|
|
366
|
+
templateId: ""
|
|
367
|
+
linkedTemplateId: ""
|
|
368
|
+
skills:
|
|
369
|
+
- analysis
|
|
370
|
+
prompt:
|
|
371
|
+
role: You are a local-source analyst preparing evidence-backed marketing notes from workspace files.
|
|
372
|
+
mission: Read the prioritized local files, extract usable facts and customer language, and account for all relevant sources before synthesis.
|
|
373
|
+
inputs: Use the upstream \`source_inventory\` handoff as the file plan. Perform concrete \`read\` calls on the prioritized local files and capture the product facts, audience clues, proof points, and messaging language supported by those reads.
|
|
374
|
+
outputContract: Return a structured handoff that includes \`read_paths\`, \`reviewed_facts\`, \`files_reviewed\`, \`files_not_reviewed\`, and \`citations_local\` so later stages can rely on concrete local evidence. Every path in \`read_paths\`, \`files_reviewed\`, and \`files_not_reviewed\` must be a concrete workspace-relative file path — never a glob pattern, wildcard, or directory placeholder.
|
|
375
|
+
guardrails: Do not invent facts from filenames alone. Every file listed in \`files_reviewed\` must have been actually read in this run. Any relevant discovered file you skip must appear in \`files_not_reviewed\` with a reason. Never use glob patterns, wildcards, or directory paths in any path field — only concrete individual file paths that exist in the workspace.
|
|
376
|
+
modelProvider: ""
|
|
377
|
+
modelId: ""
|
|
378
|
+
toolAllowlist:
|
|
379
|
+
- glob
|
|
380
|
+
- read
|
|
381
|
+
toolDenylist: []
|
|
382
|
+
mcpAllowedServers: []
|
|
383
|
+
- agentId: research-external
|
|
384
|
+
displayName: Research External
|
|
385
|
+
role: watcher
|
|
386
|
+
avatarUrl: ""
|
|
387
|
+
templateId: ""
|
|
388
|
+
linkedTemplateId: ""
|
|
389
|
+
skills:
|
|
390
|
+
- websearch
|
|
391
|
+
- analysis
|
|
392
|
+
prompt:
|
|
393
|
+
role: You are an external research analyst gathering current market context for the marketing brief.
|
|
394
|
+
mission: Use targeted web research to validate competitor context, market framing, and external proof points that complement the local source corpus.
|
|
395
|
+
inputs: Use the upstream \`source_inventory\` and \`local_source_notes\` handoffs to guide the external research. Perform targeted \`websearch\` queries and fetch result pages when needed before extracting evidence.
|
|
396
|
+
outputContract: Return a structured handoff that includes \`external_research_mode\`, \`queries_attempted\`, \`sources_reviewed\`, \`citations_external\`, and \`research_limitations\` so the final brief can disclose what web validation was or was not completed.
|
|
397
|
+
guardrails: If web research is unavailable, record that limitation clearly and continue without inventing external evidence. Do not write the final brief in this stage.
|
|
398
|
+
modelProvider: ""
|
|
399
|
+
modelId: ""
|
|
400
|
+
toolAllowlist:
|
|
401
|
+
- read
|
|
402
|
+
- websearch
|
|
403
|
+
- webfetch
|
|
404
|
+
- glob
|
|
405
|
+
toolDenylist: []
|
|
406
|
+
mcpAllowedServers: []
|
|
407
|
+
- agentId: research
|
|
408
|
+
displayName: Research
|
|
409
|
+
role: watcher
|
|
410
|
+
avatarUrl: ""
|
|
411
|
+
templateId: ""
|
|
412
|
+
linkedTemplateId: ""
|
|
413
|
+
skills:
|
|
414
|
+
- analysis
|
|
415
|
+
prompt:
|
|
416
|
+
role: You are a product marketing researcher focused on campaign positioning, audience insight, and competitive context.
|
|
417
|
+
mission: Turn the upstream discovery, local source evidence, and external research into the first complete marketing brief for the workflow.
|
|
418
|
+
inputs: Use the upstream \`source_inventory\`, \`local_source_notes\`, and \`external_research\` handoffs as the source of truth. Read \`marketing-brief.md\` from disk only as a fallback or verification step. Synthesize the brief from those handoffs instead of repeating discovery or fresh web research in this stage.
|
|
419
|
+
outputContract: "Use the write tool to create \`marketing-brief.md\` in the workspace even if it does not exist yet. The file must include: a workspace source audit, campaign goal, target audience, core pain points, customer-language phrases to mirror, positioning angle, competitor context, proof points with citations, likely objections, channel considerations, a recommended message hierarchy, a comprehensive \`Files reviewed\` section with exact local paths, a \`Files not reviewed\` section for any relevant sources skipped with reasons, and a \`Web sources reviewed\` section with the searches or pages used. Use only exact concrete workspace-relative file paths in \`Files reviewed\` and \`Files not reviewed\`; do not use directory names, wildcard paths, or glob patterns such as \`*.yaml\`. The brief should be usable even if no prior campaign brief existed."
|
|
420
|
+
guardrails: Do not invent metrics, testimonials, or competitor claims. Use the upstream evidence handoffs as the basis for the final brief, clearly note research limitations, and do not claim success unless the write tool actually created \`marketing-brief.md\`. Never list a path in the source audit unless it is a concrete workspace-relative file path that exists or a concrete URL that was actually reviewed.
|
|
421
|
+
modelProvider: ""
|
|
422
|
+
modelId: ""
|
|
423
|
+
toolAllowlist:
|
|
424
|
+
- read
|
|
425
|
+
- write
|
|
426
|
+
- glob
|
|
427
|
+
toolDenylist: []
|
|
428
|
+
mcpAllowedServers: []
|
|
429
|
+
- agentId: copywriter
|
|
430
|
+
displayName: Copywriter
|
|
431
|
+
role: worker
|
|
432
|
+
avatarUrl: ""
|
|
433
|
+
templateId: ""
|
|
434
|
+
linkedTemplateId: ""
|
|
435
|
+
skills:
|
|
436
|
+
- copywriting
|
|
437
|
+
- messaging
|
|
438
|
+
prompt:
|
|
439
|
+
role: You are a conversion-focused marketing copywriter who turns research into clear, persuasive, channel-native copy.
|
|
440
|
+
mission: Translate the newly created marketing brief into copy that is specific, audience-aware, and built around one clear promise and one clear call to action.
|
|
441
|
+
inputs: Use the upstream \`marketing_brief\` handoff from the previous stage as the primary source of truth. Only read \`marketing-brief.md\` from disk as a fallback or verification step. Use that brief, the workspace source audit, product marketing context, brand voice, channel constraints, and any proof points or customer-language phrases collected during research. Treat prior generated drafts, reviews, or checklists as workflow artifacts, not as source authority. Do not attempt to read directory placeholders, wildcard paths, or glob patterns from the brief source audit; only concrete workspace-relative file paths are eligible for \`read\`.
|
|
442
|
+
outputContract: "Use the write tool to create \`draft-post.md\` in the workspace. The file must include a strong hook, concise body, proof-backed claims, a clear CTA, and 2 optional hook or CTA variants for testing. Make the message progression obvious: problem, promise, proof, action."
|
|
443
|
+
guardrails: Choose clarity over cleverness, benefits over feature lists, and specificity over vague hype. Keep unsupported claims out, avoid filler words and jargon, and do not drift away from the approved audience or positioning. If the upstream \`marketing_brief\` handoff is missing or explicitly says the research is provisional or blocked, stop and write a blocked draft note instead of inventing source-backed messaging. Do not claim success unless the write tool actually created \`draft-post.md\`.
|
|
444
|
+
modelProvider: ""
|
|
445
|
+
modelId: ""
|
|
446
|
+
toolAllowlist:
|
|
447
|
+
- read
|
|
448
|
+
- write
|
|
449
|
+
- glob
|
|
450
|
+
toolDenylist: []
|
|
451
|
+
mcpAllowedServers: []
|
|
452
|
+
- agentId: reviewer
|
|
453
|
+
displayName: Reviewer
|
|
454
|
+
role: reviewer
|
|
455
|
+
avatarUrl: ""
|
|
456
|
+
templateId: ""
|
|
457
|
+
linkedTemplateId: ""
|
|
458
|
+
skills:
|
|
459
|
+
- fact-checking
|
|
460
|
+
- brand-review
|
|
461
|
+
prompt:
|
|
462
|
+
role: You are an editorial reviewer applying a claims check, brand check, and conversion copy edit before anything is approved.
|
|
463
|
+
mission: Pressure-test the draft for clarity, tone, specificity, proof, and actionability so only publishable marketing copy moves forward.
|
|
464
|
+
inputs: Use the upstream \`draft\` handoff as the primary draft input and the upstream \`marketing_brief\` context from the earlier stage when available. Read \`draft-post.md\` or \`marketing-brief.md\` from disk only as a fallback or verification step. Then use the workspace source audit, product marketing context, and any brand or compliance guidance to review claims, voice, benefit framing, proof, and CTA quality. Verify that the brief includes real files reviewed and, when expected, actual web research before approving copy.
|
|
465
|
+
outputContract: Always use the write tool for review output. If the draft is approved, write the approved version to \`approved-post.md\` and briefly note approval in \`review-notes.md\`. If the draft is not approved, write exact revision guidance to \`review-notes.md\` and clearly state that \`approved-post.md\` was not created yet.
|
|
466
|
+
guardrails: Do not approve unsupported or exaggerated claims. Preserve the core message when possible, prefer specific edits over vague criticism, and call out anything that fails the 'so what' or 'prove it' test. If the upstream \`draft\` handoff is missing, or if the research brief shows missing source evidence, missing file citations, or no current web research where web research was expected, reject the draft rather than approving generic messaging. Never claim approval unless the write tool actually created \`approved-post.md\`.
|
|
467
|
+
modelProvider: ""
|
|
468
|
+
modelId: ""
|
|
469
|
+
toolAllowlist:
|
|
470
|
+
- read
|
|
471
|
+
- write
|
|
472
|
+
- glob
|
|
473
|
+
toolDenylist: []
|
|
474
|
+
mcpAllowedServers: []
|
|
475
|
+
- agentId: poster
|
|
476
|
+
displayName: Poster
|
|
477
|
+
role: committer
|
|
478
|
+
avatarUrl: ""
|
|
479
|
+
templateId: ""
|
|
480
|
+
linkedTemplateId: ""
|
|
481
|
+
skills:
|
|
482
|
+
- publishing
|
|
483
|
+
prompt:
|
|
484
|
+
role: You are a publishing operator who adapts approved copy into a channel-ready final artifact without losing the approved message.
|
|
485
|
+
mission: Prepare the approved copy for handoff or posting on the intended channel, including formatting, metadata, and an operator-ready checklist.
|
|
486
|
+
inputs: Use the upstream \`approved_copy\` handoff as the primary source of truth for approved content. Read \`approved-post.md\` from disk only as a fallback or verification step. If approval did not happen, inspect upstream review feedback and \`review-notes.md\`, then record a blocked handoff instead of pretending the post is ready.
|
|
487
|
+
outputContract: Always use the write tool to create \`publish-checklist.md\`. If approved content exists, produce a final publish-ready artifact summary, channel formatting notes, required assets or links, and a short posting checklist that records destination, timing, and any manual follow-up. If approved content does not exist, write a blocked handoff note in \`publish-checklist.md\` explaining exactly what is missing.
|
|
488
|
+
guardrails: Never publish unapproved text. Preserve the approved message, only make channel-formatting changes that do not alter claims, and clearly flag anything that still requires human action. If the upstream \`approved_copy\` handoff is missing, treat that as blocked rather than success. Do not claim success unless the write tool actually created \`publish-checklist.md\`.
|
|
489
|
+
modelProvider: ""
|
|
490
|
+
modelId: ""
|
|
491
|
+
toolAllowlist:
|
|
492
|
+
- read
|
|
493
|
+
- write
|
|
494
|
+
- glob
|
|
495
|
+
toolDenylist: []
|
|
496
|
+
mcpAllowedServers: []
|
|
497
|
+
nodes:
|
|
498
|
+
- nodeId: research-discover-sources
|
|
499
|
+
title: Discover Sources
|
|
500
|
+
agentId: research-discover
|
|
501
|
+
objective: Enumerate the workspace, identify the relevant source corpus, and prioritize which local files must be read for the marketing brief.
|
|
502
|
+
dependsOn: []
|
|
503
|
+
inputRefs: []
|
|
504
|
+
stageKind: research_discover
|
|
505
|
+
outputKind: structured_json
|
|
506
|
+
outputPath: ""
|
|
507
|
+
taskKind: ""
|
|
508
|
+
projectBacklogTasks: false
|
|
509
|
+
backlogTaskId: ""
|
|
510
|
+
repoRoot: ""
|
|
511
|
+
writeScope: ""
|
|
512
|
+
acceptanceCriteria: ""
|
|
513
|
+
taskDependencies: ""
|
|
514
|
+
verificationState: ""
|
|
515
|
+
taskOwner: ""
|
|
516
|
+
verificationCommand: ""
|
|
517
|
+
- nodeId: research-local-sources
|
|
518
|
+
title: Read Local Sources
|
|
519
|
+
agentId: research-local-sources
|
|
520
|
+
objective: Read the prioritized local product and marketing files and produce source-backed notes for the brief.
|
|
521
|
+
dependsOn:
|
|
522
|
+
- research-discover-sources
|
|
523
|
+
inputRefs:
|
|
524
|
+
- fromStepId: research-discover-sources
|
|
525
|
+
alias: source_inventory
|
|
526
|
+
stageKind: research_local_sources
|
|
527
|
+
outputKind: structured_json
|
|
528
|
+
outputPath: ""
|
|
529
|
+
taskKind: ""
|
|
530
|
+
projectBacklogTasks: false
|
|
531
|
+
backlogTaskId: ""
|
|
532
|
+
repoRoot: ""
|
|
533
|
+
writeScope: ""
|
|
534
|
+
acceptanceCriteria: ""
|
|
535
|
+
taskDependencies: ""
|
|
536
|
+
verificationState: ""
|
|
537
|
+
taskOwner: ""
|
|
538
|
+
verificationCommand: ""
|
|
539
|
+
- nodeId: research-external-research
|
|
540
|
+
title: External Research
|
|
541
|
+
agentId: research-external
|
|
542
|
+
objective: Perform targeted external research that complements the local source notes and record what web evidence was gathered or unavailable.
|
|
543
|
+
dependsOn:
|
|
544
|
+
- research-discover-sources
|
|
545
|
+
- research-local-sources
|
|
546
|
+
inputRefs:
|
|
547
|
+
- fromStepId: research-discover-sources
|
|
548
|
+
alias: source_inventory
|
|
549
|
+
- fromStepId: research-local-sources
|
|
550
|
+
alias: local_source_notes
|
|
551
|
+
stageKind: research_external_sources
|
|
552
|
+
outputKind: structured_json
|
|
553
|
+
outputPath: ""
|
|
554
|
+
taskKind: ""
|
|
555
|
+
projectBacklogTasks: false
|
|
556
|
+
backlogTaskId: ""
|
|
557
|
+
repoRoot: ""
|
|
558
|
+
writeScope: ""
|
|
559
|
+
acceptanceCriteria: ""
|
|
560
|
+
taskDependencies: ""
|
|
561
|
+
verificationState: ""
|
|
562
|
+
taskOwner: ""
|
|
563
|
+
verificationCommand: ""
|
|
564
|
+
- nodeId: research-brief
|
|
565
|
+
title: Research Brief
|
|
566
|
+
agentId: research
|
|
567
|
+
objective: Write \`marketing-brief.md\` from the structured discovery, local source notes, and external research gathered earlier in the workflow.
|
|
568
|
+
dependsOn:
|
|
569
|
+
- research-discover-sources
|
|
570
|
+
- research-local-sources
|
|
571
|
+
- research-external-research
|
|
572
|
+
inputRefs:
|
|
573
|
+
- fromStepId: research-discover-sources
|
|
574
|
+
alias: source_inventory
|
|
575
|
+
- fromStepId: research-local-sources
|
|
576
|
+
alias: local_source_notes
|
|
577
|
+
- fromStepId: research-external-research
|
|
578
|
+
alias: external_research
|
|
579
|
+
stageKind: research_finalize
|
|
580
|
+
outputKind: brief
|
|
581
|
+
outputPath: marketing-brief.md
|
|
582
|
+
taskKind: ""
|
|
583
|
+
projectBacklogTasks: false
|
|
584
|
+
backlogTaskId: ""
|
|
585
|
+
repoRoot: ""
|
|
586
|
+
writeScope: ""
|
|
587
|
+
acceptanceCriteria: ""
|
|
588
|
+
taskDependencies: ""
|
|
589
|
+
verificationState: ""
|
|
590
|
+
taskOwner: ""
|
|
591
|
+
verificationCommand: ""
|
|
592
|
+
- nodeId: draft-copy
|
|
593
|
+
title: Draft Copy
|
|
594
|
+
agentId: copywriter
|
|
595
|
+
objective: Write \`draft-post.md\` from the newly created marketing brief and workspace context.
|
|
596
|
+
dependsOn:
|
|
597
|
+
- research-brief
|
|
598
|
+
inputRefs:
|
|
599
|
+
- fromStepId: research-brief
|
|
600
|
+
alias: marketing_brief
|
|
601
|
+
outputKind: draft
|
|
602
|
+
outputPath: draft-post.md
|
|
603
|
+
taskKind: ""
|
|
604
|
+
projectBacklogTasks: false
|
|
605
|
+
backlogTaskId: ""
|
|
606
|
+
repoRoot: ""
|
|
607
|
+
writeScope: ""
|
|
608
|
+
acceptanceCriteria: ""
|
|
609
|
+
taskDependencies: ""
|
|
610
|
+
verificationState: ""
|
|
611
|
+
taskOwner: ""
|
|
612
|
+
verificationCommand: ""
|
|
613
|
+
- nodeId: review-copy
|
|
614
|
+
title: Review Copy
|
|
615
|
+
agentId: reviewer
|
|
616
|
+
objective: Review \`draft-post.md\` against the marketing brief and source evidence, then write \`review-notes.md\` and, when approved, \`approved-post.md\`.
|
|
617
|
+
dependsOn:
|
|
618
|
+
- draft-copy
|
|
619
|
+
inputRefs:
|
|
620
|
+
- fromStepId: draft-copy
|
|
621
|
+
alias: draft
|
|
622
|
+
outputKind: review
|
|
623
|
+
outputPath: review-notes.md
|
|
624
|
+
taskKind: ""
|
|
625
|
+
projectBacklogTasks: false
|
|
626
|
+
backlogTaskId: ""
|
|
627
|
+
repoRoot: ""
|
|
628
|
+
writeScope: ""
|
|
629
|
+
acceptanceCriteria: ""
|
|
630
|
+
taskDependencies: ""
|
|
631
|
+
verificationState: ""
|
|
632
|
+
taskOwner: ""
|
|
633
|
+
verificationCommand: ""
|
|
634
|
+
- nodeId: publish-copy
|
|
635
|
+
title: Publish Copy
|
|
636
|
+
agentId: poster
|
|
637
|
+
objective: Prepare the approved post for the requested channel and always write \`publish-checklist.md\`, including a blocked handoff note if approval has not happened yet.
|
|
638
|
+
dependsOn:
|
|
639
|
+
- review-copy
|
|
640
|
+
inputRefs:
|
|
641
|
+
- fromStepId: review-copy
|
|
642
|
+
alias: approved_copy
|
|
643
|
+
outputKind: publish
|
|
644
|
+
outputPath: publish-checklist.md
|
|
645
|
+
taskKind: ""
|
|
646
|
+
projectBacklogTasks: false
|
|
647
|
+
backlogTaskId: ""
|
|
648
|
+
repoRoot: ""
|
|
649
|
+
writeScope: ""
|
|
650
|
+
acceptanceCriteria: ""
|
|
651
|
+
taskDependencies: ""
|
|
652
|
+
verificationState: ""
|
|
653
|
+
taskOwner: ""
|
|
654
|
+
verificationCommand: ""
|
|
655
|
+
`,Gd=`id: prd-to-launch-plan-team
|
|
656
|
+
order: 6
|
|
657
|
+
name: PRD to Launch Plan Team
|
|
658
|
+
icon: rocket
|
|
659
|
+
summary: Turn a product brief into an execution plan, review it, and prepare launch handoff.
|
|
660
|
+
description: A cross-functional planning workflow that reads a PRD, drafts an execution plan, reviews risks, and prepares a launch-ready brief.
|
|
661
|
+
suggestedOutputs:
|
|
662
|
+
- execution-plan.md
|
|
663
|
+
- risk-review.md
|
|
664
|
+
- launch-brief.md
|
|
665
|
+
agents:
|
|
666
|
+
- agentId: planner
|
|
667
|
+
displayName: Planner
|
|
668
|
+
role: delegator
|
|
669
|
+
avatarUrl: ""
|
|
670
|
+
templateId: ""
|
|
671
|
+
linkedTemplateId: ""
|
|
672
|
+
skills:
|
|
673
|
+
- planning
|
|
674
|
+
prompt:
|
|
675
|
+
role: You are the implementation planner.
|
|
676
|
+
mission: Convert the PRD into a realistic execution plan with milestones and owners.
|
|
677
|
+
inputs: Use the PRD, known constraints, and delivery context.
|
|
678
|
+
outputContract: Produce a step-by-step plan with dependencies and key open questions.
|
|
679
|
+
guardrails: Call out assumptions and missing information explicitly.
|
|
680
|
+
modelProvider: ""
|
|
681
|
+
modelId: ""
|
|
682
|
+
toolAllowlist:
|
|
683
|
+
- read
|
|
684
|
+
- write
|
|
685
|
+
- glob
|
|
686
|
+
toolDenylist: []
|
|
687
|
+
mcpAllowedServers: []
|
|
688
|
+
- agentId: go-to-market
|
|
689
|
+
displayName: Go To Market
|
|
690
|
+
role: worker
|
|
691
|
+
avatarUrl: ""
|
|
692
|
+
templateId: ""
|
|
693
|
+
linkedTemplateId: ""
|
|
694
|
+
skills:
|
|
695
|
+
- launch-planning
|
|
696
|
+
prompt:
|
|
697
|
+
role: You are the launch planning writer.
|
|
698
|
+
mission: Add launch, messaging, enablement, and rollout considerations to the plan.
|
|
699
|
+
inputs: Use the execution plan and product context.
|
|
700
|
+
outputContract: Produce the GTM and rollout sections required for launch readiness.
|
|
701
|
+
guardrails: Keep dependencies and owner requests concrete.
|
|
702
|
+
modelProvider: ""
|
|
703
|
+
modelId: ""
|
|
704
|
+
toolAllowlist:
|
|
705
|
+
- read
|
|
706
|
+
- write
|
|
707
|
+
- glob
|
|
708
|
+
toolDenylist: []
|
|
709
|
+
mcpAllowedServers: []
|
|
710
|
+
- agentId: risk-review
|
|
711
|
+
displayName: Risk Review
|
|
712
|
+
role: reviewer
|
|
713
|
+
avatarUrl: ""
|
|
714
|
+
templateId: ""
|
|
715
|
+
linkedTemplateId: ""
|
|
716
|
+
skills:
|
|
717
|
+
- risk-analysis
|
|
718
|
+
prompt:
|
|
719
|
+
role: You are the delivery risk reviewer.
|
|
720
|
+
mission: Review the plan for sequencing risks, unclear owners, and launch gaps.
|
|
721
|
+
inputs: Use the implementation plan and GTM additions.
|
|
722
|
+
outputContract: Approve or provide explicit risk and gap notes for revision.
|
|
723
|
+
guardrails: Prioritize real execution blockers over stylistic concerns.
|
|
724
|
+
modelProvider: ""
|
|
725
|
+
modelId: ""
|
|
726
|
+
toolAllowlist:
|
|
727
|
+
- read
|
|
728
|
+
- write
|
|
729
|
+
- glob
|
|
730
|
+
toolDenylist: []
|
|
731
|
+
mcpAllowedServers: []
|
|
732
|
+
- agentId: launch-ops
|
|
733
|
+
displayName: Launch Ops
|
|
734
|
+
role: committer
|
|
735
|
+
avatarUrl: ""
|
|
736
|
+
templateId: ""
|
|
737
|
+
linkedTemplateId: ""
|
|
738
|
+
skills:
|
|
739
|
+
- operations
|
|
740
|
+
- handoff
|
|
741
|
+
prompt:
|
|
742
|
+
role: You are the launch handoff operator.
|
|
743
|
+
mission: Prepare the reviewed plan for team handoff and launch tracking.
|
|
744
|
+
inputs: Use the approved plan and rollout notes.
|
|
745
|
+
outputContract: Produce a launch brief with owners, timeline, and readiness checklist.
|
|
746
|
+
guardrails: Do not hide unresolved risks; surface them clearly in the brief.
|
|
747
|
+
modelProvider: ""
|
|
748
|
+
modelId: ""
|
|
749
|
+
toolAllowlist:
|
|
750
|
+
- read
|
|
751
|
+
- write
|
|
752
|
+
- glob
|
|
753
|
+
toolDenylist: []
|
|
754
|
+
mcpAllowedServers: []
|
|
755
|
+
nodes:
|
|
756
|
+
- nodeId: draft-plan
|
|
757
|
+
title: Draft Plan
|
|
758
|
+
agentId: planner
|
|
759
|
+
objective: Draft the implementation plan from the PRD.
|
|
760
|
+
dependsOn: []
|
|
761
|
+
inputRefs: []
|
|
762
|
+
outputKind: plan
|
|
763
|
+
outputPath: ""
|
|
764
|
+
taskKind: ""
|
|
765
|
+
projectBacklogTasks: false
|
|
766
|
+
backlogTaskId: ""
|
|
767
|
+
repoRoot: ""
|
|
768
|
+
writeScope: ""
|
|
769
|
+
acceptanceCriteria: ""
|
|
770
|
+
taskDependencies: ""
|
|
771
|
+
verificationState: ""
|
|
772
|
+
taskOwner: ""
|
|
773
|
+
verificationCommand: ""
|
|
774
|
+
- nodeId: add-rollout
|
|
775
|
+
title: Add Rollout
|
|
776
|
+
agentId: go-to-market
|
|
777
|
+
objective: Add GTM and rollout planning details to the execution plan.
|
|
778
|
+
dependsOn:
|
|
779
|
+
- draft-plan
|
|
780
|
+
inputRefs:
|
|
781
|
+
- fromStepId: draft-plan
|
|
782
|
+
alias: implementation_plan
|
|
783
|
+
outputKind: rollout
|
|
784
|
+
outputPath: ""
|
|
785
|
+
taskKind: ""
|
|
786
|
+
projectBacklogTasks: false
|
|
787
|
+
backlogTaskId: ""
|
|
788
|
+
repoRoot: ""
|
|
789
|
+
writeScope: ""
|
|
790
|
+
acceptanceCriteria: ""
|
|
791
|
+
taskDependencies: ""
|
|
792
|
+
verificationState: ""
|
|
793
|
+
taskOwner: ""
|
|
794
|
+
verificationCommand: ""
|
|
795
|
+
- nodeId: review-risks
|
|
796
|
+
title: Review Risks
|
|
797
|
+
agentId: risk-review
|
|
798
|
+
objective: Review the plan for risk, sequencing, and readiness gaps.
|
|
799
|
+
dependsOn:
|
|
800
|
+
- add-rollout
|
|
801
|
+
inputRefs:
|
|
802
|
+
- fromStepId: add-rollout
|
|
803
|
+
alias: launch_plan
|
|
804
|
+
outputKind: review
|
|
805
|
+
outputPath: ""
|
|
806
|
+
taskKind: ""
|
|
807
|
+
projectBacklogTasks: false
|
|
808
|
+
backlogTaskId: ""
|
|
809
|
+
repoRoot: ""
|
|
810
|
+
writeScope: ""
|
|
811
|
+
acceptanceCriteria: ""
|
|
812
|
+
taskDependencies: ""
|
|
813
|
+
verificationState: ""
|
|
814
|
+
taskOwner: ""
|
|
815
|
+
verificationCommand: ""
|
|
816
|
+
- nodeId: prepare-launch-brief
|
|
817
|
+
title: Prepare Launch Brief
|
|
818
|
+
agentId: launch-ops
|
|
819
|
+
objective: Prepare the reviewed launch plan for cross-functional handoff.
|
|
820
|
+
dependsOn:
|
|
821
|
+
- review-risks
|
|
822
|
+
inputRefs:
|
|
823
|
+
- fromStepId: review-risks
|
|
824
|
+
alias: approved_plan
|
|
825
|
+
outputKind: launch_brief
|
|
826
|
+
outputPath: ""
|
|
827
|
+
taskKind: ""
|
|
828
|
+
projectBacklogTasks: false
|
|
829
|
+
backlogTaskId: ""
|
|
830
|
+
repoRoot: ""
|
|
831
|
+
writeScope: ""
|
|
832
|
+
acceptanceCriteria: ""
|
|
833
|
+
taskDependencies: ""
|
|
834
|
+
verificationState: ""
|
|
835
|
+
taskOwner: ""
|
|
836
|
+
verificationCommand: ""
|
|
837
|
+
`,Vd=`id: repo-coding-backlog
|
|
838
|
+
order: 1
|
|
839
|
+
name: Repo Coding Backlog
|
|
840
|
+
icon: code-2
|
|
841
|
+
summary: Analyze a repository task backlog, implement scoped changes, verify them, and prepare a merge-ready handoff.
|
|
842
|
+
description: "A coding workflow for long-running repository work: understand the task and repo area, make scoped code changes, run verification, review the outcome, and prepare a handoff with changed files and next steps."
|
|
843
|
+
suggestedOutputs:
|
|
844
|
+
- coding-backlog-plan.md
|
|
845
|
+
- implementation-notes.md
|
|
846
|
+
- verification-report.md
|
|
847
|
+
- merge-handoff.md
|
|
848
|
+
agents:
|
|
849
|
+
- agentId: repo-planner
|
|
850
|
+
displayName: Repo Planner
|
|
851
|
+
role: delegator
|
|
852
|
+
avatarUrl: ""
|
|
853
|
+
templateId: ""
|
|
854
|
+
linkedTemplateId: ""
|
|
855
|
+
skills:
|
|
856
|
+
- planning
|
|
857
|
+
- codebase-analysis
|
|
858
|
+
prompt:
|
|
859
|
+
role: You are a repository task planner turning backlog items into a concrete implementation approach.
|
|
860
|
+
mission: Inspect the repository, understand the requested task, identify the likely write scope, and prepare an implementation brief that downstream coding stages can execute safely.
|
|
861
|
+
inputs: Treat the workspace as a real repository, not a single-file task. Enumerate the repo, read the task-relevant source files, docs, manifests, tests, and configuration, and identify the modules most likely to change. If issue text, backlog text, or acceptance criteria are present in the workspace, use them as source-of-truth inputs.
|
|
862
|
+
outputContract: Create \`coding-backlog-plan.md\` with the task summary, acceptance criteria, likely write scope, affected files/modules, key architectural constraints, verification commands to run later, and a concise implementation approach. Also include a fenced \`json\` block for projected backlog tasks so downstream systems can ingest multiple coding tasks from this plan.
|
|
863
|
+
guardrails: Do not invent repository structure or acceptance criteria. List uncertainties explicitly, distinguish observed facts from inferred approach, and do not treat prior generated workflow artifacts as authoritative task inputs.
|
|
864
|
+
modelProvider: ""
|
|
865
|
+
modelId: ""
|
|
866
|
+
toolAllowlist:
|
|
867
|
+
- glob
|
|
868
|
+
- read
|
|
869
|
+
- write
|
|
870
|
+
- bash
|
|
871
|
+
toolDenylist: []
|
|
872
|
+
mcpAllowedServers: []
|
|
873
|
+
- agentId: implementer
|
|
874
|
+
displayName: Implementer
|
|
875
|
+
role: worker
|
|
876
|
+
avatarUrl: ""
|
|
877
|
+
templateId: ""
|
|
878
|
+
linkedTemplateId: ""
|
|
879
|
+
skills:
|
|
880
|
+
- coding
|
|
881
|
+
- debugging
|
|
882
|
+
prompt:
|
|
883
|
+
role: You are a coding agent implementing repository changes inside a declared scope with minimal churn.
|
|
884
|
+
mission: Make the requested code or config changes, keep edits scoped, and leave clear implementation notes for verification and review.
|
|
885
|
+
inputs: Use the upstream \`repo_plan\` handoff as the implementation guide, then inspect the referenced source files directly before editing. Prefer repo-local evidence over assumptions. When available, keep changes inside the declared write scope and note any necessary scope expansion explicitly.
|
|
886
|
+
outputContract: Create \`implementation-notes.md\` summarizing what changed, files touched, unresolved risks, and which verification commands should be run next. Also make the actual repository edits required by the task.
|
|
887
|
+
guardrails: Prefer \`apply_patch\` or \`edit\` for existing source files, and use \`write\` only for new files or when patch/edit cannot express the change. Do not replace source files with placeholders, status notes, or preservation notes. Keep modifications inside the planned scope unless new evidence forces a change, and then explain why.
|
|
888
|
+
modelProvider: ""
|
|
889
|
+
modelId: ""
|
|
890
|
+
toolAllowlist:
|
|
891
|
+
- glob
|
|
892
|
+
- read
|
|
893
|
+
- edit
|
|
894
|
+
- apply_patch
|
|
895
|
+
- write
|
|
896
|
+
- bash
|
|
897
|
+
toolDenylist: []
|
|
898
|
+
mcpAllowedServers: []
|
|
899
|
+
- agentId: verifier
|
|
900
|
+
displayName: Verifier
|
|
901
|
+
role: tester
|
|
902
|
+
avatarUrl: ""
|
|
903
|
+
templateId: ""
|
|
904
|
+
linkedTemplateId: ""
|
|
905
|
+
skills:
|
|
906
|
+
- testing
|
|
907
|
+
- qa
|
|
908
|
+
prompt:
|
|
909
|
+
role: You are a verification engineer responsible for proving whether the repository changes satisfy the task.
|
|
910
|
+
mission: Run the most relevant build, test, lint, or task-specific verification commands, then summarize whether the implementation is ready to review or needs more work.
|
|
911
|
+
inputs: Use the upstream \`implementation\` handoff, the repository files, and the verification commands identified earlier. Read changed files and related tests before running commands so the report explains what was actually checked.
|
|
912
|
+
outputContract: "Create \`verification-report.md\` with commands run, pass/fail results, failing output excerpts when relevant, changed files reviewed, and a clear verdict: verified, verify_failed, or blocked."
|
|
913
|
+
guardrails: Do not claim verification without actually running the commands you report. If a command cannot run, record the exact blocker. Keep the report factual and concise.
|
|
914
|
+
modelProvider: ""
|
|
915
|
+
modelId: ""
|
|
916
|
+
toolAllowlist:
|
|
917
|
+
- glob
|
|
918
|
+
- read
|
|
919
|
+
- write
|
|
920
|
+
- bash
|
|
921
|
+
toolDenylist: []
|
|
922
|
+
mcpAllowedServers: []
|
|
923
|
+
- agentId: handoff
|
|
924
|
+
displayName: Handoff
|
|
925
|
+
role: reviewer
|
|
926
|
+
avatarUrl: ""
|
|
927
|
+
templateId: ""
|
|
928
|
+
linkedTemplateId: ""
|
|
929
|
+
skills:
|
|
930
|
+
- code-review
|
|
931
|
+
- handoff
|
|
932
|
+
prompt:
|
|
933
|
+
role: You are the final coding workflow reviewer and handoff operator.
|
|
934
|
+
mission: Review the implementation notes and verification report, then prepare a merge-ready handoff that clearly states readiness, changed scope, and any remaining follow-up work.
|
|
935
|
+
inputs: Use the upstream \`implementation\` and \`verification\` handoffs as primary inputs. Read the changed files from disk only as needed to confirm claims or summarize the scope of change.
|
|
936
|
+
outputContract: Create \`merge-handoff.md\` with the task summary, changed files, verification outcome, review findings, follow-up items, and a clear release/merge recommendation.
|
|
937
|
+
guardrails: Do not mark work ready if verification failed or critical blockers remain. Keep review comments specific, and do not overwrite prior artifacts with status placeholders.
|
|
938
|
+
modelProvider: ""
|
|
939
|
+
modelId: ""
|
|
940
|
+
toolAllowlist:
|
|
941
|
+
- glob
|
|
942
|
+
- read
|
|
943
|
+
- write
|
|
944
|
+
toolDenylist: []
|
|
945
|
+
mcpAllowedServers: []
|
|
946
|
+
nodes:
|
|
947
|
+
- nodeId: plan-backlog-task
|
|
948
|
+
title: Plan Backlog Task
|
|
949
|
+
agentId: repo-planner
|
|
950
|
+
objective: Inspect the repository and backlog context, then write \`coding-backlog-plan.md\` with task scope, affected areas, and verification approach.
|
|
951
|
+
dependsOn: []
|
|
952
|
+
inputRefs: []
|
|
953
|
+
outputKind: plan
|
|
954
|
+
outputPath: coding-backlog-plan.md
|
|
955
|
+
taskKind: repo_plan
|
|
956
|
+
projectBacklogTasks: true
|
|
957
|
+
backlogTaskId: backlog-task
|
|
958
|
+
repoRoot: .
|
|
959
|
+
writeScope: repository analysis, docs, manifests, and task-relevant source files
|
|
960
|
+
acceptanceCriteria: Identify the task scope, affected repo areas, constraints, and a concrete verification plan.
|
|
961
|
+
taskDependencies: ""
|
|
962
|
+
verificationState: planned
|
|
963
|
+
taskOwner: repo-planner
|
|
964
|
+
verificationCommand: ""
|
|
965
|
+
- nodeId: implement-change
|
|
966
|
+
title: Implement Change
|
|
967
|
+
agentId: implementer
|
|
968
|
+
objective: Implement the repository changes described in the plan, update the relevant source files, and write \`implementation-notes.md\`.
|
|
969
|
+
dependsOn:
|
|
970
|
+
- plan-backlog-task
|
|
971
|
+
inputRefs:
|
|
972
|
+
- fromStepId: plan-backlog-task
|
|
973
|
+
alias: repo_plan
|
|
974
|
+
outputKind: code_change
|
|
975
|
+
outputPath: implementation-notes.md
|
|
976
|
+
taskKind: code_change
|
|
977
|
+
backlogTaskId: backlog-task
|
|
978
|
+
repoRoot: .
|
|
979
|
+
writeScope: task-scoped source files, tests, configs, and new files required by the change
|
|
980
|
+
acceptanceCriteria: Implement the planned repo change inside scope and leave clear notes for verification.
|
|
981
|
+
taskDependencies: plan-backlog-task
|
|
982
|
+
verificationState: pending
|
|
983
|
+
taskOwner: implementer
|
|
984
|
+
verificationCommand: Run the repo-appropriate build/test/lint commands for the touched area.
|
|
985
|
+
projectBacklogTasks: false
|
|
986
|
+
- nodeId: verify-change
|
|
987
|
+
title: Verify Change
|
|
988
|
+
agentId: verifier
|
|
989
|
+
objective: Verify the implementation with the relevant build, test, or lint commands and write \`verification-report.md\`.
|
|
990
|
+
dependsOn:
|
|
991
|
+
- implement-change
|
|
992
|
+
inputRefs:
|
|
993
|
+
- fromStepId: implement-change
|
|
994
|
+
alias: implementation
|
|
995
|
+
outputKind: verification
|
|
996
|
+
outputPath: verification-report.md
|
|
997
|
+
taskKind: verification
|
|
998
|
+
backlogTaskId: backlog-task
|
|
999
|
+
repoRoot: .
|
|
1000
|
+
writeScope: changed files plus directly relevant tests and config
|
|
1001
|
+
acceptanceCriteria: Run the relevant repo-local verification commands and return a factual pass/fail verdict.
|
|
1002
|
+
taskDependencies: implement-change
|
|
1003
|
+
verificationState: required
|
|
1004
|
+
taskOwner: verifier
|
|
1005
|
+
verificationCommand: Use the best repo-local verification commands for the touched files and report exact results.
|
|
1006
|
+
projectBacklogTasks: false
|
|
1007
|
+
- nodeId: prepare-merge-handoff
|
|
1008
|
+
title: Prepare Merge Handoff
|
|
1009
|
+
agentId: handoff
|
|
1010
|
+
objective: Review the implementation and verification outputs, then write \`merge-handoff.md\` with merge readiness and follow-up notes.
|
|
1011
|
+
dependsOn:
|
|
1012
|
+
- verify-change
|
|
1013
|
+
inputRefs:
|
|
1014
|
+
- fromStepId: implement-change
|
|
1015
|
+
alias: implementation
|
|
1016
|
+
- fromStepId: verify-change
|
|
1017
|
+
alias: verification
|
|
1018
|
+
outputKind: review
|
|
1019
|
+
outputPath: merge-handoff.md
|
|
1020
|
+
taskKind: review
|
|
1021
|
+
backlogTaskId: backlog-task
|
|
1022
|
+
repoRoot: .
|
|
1023
|
+
writeScope: implementation notes, verification report, and changed files for spot checks
|
|
1024
|
+
acceptanceCriteria: Summarize change scope, verification outcome, and merge readiness for the backlog task.
|
|
1025
|
+
taskDependencies: implement-change, verify-change
|
|
1026
|
+
verificationState: reported
|
|
1027
|
+
taskOwner: handoff
|
|
1028
|
+
verificationCommand: ""
|
|
1029
|
+
projectBacklogTasks: false
|
|
1030
|
+
`,Yd=`id: sales-prospecting-team
|
|
1031
|
+
order: 5
|
|
1032
|
+
name: Sales Prospecting Team
|
|
1033
|
+
icon: target
|
|
1034
|
+
summary: Research accounts, write outreach, review positioning, and prepare sending.
|
|
1035
|
+
description: A prospecting workflow that researches a target account, drafts outreach, reviews fit and claims, and prepares the outbound package.
|
|
1036
|
+
suggestedOutputs:
|
|
1037
|
+
- account-brief.md
|
|
1038
|
+
- outreach-draft.md
|
|
1039
|
+
- send-pack.md
|
|
1040
|
+
agents:
|
|
1041
|
+
- agentId: account-discover
|
|
1042
|
+
displayName: Account Discover
|
|
1043
|
+
role: watcher
|
|
1044
|
+
avatarUrl: ""
|
|
1045
|
+
templateId: ""
|
|
1046
|
+
linkedTemplateId: ""
|
|
1047
|
+
skills:
|
|
1048
|
+
- account-research
|
|
1049
|
+
prompt:
|
|
1050
|
+
role: You are a prospecting source scout.
|
|
1051
|
+
mission: Identify the local account context, CRM notes, and source corpus that should be reviewed before outreach research begins.
|
|
1052
|
+
inputs: Inspect the workspace for account lists, CRM notes, ICP context, and prior research files, then prioritize the concrete sources to read next.
|
|
1053
|
+
outputContract: Return a structured handoff with \`workspace_inventory_summary\`, \`discovered_paths\`, \`priority_paths\`, and \`skipped_paths_initial\`.
|
|
1054
|
+
guardrails: Do not write the final account brief in this stage.
|
|
1055
|
+
modelProvider: ""
|
|
1056
|
+
modelId: ""
|
|
1057
|
+
toolAllowlist:
|
|
1058
|
+
- read
|
|
1059
|
+
- glob
|
|
1060
|
+
toolDenylist: []
|
|
1061
|
+
mcpAllowedServers: []
|
|
1062
|
+
- agentId: account-local-sources
|
|
1063
|
+
displayName: Account Local Sources
|
|
1064
|
+
role: watcher
|
|
1065
|
+
avatarUrl: ""
|
|
1066
|
+
templateId: ""
|
|
1067
|
+
linkedTemplateId: ""
|
|
1068
|
+
skills:
|
|
1069
|
+
- account-research
|
|
1070
|
+
prompt:
|
|
1071
|
+
role: You are a local account-context analyst.
|
|
1072
|
+
mission: Read the prioritized local account and ICP files and extract the most reliable personalization inputs.
|
|
1073
|
+
inputs: Use the upstream \`source_inventory\` handoff to choose concrete files to read and capture the facts that will anchor the account brief.
|
|
1074
|
+
outputContract: Return a structured handoff with \`read_paths\`, \`reviewed_facts\`, \`files_reviewed\`, \`files_not_reviewed\`, and \`citations_local\`.
|
|
1075
|
+
guardrails: Only cite files that were actually read in this run.
|
|
1076
|
+
modelProvider: ""
|
|
1077
|
+
modelId: ""
|
|
1078
|
+
toolAllowlist:
|
|
1079
|
+
- read
|
|
1080
|
+
- glob
|
|
1081
|
+
toolDenylist: []
|
|
1082
|
+
mcpAllowedServers: []
|
|
1083
|
+
- agentId: account-external
|
|
1084
|
+
displayName: Account External
|
|
1085
|
+
role: watcher
|
|
1086
|
+
avatarUrl: ""
|
|
1087
|
+
templateId: ""
|
|
1088
|
+
linkedTemplateId: ""
|
|
1089
|
+
skills:
|
|
1090
|
+
- account-research
|
|
1091
|
+
prompt:
|
|
1092
|
+
role: You are an external account researcher focused on current buying context and public signals.
|
|
1093
|
+
mission: Gather current public context that can strengthen or disprove likely personalization hooks before outreach is drafted.
|
|
1094
|
+
inputs: Use the upstream \`source_inventory\` and \`local_source_notes\` handoffs to guide targeted external account research.
|
|
1095
|
+
outputContract: Return a structured handoff with \`external_research_mode\`, \`queries_attempted\`, \`sources_reviewed\`, \`citations_external\`, and \`research_limitations\`.
|
|
1096
|
+
guardrails: Do not invent buying signals. If search is unavailable, capture that limitation explicitly.
|
|
1097
|
+
modelProvider: ""
|
|
1098
|
+
modelId: ""
|
|
1099
|
+
toolAllowlist:
|
|
1100
|
+
- read
|
|
1101
|
+
- websearch
|
|
1102
|
+
- webfetch
|
|
1103
|
+
- glob
|
|
1104
|
+
toolDenylist: []
|
|
1105
|
+
mcpAllowedServers: []
|
|
1106
|
+
- agentId: account-research
|
|
1107
|
+
displayName: Account Research
|
|
1108
|
+
role: watcher
|
|
1109
|
+
avatarUrl: ""
|
|
1110
|
+
templateId: ""
|
|
1111
|
+
linkedTemplateId: ""
|
|
1112
|
+
skills:
|
|
1113
|
+
- account-research
|
|
1114
|
+
prompt:
|
|
1115
|
+
role: You are an account researcher focused on finding real buying context and usable personalization hooks.
|
|
1116
|
+
mission: Turn the upstream source discovery, local account evidence, and external account research into the final account brief.
|
|
1117
|
+
inputs: Use the upstream \`source_inventory\`, \`local_source_notes\`, and \`external_research\` handoffs as the source of truth.
|
|
1118
|
+
outputContract: Produce a concise account brief with company context, likely priorities, buying signals, possible pain points, messaging angles, and high-confidence personalization hooks labeled by confidence.
|
|
1119
|
+
guardrails: Do not invent buying signals or pretend certainty. Separate observed facts from hypotheses and avoid re-running discovery or fresh web research in this stage.
|
|
1120
|
+
modelProvider: ""
|
|
1121
|
+
modelId: ""
|
|
1122
|
+
toolAllowlist:
|
|
1123
|
+
- read
|
|
1124
|
+
- glob
|
|
1125
|
+
toolDenylist: []
|
|
1126
|
+
mcpAllowedServers: []
|
|
1127
|
+
- agentId: outreach-writer
|
|
1128
|
+
displayName: Outreach Writer
|
|
1129
|
+
role: worker
|
|
1130
|
+
avatarUrl: ""
|
|
1131
|
+
templateId: ""
|
|
1132
|
+
linkedTemplateId: ""
|
|
1133
|
+
skills:
|
|
1134
|
+
- sales-copy
|
|
1135
|
+
prompt:
|
|
1136
|
+
role: You are an outbound copywriter who writes concise outreach anchored in relevance, not generic personalization theater.
|
|
1137
|
+
mission: Write outreach that connects the account context to a clear value hypothesis and a low-friction next step.
|
|
1138
|
+
inputs: Use the account brief, ICP, offer positioning, proof points, and any approved email or messaging guidelines.
|
|
1139
|
+
outputContract: Produce first-touch outreach with subject line, opening line, body, CTA, and one optional variant that tests a different angle or proof point.
|
|
1140
|
+
guardrails: Keep it personal, specific, and easy to reply to. Avoid generic hype, fake familiarity, and unsupported claims.
|
|
1141
|
+
modelProvider: ""
|
|
1142
|
+
modelId: ""
|
|
1143
|
+
toolAllowlist:
|
|
1144
|
+
- read
|
|
1145
|
+
- write
|
|
1146
|
+
- glob
|
|
1147
|
+
toolDenylist: []
|
|
1148
|
+
mcpAllowedServers: []
|
|
1149
|
+
- agentId: positioning-review
|
|
1150
|
+
displayName: Positioning Review
|
|
1151
|
+
role: reviewer
|
|
1152
|
+
avatarUrl: ""
|
|
1153
|
+
templateId: ""
|
|
1154
|
+
linkedTemplateId: ""
|
|
1155
|
+
skills:
|
|
1156
|
+
- message-review
|
|
1157
|
+
prompt:
|
|
1158
|
+
role: You are the outreach reviewer applying a quality and credibility check before anything is sent.
|
|
1159
|
+
mission: Review personalization, claims, tone, and CTA quality so outbound messages feel credible and worth replying to.
|
|
1160
|
+
inputs: Use the account brief, outreach draft, proof points, and any team messaging rules.
|
|
1161
|
+
outputContract: Approve or return revision notes focused on personalization quality, claim support, clarity, and CTA friction.
|
|
1162
|
+
guardrails: Reject fluff, weak personalization, false urgency, and unsupported claims. Prefer direct revision guidance over general criticism.
|
|
1163
|
+
modelProvider: ""
|
|
1164
|
+
modelId: ""
|
|
1165
|
+
toolAllowlist:
|
|
1166
|
+
- read
|
|
1167
|
+
- write
|
|
1168
|
+
- glob
|
|
1169
|
+
toolDenylist: []
|
|
1170
|
+
mcpAllowedServers: []
|
|
1171
|
+
- agentId: send-prep
|
|
1172
|
+
displayName: Send Prep
|
|
1173
|
+
role: committer
|
|
1174
|
+
avatarUrl: ""
|
|
1175
|
+
templateId: ""
|
|
1176
|
+
linkedTemplateId: ""
|
|
1177
|
+
skills:
|
|
1178
|
+
- ops
|
|
1179
|
+
prompt:
|
|
1180
|
+
role: You are the send-prep operator.
|
|
1181
|
+
mission: Prepare approved outreach for the outbound system or rep handoff.
|
|
1182
|
+
inputs: Use the approved message, account info, and sequencing metadata.
|
|
1183
|
+
outputContract: Produce a send-ready package with follow-up notes.
|
|
1184
|
+
guardrails: Do not alter approved claims without review.
|
|
1185
|
+
modelProvider: ""
|
|
1186
|
+
modelId: ""
|
|
1187
|
+
toolAllowlist:
|
|
1188
|
+
- read
|
|
1189
|
+
- write
|
|
1190
|
+
- glob
|
|
1191
|
+
toolDenylist: []
|
|
1192
|
+
mcpAllowedServers: []
|
|
1193
|
+
nodes:
|
|
1194
|
+
- nodeId: research-account-discover
|
|
1195
|
+
title: Discover Account Sources
|
|
1196
|
+
agentId: account-discover
|
|
1197
|
+
objective: Identify the source corpus that should guide account research.
|
|
1198
|
+
dependsOn: []
|
|
1199
|
+
inputRefs: []
|
|
1200
|
+
stageKind: research_discover
|
|
1201
|
+
outputKind: structured_json
|
|
1202
|
+
outputPath: ""
|
|
1203
|
+
taskKind: ""
|
|
1204
|
+
projectBacklogTasks: false
|
|
1205
|
+
backlogTaskId: ""
|
|
1206
|
+
repoRoot: ""
|
|
1207
|
+
writeScope: ""
|
|
1208
|
+
acceptanceCriteria: ""
|
|
1209
|
+
taskDependencies: ""
|
|
1210
|
+
verificationState: ""
|
|
1211
|
+
taskOwner: ""
|
|
1212
|
+
verificationCommand: ""
|
|
1213
|
+
- nodeId: research-account-local-sources
|
|
1214
|
+
title: Read Account Sources
|
|
1215
|
+
agentId: account-local-sources
|
|
1216
|
+
objective: Read the prioritized local account and ICP files before drafting the account brief.
|
|
1217
|
+
dependsOn:
|
|
1218
|
+
- research-account-discover
|
|
1219
|
+
inputRefs:
|
|
1220
|
+
- fromStepId: research-account-discover
|
|
1221
|
+
alias: source_inventory
|
|
1222
|
+
stageKind: research_local_sources
|
|
1223
|
+
outputKind: structured_json
|
|
1224
|
+
outputPath: ""
|
|
1225
|
+
taskKind: ""
|
|
1226
|
+
projectBacklogTasks: false
|
|
1227
|
+
backlogTaskId: ""
|
|
1228
|
+
repoRoot: ""
|
|
1229
|
+
writeScope: ""
|
|
1230
|
+
acceptanceCriteria: ""
|
|
1231
|
+
taskDependencies: ""
|
|
1232
|
+
verificationState: ""
|
|
1233
|
+
taskOwner: ""
|
|
1234
|
+
verificationCommand: ""
|
|
1235
|
+
- nodeId: research-account-external-research
|
|
1236
|
+
title: Research Account Externally
|
|
1237
|
+
agentId: account-external
|
|
1238
|
+
objective: Gather targeted external account context and buying signals to support the brief.
|
|
1239
|
+
dependsOn:
|
|
1240
|
+
- research-account-discover
|
|
1241
|
+
- research-account-local-sources
|
|
1242
|
+
inputRefs:
|
|
1243
|
+
- fromStepId: research-account-discover
|
|
1244
|
+
alias: source_inventory
|
|
1245
|
+
- fromStepId: research-account-local-sources
|
|
1246
|
+
alias: local_source_notes
|
|
1247
|
+
stageKind: research_external_sources
|
|
1248
|
+
outputKind: structured_json
|
|
1249
|
+
outputPath: ""
|
|
1250
|
+
taskKind: ""
|
|
1251
|
+
projectBacklogTasks: false
|
|
1252
|
+
backlogTaskId: ""
|
|
1253
|
+
repoRoot: ""
|
|
1254
|
+
writeScope: ""
|
|
1255
|
+
acceptanceCriteria: ""
|
|
1256
|
+
taskDependencies: ""
|
|
1257
|
+
verificationState: ""
|
|
1258
|
+
taskOwner: ""
|
|
1259
|
+
verificationCommand: ""
|
|
1260
|
+
- nodeId: research-account
|
|
1261
|
+
title: Research Account
|
|
1262
|
+
agentId: account-research
|
|
1263
|
+
objective: Prepare the final account brief from the staged discovery, local evidence, and external research.
|
|
1264
|
+
dependsOn:
|
|
1265
|
+
- research-account-discover
|
|
1266
|
+
- research-account-local-sources
|
|
1267
|
+
- research-account-external-research
|
|
1268
|
+
inputRefs:
|
|
1269
|
+
- fromStepId: research-account-discover
|
|
1270
|
+
alias: source_inventory
|
|
1271
|
+
- fromStepId: research-account-local-sources
|
|
1272
|
+
alias: local_source_notes
|
|
1273
|
+
- fromStepId: research-account-external-research
|
|
1274
|
+
alias: external_research
|
|
1275
|
+
stageKind: research_finalize
|
|
1276
|
+
outputKind: brief
|
|
1277
|
+
outputPath: ""
|
|
1278
|
+
taskKind: ""
|
|
1279
|
+
projectBacklogTasks: false
|
|
1280
|
+
backlogTaskId: ""
|
|
1281
|
+
repoRoot: ""
|
|
1282
|
+
writeScope: ""
|
|
1283
|
+
acceptanceCriteria: ""
|
|
1284
|
+
taskDependencies: ""
|
|
1285
|
+
verificationState: ""
|
|
1286
|
+
taskOwner: ""
|
|
1287
|
+
verificationCommand: ""
|
|
1288
|
+
- nodeId: draft-outreach
|
|
1289
|
+
title: Draft Outreach
|
|
1290
|
+
agentId: outreach-writer
|
|
1291
|
+
objective: Draft outbound outreach from the account brief.
|
|
1292
|
+
dependsOn:
|
|
1293
|
+
- research-account
|
|
1294
|
+
inputRefs:
|
|
1295
|
+
- fromStepId: research-account
|
|
1296
|
+
alias: account_brief
|
|
1297
|
+
outputKind: draft
|
|
1298
|
+
outputPath: ""
|
|
1299
|
+
taskKind: ""
|
|
1300
|
+
projectBacklogTasks: false
|
|
1301
|
+
backlogTaskId: ""
|
|
1302
|
+
repoRoot: ""
|
|
1303
|
+
writeScope: ""
|
|
1304
|
+
acceptanceCriteria: ""
|
|
1305
|
+
taskDependencies: ""
|
|
1306
|
+
verificationState: ""
|
|
1307
|
+
taskOwner: ""
|
|
1308
|
+
verificationCommand: ""
|
|
1309
|
+
- nodeId: review-outreach
|
|
1310
|
+
title: Review Outreach
|
|
1311
|
+
agentId: positioning-review
|
|
1312
|
+
objective: Review the outreach for fit, personalization, and quality.
|
|
1313
|
+
dependsOn:
|
|
1314
|
+
- draft-outreach
|
|
1315
|
+
inputRefs:
|
|
1316
|
+
- fromStepId: draft-outreach
|
|
1317
|
+
alias: outreach_draft
|
|
1318
|
+
outputKind: review
|
|
1319
|
+
outputPath: ""
|
|
1320
|
+
taskKind: ""
|
|
1321
|
+
projectBacklogTasks: false
|
|
1322
|
+
backlogTaskId: ""
|
|
1323
|
+
repoRoot: ""
|
|
1324
|
+
writeScope: ""
|
|
1325
|
+
acceptanceCriteria: ""
|
|
1326
|
+
taskDependencies: ""
|
|
1327
|
+
verificationState: ""
|
|
1328
|
+
taskOwner: ""
|
|
1329
|
+
verificationCommand: ""
|
|
1330
|
+
- nodeId: prepare-send
|
|
1331
|
+
title: Prepare Send
|
|
1332
|
+
agentId: send-prep
|
|
1333
|
+
objective: Prepare the approved outreach for the sending workflow.
|
|
1334
|
+
dependsOn:
|
|
1335
|
+
- review-outreach
|
|
1336
|
+
inputRefs:
|
|
1337
|
+
- fromStepId: review-outreach
|
|
1338
|
+
alias: approved_outreach
|
|
1339
|
+
outputKind: send_pack
|
|
1340
|
+
outputPath: ""
|
|
1341
|
+
taskKind: ""
|
|
1342
|
+
projectBacklogTasks: false
|
|
1343
|
+
backlogTaskId: ""
|
|
1344
|
+
repoRoot: ""
|
|
1345
|
+
writeScope: ""
|
|
1346
|
+
acceptanceCriteria: ""
|
|
1347
|
+
taskDependencies: ""
|
|
1348
|
+
verificationState: ""
|
|
1349
|
+
taskOwner: ""
|
|
1350
|
+
verificationCommand: ""
|
|
1351
|
+
`,Xd=`id: support-triage-team
|
|
1352
|
+
order: 4
|
|
1353
|
+
name: Support Triage Team
|
|
1354
|
+
icon: life-buoy
|
|
1355
|
+
summary: Classify support work, draft responses, review quality, and route action items.
|
|
1356
|
+
description: A support workflow for intake, response drafting, quality review, and escalation or publishing.
|
|
1357
|
+
suggestedOutputs:
|
|
1358
|
+
- triage-report.md
|
|
1359
|
+
- response-draft.md
|
|
1360
|
+
- escalation-summary.md
|
|
1361
|
+
agents:
|
|
1362
|
+
- agentId: intake
|
|
1363
|
+
displayName: Intake
|
|
1364
|
+
role: watcher
|
|
1365
|
+
avatarUrl: ""
|
|
1366
|
+
templateId: ""
|
|
1367
|
+
linkedTemplateId: ""
|
|
1368
|
+
skills:
|
|
1369
|
+
- triage
|
|
1370
|
+
prompt:
|
|
1371
|
+
role: You are the support intake analyst.
|
|
1372
|
+
mission: Classify incoming issues by severity, category, and owner.
|
|
1373
|
+
inputs: Use the support thread, customer metadata, and routing rules.
|
|
1374
|
+
outputContract: Produce a triage summary with next-step recommendations.
|
|
1375
|
+
guardrails: Escalate safety, billing, and security risks immediately.
|
|
1376
|
+
modelProvider: ""
|
|
1377
|
+
modelId: ""
|
|
1378
|
+
toolAllowlist:
|
|
1379
|
+
- read
|
|
1380
|
+
- glob
|
|
1381
|
+
toolDenylist: []
|
|
1382
|
+
mcpAllowedServers: []
|
|
1383
|
+
- agentId: responder
|
|
1384
|
+
displayName: Responder
|
|
1385
|
+
role: worker
|
|
1386
|
+
avatarUrl: ""
|
|
1387
|
+
templateId: ""
|
|
1388
|
+
linkedTemplateId: ""
|
|
1389
|
+
skills:
|
|
1390
|
+
- customer-support
|
|
1391
|
+
prompt:
|
|
1392
|
+
role: You are the support response drafter.
|
|
1393
|
+
mission: Draft a helpful, accurate customer-facing response.
|
|
1394
|
+
inputs: Use the triage result, product knowledge, and approved response patterns.
|
|
1395
|
+
outputContract: Produce a response draft and any internal notes required.
|
|
1396
|
+
guardrails: Do not promise unavailable fixes or timelines.
|
|
1397
|
+
modelProvider: ""
|
|
1398
|
+
modelId: ""
|
|
1399
|
+
toolAllowlist:
|
|
1400
|
+
- read
|
|
1401
|
+
- write
|
|
1402
|
+
- glob
|
|
1403
|
+
toolDenylist: []
|
|
1404
|
+
mcpAllowedServers: []
|
|
1405
|
+
- agentId: qa
|
|
1406
|
+
displayName: QA
|
|
1407
|
+
role: reviewer
|
|
1408
|
+
avatarUrl: ""
|
|
1409
|
+
templateId: ""
|
|
1410
|
+
linkedTemplateId: ""
|
|
1411
|
+
skills:
|
|
1412
|
+
- quality-review
|
|
1413
|
+
prompt:
|
|
1414
|
+
role: You are the support QA reviewer.
|
|
1415
|
+
mission: Check the drafted response for clarity, policy fit, and tone.
|
|
1416
|
+
inputs: Use the triage summary and drafted response.
|
|
1417
|
+
outputContract: Approve or provide concrete revision guidance.
|
|
1418
|
+
guardrails: Catch risky language, policy errors, and missing action items.
|
|
1419
|
+
modelProvider: ""
|
|
1420
|
+
modelId: ""
|
|
1421
|
+
toolAllowlist:
|
|
1422
|
+
- read
|
|
1423
|
+
- write
|
|
1424
|
+
- glob
|
|
1425
|
+
toolDenylist: []
|
|
1426
|
+
mcpAllowedServers: []
|
|
1427
|
+
- agentId: dispatcher
|
|
1428
|
+
displayName: Dispatcher
|
|
1429
|
+
role: committer
|
|
1430
|
+
avatarUrl: ""
|
|
1431
|
+
templateId: ""
|
|
1432
|
+
linkedTemplateId: ""
|
|
1433
|
+
skills:
|
|
1434
|
+
- operations
|
|
1435
|
+
prompt:
|
|
1436
|
+
role: You are the support dispatcher.
|
|
1437
|
+
mission: Finalize the response or route the case to the proper team.
|
|
1438
|
+
inputs: Use the QA-reviewed response and routing rules.
|
|
1439
|
+
outputContract: Prepare the final reply or escalation summary with correct owner.
|
|
1440
|
+
guardrails: Do not close unresolved escalations.
|
|
1441
|
+
modelProvider: ""
|
|
1442
|
+
modelId: ""
|
|
1443
|
+
toolAllowlist:
|
|
1444
|
+
- read
|
|
1445
|
+
- write
|
|
1446
|
+
- glob
|
|
1447
|
+
toolDenylist: []
|
|
1448
|
+
mcpAllowedServers: []
|
|
1449
|
+
nodes:
|
|
1450
|
+
- nodeId: triage-ticket
|
|
1451
|
+
title: Triage Ticket
|
|
1452
|
+
agentId: intake
|
|
1453
|
+
objective: Classify the issue and identify the right handling path.
|
|
1454
|
+
dependsOn: []
|
|
1455
|
+
inputRefs: []
|
|
1456
|
+
outputKind: triage
|
|
1457
|
+
outputPath: ""
|
|
1458
|
+
taskKind: ""
|
|
1459
|
+
projectBacklogTasks: false
|
|
1460
|
+
backlogTaskId: ""
|
|
1461
|
+
repoRoot: ""
|
|
1462
|
+
writeScope: ""
|
|
1463
|
+
acceptanceCriteria: ""
|
|
1464
|
+
taskDependencies: ""
|
|
1465
|
+
verificationState: ""
|
|
1466
|
+
taskOwner: ""
|
|
1467
|
+
verificationCommand: ""
|
|
1468
|
+
- nodeId: draft-response
|
|
1469
|
+
title: Draft Response
|
|
1470
|
+
agentId: responder
|
|
1471
|
+
objective: Draft the customer-facing response from the triage summary.
|
|
1472
|
+
dependsOn:
|
|
1473
|
+
- triage-ticket
|
|
1474
|
+
inputRefs:
|
|
1475
|
+
- fromStepId: triage-ticket
|
|
1476
|
+
alias: triage
|
|
1477
|
+
outputKind: draft
|
|
1478
|
+
outputPath: ""
|
|
1479
|
+
taskKind: ""
|
|
1480
|
+
projectBacklogTasks: false
|
|
1481
|
+
backlogTaskId: ""
|
|
1482
|
+
repoRoot: ""
|
|
1483
|
+
writeScope: ""
|
|
1484
|
+
acceptanceCriteria: ""
|
|
1485
|
+
taskDependencies: ""
|
|
1486
|
+
verificationState: ""
|
|
1487
|
+
taskOwner: ""
|
|
1488
|
+
verificationCommand: ""
|
|
1489
|
+
- nodeId: review-response
|
|
1490
|
+
title: Review Response
|
|
1491
|
+
agentId: qa
|
|
1492
|
+
objective: Review the response for quality and policy fit.
|
|
1493
|
+
dependsOn:
|
|
1494
|
+
- draft-response
|
|
1495
|
+
inputRefs:
|
|
1496
|
+
- fromStepId: draft-response
|
|
1497
|
+
alias: response_draft
|
|
1498
|
+
outputKind: review
|
|
1499
|
+
outputPath: ""
|
|
1500
|
+
taskKind: ""
|
|
1501
|
+
projectBacklogTasks: false
|
|
1502
|
+
backlogTaskId: ""
|
|
1503
|
+
repoRoot: ""
|
|
1504
|
+
writeScope: ""
|
|
1505
|
+
acceptanceCriteria: ""
|
|
1506
|
+
taskDependencies: ""
|
|
1507
|
+
verificationState: ""
|
|
1508
|
+
taskOwner: ""
|
|
1509
|
+
verificationCommand: ""
|
|
1510
|
+
- nodeId: route-case
|
|
1511
|
+
title: Route Case
|
|
1512
|
+
agentId: dispatcher
|
|
1513
|
+
objective: Finalize the approved response or route the case to an owner.
|
|
1514
|
+
dependsOn:
|
|
1515
|
+
- review-response
|
|
1516
|
+
inputRefs:
|
|
1517
|
+
- fromStepId: review-response
|
|
1518
|
+
alias: approved_response
|
|
1519
|
+
outputKind: dispatch
|
|
1520
|
+
outputPath: ""
|
|
1521
|
+
taskKind: ""
|
|
1522
|
+
projectBacklogTasks: false
|
|
1523
|
+
backlogTaskId: ""
|
|
1524
|
+
repoRoot: ""
|
|
1525
|
+
writeScope: ""
|
|
1526
|
+
acceptanceCriteria: ""
|
|
1527
|
+
taskDependencies: ""
|
|
1528
|
+
verificationState: ""
|
|
1529
|
+
taskOwner: ""
|
|
1530
|
+
verificationCommand: ""
|
|
1531
|
+
`,Zd=`id: weekly-newsletter-builder
|
|
1532
|
+
order: 3
|
|
1533
|
+
name: Weekly Newsletter Builder
|
|
1534
|
+
icon: mail
|
|
1535
|
+
summary: Assemble a weekly newsletter from source updates, editorial drafting, and review.
|
|
1536
|
+
description: A newsletter production workflow that curates source material, drafts the issue, reviews it, and prepares a send-ready package.
|
|
1537
|
+
suggestedOutputs:
|
|
1538
|
+
- newsletter-outline.md
|
|
1539
|
+
- newsletter-draft.md
|
|
1540
|
+
- newsletter-final.md
|
|
1541
|
+
agents:
|
|
1542
|
+
- agentId: curator-discover
|
|
1543
|
+
displayName: Curator Discover
|
|
1544
|
+
role: watcher
|
|
1545
|
+
avatarUrl: ""
|
|
1546
|
+
templateId: ""
|
|
1547
|
+
linkedTemplateId: ""
|
|
1548
|
+
skills:
|
|
1549
|
+
- research
|
|
1550
|
+
prompt:
|
|
1551
|
+
role: You are a newsletter source scout.
|
|
1552
|
+
mission: Identify the local source corpus and candidate story files that should be reviewed before curation begins.
|
|
1553
|
+
inputs: Inspect prior issues, internal updates, source bundles, and audience context files to decide what deserves concrete reading next.
|
|
1554
|
+
outputContract: Return a structured handoff with \`workspace_inventory_summary\`, \`discovered_paths\`, \`priority_paths\`, and \`skipped_paths_initial\`.
|
|
1555
|
+
guardrails: Do not curate the final issue in this stage.
|
|
1556
|
+
modelProvider: ""
|
|
1557
|
+
modelId: ""
|
|
1558
|
+
toolAllowlist:
|
|
1559
|
+
- read
|
|
1560
|
+
- glob
|
|
1561
|
+
toolDenylist: []
|
|
1562
|
+
mcpAllowedServers: []
|
|
1563
|
+
- agentId: curator-local-sources
|
|
1564
|
+
displayName: Curator Local Sources
|
|
1565
|
+
role: watcher
|
|
1566
|
+
avatarUrl: ""
|
|
1567
|
+
templateId: ""
|
|
1568
|
+
linkedTemplateId: ""
|
|
1569
|
+
skills:
|
|
1570
|
+
- research
|
|
1571
|
+
- curation
|
|
1572
|
+
prompt:
|
|
1573
|
+
role: You are a local-source curator for the newsletter workflow.
|
|
1574
|
+
mission: Read the prioritized local updates and capture the strongest story candidates and supporting facts.
|
|
1575
|
+
inputs: Use the upstream \`source_inventory\` handoff to decide what to read and extract the facts that make each item worth including.
|
|
1576
|
+
outputContract: Return a structured handoff with \`read_paths\`, \`reviewed_facts\`, \`files_reviewed\`, \`files_not_reviewed\`, and \`citations_local\`.
|
|
1577
|
+
guardrails: Only elevate items that are supported by actual file reads in this run.
|
|
1578
|
+
modelProvider: ""
|
|
1579
|
+
modelId: ""
|
|
1580
|
+
toolAllowlist:
|
|
1581
|
+
- read
|
|
1582
|
+
- glob
|
|
1583
|
+
toolDenylist: []
|
|
1584
|
+
mcpAllowedServers: []
|
|
1585
|
+
- agentId: curator-external
|
|
1586
|
+
displayName: Curator External
|
|
1587
|
+
role: watcher
|
|
1588
|
+
avatarUrl: ""
|
|
1589
|
+
templateId: ""
|
|
1590
|
+
linkedTemplateId: ""
|
|
1591
|
+
skills:
|
|
1592
|
+
- research
|
|
1593
|
+
- curation
|
|
1594
|
+
prompt:
|
|
1595
|
+
role: You are an external-news analyst for newsletter curation.
|
|
1596
|
+
mission: Gather timely external signals that complement the local updates and help determine what belongs in this week’s issue.
|
|
1597
|
+
inputs: Use the upstream \`source_inventory\` and \`local_source_notes\` handoffs to guide targeted external searches and page fetches.
|
|
1598
|
+
outputContract: Return a structured handoff with \`external_research_mode\`, \`queries_attempted\`, \`sources_reviewed\`, \`citations_external\`, and \`research_limitations\`.
|
|
1599
|
+
guardrails: If search is unavailable, capture that limitation and continue with the evidence already gathered.
|
|
1600
|
+
modelProvider: ""
|
|
1601
|
+
modelId: ""
|
|
1602
|
+
toolAllowlist:
|
|
1603
|
+
- read
|
|
1604
|
+
- websearch
|
|
1605
|
+
- webfetch
|
|
1606
|
+
- glob
|
|
1607
|
+
toolDenylist: []
|
|
1608
|
+
mcpAllowedServers: []
|
|
1609
|
+
- agentId: curator
|
|
1610
|
+
displayName: Curator
|
|
1611
|
+
role: watcher
|
|
1612
|
+
avatarUrl: ""
|
|
1613
|
+
templateId: ""
|
|
1614
|
+
linkedTemplateId: ""
|
|
1615
|
+
skills:
|
|
1616
|
+
- curation
|
|
1617
|
+
prompt:
|
|
1618
|
+
role: You are a newsletter curator selecting stories and updates that deserve the audience's limited attention.
|
|
1619
|
+
mission: Choose the strongest mix of timely updates, useful insights, and product-relevant stories from the upstream evidence bundle.
|
|
1620
|
+
inputs: Use the upstream \`source_inventory\`, \`local_source_notes\`, and \`external_research\` handoffs. Turn them into the final curated shortlist and section order for the issue.
|
|
1621
|
+
outputContract: Produce a shortlist with item summaries, why each matters now, the intended audience takeaway, and a recommended section order for the issue.
|
|
1622
|
+
guardrails: Prefer relevance, freshness, and distinctiveness over volume. Do not redo discovery or fresh web research in this stage.
|
|
1623
|
+
modelProvider: ""
|
|
1624
|
+
modelId: ""
|
|
1625
|
+
toolAllowlist:
|
|
1626
|
+
- read
|
|
1627
|
+
- glob
|
|
1628
|
+
toolDenylist: []
|
|
1629
|
+
mcpAllowedServers: []
|
|
1630
|
+
- agentId: editor
|
|
1631
|
+
displayName: Editor
|
|
1632
|
+
role: worker
|
|
1633
|
+
avatarUrl: ""
|
|
1634
|
+
templateId: ""
|
|
1635
|
+
linkedTemplateId: ""
|
|
1636
|
+
skills:
|
|
1637
|
+
- writing
|
|
1638
|
+
- editing
|
|
1639
|
+
prompt:
|
|
1640
|
+
role: You are the newsletter editor responsible for turning curated inputs into a cohesive, highly readable issue.
|
|
1641
|
+
mission: Write a newsletter that feels timely, useful, and easy to scan while preserving a consistent editorial voice.
|
|
1642
|
+
inputs: Use the curated shortlist, publication tone guidance, prior issue patterns, and any desired structure or CTA rules.
|
|
1643
|
+
outputContract: Produce a full issue draft with subject line options, preview text, section transitions, concise commentary for each item, and a final CTA or reply prompt.
|
|
1644
|
+
guardrails: Keep the issue skimmable, specific, and audience-first. Avoid generic roundup filler, and make every section earn its place.
|
|
1645
|
+
modelProvider: ""
|
|
1646
|
+
modelId: ""
|
|
1647
|
+
toolAllowlist:
|
|
1648
|
+
- read
|
|
1649
|
+
- write
|
|
1650
|
+
- glob
|
|
1651
|
+
toolDenylist: []
|
|
1652
|
+
mcpAllowedServers: []
|
|
1653
|
+
- agentId: copy-review
|
|
1654
|
+
displayName: Copy Review
|
|
1655
|
+
role: reviewer
|
|
1656
|
+
avatarUrl: ""
|
|
1657
|
+
templateId: ""
|
|
1658
|
+
linkedTemplateId: ""
|
|
1659
|
+
skills:
|
|
1660
|
+
- fact-checking
|
|
1661
|
+
- copy-editing
|
|
1662
|
+
prompt:
|
|
1663
|
+
role: You are the newsletter reviewer applying a copy-edit and fact-check pass before send.
|
|
1664
|
+
mission: Review the issue for claim accuracy, clarity, formatting, consistency, and whether each section answers 'why should I care?'
|
|
1665
|
+
inputs: Use the draft, curation notes, proof sources, and any editorial or compliance guidance.
|
|
1666
|
+
outputContract: Approve or return exact edits needed before send, grouped by claims, flow, clarity, formatting, and CTA quality.
|
|
1667
|
+
guardrails: Catch broken references, vague claims, weak transitions, and unsupported statements. Do not let filler or overlong sections through.
|
|
1668
|
+
modelProvider: ""
|
|
1669
|
+
modelId: ""
|
|
1670
|
+
toolAllowlist:
|
|
1671
|
+
- read
|
|
1672
|
+
- write
|
|
1673
|
+
- glob
|
|
1674
|
+
toolDenylist: []
|
|
1675
|
+
mcpAllowedServers: []
|
|
1676
|
+
- agentId: publisher
|
|
1677
|
+
displayName: Publisher
|
|
1678
|
+
role: committer
|
|
1679
|
+
avatarUrl: ""
|
|
1680
|
+
templateId: ""
|
|
1681
|
+
linkedTemplateId: ""
|
|
1682
|
+
skills:
|
|
1683
|
+
- publishing
|
|
1684
|
+
prompt:
|
|
1685
|
+
role: You are the newsletter publishing operator responsible for final packaging and send readiness.
|
|
1686
|
+
mission: Prepare the approved issue for the ESP or publishing workflow with all required metadata and preflight checks complete.
|
|
1687
|
+
inputs: Use the approved newsletter draft, publish metadata, audience segment details, and delivery platform requirements.
|
|
1688
|
+
outputContract: Produce the final issue package, send checklist, subject and preview confirmation, and any handoff notes needed for scheduling.
|
|
1689
|
+
guardrails: Do not send unrevised drafts, and flag anything missing that could break layout, tracking, or links.
|
|
1690
|
+
modelProvider: ""
|
|
1691
|
+
modelId: ""
|
|
1692
|
+
toolAllowlist:
|
|
1693
|
+
- read
|
|
1694
|
+
- write
|
|
1695
|
+
- glob
|
|
1696
|
+
toolDenylist: []
|
|
1697
|
+
mcpAllowedServers: []
|
|
1698
|
+
nodes:
|
|
1699
|
+
- nodeId: curate-issue-discover
|
|
1700
|
+
title: Discover Issue Sources
|
|
1701
|
+
agentId: curator-discover
|
|
1702
|
+
objective: Identify the local source corpus and candidate files that should feed this week's issue.
|
|
1703
|
+
dependsOn: []
|
|
1704
|
+
inputRefs: []
|
|
1705
|
+
stageKind: research_discover
|
|
1706
|
+
outputKind: structured_json
|
|
1707
|
+
outputPath: ""
|
|
1708
|
+
taskKind: ""
|
|
1709
|
+
projectBacklogTasks: false
|
|
1710
|
+
backlogTaskId: ""
|
|
1711
|
+
repoRoot: ""
|
|
1712
|
+
writeScope: ""
|
|
1713
|
+
acceptanceCriteria: ""
|
|
1714
|
+
taskDependencies: ""
|
|
1715
|
+
verificationState: ""
|
|
1716
|
+
taskOwner: ""
|
|
1717
|
+
verificationCommand: ""
|
|
1718
|
+
- nodeId: curate-issue-local-sources
|
|
1719
|
+
title: Read Issue Sources
|
|
1720
|
+
agentId: curator-local-sources
|
|
1721
|
+
objective: Read the prioritized local source files and extract the strongest issue candidates.
|
|
1722
|
+
dependsOn:
|
|
1723
|
+
- curate-issue-discover
|
|
1724
|
+
inputRefs:
|
|
1725
|
+
- fromStepId: curate-issue-discover
|
|
1726
|
+
alias: source_inventory
|
|
1727
|
+
stageKind: research_local_sources
|
|
1728
|
+
outputKind: structured_json
|
|
1729
|
+
outputPath: ""
|
|
1730
|
+
taskKind: ""
|
|
1731
|
+
projectBacklogTasks: false
|
|
1732
|
+
backlogTaskId: ""
|
|
1733
|
+
repoRoot: ""
|
|
1734
|
+
writeScope: ""
|
|
1735
|
+
acceptanceCriteria: ""
|
|
1736
|
+
taskDependencies: ""
|
|
1737
|
+
verificationState: ""
|
|
1738
|
+
taskOwner: ""
|
|
1739
|
+
verificationCommand: ""
|
|
1740
|
+
- nodeId: curate-issue-external-research
|
|
1741
|
+
title: Research Issue
|
|
1742
|
+
agentId: curator-external
|
|
1743
|
+
objective: Gather timely external signals that should influence this week's issue.
|
|
1744
|
+
dependsOn:
|
|
1745
|
+
- curate-issue-discover
|
|
1746
|
+
- curate-issue-local-sources
|
|
1747
|
+
inputRefs:
|
|
1748
|
+
- fromStepId: curate-issue-discover
|
|
1749
|
+
alias: source_inventory
|
|
1750
|
+
- fromStepId: curate-issue-local-sources
|
|
1751
|
+
alias: local_source_notes
|
|
1752
|
+
stageKind: research_external_sources
|
|
1753
|
+
outputKind: structured_json
|
|
1754
|
+
outputPath: ""
|
|
1755
|
+
taskKind: ""
|
|
1756
|
+
projectBacklogTasks: false
|
|
1757
|
+
backlogTaskId: ""
|
|
1758
|
+
repoRoot: ""
|
|
1759
|
+
writeScope: ""
|
|
1760
|
+
acceptanceCriteria: ""
|
|
1761
|
+
taskDependencies: ""
|
|
1762
|
+
verificationState: ""
|
|
1763
|
+
taskOwner: ""
|
|
1764
|
+
verificationCommand: ""
|
|
1765
|
+
- nodeId: curate-issue
|
|
1766
|
+
title: Curate Issue
|
|
1767
|
+
agentId: curator
|
|
1768
|
+
objective: Curate the best items for this week's issue from the staged research handoffs.
|
|
1769
|
+
dependsOn:
|
|
1770
|
+
- curate-issue-discover
|
|
1771
|
+
- curate-issue-local-sources
|
|
1772
|
+
- curate-issue-external-research
|
|
1773
|
+
inputRefs:
|
|
1774
|
+
- fromStepId: curate-issue-discover
|
|
1775
|
+
alias: source_inventory
|
|
1776
|
+
- fromStepId: curate-issue-local-sources
|
|
1777
|
+
alias: local_source_notes
|
|
1778
|
+
- fromStepId: curate-issue-external-research
|
|
1779
|
+
alias: external_research
|
|
1780
|
+
stageKind: research_finalize
|
|
1781
|
+
outputKind: outline
|
|
1782
|
+
outputPath: ""
|
|
1783
|
+
taskKind: ""
|
|
1784
|
+
projectBacklogTasks: false
|
|
1785
|
+
backlogTaskId: ""
|
|
1786
|
+
repoRoot: ""
|
|
1787
|
+
writeScope: ""
|
|
1788
|
+
acceptanceCriteria: ""
|
|
1789
|
+
taskDependencies: ""
|
|
1790
|
+
verificationState: ""
|
|
1791
|
+
taskOwner: ""
|
|
1792
|
+
verificationCommand: ""
|
|
1793
|
+
- nodeId: draft-issue
|
|
1794
|
+
title: Draft Issue
|
|
1795
|
+
agentId: editor
|
|
1796
|
+
objective: Draft the newsletter issue from the curated outline.
|
|
1797
|
+
dependsOn:
|
|
1798
|
+
- curate-issue
|
|
1799
|
+
inputRefs:
|
|
1800
|
+
- fromStepId: curate-issue
|
|
1801
|
+
alias: outline
|
|
1802
|
+
outputKind: draft
|
|
1803
|
+
outputPath: ""
|
|
1804
|
+
taskKind: ""
|
|
1805
|
+
projectBacklogTasks: false
|
|
1806
|
+
backlogTaskId: ""
|
|
1807
|
+
repoRoot: ""
|
|
1808
|
+
writeScope: ""
|
|
1809
|
+
acceptanceCriteria: ""
|
|
1810
|
+
taskDependencies: ""
|
|
1811
|
+
verificationState: ""
|
|
1812
|
+
taskOwner: ""
|
|
1813
|
+
verificationCommand: ""
|
|
1814
|
+
- nodeId: review-issue
|
|
1815
|
+
title: Review Issue
|
|
1816
|
+
agentId: copy-review
|
|
1817
|
+
objective: Review the newsletter draft before distribution.
|
|
1818
|
+
dependsOn:
|
|
1819
|
+
- draft-issue
|
|
1820
|
+
inputRefs:
|
|
1821
|
+
- fromStepId: draft-issue
|
|
1822
|
+
alias: draft
|
|
1823
|
+
outputKind: review
|
|
1824
|
+
outputPath: ""
|
|
1825
|
+
taskKind: ""
|
|
1826
|
+
projectBacklogTasks: false
|
|
1827
|
+
backlogTaskId: ""
|
|
1828
|
+
repoRoot: ""
|
|
1829
|
+
writeScope: ""
|
|
1830
|
+
acceptanceCriteria: ""
|
|
1831
|
+
taskDependencies: ""
|
|
1832
|
+
verificationState: ""
|
|
1833
|
+
taskOwner: ""
|
|
1834
|
+
verificationCommand: ""
|
|
1835
|
+
- nodeId: publish-issue
|
|
1836
|
+
title: Publish Issue
|
|
1837
|
+
agentId: publisher
|
|
1838
|
+
objective: Prepare the issue for the sending platform and final approval.
|
|
1839
|
+
dependsOn:
|
|
1840
|
+
- review-issue
|
|
1841
|
+
inputRefs:
|
|
1842
|
+
- fromStepId: review-issue
|
|
1843
|
+
alias: approved_issue
|
|
1844
|
+
outputKind: publish
|
|
1845
|
+
outputPath: ""
|
|
1846
|
+
taskKind: ""
|
|
1847
|
+
projectBacklogTasks: false
|
|
1848
|
+
backlogTaskId: ""
|
|
1849
|
+
repoRoot: ""
|
|
1850
|
+
writeScope: ""
|
|
1851
|
+
acceptanceCriteria: ""
|
|
1852
|
+
taskDependencies: ""
|
|
1853
|
+
verificationState: ""
|
|
1854
|
+
taskOwner: ""
|
|
1855
|
+
verificationCommand: ""
|
|
1856
|
+
`,eu=Object.assign({"./templates/competitor-research-pipeline.yaml":Qd,"./templates/marketing-content-pipeline.yaml":Hd,"./templates/prd-to-launch-plan-team.yaml":Gd,"./templates/repo-coding-backlog.yaml":Vd,"./templates/sales-prospecting-team.yaml":Yd,"./templates/support-triage-team.yaml":Xd,"./templates/weekly-newsletter-builder.yaml":Zd});function tu(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),D=r.suggestedOutputs,x=r.agents,M=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(D))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(M))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:D,agents:x,nodes:M}}const Ba=Object.entries(eu).map(([a,t])=>tu(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 au(a={}){return{role:"",mission:"",inputs:"",outputContract:"",guardrails:"",...a}}function $s(a,t,n={}){return{agentId:a,displayName:t,role:"worker",avatarUrl:"",templateId:"",linkedTemplateId:"",skills:[],prompt:au(),modelProvider:"",modelId:"",toolAllowlist:["read","write","glob"],toolDenylist:[],mcpAllowedServers:[],...n}}function nu(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 ru=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],su="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 iu(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 cs(a){const t=g(a.taskKind).toLowerCase();return t==="code_change"||t==="repo_fix"||t==="implementation"||iu(a.outputPath)}function Ki(a){return!!a.projectBacklogTasks}function ds(a){const t=a.map(n=>g(n)).filter(Boolean);return t.includes("*")?["*"]:Array.from(new Set(t))}function Os(a,t){const n=ds(a);if(n.includes("*"))return["*"];const s=t.some(c=>cs(c))?["read","glob","edit","apply_patch","write","bash"]:[];return Array.from(new Set([...n,...s]))}function ou(a){const t=g(a);return t?t.length<=18?t:`${t.slice(0,8)}...${t.slice(-6)}`:""}function Es(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 Pn(a){return String(a||"").split(",").map(t=>t.trim()).filter(Boolean)}function Tn(a){return a.join(", ")}function Qr(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)}function tr(a,t){return Qr(a)||t}function Hr(a){const t=g(a);return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Ds(a){try{sessionStorage.setItem(su,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
|
+
${String(r).trim()}`).join(`
|
|
1858
|
+
|
|
1859
|
+
`)}function lu(a){if(!(!g(a.modelProvider)||!g(a.modelId)))return{default_model:{provider_id:g(a.modelProvider),model_id:g(a.modelId)}}}function cu(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 un(a,t){return a.find(n=>n.id===t)?.models||[]}function Rn(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 Wi(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 js(a,t,n){const r=g(t),s=g(n);return!r||!s?a:a.map(c=>({...c,modelProvider:r,modelId:s}))}function du(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 uu(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 mu(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 us(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 zi(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 Us(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)}:us(g(a?.systemPrompt||a?.system_prompt)),modelProvider:g(a?.modelProvider||a?.model_provider),modelId:g(a?.modelId||a?.model_id),toolAllowlist:ds(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 Bs(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 pu(a,t){const n=cs(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)}.`:"",Ki(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 Ji(a,t,n){const r=Ba.find(c=>c.id===a);return r&&ur(r,n||"").agents.find(c=>c.agentId===t)||null}function Gr(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=Ji(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:ds(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 Fs(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 hu(a,t){const n=[],r=Hr(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 gu(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(Us):[],p=Array.isArray(s?.node_drafts)?s.node_drafts.map(Bs):[],N=Array.isArray(a?.agents)?a.agents.map(S=>{const W=g(S?.template_id||S?.templateId),I=W?n.get(W):null,Q=!I&&d?Ji(d,g(S?.agent_id||S?.agentId),g(a?.workspace_root||a?.workspaceRoot||r?.workspace_root||t)):null;return Us({agentId:S?.agent_id||S?.agentId,displayName:S?.display_name||S?.displayName||Q?.displayName||S?.agent_id||S?.agentId,role:I?.role||Q?.role||"worker",templateId:W,linkedTemplateId:W,skills:Array.isArray(S?.skills)?S.skills:I?.skills||Q?.skills||[],prompt:I?.systemPrompt?us(I.systemPrompt):Q?.prompt,modelProvider:S?.model_policy?.default_model?.provider_id||S?.modelPolicy?.defaultModel?.providerId||Q?.modelProvider||I?.modelProvider||"",modelId:S?.model_policy?.default_model?.model_id||S?.modelPolicy?.defaultModel?.modelId||Q?.modelId||I?.modelId||"",toolAllowlist:S?.tool_policy?.allowlist||S?.toolPolicy?.allowlist||[],toolDenylist:S?.tool_policy?.denylist||S?.toolPolicy?.denylist||[],mcpAllowedServers:S?.mcp_policy?.allowed_servers||S?.mcpPolicy?.allowedServers||[]})}):[],D=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map(S=>Bs({nodeId:S?.node_id||S?.nodeId,title:S?.metadata?.builder?.title||S?.metadata?.studio?.title||S?.objective||S?.node_id||S?.nodeId,agentId:S?.agent_id||S?.agentId,objective:S?.objective,dependsOn:S?.depends_on||S?.dependsOn||[],inputRefs:S?.input_refs||S?.inputRefs||[],outputKind:S?.output_contract?.kind||S?.outputContract?.kind||"artifact",metadata:S?.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(S=>g(S)).filter(Boolean):Array.isArray(c?.output_targets)?c.output_targets.map(S=>g(S)).filter(Boolean):[],agents:u.length?u:N,nodes:p.length?p:D},M=Wi(x.agents);return x.useSharedModel=M.useSharedModel,x.sharedModelProvider=M.provider,x.sharedModelId=M.model,Gr(x,n)}function fu(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 bu(a,t,n){const r=zi(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 vu(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 yu(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 wu({client:a,api:t,toast:n,navigate:r}){const s=ca(),c=Li(!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}),D=V({queryKey:["studio","mcp"],queryFn:()=>a.mcp.list().catch(()=>({})),refetchInterval:15e3}),x=g(c.data?.workspaceRoot||c.data?.workspace_root),M=B(()=>mr(u.data,"templates").map(mu).filter(l=>l.templateId),[u.data]),E=B(()=>new Map(M.map(l=>[l.templateId,l])),[M]),S=B(()=>(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]),W=B(()=>cu(S,N.data),[S,N.data]),I=B(()=>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=B(()=>I.map(l=>g(l?.automation_id||l?.automationId||l?.id)).filter(Boolean),[I]),ee=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}),ce=B(()=>{const l=mr(ee.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},[ee.data]),C=B(()=>uu(D.data),[D.data]),[P,O]=y(()=>ur(Ba[0],"")),[A,ve]=y(()=>Ba[0]?.nodes?.[0]?.nodeId||""),[z,k]=y(()=>Ba[0]?.agents?.[0]?.agentId||""),[v,te]=y(""),[H,Pe]=y(!1),[$e,Le]=y(!1),[re,pe]=y(!0),[q,ge]=y(!0),[Te,Re]=y(!1),[se,Oe]=y(""),[qe,He]=y(""),[Y,Ze]=y(null),[ne,Ae]=y(null);fe(()=>{x&&O(l=>g(l.workspaceRoot)?l:{...l,workspaceRoot:x})},[x]),fe(()=>{!W.provider||!W.model||O(l=>{const b=Rn(l.agents,W);return b.some((R,$)=>R.modelProvider!==l.agents[$]?.modelProvider||R.modelId!==l.agents[$]?.modelId)?{...l,agents:b}:l})},[W]),fe(()=>{P.useSharedModel&&(!g(P.sharedModelProvider)||!g(P.sharedModelId)||O(l=>{if(!l.useSharedModel)return l;const b=js(l.agents,l.sharedModelProvider,l.sharedModelId);return b.some((R,$)=>R.modelProvider!==l.agents[$]?.modelProvider||R.modelId!==l.agents[$]?.modelId)?{...l,agents:b}:l}))},[P.useSharedModel,P.sharedModelProvider,P.sharedModelId]),fe(()=>{new Set(P.nodes.map(b=>b.nodeId)).has(A)||ve(P.nodes[0]?.nodeId||"")},[P.nodes,A]),fe(()=>{new Set(P.agents.map(b=>b.agentId)).has(z)||k(P.agents[0]?.agentId||"")},[P.agents,z]),fe(()=>{try{xa()}catch{}},[P,A,v,re,q,I.length,M.length,Te,qe]);const St=V({queryKey:["studio","workspace-browser",se],enabled:Te&&!!se,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(se)}`,{method:"GET"}),refetchInterval:Te?15e3:!1}),oe=P.nodes.find(l=>l.nodeId===A)||P.nodes[0]||null,K=P.agents.find(l=>l.agentId===(z||oe?.agentId))||P.agents.find(l=>l.agentId===oe?.agentId)||P.agents[0]||null,lt=Hr(P.workspaceRoot),xt=Array.isArray(St.data?.directories)?St.data.directories:[],rt=g(St.data?.parent),Et=g(St.data?.dir||se||""),Fe=B(()=>{const l=g(qe).toLowerCase();return l?xt.filter(b=>g(b?.name||b?.path).toLowerCase().includes(l)):xt},[qe,xt]),Bt=B(()=>zi(P.nodes),[P.nodes]),At=B(()=>{const l=new Map;for(const b of P.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])},[P.nodes,Bt]),$t=l=>{const b=Ba.find(R=>R.id===l)||Ba[0],T=ur(b,P.workspaceRoot||x);O({...T,agents:Rn(T.agents,W)}),ve(T.nodes[0]?.nodeId||""),k(T.agents[0]?.agentId||""),Pe(!1),Ae(null)},We=l=>O(b=>({...b,...l})),ze=(l,b)=>O(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)=>O(T=>({...T,agents:T.agents.map(R=>R.agentId===l?{...R,...b}:R)})),be=()=>{const l=`agent-${P.agents.length+1}`,b=P.agents.some(T=>T.agentId===l)?`agent-${Date.now().toString().slice(-5)}`:l;O(T=>({...T,agents:[...T.agents,Rn([$s(b,`Agent ${T.agents.length+1}`)],W)[0]]})),k(b)},Se=()=>{const l=P.nodes.length+1,b=`stage-${l}`,T=K?.agentId||P.agents[0]?.agentId||"",R=nu(b,`Stage ${l}`,T,oe?[oe.nodeId]:[],oe?[{fromStepId:oe.nodeId,alias:oe.nodeId.replace(/-/g,"_")}]:[],{objective:"Describe what this stage should produce."});O($=>({...$,nodes:[...$.nodes,R]})),ve(b),T&&k(T)},Ve=()=>{oe&&O(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))}})}))},de=()=>{if(!K)return;if(P.nodes.some(b=>b.agentId===K.agentId)){n("warn","Reassign or remove the stages using this agent first.");return}O(b=>({...b,agents:b.agents.filter(T=>T.agentId!==K.agentId)})),k("")},dt=()=>{if(!K||!v)return;const l=E.get(v);l&&(tt(K.agentId,{displayName:l.displayName||K.displayName,avatarUrl:l.avatarUrl||K.avatarUrl,role:l.role||K.role,linkedTemplateId:l.templateId,templateId:l.templateId,prompt:l.systemPrompt?us(l.systemPrompt):K.prompt,modelProvider:l.modelProvider||K.modelProvider,modelId:l.modelId||K.modelId,skills:l.skills.length?l.skills:K.skills}),Ae(b=>b&&{...b,repairedAgentIds:b.repairedAgentIds.filter(T=>T!==K.agentId),repairedTemplateIds:b.repairedTemplateIds.filter(T=>T!==l.templateId)}),n("ok",`Loaded template ${l.templateId}.`))},_=l=>{const b=gu(l,x,E),T={...b.draft,agents:Rn(b.draft.agents,W)};O(T),ve(T.nodes[0]?.nodeId||""),k(T.agents[0]?.agentId||""),Pe(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(Fs(l,E).isBroken){_(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."),Ds({tab:"running",runId:$,automationId:b,openTaskInspector:!0}),r("automations")},me=ke({mutationFn:async()=>{const l=H?P:Gr(P,E).draft;let b={...l,agents:Rn(l.agents,W)};b.useSharedModel&&g(b.sharedModelProvider)&&g(b.sharedModelId)&&(b={...b,agents:js(b.agents,b.sharedModelProvider,b.sharedModelId)});const T=Hr(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=hu(b,E);if(R.errors.length)throw new Error(R.errors[0]);const $=b.agents.filter(ae=>!g(ae.modelProvider)||!g(ae.modelId)).map(ae=>ae.displayName||ae.agentId);if($.length)throw new Error(`Model selection is required. Set a default provider/model in Settings or choose one for: ${$.join(", ")}.`);const Ye=Qr(b.name)||"studio-workflow",Xe=new Map;if(H)for(const ae of b.agents){const Ne=g(ae.linkedTemplateId)||g(ae.templateId)||`${Ye}--${Qr(ae.agentId)||"agent"}`;Xe.set(ae.agentId,Ne),E.has(Ne)?await a.agentTeams.updateTemplate(Ne,{display_name:g(ae.displayName)||Ne,avatar_url:g(ae.avatarUrl)||void 0,role:g(ae.role)||"worker",system_prompt:vr(ae.prompt)||void 0,default_model:g(ae.modelProvider)&&g(ae.modelId)?{provider_id:g(ae.modelProvider),model_id:g(ae.modelId)}:void 0,skills:ae.skills.map(h=>({id:h,skill_id:h,name:h}))}):await a.agentTeams.createTemplate({template:fu(ae,Ne)})}const Ot=vu(b.nodes),Ft={name:g(b.name),description:g(b.description)||void 0,status:b.status,schedule:du(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(ae=>g(ae)).filter(Boolean),agents:b.agents.map(ae=>({agent_id:g(ae.agentId),template_id:H&&(Xe.get(ae.agentId)||g(ae.linkedTemplateId))||void 0,display_name:g(ae.displayName)||g(ae.agentId),avatar_url:g(ae.avatarUrl)||void 0,model_policy:lu(ae),skills:ae.skills.map(Ne=>g(Ne)).filter(Boolean),tool_policy:{allowlist:Os(ae.toolAllowlist,Ot.filter(Ne=>Ne.agentId===ae.agentId)),denylist:ae.toolDenylist.map(Ne=>g(Ne)).filter(Boolean)},mcp_policy:{allowed_servers:ae.mcpAllowedServers.map(Ne=>g(Ne)).filter(Boolean),allowed_tools:[]}})),flow:{nodes:Ot.map(ae=>{const Ne=b.agents.find(Ge=>Ge.agentId===ae.agentId),h=g(ae.outputPath),U=cs(ae),J=g(ae.stageKind),F=J==="research_finalize",X=!!J&&!h,we=ae.inputRefs.some(Ge=>g(Ge.alias)==="external_research"),Ue=Os(Ne?.toolAllowlist||[],Ot.filter(Ge=>Ge.agentId===ae.agentId)),st=!!Ne?.toolAllowlist?.includes("websearch")&&!F,vt=g(ae.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")&&!F?"read":null,Ue.includes("websearch")&&!F?"websearch":null].filter(Ge=>!!Ge).filter((Ge,da,Ce)=>Ce.indexOf(Ge)===da):X?[et?"read":null,yt?"websearch":null].filter(Ge=>!!Ge):[],Ht=h?[!F&&(Lt.includes("read")||vt)?"local_source_reads":null,!F&&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||we?"web_sources_reviewed":null].filter(Ge=>!!Ge):[],Gt=h?[F?null:"workspace_inspection",!F&&(Lt.includes("read")||vt)?"concrete_reads":null,!F&&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=[...Ht,...Ct,...Gt];return{node_id:g(ae.nodeId),agent_id:g(ae.agentId),objective:g(ae.objective)||g(ae.title),depends_on:ae.dependsOn.map(Ge=>g(Ge)).filter(Boolean),input_refs:jn(ae.dependsOn,ae.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(ae.outputKind)||"artifact",enforcement:h?{required_tools:Lt,required_evidence:Ht,required_sections:Ct,prewrite_gates:Gt,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(ae.title)||g(ae.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(ae.taskKind)||void 0,project_backlog_tasks:Ki(ae)||void 0,task_id:g(ae.backlogTaskId)||void 0,repo_root:g(ae.repoRoot)||void 0,write_scope:g(ae.writeScope)||void 0,acceptance_criteria:g(ae.acceptanceCriteria)||void 0,task_dependencies:g(ae.taskDependencies)||void 0,verification_state:g(ae.verificationState)||void 0,task_owner:g(ae.taskOwner)||void 0,verification_command:g(ae.verificationCommand)||void 0,prompt:pu(ae,Ne||$s(g(ae.agentId),g(ae.agentId)))}}}})},metadata:{workspace_root:g(P.workspaceRoot),studio:bu({...b,agents:b.agents.map(ae=>({...ae,templateId:H?Xe.get(ae.agentId)||g(ae.linkedTemplateId)||g(ae.templateId):"",linkedTemplateId:H?Xe.get(ae.agentId)||g(ae.linkedTemplateId)||g(ae.templateId):""}))},Ot,H?null:ne||Gr(b,E).repairState)}},Ie=P.automationId?await a.automationsV2.update(P.automationId,Ft):await a.automationsV2.create(Ft),Pt=g(Ie?.automation?.automation_id||Ie?.automation?.automationId);let bt="";if($e&&Pt){const ae=await a.automationsV2.runNow(Pt);bt=g(ae?.run?.run_id||ae?.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"]})]),O(Ye=>({...Ye,...R,automationId:b||g(l?.automation?.automation_id||l?.automation?.automationId),agents:R.agents.map(Xe=>({...Xe,templateId:H?T.get(Xe.agentId)||Xe.templateId:"",linkedTemplateId:H?T.get(Xe.agentId)||Xe.linkedTemplateId:""}))})),Ae(Ye=>Ye?{...Ye,requiresSave:!1,reason:"save"}:null),$e&&(Ds({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 yu(a,l),l),onSuccess:async l=>{if(P.automationId===l){const b=ur(Ba[0],x||"");O(b),ve(b.nodes[0]?.nodeId||""),k(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(Xt,{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(P.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:me.isPending,onClick:()=>me.mutate(),children:[e("i",{"data-lucide":me.isPending?"loader-circle":"save"}),me.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(Xt,{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:()=>pe(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(Me.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 ${P.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(Me.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:I.length?[...I].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=ce.get(b)||null,R=Dd(T),$=g(R.status),Ye=g(R.failureKind),Xe=g(R.phase),Ot=Es(T?.updated_at_ms||T?.updatedAtMs||T?.created_at_ms||T?.createdAtMs),Ft=l?.metadata?.studio||{},Ie=Fs(l,E),Pt=g(Ft?.template_id||Ft?.templateId||Ft?.starter_template_id||Ft?.starterTemplateId),bt=Es(l?.updated_at_ms||l?.updatedAtMs||l?.created_at_ms||l?.createdAtMs),ae=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: ",ou(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:()=>{_(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:ae,onClick:()=>{Ze({automationId:b,title:g(l?.name)||b})},children:[e("i",{"data-lucide":"trash-2"}),ae?"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:[ne?.requiresSave&&(ne?.repairedAgentIds.length||ne?.missingNodeAgentIds.length)?e(Xt,{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:()=>me.mutate(),disabled:me.isPending,children:[e("i",{"data-lucide":me.isPending?"loader-circle":"save"}),me.isPending?"Saving...":"Save Repaired Workflow"]}),children:e("div",{className:"grid gap-2 text-sm text-slate-300",children:[ne.repairedAgentIds.length?e("div",{children:["Repaired missing template links for: ",ne.repairedAgentIds.join(", ")]}):null,ne.missingNodeAgentIds.length?e("div",{children:["Stages still reference missing agents:"," ",ne.missingNodeAgentIds.join(", ")]}):null,e("div",{className:"text-xs text-slate-400",children:"Save this workflow to persist the repaired local-first configuration."})]})}):null,e(Xt,{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:P.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:P.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(P.workspaceRoot||x||"/");Oe(l||"/"),He(""),Re(!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:P.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:!P.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:Tn(P.outputTargets),onInput:l=>We({outputTargets:Pn(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:P.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:P.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:P.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"})]})]}),P.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:P.cronExpression,onInput:l=>We({cronExpression:l.target.value}),placeholder:"0 9 * * 1"})]}):null,P.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:P.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:H,onInput:l=>Pe(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:"," ",W.provider&&W.model?`${W.provider}/${W.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:P.useSharedModel,onInput:l=>{const b=l.target.checked,T=Wi(P.agents);We({useSharedModel:b,sharedModelProvider:b?g(P.sharedModelProvider)||T.provider||W.provider:P.sharedModelProvider,sharedModelId:b?g(P.sharedModelId)||T.model||W.model:P.sharedModelId})}}),"Use one model for all agents in this workflow"]}),P.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:P.sharedModelProvider,onInput:l=>{const b=l.target.value,T=un(S,b);We({sharedModelProvider:b,sharedModelId:T.includes(P.sharedModelId)?P.sharedModelId:T[0]||P.sharedModelId})},children:[e("option",{value:"",children:"Select provider..."}),S.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"}),un(S,P.sharedModelProvider).length?e("select",{className:"tcp-input text-sm",value:P.sharedModelId,onInput:l=>We({sharedModelId:l.target.value}),children:un(S,P.sharedModelProvider).map(l=>e("option",{value:l,children:l},l))}):e("input",{className:"tcp-input text-sm",value:P.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"]}),ne&&!ne.requiresSave&&ne.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]})]})}),Te?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:()=>{Re(!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}),Re(!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:()=>{Re(!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:qe,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(qe)?"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(Xt,{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=P.agents.find(Ye=>Ye.agentId===T.agentId),$=T.nodeId===A;return e("button",{className:`tcp-list-item flex flex-col text-left ${$?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{ve(T.nodeId),k(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(Xt,{title:"Agent Directory",subtitle:"All agents currently participating in this workflow.",children:e("div",{className:"grid gap-2 md:grid-cols-2",children:P.agents.map(l=>{const b=K?.agentId===l.agentId;return e("button",{className:`tcp-list-item text-left ${b?"border-emerald-400/60 bg-emerald-500/10":""}`,onClick:()=>{k(l.agentId);const T=P.nodes.find(R=>R.agentId===l.agentId);T&&ve(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}),ne?.repairedAgentIds.includes(l.agentId)?e("span",{className:"tcp-badge-warn",children:"missing/repaired"}):g(l.linkedTemplateId||l.templateId)?E.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(Xt,{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}),k(b)},children:P.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:P.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(Xt,{title:K?`Agent: ${K.displayName||K.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:de,disabled:!K,children:[e("i",{"data-lucide":"trash-2"}),"Remove Agent"]}),children:K?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:K.displayName,onInput:l=>tt(K.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:K.role,onInput:l=>tt(K.agentId,{role:l.target.value}),children:ru.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:Tn(K.skills),onInput:l=>tt(K.agentId,{skills:Pn(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"}),K.linkedTemplateId?e("button",{className:"tcp-btn inline-flex h-7 items-center gap-2 px-2 text-xs",onClick:()=>tt(K.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:v,onInput:l=>te(l.target.value),children:[e("option",{value:"",children:"Select an existing agent template..."}),M.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:!v,onClick:dt,children:[e("i",{"data-lucide":"download"}),"Load Template"]})]}),e("div",{className:"mt-2 text-xs text-slate-400",children:ne?.repairedAgentIds.includes(K.agentId)?"This agent had a missing shared template link. Studio repaired it into a workflow-local prompt.":K.linkedTemplateId?E.has(K.linkedTemplateId)?`Linked template: ${K.linkedTemplateId}`:`Missing template link repaired locally: ${K.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:K.modelProvider,disabled:P.useSharedModel,onInput:l=>tt(K.agentId,(()=>{const b=l.target.value,T=un(S,b);return{modelProvider:b,modelId:T.includes(K.modelId)?K.modelId:T[0]||K.modelId}})()),children:[e("option",{value:"",children:"Select provider..."}),S.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"}),un(S,K.modelProvider).length?e("select",{className:"tcp-input text-sm",value:K.modelId,disabled:P.useSharedModel,onInput:l=>tt(K.agentId,{modelId:l.target.value}),children:un(S,K.modelProvider).map(l=>e("option",{value:l,children:l},l))}):e("input",{className:"tcp-input text-sm",value:K.modelId,disabled:P.useSharedModel,onInput:l=>tt(K.agentId,{modelId:l.target.value}),placeholder:"provider-specific model id"})]}),P.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:Tn(K.toolAllowlist),onInput:l=>tt(K.agentId,{toolAllowlist:Pn(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:Tn(K.toolDenylist),onInput:l=>tt(K.agentId,{toolDenylist:Pn(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:Tn(K.mcpAllowedServers),onInput:l=>tt(K.agentId,{mcpAllowedServers:Pn(l.target.value)}),placeholder:C.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:K.prompt.role,onInput:l=>tt(K.agentId,{prompt:{...K.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:K.prompt.mission,onInput:l=>tt(K.agentId,{prompt:{...K.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:K.prompt.inputs,onInput:l=>tt(K.agentId,{prompt:{...K.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:K.prompt.outputContract,onInput:l=>tt(K.agentId,{prompt:{...K.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:K.prompt.guardrails,onInput:l=>tt(K.agentId,{prompt:{...K.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(K.prompt)||"Prompt preview will appear here."})]})]}):e(je,{text:"Select or add an agent to edit it."})})]})]})})})}const xu=`defaults:
|
|
1861
|
+
schedulePreset: Every morning
|
|
1862
|
+
mode: team
|
|
1863
|
+
maxAgents: "4"
|
|
1864
|
+
steps:
|
|
1865
|
+
- What?
|
|
1866
|
+
- When?
|
|
1867
|
+
- How?
|
|
1868
|
+
- Review
|
|
1869
|
+
goalExamples:
|
|
1870
|
+
- Check my email every morning and send me a summary of what's important
|
|
1871
|
+
- Monitor GitHub issues and post daily standup updates to Slack
|
|
1872
|
+
- Summarize my calendar each Sunday and plan the upcoming week
|
|
1873
|
+
- Watch for price changes on competitor products and alert me
|
|
1874
|
+
- Generate a weekly report from our Notion workspace
|
|
1875
|
+
schedulePresets:
|
|
1876
|
+
- label: Every hour
|
|
1877
|
+
desc: Good for monitoring & alerts
|
|
1878
|
+
icon: "⏰"
|
|
1879
|
+
cron: ""
|
|
1880
|
+
intervalSeconds: 3600
|
|
1881
|
+
- label: Every morning
|
|
1882
|
+
desc: Daily digest at 9 AM
|
|
1883
|
+
icon: "☀️"
|
|
1884
|
+
cron: "0 9 * * *"
|
|
1885
|
+
- label: Every evening
|
|
1886
|
+
desc: End-of-day summary at 6 PM
|
|
1887
|
+
icon: "🌙"
|
|
1888
|
+
cron: "0 18 * * *"
|
|
1889
|
+
- label: Daily at midnight
|
|
1890
|
+
desc: Nightly data processing
|
|
1891
|
+
icon: "🔄"
|
|
1892
|
+
cron: "0 0 * * *"
|
|
1893
|
+
- label: Weekly Monday
|
|
1894
|
+
desc: Weekly reports & reviews
|
|
1895
|
+
icon: "📋"
|
|
1896
|
+
cron: "0 9 * * 1"
|
|
1897
|
+
- label: Manual only
|
|
1898
|
+
desc: Run whenever you want
|
|
1899
|
+
icon: "🎯"
|
|
1900
|
+
cron: ""
|
|
1901
|
+
executionModes:
|
|
1902
|
+
- id: single
|
|
1903
|
+
label: Single Agent
|
|
1904
|
+
icon: "🤖"
|
|
1905
|
+
desc: One focused AI handles the whole task
|
|
1906
|
+
bestFor: Simple, well-defined tasks
|
|
1907
|
+
- id: team
|
|
1908
|
+
label: Agent Team
|
|
1909
|
+
icon: "👥"
|
|
1910
|
+
desc: Multiple specialized AIs collaborate with a planner and workers
|
|
1911
|
+
bestFor: Complex multi-step tasks (recommended)
|
|
1912
|
+
- id: swarm
|
|
1913
|
+
label: Swarm
|
|
1914
|
+
icon: "🐝"
|
|
1915
|
+
desc: A swarm of AIs work in parallel on sub-tasks
|
|
1916
|
+
bestFor: Large-scale parallel work
|
|
1917
|
+
`;function Qi(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 ku(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 Nu(a,t){const n=Qi(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 _u(a,t){const n=Qi(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 Hi(a){const t=ku(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=>Nu(x,t[String(x?.id||"").trim()])).filter(x=>x.id),d=s.map(x=>_u(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 M=u.get(x.id);M&&u.set(x.id,{...M,session_id:M.session_id||x.session_id,runtime_status:M.runtime_status||x.runtime_status,runtime_detail:M.runtime_detail||x.runtime_detail,assigned_role:M.assigned_role||x.assigned_role,error_message:M.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||"",D=c.length?d.length?"hybrid":(n.length,"blackboard"):d.length?"context_steps":"empty";return{currentTaskId:N,taskSource:D,tasks:p}}const Su={created:"Created",pending:"Pending",runnable:"Runnable",assigned:"Assigned",in_progress:"In Progress",blocked:"Blocked",done:"Done",failed:"Failed",validated:"Validated"};function Iu(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 Cu(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 Au(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 Ls({task:a,isCurrent:t,isSelected:n,workflowSummary:r,onTaskSelect:s,onRetryTask:c}){const[d,u]=y(!1),p=a.state==="failed"||a.state==="blocked"?String(a.error_message||"").trim():"";return e("div",{className:`cursor-pointer rounded-lg border p-2 ${Cu(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:`${Iu(a.state)} inline-flex shrink-0 items-center gap-1`,children:[Au(a.state),e("span",{children:Su[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 Gi({tasks:a,currentTaskId:t,selectedTaskId:n,workflowSummaryByTaskId:r,onTaskSelect:s,onRetryTask:c}){const[d,u]=y("runnable"),p=Rt(null),N=Rt({}),D=B(()=>{const I={created:[],pending:[],runnable:[],assigned:[],in_progress:[],blocked:[],done:[],failed:[],validated:[]};for(const C of a)I[C.state].push(C);const Q=new Set([...I.done,...I.validated].map(C=>C.id)),ee=[...I.runnable],ce=[];for(const C of[...I.created,...I.pending])C.dependencies.length===0||C.dependencies.every(O=>Q.has(O))?ee.push(C):ce.push(C);return{runnable:ee,waiting:ce,assigned:I.assigned,in_progress:I.in_progress,blocked:I.blocked,done:[...I.done,...I.validated],failed:I.failed}},[a]),x=[{key:"runnable",label:"Ready",tasks:D.runnable},{key:"waiting",label:"Waiting on deps",tasks:D.waiting},{key:"assigned",label:"Assigned",tasks:D.assigned},{key:"in_progress",label:"In Progress",tasks:D.in_progress},{key:"blocked",label:"Blocked",tasks:D.blocked},{key:"done",label:"Done",tasks:D.done},{key:"failed",label:"Failed",tasks:D.failed}],M=B(()=>{const I=x.find(Q=>Q.tasks.some(ee=>ee.id===t));return I?I.key:x.find(Q=>Q.tasks.length>0)?.key||"runnable"},[x,t]),E=M;fe(()=>{u(I=>x.some(Q=>Q.key===I)?I:M)},[x,M]);const S=I=>{const Q=N.current[I];Q&&Q.scrollIntoView({behavior:"smooth",inline:"start",block:"nearest"})},W=()=>{E&&S(E)};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(E),children:"Jump to active task"}):null}),e("div",{className:"flex gap-2 overflow-x-auto pb-1",children:x.map(I=>{const Q=I.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(I.key),children:[I.label," (",I.tasks.length,")"]},I.key)})}),x.filter(I=>I.key===d).map(I=>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:I.label}),e("div",{className:"tcp-subtle text-xs",children:I.tasks.length})]}),e("div",{className:"grid gap-2",children:[I.tasks.map(Q=>e(Ls,{task:Q,isCurrent:Q.id===t,isSelected:Q.id===n,workflowSummary:r?.[Q.id],onTaskSelect:s,onRetryTask:c},Q.id)),I.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},I.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:W,children:"Jump to active task"}):null,e("div",{className:"flex flex-wrap gap-2",children:x.map(I=>{const Q=I.key===E;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:()=>S(I.key),children:[I.label," (",I.tasks.length,")"]},`desktop-tab-${I.key}`)})})]}),e("div",{ref:p,className:"overflow-x-auto pb-2",children:e("div",{className:"flex min-w-max gap-3",children:x.map(I=>e("div",{ref:Q=>{N.current[I.key]=Q},className:`min-h-[16rem] w-[320px] shrink-0 rounded-xl border p-2 ${I.key===E?"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:I.label}),e("div",{className:"tcp-subtle text-xs",children:I.tasks.length})]}),e("div",{className:"grid gap-2",children:[I.tasks.map(Q=>e(Ls,{task:Q,isCurrent:Q.id===t,isSelected:Q.id===n,workflowSummary:r?.[Q.id],onTaskSelect:s,onRetryTask:c},Q.id)),I.tasks.length?null:e("div",{className:"tcp-subtle text-xs",children:"No tasks"})]})]},I.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 ts(a,t,{withCredentials:n.withCredentials})},[t,n.enabled,n.withCredentials,a])}const Pu=`id: agentic-design
|
|
1918
|
+
label: Agentic Design
|
|
1919
|
+
description: Design a multi-agent workflow with explicit orchestration, gates, and operator controls.
|
|
1920
|
+
blueprint:
|
|
1921
|
+
mission_id: mission_agentic_design
|
|
1922
|
+
title: Agentic system design mission
|
|
1923
|
+
goal: Design a multi-agent workflow for a target operation, including orchestration, handoffs, models, tools, and safeguards.
|
|
1924
|
+
success_criteria:
|
|
1925
|
+
- Agent roles and responsibilities are clearly defined
|
|
1926
|
+
- Handoffs, gates, and dependencies are explicit
|
|
1927
|
+
- The design includes observability, stop controls, and repair flow
|
|
1928
|
+
shared_context: This is a design mission, not code generation. Optimize for robust orchestration, role clarity, bounded autonomy, and human trust. Make model/tool choices explicit where they matter.
|
|
1929
|
+
workspace_root: ""
|
|
1930
|
+
orchestrator_template_id: ""
|
|
1931
|
+
phases:
|
|
1932
|
+
- phase_id: architecture
|
|
1933
|
+
title: Architecture
|
|
1934
|
+
execution_mode: soft
|
|
1935
|
+
- phase_id: governance
|
|
1936
|
+
title: Governance
|
|
1937
|
+
execution_mode: barrier
|
|
1938
|
+
milestones:
|
|
1939
|
+
- milestone_id: design-basis-ready
|
|
1940
|
+
title: Design basis ready
|
|
1941
|
+
phase_id: architecture
|
|
1942
|
+
required_stage_ids:
|
|
1943
|
+
- role-design
|
|
1944
|
+
- flow-design
|
|
1945
|
+
team:
|
|
1946
|
+
allowed_template_ids: []
|
|
1947
|
+
default_model_policy: null
|
|
1948
|
+
allowed_mcp_servers: []
|
|
1949
|
+
max_parallel_agents: 4
|
|
1950
|
+
mission_budget: {}
|
|
1951
|
+
orchestrator_only_tool_calls: false
|
|
1952
|
+
workstreams:
|
|
1953
|
+
- workstream_id: role-design
|
|
1954
|
+
title: Role and agent design
|
|
1955
|
+
objective: Define the orchestrator and worker roles with clear responsibilities and escalation boundaries.
|
|
1956
|
+
role: architect
|
|
1957
|
+
prompt: Design the agent roles for this system. Define the orchestrator, specialized workers, reviewers, testers, and approval actors. Be explicit about what each role owns, when it should escalate, and what outputs it produces.
|
|
1958
|
+
priority: 1
|
|
1959
|
+
phase_id: architecture
|
|
1960
|
+
lane: roles
|
|
1961
|
+
milestone: design-basis-ready
|
|
1962
|
+
depends_on: []
|
|
1963
|
+
input_refs: []
|
|
1964
|
+
tool_allowlist_override: []
|
|
1965
|
+
mcp_servers_override: []
|
|
1966
|
+
output_contract:
|
|
1967
|
+
kind: report_markdown
|
|
1968
|
+
summary_guidance: Agent roster, role boundaries, escalation points, and expected outputs.
|
|
1969
|
+
- workstream_id: flow-design
|
|
1970
|
+
title: Flow and handoff design
|
|
1971
|
+
objective: Design the mission graph, dependencies, handoffs, and artifact contracts.
|
|
1972
|
+
role: analyst
|
|
1973
|
+
prompt: Design the multi-agent workflow graph. Specify phases, dependencies, artifact contracts, fan-out and fan-in points, and where review or approval gates should exist. Make the handoffs explicit and operationally understandable.
|
|
1974
|
+
priority: 1
|
|
1975
|
+
phase_id: architecture
|
|
1976
|
+
lane: flow
|
|
1977
|
+
milestone: design-basis-ready
|
|
1978
|
+
depends_on: []
|
|
1979
|
+
input_refs: []
|
|
1980
|
+
tool_allowlist_override: []
|
|
1981
|
+
mcp_servers_override: []
|
|
1982
|
+
output_contract:
|
|
1983
|
+
kind: report_markdown
|
|
1984
|
+
summary_guidance: Mission graph, dependencies, handoffs, and output contracts.
|
|
1985
|
+
- workstream_id: governance-design
|
|
1986
|
+
title: Governance and safety design
|
|
1987
|
+
objective: Define runtime controls, observability, kill switches, and repair mechanisms.
|
|
1988
|
+
role: coordinator
|
|
1989
|
+
prompt: Design the governance layer for the system. Specify approval gates, model and tool boundaries, logging, token or budget guardrails, kill switch semantics, pause and resume behavior, and step-level repair expectations.
|
|
1990
|
+
priority: 1
|
|
1991
|
+
phase_id: governance
|
|
1992
|
+
lane: governance
|
|
1993
|
+
depends_on:
|
|
1994
|
+
- role-design
|
|
1995
|
+
- flow-design
|
|
1996
|
+
input_refs: []
|
|
1997
|
+
tool_allowlist_override: []
|
|
1998
|
+
mcp_servers_override: []
|
|
1999
|
+
output_contract:
|
|
2000
|
+
kind: plan_markdown
|
|
2001
|
+
summary_guidance: Safety model, review points, observability, recovery, and operator controls.
|
|
2002
|
+
review_stages:
|
|
2003
|
+
- stage_id: design-approval
|
|
2004
|
+
stage_kind: approval
|
|
2005
|
+
title: Agentic design review
|
|
2006
|
+
target_ids:
|
|
2007
|
+
- governance-design
|
|
2008
|
+
role: approver
|
|
2009
|
+
prompt: Review the complete agentic design for coherence. Reject designs with unclear role boundaries, missing observability, or unbounded autonomy.
|
|
2010
|
+
checklist:
|
|
2011
|
+
- Role boundaries are clear
|
|
2012
|
+
- Handoffs and gates are explicit
|
|
2013
|
+
- Safety and repair paths are credible
|
|
2014
|
+
priority: 1
|
|
2015
|
+
phase_id: governance
|
|
2016
|
+
lane: approval
|
|
2017
|
+
tool_allowlist_override: []
|
|
2018
|
+
mcp_servers_override: []
|
|
2019
|
+
gate:
|
|
2020
|
+
required: true
|
|
2021
|
+
decisions:
|
|
2022
|
+
- approve
|
|
2023
|
+
- rework
|
|
2024
|
+
- cancel
|
|
2025
|
+
rework_targets:
|
|
2026
|
+
- governance-design
|
|
2027
|
+
instructions: Use rework if the design lacks control boundaries, clear outputs, or repairability.
|
|
2028
|
+
metadata: null
|
|
2029
|
+
`,Tu=`id: ai-opportunity
|
|
2030
|
+
label: AI Opportunities
|
|
2031
|
+
description: Map workflow pain points to realistic AI, copilot, and agentic opportunities.
|
|
2032
|
+
blueprint:
|
|
2033
|
+
mission_id: mission_ai_opportunity
|
|
2034
|
+
title: AI opportunity assessment
|
|
2035
|
+
goal: Identify the highest-value AI opportunities in the target business process and produce a prioritized implementation brief.
|
|
2036
|
+
success_criteria:
|
|
2037
|
+
- Workflow bottlenecks and repetitive work are identified
|
|
2038
|
+
- AI opportunities are ranked by value, feasibility, and risk
|
|
2039
|
+
- Final brief recommends concrete next pilots
|
|
2040
|
+
shared_context: Audience is operators and product leadership. Focus on realistic AI leverage, not hype. Separate automation, copilots, and fully agentic opportunities. Flag data, tooling, and approval constraints explicitly.
|
|
2041
|
+
workspace_root: ""
|
|
2042
|
+
orchestrator_template_id: ""
|
|
2043
|
+
phases:
|
|
2044
|
+
- phase_id: discovery
|
|
2045
|
+
title: Discovery
|
|
2046
|
+
execution_mode: soft
|
|
2047
|
+
- phase_id: recommendation
|
|
2048
|
+
title: Recommendation
|
|
2049
|
+
execution_mode: barrier
|
|
2050
|
+
milestones:
|
|
2051
|
+
- milestone_id: opportunity-map-ready
|
|
2052
|
+
title: Opportunity map ready
|
|
2053
|
+
phase_id: discovery
|
|
2054
|
+
required_stage_ids:
|
|
2055
|
+
- workflow-analysis
|
|
2056
|
+
- capability-map
|
|
2057
|
+
team:
|
|
2058
|
+
allowed_template_ids: []
|
|
2059
|
+
default_model_policy: null
|
|
2060
|
+
allowed_mcp_servers: []
|
|
2061
|
+
max_parallel_agents: 4
|
|
2062
|
+
mission_budget: {}
|
|
2063
|
+
orchestrator_only_tool_calls: false
|
|
2064
|
+
workstreams:
|
|
2065
|
+
- workstream_id: workflow-analysis
|
|
2066
|
+
title: Workflow analysis
|
|
2067
|
+
objective: Break down the current workflow, identify friction, handoffs, delays, and repeated manual work.
|
|
2068
|
+
role: analyst
|
|
2069
|
+
prompt: Act as an AI workflow analyst. Map the current workflow step by step, identify where humans are spending time, where handoffs fail, where decisions bottleneck, and where information must be gathered, transformed, or checked. Produce a workflow analysis memo that distinguishes repetitive work, judgment-heavy work, and coordination-heavy work.
|
|
2070
|
+
priority: 1
|
|
2071
|
+
phase_id: discovery
|
|
2072
|
+
lane: workflow
|
|
2073
|
+
milestone: opportunity-map-ready
|
|
2074
|
+
depends_on: []
|
|
2075
|
+
input_refs: []
|
|
2076
|
+
tool_allowlist_override: []
|
|
2077
|
+
mcp_servers_override: []
|
|
2078
|
+
output_contract:
|
|
2079
|
+
kind: report_markdown
|
|
2080
|
+
summary_guidance: Workflow steps, bottlenecks, repeated work, approval points, and observed failure modes.
|
|
2081
|
+
- workstream_id: capability-map
|
|
2082
|
+
title: AI capability map
|
|
2083
|
+
objective: Match workflow problems to realistic AI patterns such as extraction, triage, drafting, routing, review, and autonomous follow-through.
|
|
2084
|
+
role: strategist
|
|
2085
|
+
prompt: Act as an agentic systems strategist. Review the workflow analysis context and map each major problem to practical AI patterns. Distinguish simple automation, LLM copilots, tool-using agents, and multi-agent orchestration. Be explicit about prerequisites, risks, and where human approval is still required.
|
|
2086
|
+
priority: 2
|
|
2087
|
+
phase_id: discovery
|
|
2088
|
+
lane: capability
|
|
2089
|
+
milestone: opportunity-map-ready
|
|
2090
|
+
depends_on: []
|
|
2091
|
+
input_refs: []
|
|
2092
|
+
tool_allowlist_override: []
|
|
2093
|
+
mcp_servers_override: []
|
|
2094
|
+
output_contract:
|
|
2095
|
+
kind: report_markdown
|
|
2096
|
+
summary_guidance: Problem-to-capability map with candidate AI patterns, prerequisites, and operational risks.
|
|
2097
|
+
- workstream_id: opportunity-brief
|
|
2098
|
+
title: Opportunity brief
|
|
2099
|
+
objective: Synthesize the findings into a prioritized AI opportunity brief with clear next pilots.
|
|
2100
|
+
role: analyst
|
|
2101
|
+
prompt: Synthesize the workflow analysis and capability map into an executive-ready AI opportunity brief. Rank candidates by expected value, implementation complexity, operator trust requirements, and data/tool prerequisites. Recommend the best near-term pilots and explain why weaker options were not prioritized.
|
|
2102
|
+
priority: 1
|
|
2103
|
+
phase_id: recommendation
|
|
2104
|
+
lane: synthesis
|
|
2105
|
+
depends_on:
|
|
2106
|
+
- workflow-analysis
|
|
2107
|
+
- capability-map
|
|
2108
|
+
input_refs: []
|
|
2109
|
+
tool_allowlist_override: []
|
|
2110
|
+
mcp_servers_override: []
|
|
2111
|
+
output_contract:
|
|
2112
|
+
kind: brief_markdown
|
|
2113
|
+
summary_guidance: Ranked AI opportunities, reasoning, operational implications, and recommended pilots.
|
|
2114
|
+
review_stages:
|
|
2115
|
+
- stage_id: opportunity-review
|
|
2116
|
+
stage_kind: review
|
|
2117
|
+
title: Feasibility and trust review
|
|
2118
|
+
target_ids:
|
|
2119
|
+
- opportunity-brief
|
|
2120
|
+
role: reviewer
|
|
2121
|
+
prompt: Review the opportunity brief for realism. Reject vague AI claims, hidden implementation assumptions, and missing trust or approval considerations. The brief should make clear what can be automated, what needs a copilot, and what still requires strong human judgment.
|
|
2122
|
+
checklist:
|
|
2123
|
+
- Opportunities are realistically scoped
|
|
2124
|
+
- Human approval needs are explicit
|
|
2125
|
+
- Recommended pilots are specific and actionable
|
|
2126
|
+
priority: 1
|
|
2127
|
+
phase_id: recommendation
|
|
2128
|
+
lane: review
|
|
2129
|
+
tool_allowlist_override: []
|
|
2130
|
+
mcp_servers_override: []
|
|
2131
|
+
metadata: null
|
|
2132
|
+
`,Ru=`id: automation-rollout
|
|
2133
|
+
label: Rollout
|
|
2134
|
+
description: Plan rollout, enablement, controls, and measurement for an automation initiative.
|
|
2135
|
+
blueprint:
|
|
2136
|
+
mission_id: mission_automation_rollout
|
|
2137
|
+
title: Automation rollout mission
|
|
2138
|
+
goal: Plan the rollout of an AI or agentic automation initiative across process, tooling, operating model, and measurement.
|
|
2139
|
+
success_criteria:
|
|
2140
|
+
- Rollout plan includes sequencing, owners, risks, and readiness needs
|
|
2141
|
+
- Metrics and operator controls are explicit
|
|
2142
|
+
- Human change-management needs are addressed
|
|
2143
|
+
shared_context: Optimize for actual operational rollout. Include enablement, communications, governance, training, and success measurement. Avoid purely technical plans.
|
|
2144
|
+
workspace_root: ""
|
|
2145
|
+
orchestrator_template_id: ""
|
|
2146
|
+
phases:
|
|
2147
|
+
- phase_id: readiness
|
|
2148
|
+
title: Readiness
|
|
2149
|
+
execution_mode: soft
|
|
2150
|
+
- phase_id: launch
|
|
2151
|
+
title: Launch
|
|
2152
|
+
execution_mode: barrier
|
|
2153
|
+
milestones: []
|
|
2154
|
+
team:
|
|
2155
|
+
allowed_template_ids: []
|
|
2156
|
+
default_model_policy: null
|
|
2157
|
+
allowed_mcp_servers: []
|
|
2158
|
+
max_parallel_agents: 4
|
|
2159
|
+
mission_budget: {}
|
|
2160
|
+
orchestrator_only_tool_calls: false
|
|
2161
|
+
workstreams:
|
|
2162
|
+
- workstream_id: process-readiness
|
|
2163
|
+
title: Process readiness
|
|
2164
|
+
objective: Define the target operating process, roles, and readiness gaps.
|
|
2165
|
+
role: operator
|
|
2166
|
+
prompt: Plan the operating-process changes required to adopt the automation. Identify role changes, review points, ownership, runbooks, and readiness blockers.
|
|
2167
|
+
priority: 1
|
|
2168
|
+
phase_id: readiness
|
|
2169
|
+
lane: operations
|
|
2170
|
+
depends_on: []
|
|
2171
|
+
input_refs: []
|
|
2172
|
+
tool_allowlist_override: []
|
|
2173
|
+
mcp_servers_override: []
|
|
2174
|
+
output_contract:
|
|
2175
|
+
kind: plan_markdown
|
|
2176
|
+
summary_guidance: Operating model changes, ownership, readiness blockers, and process notes.
|
|
2177
|
+
- workstream_id: platform-readiness
|
|
2178
|
+
title: Platform and tooling readiness
|
|
2179
|
+
objective: Define the tooling, integration, data, and observability requirements for launch.
|
|
2180
|
+
role: planner
|
|
2181
|
+
prompt: "Plan the platform requirements for rollout: integrations, tools, permissions, logs, metrics, data dependencies, guardrails, and monitoring expectations."
|
|
2182
|
+
priority: 1
|
|
2183
|
+
phase_id: readiness
|
|
2184
|
+
lane: platform
|
|
2185
|
+
depends_on: []
|
|
2186
|
+
input_refs: []
|
|
2187
|
+
tool_allowlist_override: []
|
|
2188
|
+
mcp_servers_override: []
|
|
2189
|
+
output_contract:
|
|
2190
|
+
kind: plan_markdown
|
|
2191
|
+
summary_guidance: Tooling, integrations, observability, and launch prerequisites.
|
|
2192
|
+
- workstream_id: launch-plan
|
|
2193
|
+
title: Rollout and adoption plan
|
|
2194
|
+
objective: Create the rollout sequence, communications, operator enablement, and measurement plan.
|
|
2195
|
+
role: coordinator
|
|
2196
|
+
prompt: Using the readiness work, create a rollout plan with phases, launch criteria, internal communications, operator training, fallback plans, and success metrics. Make the rollout sequence explicit.
|
|
2197
|
+
priority: 2
|
|
2198
|
+
phase_id: launch
|
|
2199
|
+
lane: rollout
|
|
2200
|
+
depends_on:
|
|
2201
|
+
- process-readiness
|
|
2202
|
+
- platform-readiness
|
|
2203
|
+
input_refs: []
|
|
2204
|
+
tool_allowlist_override: []
|
|
2205
|
+
mcp_servers_override: []
|
|
2206
|
+
output_contract:
|
|
2207
|
+
kind: plan_markdown
|
|
2208
|
+
summary_guidance: Rollout sequencing, enablement, communications, fallback, and success metrics.
|
|
2209
|
+
review_stages:
|
|
2210
|
+
- stage_id: launch-gate
|
|
2211
|
+
stage_kind: approval
|
|
2212
|
+
title: Launch readiness gate
|
|
2213
|
+
target_ids:
|
|
2214
|
+
- launch-plan
|
|
2215
|
+
role: approver
|
|
2216
|
+
prompt: Review the rollout plan for operational readiness. Confirm that controls, training, communications, fallback, and measurement are credible before launch.
|
|
2217
|
+
checklist:
|
|
2218
|
+
- Launch prerequisites are explicit
|
|
2219
|
+
- Operator enablement is covered
|
|
2220
|
+
- Fallback and measurement are defined
|
|
2221
|
+
priority: 1
|
|
2222
|
+
phase_id: launch
|
|
2223
|
+
lane: approval
|
|
2224
|
+
tool_allowlist_override: []
|
|
2225
|
+
mcp_servers_override: []
|
|
2226
|
+
gate:
|
|
2227
|
+
required: true
|
|
2228
|
+
decisions:
|
|
2229
|
+
- approve
|
|
2230
|
+
- rework
|
|
2231
|
+
- cancel
|
|
2232
|
+
rework_targets:
|
|
2233
|
+
- launch-plan
|
|
2234
|
+
instructions: Use rework if the rollout plan lacks readiness criteria, operator enablement, or fallback handling.
|
|
2235
|
+
metadata: null
|
|
2236
|
+
`,Mu=`id: workflow-audit
|
|
2237
|
+
label: Workflow Audit
|
|
2238
|
+
description: Audit an existing workflow and design a safer, observable automation model.
|
|
2239
|
+
blueprint:
|
|
2240
|
+
mission_id: mission_workflow_audit
|
|
2241
|
+
title: Workflow automation audit
|
|
2242
|
+
goal: Audit an existing workflow and produce a concrete automation design with failure points, control points, and implementation recommendations.
|
|
2243
|
+
success_criteria:
|
|
2244
|
+
- Current-state workflow is documented
|
|
2245
|
+
- Automation candidates include controls and failure handling
|
|
2246
|
+
- A practical implementation plan is produced
|
|
2247
|
+
shared_context: Focus on operational reliability. Make human approvals, logging needs, repair loops, and recovery paths explicit. Favor concrete workflow shapes over abstract transformation language.
|
|
2248
|
+
workspace_root: ""
|
|
2249
|
+
orchestrator_template_id: ""
|
|
2250
|
+
phases:
|
|
2251
|
+
- phase_id: audit
|
|
2252
|
+
title: Audit
|
|
2253
|
+
execution_mode: soft
|
|
2254
|
+
- phase_id: design
|
|
2255
|
+
title: Design
|
|
2256
|
+
execution_mode: barrier
|
|
2257
|
+
milestones:
|
|
2258
|
+
- milestone_id: audit-complete
|
|
2259
|
+
title: Audit complete
|
|
2260
|
+
phase_id: audit
|
|
2261
|
+
required_stage_ids:
|
|
2262
|
+
- current-state
|
|
2263
|
+
- failure-analysis
|
|
2264
|
+
team:
|
|
2265
|
+
allowed_template_ids: []
|
|
2266
|
+
default_model_policy: null
|
|
2267
|
+
allowed_mcp_servers: []
|
|
2268
|
+
max_parallel_agents: 4
|
|
2269
|
+
mission_budget: {}
|
|
2270
|
+
orchestrator_only_tool_calls: false
|
|
2271
|
+
workstreams:
|
|
2272
|
+
- workstream_id: current-state
|
|
2273
|
+
title: Current-state workflow
|
|
2274
|
+
objective: Document the current workflow, actors, triggers, tools, and handoffs.
|
|
2275
|
+
role: operator
|
|
2276
|
+
prompt: "Act as an operations architect. Document the workflow as it exists today: triggers, inputs, outputs, handoffs, approvals, tools, data dependencies, and places where work stalls or gets retried."
|
|
2277
|
+
priority: 1
|
|
2278
|
+
phase_id: audit
|
|
2279
|
+
lane: mapping
|
|
2280
|
+
milestone: audit-complete
|
|
2281
|
+
depends_on: []
|
|
2282
|
+
input_refs: []
|
|
2283
|
+
tool_allowlist_override: []
|
|
2284
|
+
mcp_servers_override: []
|
|
2285
|
+
output_contract:
|
|
2286
|
+
kind: report_markdown
|
|
2287
|
+
summary_guidance: Current-state workflow map, actors, tools, handoffs, and bottlenecks.
|
|
2288
|
+
- workstream_id: failure-analysis
|
|
2289
|
+
title: Failure and control analysis
|
|
2290
|
+
objective: Identify where workflow automation can fail, what needs approval, and what must be observable.
|
|
2291
|
+
role: reviewer
|
|
2292
|
+
prompt: Act as a workflow reliability reviewer. Inspect the current-state map and identify failure modes, ambiguous steps, risky autonomous actions, missing approvals, recovery gaps, and required logging or metrics.
|
|
2293
|
+
priority: 1
|
|
2294
|
+
phase_id: audit
|
|
2295
|
+
lane: controls
|
|
2296
|
+
milestone: audit-complete
|
|
2297
|
+
depends_on: []
|
|
2298
|
+
input_refs: []
|
|
2299
|
+
tool_allowlist_override: []
|
|
2300
|
+
mcp_servers_override: []
|
|
2301
|
+
output_contract:
|
|
2302
|
+
kind: brief_markdown
|
|
2303
|
+
summary_guidance: Failure modes, control points, approval needs, logging, and recovery requirements.
|
|
2304
|
+
- workstream_id: automation-design
|
|
2305
|
+
title: Automation design
|
|
2306
|
+
objective: Turn the audit into a practical automation architecture and rollout plan.
|
|
2307
|
+
role: planner
|
|
2308
|
+
prompt: Design the target workflow automation. Specify which steps remain human, which become deterministic automation, which should use agents, and where review gates, kill switches, repair loops, and observability are required. Produce a rollout plan that can be implemented incrementally.
|
|
2309
|
+
priority: 2
|
|
2310
|
+
phase_id: design
|
|
2311
|
+
lane: design
|
|
2312
|
+
depends_on:
|
|
2313
|
+
- current-state
|
|
2314
|
+
- failure-analysis
|
|
2315
|
+
input_refs: []
|
|
2316
|
+
tool_allowlist_override: []
|
|
2317
|
+
mcp_servers_override: []
|
|
2318
|
+
output_contract:
|
|
2319
|
+
kind: plan_markdown
|
|
2320
|
+
summary_guidance: Target workflow design, control model, observability plan, and incremental rollout steps.
|
|
2321
|
+
review_stages:
|
|
2322
|
+
- stage_id: automation-review
|
|
2323
|
+
stage_kind: approval
|
|
2324
|
+
title: Automation readiness review
|
|
2325
|
+
target_ids:
|
|
2326
|
+
- automation-design
|
|
2327
|
+
role: approver
|
|
2328
|
+
prompt: Review the automation design for realism, controllability, operator trust, and failure recovery. Reject designs that automate too aggressively without approvals or observability.
|
|
2329
|
+
checklist:
|
|
2330
|
+
- Control points are explicit
|
|
2331
|
+
- Failure recovery is defined
|
|
2332
|
+
- Rollout is incremental and realistic
|
|
2333
|
+
priority: 1
|
|
2334
|
+
phase_id: design
|
|
2335
|
+
lane: approval
|
|
2336
|
+
tool_allowlist_override: []
|
|
2337
|
+
mcp_servers_override: []
|
|
2338
|
+
gate:
|
|
2339
|
+
required: true
|
|
2340
|
+
decisions:
|
|
2341
|
+
- approve
|
|
2342
|
+
- rework
|
|
2343
|
+
- cancel
|
|
2344
|
+
rework_targets:
|
|
2345
|
+
- automation-design
|
|
2346
|
+
instructions: Approve only when the automation design is safe, observable, and realistically deployable.
|
|
2347
|
+
metadata: null
|
|
2348
|
+
`,qu={"ai-opportunity":"sparkles","workflow-audit":"workflow","agentic-design":"bot","automation-rollout":"arrow-up-circle"},$u=Object.assign({"../presets/mission-builder/agentic-design.yaml":Pu,"../presets/mission-builder/ai-opportunity.yaml":Tu,"../presets/mission-builder/automation-rollout.yaml":Ru,"../presets/mission-builder/workflow-audit.yaml":Mu});function Ou(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 Ks(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 Eu(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 Ws=Object.entries($u).map(([a,t])=>Eu(t,a)).sort((a,t)=>a.label.localeCompare(t.label,void 0,{sensitivity:"base"}));function Vi(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function Du(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=Vi(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 ju(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 Mn({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 Uu({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 Bu({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 Fu({value:a,error:t,open:n,browseDir:r,search:s,parentDir:c,currentDir:d,directories:u,onOpen:p,onClose:N,onClear:D,onSearchChange:x,onBrowseParent:M,onBrowseDirectory:E,onSelectDirectory:S}){const W=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:D,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:M,disabled:!c,children:[e("i",{"data-lucide":"arrow-left-to-line"}),"Up"]}),e("button",{className:"tcp-btn-primary",type:"button",onClick:S,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:I=>x(I.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(I=>e("button",{className:"tcp-list-item mb-1 w-full text-left",type:"button",onClick:()=>E(String(I?.path||"")),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(I?.name||I?.path||"")})]})},String(I?.path||I?.name))):e(Bu,{text:W?"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(D=>D.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 Lu({client:a,api:t,toast:n,defaultProvider:r,defaultModel:s,editingAutomation:c=null,onShowAutomations:d,onShowRuns:u,onClearEditing:p}){const N=ca(),D=Rt(null),[x,M]=y("mission"),[E,S]=y("manual"),[W,I]=y("3600"),[Q,ee]=y(""),[ce,C]=y(!0),[P,O]=y(""),[A,ve]=y(""),[z,k]=y(null),[v,te]=y(""),[H,Pe]=y(Za("")),[$e,Le]=y({provider:r,model:s}),[re,pe]=y({}),[q,ge]=y({}),[Te,Re]=y(!1),[se,Oe]=y(!1),[qe,He]=y(""),[Y,Ze]=y(""),ne=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}),K=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",qe],enabled:se&&!!qe,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(qe)}`,{method:"GET"})});fe(()=>{const l=String(lt.data?.workspaceRoot||lt.data?.workspace_root||"").trim();l&&(te(l),Pe(b=>b.workspace_root?b:{...Za(l),workspace_root:l}))},[lt.data]),fe(()=>{const l=v||String(lt.data?.workspaceRoot||lt.data?.workspace_root||"").trim();if(!c){Pe(Za(l)),k(null),O(""),C(!0),S("manual"),I("3600"),ee(""),Le({provider:r,model:s}),pe({}),ge({});return}const b=ju(c,l);if(!b)return;Pe(b),Le(qr(b.team.default_model_policy));const T={};for(const Xe of b.workstreams)T[Xe.workstream_id]=qr(Xe.model_override);pe(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"?(S("cron"),ee(String($?.cron_expression||"").trim())):Ye==="interval"?(S("interval"),I(String($?.interval_seconds||3600))):(S("manual"),ee(""),I("3600")),C(!1),k(null),O("")},[c?.automation_id,v,r,s,lt.data]);const rt=B(()=>{const l=Array.isArray(ne.data?.all)?ne.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,ne.data,Ae.data]),Et=B(()=>Ou(St.data),[St.data]),Fe=B(()=>(Array.isArray(oe.data)?oe.data:[]).map(l=>String(l||"").trim()).filter(Boolean).sort(),[oe.data]),Bt=B(()=>(Array.isArray(K.data)?K.data:[]).map(l=>({template_id:String(l?.template_id||l?.templateId||"").trim(),role:String(l?.role||"").trim()})).filter(l=>l.template_id),[K.data]),At=Array.isArray(xt.data?.directories)?xt.data.directories:[],$t=String(xt.data?.parent||"").trim(),We=String(xt.data?.dir||qe||"").trim(),ze=B(()=>{const l=String(Y||"").trim().toLowerCase();return l?At.filter(b=>String(b?.name||b?.path||"").trim().toLowerCase().includes(l)):At},[Y,At]),tt=Vi(H.workspace_root||v);fe(()=>{try{D.current?xa(D.current):xa()}catch{}},[x,Te,z,A,H,$e,re,q]);const be=B(()=>({...H,workspace_root:H.workspace_root||v,team:{...H.team,default_model_policy:Mr($e)},workstreams:H.workstreams.map(l=>({...l,model_override:Mr(re[l.workstream_id]||{provider:"",model:""})})),review_stages:H.review_stages.map(l=>({...l,model_override:Mr(q[l.stage_id]||{provider:"",model:""})}))}),[H,v,$e,re,q]),Se=B(()=>Du(be),[be]),Ve=B(()=>[...be.workstreams.map(l=>l.workstream_id),...be.review_stages.map(l=>l.stage_id)],[be]);function de(l){Pe(b=>({...b,...l})),k(null)}function dt(){Pe(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:""}}]})),k(null)}function _(){Pe(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:""}}]})),k(null)}function G(l){const b=Ws.find(R=>R.id===l);if(!b)return;const T={...Za(H.workspace_root||v),...b.blueprint,mission_id:`mission_${crypto.randomUUID().slice(0,8)}`,workspace_root:H.workspace_root||v};Pe(T),k(null),O(""),M("mission"),Le({provider:r,model:s}),pe({}),ge({}),n("info",`Loaded ${b.label}. Review the prompts and adapt them to your mission.`)}async function me(){if(Se.length){const l=Se.join(" ");O(l),n("err",l),M("mission");return}ve("preview"),O("");try{const l=await t("/api/engine/mission-builder/compile-preview",{method:"POST",body:JSON.stringify({blueprint:be,schedule:Ks(E,W,Q)})});k(l),M("compile")}catch(l){const b=l instanceof Error?l.message:String(l||""),T=b==="mission blueprint validation failed"&&Se.length?Se.join(" "):b;O(T),n("err",T)}finally{ve("")}}async function Ke(){if(Se.length){const l=Se.join(" ");O(l),n("err",l),M("mission");return}ve("apply"),O("");try{const l=Ks(E,W,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();ce&&T?(await a.automationsV2.runNow(T),n("ok","Advanced mission created and started."),u()):(n("ok","Advanced mission created."),d()),Pe(Za(v)),k(null),C(!0)}catch(l){const b=l instanceof Error?l.message:String(l||""),T=b==="mission blueprint validation failed"&&Se.length?Se.join(" "):b;O(T),n("err",T)}finally{ve("")}}return e("div",{ref:D,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:()=>Re(!0),children:[e("i",{"data-lucide":"book-open"}),"How this works"]}),e("span",{className:"tcp-subtle text-xs",children:"Start from example:"}),Ws.map(l=>e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>G(l.id),children:[e("i",{"data-lucide":qu[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(Uu,{active:x===l,label:l==="workstreams"?"workstreams":l,icon:b,onClick:()=>M(l)},l))})]}),P?e("div",{className:"rounded-xl border border-red-500/40 bg-red-500/10 p-3 text-sm text-red-200",children:P}):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,Te?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:()=>Re(!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:H.title,onInput:l=>de({title:l})}),e(wt,{label:"Mission ID",value:H.mission_id,onInput:l=>de({mission_id:l})})]}),e(ta,{children:"Use a short title a human operator would recognize later in the automation list."}),e(Fu,{value:H.workspace_root,error:tt,open:se,browseDir:qe,search:Y,parentDir:$t,currentDir:We,directories:ze,onOpen:()=>{const l=String(H.workspace_root||v||"/").trim();He(l||"/"),Ze(""),Oe(!0)},onClose:()=>{Oe(!1),Ze("")},onClear:()=>de({workspace_root:""}),onSearchChange:Ze,onBrowseParent:()=>{$t&&He($t)},onBrowseDirectory:l=>He(l),onSelectDirectory:()=>{We&&(de({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(Mn,{label:"Mission goal",value:H.goal,onInput:l=>de({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(Mn,{label:"Shared context",value:H.shared_context||"",onInput:l=>de({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:H.success_criteria.join(", "),onInput:l=>de({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:E,onInput:l=>S(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"})]})]}),E==="interval"?e(wt,{label:"Interval seconds",value:W,onInput:I}):null,E==="cron"?e(wt,{label:"Cron expression",value:Q,onInput:ee}):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:H.orchestrator_template_id||"",onInput:l=>de({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:(H.team.allowed_template_ids||[]).join(", "),onInput:l=>de({team:{...H.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(H.team.max_parallel_agents||4),onInput:l=>de({team:{...H.team,max_parallel_agents:Math.max(1,Number.parseInt(String(l||"4"),10)||4)}}),type:"number"}),e(wt,{label:"Token ceiling",value:String(H.team.mission_budget?.max_total_tokens||""),onInput:l=>de({team:{...H.team,mission_budget:{...H.team.mission_budget||{},max_total_tokens:l?Number(l):void 0}}}),type:"number"}),e(wt,{label:"Cost ceiling USD",value:String(H.team.mission_budget?.max_total_cost_usd||""),onInput:l=>de({team:{...H.team,mission_budget:{...H.team.mission_budget||{},max_total_cost_usd:l?Number(l):void 0}}}),type:"number"}),e(wt,{label:"Tool-call ceiling",value:String(H.team.mission_budget?.max_total_tool_calls||""),onInput:l=>de({team:{...H.team,mission_budget:{...H.team.mission_budget||{},max_total_tool_calls:l?Number(l):void 0}}}),type:"number"})]}),e(wt,{label:"Allowed MCP servers",value:(H.team.allowed_mcp_servers||[]).join(", "),onInput:l=>de({team:{...H.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:()=>de({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=>de({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,title:R}:$)})}),e(wt,{label:"Role",value:l.role,onInput:R=>de({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=>de({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,phase_id:R}:$)})}),e(wt,{label:"Lane",value:l.lane||"",onInput:R=>de({workstreams:be.workstreams.map($=>$.workstream_id===l.workstream_id?{...$,lane:R}:$)})}),e(wt,{label:"Priority",value:String(l.priority||0),onInput:R=>de({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(Mn,{label:"Objective",value:l.objective,onInput:R=>de({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(Mn,{label:"Prompt",value:l.prompt,onInput:R=>de({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=>de({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=>de({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=>de({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=>de({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=>pe($=>({...$,[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:_,children:[e("i",{"data-lucide":"plus"}),"Add review stage"]}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>de({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=>de({phases:be.phases.map((R,$)=>$===b?{...R,phase_id:T}:R)})}),e(wt,{label:"Title",value:l.title,onInput:T=>de({phases:be.phases.map((R,$)=>$===b?{...R,title:T}:R)})}),e(wt,{label:"Description",value:l.description||"",onInput:T=>de({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=>de({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:()=>de({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=>de({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=>de({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=>de({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=>de({review_stages:be.review_stages.map($=>$.stage_id===l.stage_id?{...$,phase_id:R}:$)})}),e(wt,{label:"Lane",value:l.lane||"",onInput:R=>de({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(Mn,{label:"Prompt",value:l.prompt,onInput:R=>de({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=>de({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=>de({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:A==="preview",onClick:()=>{me()},children:[e("i",{"data-lucide":"refresh-cw"}),A==="preview"?"Compiling...":"Compile preview"]}),e("button",{className:"tcp-btn-primary h-8 px-3 text-xs",disabled:A==="apply",onClick:()=>{Ke()},children:[e("i",{"data-lucide":c?"save":"arrow-up-circle"}),A==="apply"?"Saving...":c?"Save automation":ce?"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:ce,onChange:l=>C(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]}),z?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(z?.validation)&&z.validation.length?e("div",{className:"grid gap-2",children:z.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(z?.automation?.name||"—")]}),e("div",{children:["nodes:"," ",Array.isArray(z?.automation?.flow?.nodes)?z.automation.flow.nodes.length:0]}),e("div",{children:["agents:"," ",Array.isArray(z?.automation?.agents)?z.automation.agents.length:0]}),e("div",{children:["max parallel:"," ",String(z?.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(z?.node_previews)?z.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 Ku=`kind: extract_format
|
|
2349
|
+
description: Two-node validator-backed workflow for cheap optimization smoke tests.
|
|
2350
|
+
status: draft
|
|
2351
|
+
schedule:
|
|
2352
|
+
type: manual
|
|
2353
|
+
timezone: UTC
|
|
2354
|
+
misfire_policy: skip
|
|
2355
|
+
agents:
|
|
2356
|
+
- agent_id: agent-1
|
|
2357
|
+
display_name: Extractor
|
|
2358
|
+
skills: []
|
|
2359
|
+
tool_policy:
|
|
2360
|
+
allowlist: []
|
|
2361
|
+
denylist: []
|
|
2362
|
+
mcp_policy:
|
|
2363
|
+
allowed_servers: []
|
|
2364
|
+
execution: {}
|
|
2365
|
+
output_targets: []
|
|
2366
|
+
creator_id: optimization-smoke-pack
|
|
2367
|
+
workspace_root: ""
|
|
2368
|
+
automation_id: wf-smoke-extract-format
|
|
2369
|
+
name: Smoke Extract Format Workflow
|
|
2370
|
+
flow:
|
|
2371
|
+
nodes:
|
|
2372
|
+
- node_id: node-1
|
|
2373
|
+
agent_id: agent-1
|
|
2374
|
+
objective: Extract the key facts only.
|
|
2375
|
+
depends_on: []
|
|
2376
|
+
input_refs: []
|
|
2377
|
+
retry_policy:
|
|
2378
|
+
max_attempts: 1
|
|
2379
|
+
timeout_ms: 45000
|
|
2380
|
+
- node_id: node-2
|
|
2381
|
+
agent_id: agent-1
|
|
2382
|
+
objective: Format the extracted facts into a short structured answer.
|
|
2383
|
+
depends_on:
|
|
2384
|
+
- node-1
|
|
2385
|
+
input_refs:
|
|
2386
|
+
- from_step_id: node-1
|
|
2387
|
+
alias: facts
|
|
2388
|
+
output_contract:
|
|
2389
|
+
kind: formatted_answer
|
|
2390
|
+
validator: structured_json
|
|
2391
|
+
summary_guidance: Return a small structured artifact with stable fields.
|
|
2392
|
+
retry_policy:
|
|
2393
|
+
max_attempts: 1
|
|
2394
|
+
timeout_ms: 60000
|
|
2395
|
+
`,Wu=`kind: summary
|
|
2396
|
+
description: Single-node validator-backed workflow for cheap optimization smoke tests.
|
|
2397
|
+
status: draft
|
|
2398
|
+
schedule:
|
|
2399
|
+
type: manual
|
|
2400
|
+
timezone: UTC
|
|
2401
|
+
misfire_policy: skip
|
|
2402
|
+
agents:
|
|
2403
|
+
- agent_id: agent-1
|
|
2404
|
+
display_name: Summarizer
|
|
2405
|
+
skills: []
|
|
2406
|
+
tool_policy:
|
|
2407
|
+
allowlist: []
|
|
2408
|
+
denylist: []
|
|
2409
|
+
mcp_policy:
|
|
2410
|
+
allowed_servers: []
|
|
2411
|
+
execution: {}
|
|
2412
|
+
output_targets: []
|
|
2413
|
+
creator_id: optimization-smoke-pack
|
|
2414
|
+
workspace_root: ""
|
|
2415
|
+
automation_id: wf-smoke-summary
|
|
2416
|
+
name: Smoke Summary Workflow
|
|
2417
|
+
flow:
|
|
2418
|
+
nodes:
|
|
2419
|
+
- node_id: node-1
|
|
2420
|
+
agent_id: agent-1
|
|
2421
|
+
objective: Write a clear report for the team
|
|
2422
|
+
depends_on: []
|
|
2423
|
+
input_refs: []
|
|
2424
|
+
output_contract:
|
|
2425
|
+
kind: summary
|
|
2426
|
+
validator: generic_artifact
|
|
2427
|
+
summary_guidance: Return a short, clean artifact that a validator can check.
|
|
2428
|
+
retry_policy:
|
|
2429
|
+
max_attempts: 1
|
|
2430
|
+
timeout_ms: 60000
|
|
2431
|
+
`;function Or(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function zs(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 zu=Object.assign({"./smoke-workflows/extract-format.yaml":Ku,"./smoke-workflows/summary.yaml":Wu}),Ju=Object.entries(zu).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 Qu(a,t){const n=Ju.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 Hu({client:a,toast:t}){const n=ca(),[r,s]=y(""),[c,d]=y({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}),D=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}),M=B(()=>Or(p.data,"optimizations"),[p.data]),E=B(()=>{const k=Array.isArray(D.data?.all)?D.data.all:[],v=x.data?.providers||{};return k.map(te=>({id:String(te?.id||"").trim(),models:Object.keys(te?.models||{}).sort(),configured:!!v[String(te?.id||"").trim()]})).filter(te=>te.id).sort((te,H)=>te.id.localeCompare(H.id))},[D.data,x.data]),S=B(()=>{const k=E.find(v=>v.id===String(c.modelProvider||"").trim());return Array.isArray(k?.models)?k.models:[]},[c.modelProvider,E]);fe(()=>{const k=String(N.data?.workspaceRoot||N.data?.workspace_root||"").trim();k&&d(v=>String(v.smokeWorkspaceRoot||"").trim()?v:{...v,smokeWorkspaceRoot:`${k}/docs/internal/optimization-smoke-pack`})},[N.data]);const W=r||String(M[0]?.optimization_id||"").trim(),I=V({queryKey:["optimizations","detail",W],enabled:!!W,queryFn:()=>a.optimizations.get(W)}),Q=V({queryKey:["optimizations","experiments",W],enabled:!!W,queryFn:()=>a.optimizations.listExperiments(W)}),ee=ke({mutationFn:async()=>{const k=String(c.sourceWorkflowId||"").trim();if(!k)throw new Error("Source workflow is required.");const v={name:String(c.name||"").trim()||void 0,source_workflow_id:k,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},te=await a.optimizations.create(v);if(c.startImmediately){const H=String(te?.optimization?.optimization_id||"").trim();H&&await a.optimizations.action(H,{action:"start"})}return te},onSuccess:async k=>{const v=String(k?.optimization?.optimization_id||"").trim();t("ok","Optimization campaign created."),v&&s(v),await n.invalidateQueries({queryKey:["optimizations"]})},onError:k=>t("err",k instanceof Error?k.message:String(k))}),ce=ke({mutationFn:async k=>{const v=String(c.smokeWorkspaceRoot||"").trim();if(!v)throw new Error("Smoke workflow workspace root is required.");if(!a?.automationsV2?.create)throw new Error("Workflow creation client is unavailable.");const te=Qu(k,v);return a.automationsV2.create(te)},onSuccess:async(k,v)=>{const te=String(k?.automation?.automation_id||k?.automation?.automationId||"").trim();d(H=>({...H,sourceWorkflowId:te||H.sourceWorkflowId,name:te&&!String(H.name||"").trim()?`Optimize ${String(k?.automation?.name||te).trim()}`:H.name})),t("ok",v==="summary"?"Smoke summary workflow created and selected.":"Smoke extract-format workflow created and selected."),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:k=>t("err",k instanceof Error?k.message:String(k))}),C=ke({mutationFn:async({optimizationId:k,action:v,experimentId:te})=>a.optimizations.action(k,{action:v,experiment_id:te}),onSuccess:async()=>{t("ok","Optimization action applied."),await n.invalidateQueries({queryKey:["optimizations"]})},onError:k=>t("err",k instanceof Error?k.message:String(k))}),P=ke({mutationFn:async({optimizationId:k,experimentId:v})=>a.optimizations.applyWinner(k,v),onSuccess:async()=>{t("ok","Approved winner applied to the live workflow."),await n.invalidateQueries({queryKey:["optimizations"]}),await n.invalidateQueries({queryKey:["optimizations","detail",W]}),await n.invalidateQueries({queryKey:["optimizations","experiments",W]}),await n.invalidateQueries({queryKey:["optimizations","workflows","automations-v2"]})},onError:k=>t("err",k instanceof Error?k.message:String(k))}),O=Or(u.data,"automations").map(k=>({id:String(k?.automation_id||k?.automationId||k?.id||"").trim(),name:String(k?.name||k?.automation_id||"Workflow").trim()})),A=I.data?.optimization||null,ve=Or(Q.data,"experiments"),z=A?.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:k=>d(v=>({...v,name:k.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:k=>d(v=>({...v,sourceWorkflowId:k.target.value})),children:[e("option",{value:"",children:"Select a workflow"}),O.map(k=>e("option",{value:k.id,children:k.name},k.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:k=>d(v=>({...v,smokeWorkspaceRoot:k.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:()=>ce.mutate("summary"),disabled:ce.isPending,children:"Create Smoke Summary"}),e("button",{className:"tcp-btn h-9 px-3 text-xs",onClick:()=>ce.mutate("extract_format"),disabled:ce.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:k=>d(v=>({...v,modelProvider:k.target.value,modelId:k.target.value&&v.modelProvider!==k.target.value?"":v.modelId})),children:[e("option",{value:"",children:"Use workflow/default model"}),E.map(k=>e("option",{value:k.id,children:[k.id,k.configured?"":" (catalog only)"]},k.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:k=>d(v=>({...v,modelId:k.target.value})),placeholder:c.modelProvider?"Pick a cheaper model for this campaign":"Optional",list:"optimization-model-ids"}),e("datalist",{id:"optimization-model-ids",children:S.map(k=>e("option",{value:k},k))}),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(([k,v])=>e("label",{className:"grid gap-1 text-xs text-slate-300",children:[e("span",{children:k}),e("input",{className:"rounded-lg border border-slate-700 bg-slate-950 px-3 py-2 text-sm",value:c[v],onChange:te=>d(H=>({...H,[v]:te.target.value}))})]},v)),e("label",{className:"flex items-center gap-2 text-xs text-slate-300",children:[e("input",{type:"checkbox",checked:c.startImmediately,onChange:k=>d(v=>({...v,startImmediately:k.target.checked}))}),"Start immediately after create"]}),e("button",{className:"tcp-btn h-10 px-3 text-sm",onClick:()=>ee.mutate(),disabled:ee.isPending,children:ee.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:M.length})]}),e("div",{className:"grid gap-2",children:M.length?M.map(k=>{const v=String(k?.optimization_id||"").trim();return e("button",{type:"button",className:`rounded-xl border px-3 py-3 text-left transition ${W===v?"border-amber-400/60 bg-amber-400/10":"border-slate-700/50 bg-slate-950/40 hover:border-slate-600"}`,onClick:()=>s(v),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("div",{className:"font-medium text-slate-100",children:String(k?.name||v||"Optimization")}),e("span",{className:zs(k?.status),children:String(k?.status||"draft")})]}),e("div",{className:"mt-1 text-xs text-slate-400",children:["workflow:"," ",String(k?.source_workflow_name||k?.source_workflow_id||"unknown")]})]},v)}):e(je,{text:"No optimization campaigns yet."})})]})]}),e("div",{className:"grid gap-4",children:A?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(A?.name||A?.optimization_id||"Optimization")}),e("div",{className:"mt-1 text-sm text-slate-400",children:["Source workflow:"," ",String(A?.source_workflow_name||A?.source_workflow_id||"unknown")]}),e("div",{className:"mt-1 text-xs text-slate-500",children:["baseline: ",String(A?.baseline_snapshot_hash||"").slice(0,12)]}),A?.execution_override?e("div",{className:"mt-1 text-xs text-slate-500",children:["model: ",String(A.execution_override.provider_id||"").trim(),"/",String(A.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:()=>C.mutate({optimizationId:W,action:"start"}),disabled:C.isPending,children:"Start"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>C.mutate({optimizationId:W,action:"pause"}),disabled:C.isPending,children:"Pause"}),e("button",{className:"tcp-btn h-8 px-3 text-xs",onClick:()=>C.mutate({optimizationId:W,action:"resume"}),disabled:C.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(A?.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:z?ar(z.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:z?ar(z.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:z?ar(z.blocked_node_rate):"n/a"})]})]}),A?.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(A.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:ve.length})]}),ve.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:ve.map(k=>{const v=String(k?.experiment_id||"").trim(),te=k?.phase1_metrics||{};return e("tr",{className:"border-t border-slate-800",children:[e("td",{className:"px-2 py-3 text-slate-200",children:v||"unknown"}),e("td",{className:"px-2 py-3",children:e("span",{className:zs(k?.status),children:String(k?.status||"draft")})}),e("td",{className:"px-2 py-3 text-slate-300",children:String(k?.mutation_summary||"pending")}),e("td",{className:"px-2 py-3 text-slate-300",children:te?ar(te.artifact_validator_pass_rate):"n/a"}),e("td",{className:"px-2 py-3 text-slate-300",children:String(k?.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:()=>C.mutate({optimizationId:W,action:"approve_winner",experimentId:v}),disabled:!v||C.isPending,children:"Approve"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>C.mutate({optimizationId:W,action:"reject_winner",experimentId:v}),disabled:!v||C.isPending,children:"Reject"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>P.mutate({optimizationId:W,experimentId:v}),disabled:!v||P.isPending||String(k?.status||"").trim().toLowerCase()!=="promotion_approved",children:"Apply"})]})})]},v)})})]})}):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 Gu=Object.assign({"./automation-wizard.yaml":xu});function Vu(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=Vu(Object.values(Gu)[0]||""),Js="tandem.automations.plannerSeed",Qs="tandem.automations.studioHandoff";function Hs(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 Yi(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 Yu(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 Xu(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 Xi(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 On(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 Zu(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 em(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 Zi(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 tm(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 ms(a){return Wn(String(a||"").split(/[\n,]/g).map(t=>String(t||"").trim()).filter(Boolean))}function am(a){return Wn(a).join(`
|
|
2432
|
+
`)}function nm(a,t,n){return t==="all"?["*"]:Wn([...ms(n),...a.map(r=>`mcp.${tm(r)}.*`)])}function rm(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 sm(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:am(n)}}function im(a){const t=String(a?.automation_id||a?.automationId||a?.id||"").trim();if(!t)return null;const n=Zi(a?.schedule),r=rm(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=sm(a),N=Array.isArray(a?.flow?.nodes)?a.flow.nodes.map((D,x)=>({nodeId:String(D?.node_id||D?.nodeId||D?.id||`node-${x}`).trim(),title:String(D?.title||D?.name||D?.objective||D?.node_id||D?.id||"Workflow step").trim(),objective:String(D?.objective||"").trim(),agentId:String(D?.agent_id||D?.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(D=>String(D||"").trim()).filter(Boolean),nodes:N}}function om(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 lm(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 cm(a){return String(a?.metadata?.feature||"").trim()==="agent_standup"}function dm(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=ms(a.customToolsText)),t}function um(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 Gs(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 mm(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 eo(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?null:t<1e12?t*1e3:t}function Vs(a){const t=eo(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 pm(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)||pm(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 ps(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
|
+
`)}return String(r?.text||"").trim()}).filter(Boolean).join(`
|
|
2434
|
+
|
|
2435
|
+
`).trim()}function hm(a){const t=String(a?.info?.role||"").trim().toLowerCase();if(t==="user")return"user";if(t==="assistant")return"assistant";const n=ps(a).toLowerCase();return n.includes("engine_error")||n.includes("error")?"error":"system"}function gm(a){return Array.isArray(a?.parts)?a.parts:[]}function fm(a){return yr(a?.info?.time?.created||a?.info?.created_at_ms||a?.created_at_ms||0)}function bm(a,t){return String(a?.info?.id||a?.id||`message-${t}`).trim()||`message-${t}`}function qn(a){const t=String(a||"").trim();return t?`session ${hr(t,18)}`:"session"}function to(a){const t=String(a||"").trim();return t?t.startsWith("node-")?t:`node-${t}`:""}function Ys(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 to(r[1])}return""}function vm(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 ym(a,t,n){const r=String(a?.status||"").trim().toLowerCase();if(!["running","pausing","paused"].includes(r))return"";const s=qd(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=to(String(d?.task_id||d?.step_id||d?.node_id||"").trim());if(u)return u;const p=Ys(String(d?.message||d?.detail||d?.reason||""));if(p)return p}for(let c=t.length-1;c>=0;c-=1){const d=Ys(ps(t[c]?.message));if(d)return d}return Pd(a)}function ao(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 wm(a,t,n){const r=[],s=(c,d,u,p,N)=>{u.trim()&&(r.some(D=>D.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",ao(a),"run")}Fi(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 ss(a)){const d=Od(c.value),u=os(c.value),p=Kn(c.value);if(String(c?.value?.status||"").trim().toLowerCase()==="blocked"){const D=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}`:"",D?`executed tools: ${D}`:"",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 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 xm({value:a,onChange:t,routedSkill:n,routingConfidence:r,validationBadge:s,generatedSkill:c,advancedMode:d,customSkillName:u,customSkillDescription:p,customWorkflowKind:N,onToggleAdvancedMode:D,onChangeCustomSkillName:x,onChangeCustomSkillDescription:M,onChangeCustomWorkflowKind:E,showArtifactPreview:S,onToggleArtifactPreview:W,artifactPreviewKey:I,onSelectArtifactPreviewKey:Q,onGenerateSkill:ee,onInstallGeneratedSkill:ce,isGeneratingSkill:C,isInstallingSkill:P,installStatus:O,topMatches:A,isMatching:ve}){const z=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:k=>t(k.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(k=>e("button",{className:"tcp-btn truncate text-left text-xs",style:{maxWidth:"280px"},onClick:()=>t(k),children:k},k))})]}),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:ve?"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."}),A.length?e("div",{className:"mt-2 flex flex-wrap gap-1",children:A.slice(0,3).map((k,v)=>e("span",{className:"tcp-badge-info",children:[String(k?.skill_name||"unknown")," ",typeof k?.confidence=="number"?`${Math.round(k.confidence*100)}%`:""]},`${String(k?.skill_name||"match")}-${v}`))}):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:D,children:d?"Hide Export Options":"Show Export Options"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:ee,disabled:!a.trim()||C,children:C?"Generating…":"Generate Reusable Skill Draft"}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:ce,disabled:!c?.artifacts||P,children:P?"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:k=>x(k.target.value)}),e("input",{className:"tcp-input text-xs",placeholder:"Short skill description",value:p,onInput:k=>M(k.target.value)}),e("select",{className:"tcp-input text-xs",value:N,onInput:k=>E(k.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:"," ",z.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:W,children:S?"Hide Raw":"Show Raw"}),S?e("select",{className:"tcp-input h-7 text-xs",value:I,onInput:k=>Q(k.target.value),children:Object.keys(c?.artifacts||{}).map(k=>e("option",{value:k,children:k},k))}):null]}),S?e("textarea",{className:"tcp-input min-h-[140px] font-mono text-[11px]",readOnly:!0,value:String(c?.artifacts?.[I]||"")}):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."}),O?e("p",{className:"mt-2 text-slate-300",children:O}):null]})]})}function km({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 Nm({selected:a,onSelect:t,maxAgents:n,onMaxAgents:r,workspaceRoot:s,onWorkspaceRootChange:c,providerOptions:d,providerId:u,modelId:p,plannerProviderId:N,plannerModelId:D,onProviderChange:x,onModelChange:M,onPlannerProviderChange:E,onPlannerModelChange:S,roleModelsJson:W,onRoleModelsChange:I,roleModelsError:Q,toolAccessMode:ee,customToolsText:ce,onToolAccessModeChange:C,onCustomToolsTextChange:P,mcpServers:O,selectedMcpServers:A,onToggleMcpServer:ve,onOpenMcpSettings:z,workspaceRootError:k,plannerModelError:v,workspaceBrowserOpen:te,workspaceBrowserDir:H,workspaceBrowserSearch:Pe,onWorkspaceBrowserSearchChange:$e,onOpenWorkspaceBrowser:Le,onCloseWorkspaceBrowser:re,onBrowseWorkspaceParent:pe,onBrowseWorkspaceDirectory:q,onSelectWorkspaceDirectory:ge,workspaceBrowserParentDir:Te,workspaceCurrentBrowseDir:Re,filteredWorkspaceDirectories:se}){const Oe=d.find(Y=>Y.id===u)?.models||[],qe=d.find(Y=>Y.id===N)?.models||[],He=String(Pe||"").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 ${k?"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."}),k?e("div",{className:"text-xs text-red-300",children:k}):null]})]}),e(Mt,{children:te?e(Me.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(Me.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: ",Re||"n/a"]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",type:"button",onClick:pe,disabled:!Te,children:"Up"}),e("button",{className:"tcp-btn-primary",type:"button",onClick:ge,disabled:!Re,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:Pe,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=>M(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=>E(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:D,list:N?`planner-models-${N}`:void 0,onInput:Y=>S(Y.target.value),placeholder:"Disabled unless provider and model are set"}),N?e("datalist",{id:`planner-models-${N}`,children:qe.map(Y=>e("option",{value:Y},Y))}):null]})]}),v?e("div",{className:"text-xs text-red-300",children:v}):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:W,onInput:Y=>I(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 ${ee==="all"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>C("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 ${ee==="custom"?"border-amber-400/60 bg-amber-400/10":""}`,onClick:()=>C("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."})]})]}),ee==="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:ce,onInput:Y=>P(Y.target.value),placeholder:`read
|
|
2437
|
+
write
|
|
2438
|
+
edit
|
|
2439
|
+
bash
|
|
2440
|
+
ls
|
|
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:z,children:"Add MCP Server"})]}),O.length?e("div",{className:"flex flex-wrap gap-2",children:O.map(Y=>{const Ze=A.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:()=>ve(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 _m({wizard:a,onToggleExportPackDraft:t,onSubmit:n,isPending:r,planPreview:s,isPreviewing:c,planningConversation:d,planningChangeSummary:u,onSendPlanningMessage:p,isSendingPlanningMessage:N,onResetPlanningChat:D,isResettingPlanningChat:x,plannerError:M,plannerDiagnostics:E,generatedSkill:S,installStatus:W}){const[I,Q]=y(""),[ee,ce]=y(!1),[C,P]=y(!1),[O,A]=y({}),ve=a.cron?a.cron:ga.schedulePresets.find(ne=>ne.label===a.schedulePreset)?.intervalSeconds?`Every ${ga.schedulePresets.find(ne=>ne.label===a.schedulePreset).intervalSeconds/3600}h`:a.schedulePreset||"Manual",z=s&&typeof s=="object"?s.operator_preferences||s.operatorPreferences||{}:{},k=String(z?.execution_mode||a.mode||"team").trim(),v=ga.executionModes.find(ne=>ne.id===k),te=Number(z?.max_parallel_agents??z?.maxParallelAgents??(k==="swarm"?a.maxAgents:1)),H=!!s,Pe=String(H?z?.model_provider||z?.modelProvider||"":a.modelProvider||"").trim(),$e=String(H?z?.model_id||z?.modelId||"":a.modelId||"").trim(),Le=z&&typeof z=="object"&&(z?.role_models?.planner||z?.roleModels?.planner),re=String(H?Le?.provider_id||Le?.providerId||"":a.plannerModelProvider||"").trim(),pe=String(H?Le?.model_id||Le?.modelId||"":a.plannerModelId||"").trim(),q=!!(re&&pe||Pe&&$e),ge=String(s?.workspace_root||s?.workspaceRoot||a.workspaceRoot||"").trim(),Te=Array.isArray(s?.allowed_mcp_servers||s?.allowedMcpServers)?s?.allowed_mcp_servers||s?.allowedMcpServers||[]:a.selectedMcpServers,Re=String(H?z?.tool_access_mode||z?.toolAccessMode||"all":a.toolAccessMode||"all").trim(),se=H?Wn((z?.tool_allowlist||z?.toolAllowlist||[]).map(ne=>String(ne||"").trim())):ms(a.customToolsText),Oe=s?.schedule?Xi(s.schedule):ve,qe=String(s?.title||"").trim(),He=String(E?.fallback_reason||E?.fallbackReason||"").trim(),Y=String(E?.detail||"").trim(),Ze=ne=>A(Ae=>({...Ae,[ne]:!Ae[ne]}));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:[qe?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:qe})]}):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:()=>ce(ne=>!ne),children:[e("span",{className:"text-sm text-slate-100 italic",children:ee?"Hide goal":"View goal"}),e("span",{className:"tcp-subtle text-xs",children:ee?"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 ${ee?"":"max-h-28 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:gn(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:[v?.icon," ",v?.label||k,Number.isFinite(te)&&te>1?` · ${te} agents`:""]})]})]}),H||Pe||$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:Pe||$e?`${Pe||"default provider"} / ${$e||"default model"}`:"Workspace default"})]}):null,H||re||pe?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||pe?`${re||"default provider"} / ${pe||"default model"}`:Pe||$e?`Using model override: ${Pe||"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"})]}),H||Te.length?e("div",{className:"grid gap-1",children:[e("span",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"MCP Servers"}),Te.length?e("div",{className:"flex flex-wrap gap-1",children:Te.map(ne=>e("span",{className:"tcp-badge-info",children:ne},ne))}):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"}),Re==="custom"?se.length?e("div",{className:"flex flex-wrap gap-1",children:se.map(ne=>e("span",{className:"tcp-badge-info",children:ne},ne))}):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")})]}),qe?e("span",{children:["Title: ",e("strong",{children:qe})]}):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((ne,Ae)=>(()=>{const St=String(ne?.step_id||ne?.stepId||`step-${Ae+1}`),oe=!!O[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,ne?.kind?e("span",{className:"ml-2 text-[11px] uppercase tracking-wide text-slate-500",children:String(ne.kind)}):null]}),typeof ne?.objective=="string"&&ne.objective.trim()?e("div",{className:"mt-1 line-clamp-2 text-xs text-slate-400",children:ne.objective}):null]}),e("span",{className:"tcp-subtle shrink-0 text-xs",children:oe?"Hide":"Details"})]}),oe&&typeof ne?.objective=="string"&&ne.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:gn(ne.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:()=>P(ne=>!ne),children:[e("span",{className:"text-sm text-slate-200",children:"Plan description"}),e("span",{className:"tcp-subtle text-xs",children:C?"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 ${C?"":"max-h-24 overflow-hidden"}`,dangerouslySetInnerHTML:{__html:gn(String(s.description||""))}})})]}):null]}):e("span",{className:"text-sm text-slate-400",children:"Workflow preview has not been generated yet."})]})]}),M?e("div",{className:"rounded-xl border border-red-500/40 bg-red-950/30 p-3 text-sm text-red-200",children:M}):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((ne,Ae)=>e("span",{className:"tcp-badge-ok",children:ne},`${ne}-${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:D,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((ne,Ae)=>e("div",{className:"grid gap-1",children:[e("span",{className:"text-[11px] uppercase tracking-wide text-slate-500",children:String(ne?.role||"assistant")}),e("div",{className:"text-sm text-slate-200",children:String(ne?.text||"").trim()})]},`${ne?.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:I,onInput:ne=>Q(ne.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||!I.trim()||!s?.plan_id,onClick:()=>{const ne=I.trim();ne&&(p(ne),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."})]})]})}),S||W?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:[S?e(la,{children:[e("span",{children:["Draft status:"," ",e("strong",{className:"text-slate-300",children:String(S?.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,W?e("span",{children:W}):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:v?.label||k})," 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 Sm({client:a,api:t,toast:n,navigate:r,defaultProvider:s,defaultModel:c}){const d=ca(),[u,p]=y(1),[N,D]=y("automations_page"),[x,M]=y([]),[E,S]=y(null),[W,I]=y(null),[Q,ee]=y([]),[ce,C]=y(""),[P,O]=y(null),[A,ve]=y(!1),[z,k]=y(""),[v,te]=y(""),[H,Pe]=y(""),[$e,Le]=y(null),[re,pe]=y(!1),[q,ge]=y("SKILL.md"),[Te,Re]=y(""),[se,Oe]=y(()=>Hs(s,c)),qe=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}),ne=V({queryKey:["automations","workspace-browser",z],enabled:A&&!!z,queryFn:()=>t(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(z)}`,{method:"GET"})}),Ae=B(()=>(Array.isArray(qe.data?.all)?qe.data.all:[]).map(G=>({id:String(G?.id||"").trim(),models:Object.keys(G?.models||{})})).filter(G=>!!G.id).sort((G,me)=>G.id.localeCompare(me.id)),[qe.data]),St=B(()=>Yi(Y.data),[Y.data]),oe=Array.isArray(ne.data?.directories)?ne.data.directories:[],K=String(ne.data?.parent||"").trim(),lt=String(ne.data?.dir||z||"").trim(),xt=String(v||"").trim().toLowerCase(),rt=B(()=>xt?oe.filter(_=>String(_?.name||_?.path||"").trim().toLowerCase().includes(xt)):oe,[oe,xt]);fe(()=>{const _=String(He.data?.default||s||"").trim();if(!_)return;const G=Ae.find(Ke=>Ke.id===_)?.models||[],me=String(He.data?.providers?.[_]?.default_model||c||G[0]||"").trim();Oe(Ke=>Ke.modelProvider&&Ke.modelId?Ke:{...Ke,modelProvider:Ke.modelProvider||_,modelId:Ke.modelId||me})},[c,s,Ae,He.data]),fe(()=>{const _=String(Ze.data?.workspaceRoot||Ze.data?.workspace_root||"").trim();_&&Oe(G=>String(G.workspaceRoot||"").trim()?G:{...G,workspaceRoot:_})},[Ze.data]);const Et=ke({mutationFn:async _=>!_.trim()||!a?.skills?.match?null:a.skills.match({goal:_,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:Yu(se),plan_source:N,allowed_mcp_servers:se.selectedMcpServers,workspace_root:se.workspaceRoot,operator_preferences:Zu(se)})||null},onSuccess:_=>{S(_?.plan||null),I(_?.conversation||null),ee([]),C(""),O(_?.planner_diagnostics||_?.plannerDiagnostics||null)},onError:_=>{S(null),I(null),ee([]),C(_ instanceof Error?_.message:String(_)),O(null)}}),Bt=ke({mutationFn:async _=>!a?.workflowPlans?.chatMessage||!E?.plan_id?null:a.workflowPlans.chatMessage({plan_id:E.plan_id,message:_}),onSuccess:_=>{S(_?.plan||null),I(_?.conversation||null),ee(Array.isArray(_?.change_summary)?_.change_summary.map(G=>String(G||"").trim()).filter(Boolean):[]),C(typeof _?.clarifier?.question=="string"?String(_.clarifier.question):""),O(_?.planner_diagnostics||_?.plannerDiagnostics||null)},onError:_=>{const G=_ instanceof Error?_.message:String(_);C(G),n("err",G)}}),At=ke({mutationFn:async()=>!a?.workflowPlans?.chatReset||!E?.plan_id?null:a.workflowPlans.chatReset({plan_id:E.plan_id}),onSuccess:_=>{S(_?.plan||null),I(_?.conversation||null),ee([]),C(""),O(_?.planner_diagnostics||_?.plannerDiagnostics||null)},onError:_=>{const G=_ instanceof Error?_.message:String(_);C(G),n("err",G)}}),$t=ke({mutationFn:async _=>{if(!a?.skills?.get||!a?.skills?.validate)return null;const me=(await a.skills.get(_))?.content;return me?a.skills.validate({content:me}):null},onSuccess:_=>{if(!_){Pe("");return}Pe(_.invalid>0?"not_validated":"validated")},onError:()=>Pe("not_validated")}),We=ke({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:_=>{Le(_);const G=Object.keys(_?.artifacts||{})[0];ge(G||"SKILL.md"),pe(!1),Re("")},onError:()=>{Le(null),pe(!1),Re("Optional skill generation failed.")}}),ze=ke({mutationFn:async()=>{if(!a?.skills?.generateInstall)return null;const _=$e?.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 G=_?.skill?.name;Re(G?`Installed optional skill as '${String(G)}' in project skills.`:"Installed optional skill in project skills."),d.invalidateQueries({queryKey:["automations"]})},onError:_=>Re(`Install failed: ${_ instanceof Error?_.message:String(_)}`)}),tt=ke({mutationFn:async()=>{if(!se.goal.trim())throw new Error("Please describe your goal first.");const _=E||await Fe.mutateAsync().catch(me=>{throw me instanceof Error?me:new Error(String(me))}),G=_?.plan||_;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 _=>{_?.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(Hs(s,c,String(Ze.data?.workspaceRoot||Ze.data?.workspace_root||"").trim())),M([]),D("automations_page"),S(null),I(null),ee([]),C(""),Pe(""),Le(null),pe(!1),ge("SKILL.md"),Re(""),p(1)},onError:_=>{const G=_ instanceof Error?_.message:String(_);C(G),n("err",G)}}),be=On(se.workspaceRoot),Se=pr(se.plannerModelProvider,se.plannerModelId),Ve=em(se.roleModelsJson),de=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)}%`:""}))):(Pe(""),Oe(Ke=>({...Ke,routedSkill:"",routingConfidence:""})));const me=Array.isArray(G?.top_matches)?G.top_matches:[];M(me)}const _=u+1;if(_===4){C(""),S(null),I(null),ee([]);try{await Fe.mutateAsync()}catch{return}}p(_)};return fe(()=>{if(u===1)try{const _=sessionStorage.getItem(Js);if(!_)return;sessionStorage.removeItem(Js);const G=JSON.parse(_),me=String(G?.prompt||"").trim();if(!me)return;const Ke=String(G?.plan_source||"chat_setup").trim()||"chat_setup";D(Ke),Oe(l=>({...l,goal:me}))}catch{}},[u]),e("div",{className:"grid gap-4",children:[e("div",{className:"flex items-center gap-2",children:ga.steps.map((_,G)=>{const me=G+1,Ke=me===u,l=me<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(me),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?"✓":me}),_]}),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%"}})})]},_)})}),e(Mt,{mode:"wait",children:e(Me.div,{initial:{opacity:0,x:16},animate:{opacity:1,x:0},exit:{opacity:0,x:-16},transition:{duration:.18},children:u===1?e(xm,{value:se.goal,onChange:_=>Oe(G=>({...G,goal:_})),routedSkill:se.routedSkill,routingConfidence:se.routingConfidence,validationBadge:H,generatedSkill:$e,advancedMode:se.advancedMode,customSkillName:se.customSkillName,customSkillDescription:se.customSkillDescription,customWorkflowKind:se.customWorkflowKind,onToggleAdvancedMode:()=>Oe(_=>({..._,advancedMode:!_.advancedMode})),onChangeCustomSkillName:_=>Oe(G=>({...G,customSkillName:_})),onChangeCustomSkillDescription:_=>Oe(G=>({...G,customSkillDescription:_})),onChangeCustomWorkflowKind:_=>Oe(G=>({...G,customWorkflowKind:_})),showArtifactPreview:re,onToggleArtifactPreview:()=>pe(_=>!_),artifactPreviewKey:q,onSelectArtifactPreviewKey:_=>ge(_),onGenerateSkill:()=>{We.mutateAsync()},onInstallGeneratedSkill:()=>{ze.mutateAsync()},isGeneratingSkill:We.isPending,isInstallingSkill:ze.isPending,installStatus:Te,topMatches:x,isMatching:Et.isPending}):u===2?e(km,{selected:se.schedulePreset,onSelect:_=>Oe(G=>({...G,schedulePreset:_.label,cron:_.cron})),customCron:se.cron,onCustomCron:_=>Oe(G=>({...G,cron:_,schedulePreset:""}))}):u===3?e(Nm,{selected:se.mode,onSelect:_=>Oe(G=>({...G,mode:_})),maxAgents:se.maxAgents,onMaxAgents:_=>Oe(G=>({...G,maxAgents:_})),workspaceRoot:se.workspaceRoot,onWorkspaceRootChange:_=>Oe(G=>({...G,workspaceRoot:_})),providerOptions:Ae,providerId:se.modelProvider,modelId:se.modelId,plannerProviderId:se.plannerModelProvider,plannerModelId:se.plannerModelId,onProviderChange:_=>Oe(G=>({...G,modelProvider:_,modelId:_===G.modelProvider?G.modelId:""})),onModelChange:_=>Oe(G=>({...G,modelId:_})),onPlannerProviderChange:_=>Oe(G=>({...G,plannerModelProvider:_,plannerModelId:_===G.plannerModelProvider?G.plannerModelId:""})),onPlannerModelChange:_=>Oe(G=>({...G,plannerModelId:_})),roleModelsJson:se.roleModelsJson,onRoleModelsChange:_=>Oe(G=>({...G,roleModelsJson:_})),roleModelsError:Ve,toolAccessMode:se.toolAccessMode,customToolsText:se.customToolsText,onToolAccessModeChange:_=>Oe(G=>({...G,toolAccessMode:_})),onCustomToolsTextChange:_=>Oe(G=>({...G,customToolsText:_})),mcpServers:St,selectedMcpServers:se.selectedMcpServers,onToggleMcpServer:_=>Oe(G=>({...G,selectedMcpServers:G.selectedMcpServers.includes(_)?G.selectedMcpServers.filter(me=>me!==_):[...G.selectedMcpServers,_]})),onOpenMcpSettings:()=>r("mcp"),workspaceRootError:be,plannerModelError:Se,workspaceBrowserOpen:A,workspaceBrowserDir:z,workspaceBrowserSearch:v,onWorkspaceBrowserSearchChange:te,onOpenWorkspaceBrowser:()=>{const _=String(se.workspaceRoot||Ze.data?.workspaceRoot||Ze.data?.workspace_root||"/").trim();k(_||"/"),te(""),ve(!0)},onCloseWorkspaceBrowser:()=>{ve(!1),te("")},onBrowseWorkspaceParent:()=>{K&&k(K)},onBrowseWorkspaceDirectory:_=>k(_),onSelectWorkspaceDirectory:()=>{lt&&(Oe(_=>({..._,workspaceRoot:lt})),ve(!1),te(""),n("ok",`Workspace selected: ${lt}`))},workspaceBrowserParentDir:K,workspaceCurrentBrowseDir:lt,filteredWorkspaceDirectories:rt}):e(_m,{wizard:se,onToggleExportPackDraft:()=>Oe(_=>({..._,exportPackDraft:!_.exportPackDraft})),onSubmit:()=>tt.mutate(),isPending:tt.isPending,planPreview:E,isPreviewing:Fe.isPending,planningConversation:W,planningChangeSummary:Q,onSendPlanningMessage:_=>{Bt.mutateAsync(_)},isSendingPlanningMessage:Bt.isPending,onResetPlanningChat:()=>{At.mutateAsync()},isResettingPlanningChat:At.isPending,plannerError:ce,plannerDiagnostics:P,generatedSkill:$e,installStatus:Te})},u)}),u<4?e("div",{className:"flex justify-between gap-2",children:[e("button",{className:"tcp-btn",disabled:u===1||Fe.isPending,onClick:()=>p(_=>_-1),children:"← Back"}),e("button",{className:"tcp-btn-primary",disabled:!de||Fe.isPending,onClick:()=>{dt()},children:Fe.isPending?"Generating Plan...":"Next →"})]}):null]})}function Xs({client:a,toast:t,navigate:n,viewMode:r,selectedRunId:s,onSelectRunId:c,onOpenRunningView:d,onOpenAdvancedEdit:u}){const p=ca(),N=Rt(null),[D,x]=y(null),[M,E]=y(null),[S,W]=y("all"),[I,Q]=y([]),[ee,ce]=y(""),[C,P]=y("all"),[O,A]=y(""),[ve,z]=y(""),[k,v]=y([]),te=Rt(null),H=Rt(null),Pe=Rt(null),[$e,Le]=y(!0),[re,pe]=y(null),q=s.startsWith("automation-v2-run-"),ge=V({queryKey:["automations","list"],queryFn:()=>a?.automations?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Te=V({queryKey:["automations","v2","list"],queryFn:()=>a?.automationsV2?.list?.().catch(()=>({automations:[]}))??Promise.resolve({automations:[]}),refetchInterval:2e4}),Re=B(()=>{const i=Fa(Te.data,"automations"),m=new Map;for(const j of i){const Z=String(j?.automation_id||j?.automationId||j?.id||"").trim();Z&&(m.has(Z)||m.set(Z,j))}return Array.from(m.values())},[Te.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}),qe=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:()=>Qt("/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}),ne=V({queryKey:["automations","run","task-reset-preview",s,O],enabled:!!s&&q&&String(O||"").startsWith("node-")&&!!String(O||"").trim()&&!!a?.automationsV2?.previewTaskReset,queryFn:()=>a?.automationsV2?.previewTaskReset(s,String(O||"").replace(/^node-/,"").trim()).catch(()=>({preview:null}))??Promise.resolve({preview:null}),refetchInterval:!1}),Ae=B(()=>Fi(Y.data?.run),[Y.data]),St=bo({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(),K=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",K],enabled:!!K,queryFn:()=>Qt(`/api/engine/context/runs/${encodeURIComponent(K)}`).catch(()=>({run:null})),refetchInterval:K&&La(Y.data?.run?.status)?5e3:!1}),Et=V({queryKey:["automations","run","context",K,"blackboard"],enabled:!!K,queryFn:()=>Qt(`/api/engine/context/runs/${encodeURIComponent(K)}/blackboard`).catch(()=>({blackboard:null})),refetchInterval:K&&La(Y.data?.run?.status)?5e3:!1}),Fe=V({queryKey:["automations","run","context",K,"events"],enabled:!!K,queryFn:()=>Qt(`/api/engine/context/runs/${encodeURIComponent(K)}/events`).catch(()=>({events:[]})),refetchInterval:K&&La(Y.data?.run?.status)?5e3:!1}),Bt=V({queryKey:["automations","run","context",K,"patches"],enabled:!!K,queryFn:()=>Qt(`/api/engine/context/runs/${encodeURIComponent(K)}/blackboard/patches`).catch(()=>({patches:[]})),refetchInterval:K&&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:j,reason:Z})=>j==="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:j})=>{if(!a?.automationsV2?.repairRun)throw new Error("Workflow repair is not available in this client.");return a.automationsV2.repairRun(i,{node_id:m,reason:j??""})},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:j})=>{if(!a?.automationsV2?.retryTask)throw new Error("Task retry is not available in this client.");return a.automationsV2.retryTask(i,m,j)},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:j})=>{if(!a?.automationsV2?.continueTask)throw new Error("Task continue is not available in this client.");return a.automationsV2.continueTask(i,m,j)},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))}),de=ke({mutationFn:async({runId:i,nodeId:m,reason:j})=>{if(!a?.automationsV2?.requeueTask)throw new Error("Task requeue is not available in this client.");return a.automationsV2.requeueTask(i,m,j)},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:j,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:j,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))}),_=ke({mutationFn:async({runId:i,taskId:m,reason:j})=>{if(!a?.automationsV2?.requeueBacklogTask)throw new Error("Backlog task requeue is not available in this client.");return a.automationsV2.requeueBacklogTask(i,m,j)},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(),j=String(i.objective||"").trim(),Z=String(i.cronExpression||"").trim(),le=Number(i.intervalSeconds);if(!m)throw new Error("Automation name is required.");if(!j)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:j},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."),E(null),await p.invalidateQueries({queryKey:["automations"]})},onError:i=>t("err",i instanceof Error?i.message:String(i))}),me=ke({mutationFn:async i=>{const m=String(i.name||"").trim(),j=String(i.description||"").trim(),Z=String(i.workspaceRoot||"").trim(),le=Er(i.modelProvider,i.modelId),nt=pr(i.plannerModelProvider,i.plannerModelId),Dt=On(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=dm(i),_a=um(Na),ha=i.selectedMcpServers.map(jt=>String(jt||"").trim()).filter(Boolean),_e=nm(ha,i.toolAccessMode,i.customToolsText),ra=Re.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}})):[],ln=Array.isArray(ra?.flow?.nodes)?ra.flow.nodes.map((jt,Sn)=>{const cn=String(jt?.node_id||jt?.nodeId||jt?.id||`node-${Sn}`).trim(),In=i.nodes.find(Vn=>Vn.nodeId===cn);return In?{...jt,objective:String(In.objective||"").trim()}:jt}):[],Sa=ra?.metadata&&typeof ra.metadata=="object"?ra.metadata:{};return a.automationsV2.update(i.automationId,{name:m,description:j||null,schedule:lm(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:ln}:ra?.flow,agents:Ca,metadata:{...Sa,workspace_root:Z,operator_preferences:Na,allowed_mcp_servers:ha}})},onSuccess:async()=>{t("ok","Workflow automation updated."),pe(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:j})=>j==="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=B(()=>{const i=[...Fa(ge.data,"automations"),...Fa(ge.data,"routines")],m=new Map;for(const j of i){const Z=String(j?.automation_id||j?.routine_id||j?.id||"").trim();Z&&(m.has(Z)||m.set(Z,j))}return Array.from(m.values())},[ge.data]),b=Fa(qe.data,"runs"),T=B(()=>(Array.isArray(se.data?.providers)?se.data.providers:[]).map(m=>({id:String(m?.id||"").trim(),models:Array.isArray(m?.models)?m.models.map(j=>String(j||"").trim()).filter(Boolean):[]})).filter(m=>m.id).sort((m,j)=>m.id.localeCompare(j.id)),[se.data]),R=B(()=>Yi(Oe.data),[Oe.data]),$=Fa(He.data,"runs"),Ye=B(()=>{const i=[...b,...$],m=new Map;for(const j of i){const Z=String(j?.run_id||j?.runId||j?.id||"").trim();Z&&(m.has(Z)||m.set(Z,j))}return Array.from(m.values()).sort((j,Z)=>{const le=yr(j?.started_at_ms||j?.startedAtMs||j?.created_at_ms||j?.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:[],ae=Array.isArray(Bt.data?.patches)?Bt.data.patches:[],Ne=B(()=>{if(!q)return{tasks:[],currentTaskId:"",taskSource:"empty"};const i=ym(Ie,[],k),m=Hi({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 j=i?m.tasks.map(Z=>Z.id===i&&["pending","runnable","assigned"].includes(Z.state)?{...Z,state:"in_progress"}:Z):m.tasks;return{...m,tasks:j,currentTaskId:m.currentTaskId||i}}return Td(Ie,i)},[q,Ie,k,Pt,bt,rt.data]),h=B(()=>Ne.tasks.find(i=>i.id===O)||null,[O,Ne.tasks]),U=B(()=>Ne.tasks.find(i=>String(i.state||"").toLowerCase()==="blocked")||null,[Ne.tasks]),J=B(()=>{if(!h)return null;const i=String(h.id||"").replace(/^node-/,"");return Nr(Ie,i)},[h,Ie]),F=B(()=>os(J),[J]),X=B(()=>Kn(J),[J]),we=B(()=>zd(h,J),[h,J]),Ue=we.touchedFiles,st=we.undeclaredFiles,vt=we.researchReadPaths,It=we.discoveredRelevantPaths,et=we.reviewedPathsBackedByRead,yt=we.unreviewedRelevantPaths,Lt=we.unmetResearchRequirements,Ht=String(h?.state||"").toLowerCase()==="blocked"?h:U,Ct=String(Ht?.id||"").replace(/^node-/,"").trim(),Gt=String(Ie?.status||"").trim().toLowerCase(),kt=Wa(Ie),Ge=Gt!==kt&&(Gt==="completed"||Gt==="done")&&dr(Ie)>0,da=q&&["failed","paused"].includes(kt)&&!!s,Ce=q&&!!s&&!!Ct,xe=B(()=>{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 j=Ie?.checkpoint?.node_outputs||Ie?.checkpoint?.nodeOutputs||{};return Object.entries(j).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||!te.current||te.current.scrollIntoView({block:"nearest",behavior:"smooth"})},[h]),fe(()=>{z("")},[s,O]);const ut=q?Array.isArray(Pt?.artifacts)?Pt.artifacts:[]:Fa(Ze.data,"artifacts"),Qe=B(()=>ut.map((i,m)=>{const j=String(i?.id||i?.artifact_id||`artifact-${m+1}`).trim(),Z=String(i?.name||i?.label||i?.kind||i?.type||i?.path||j).trim(),le=String(i?.kind||i?.type||i?.path||"").trim(),nt=rr(Bn(i));return{key:j,name:Z||j,kind:le,artifact:i,paths:nt}}),[ut]),qt=B(()=>h?rr([...Bn(J),...Bn(X),String(h.output_path||"").trim()]):[],[h,X,J]),ia=B(()=>qt.length?Qe.filter(i=>i.paths.some(m=>qt.includes(m))):[],[Qe,qt]),ba=we.verificationOutcome,Kt=we.verificationPassed,Vt=we.verificationResults,mt=B(()=>String(h?.id||"").startsWith("node-")?String(h?.id||"").replace(/^node-/,"").trim():"",[h]),ua=B(()=>String(h?.id||"").startsWith("node-"),[h]),na=B(()=>String(h?.task_type||"").trim()==="automation_backlog_item",[h]),Nt=B(()=>String(h?.state||"").trim().toLowerCase(),[h]),Je=B(()=>Number(h?.lease_expires_at_ms||0)||0,[h]),f=B(()=>!!h?.is_stale||Nt==="in_progress"&&Je>0&&Je<=Date.now(),[h,Je,Nt]),L=we.failureDetail,he=we.workflowClass,De=we.phase,Be=we.failureKind,it=we.artifactCandidates,_t=B(()=>Md(Ie,mt,8),[mt,Ie]),zt=B(()=>vm(Ne.tasks,h?.id||""),[h,Ne.tasks]),oa=B(()=>zt.map(i=>Ne.tasks.find(m=>m.id===i)||null).filter(Boolean),[zt,Ne.tasks]),ka=B(()=>{const i=ne.data?.preview,m=Array.isArray(i?.reset_nodes)?i.reset_nodes.map(j=>String(j||"").trim()).filter(Boolean):[];return m.length?m:zt.map(j=>j.replace(/^node-/,"").trim()).filter(Boolean)},[zt,ne.data]),Zt=B(()=>{const i=ne.data?.preview,m=Array.isArray(i?.cleared_outputs)?i.cleared_outputs.map(j=>String(j||"").trim()).filter(Boolean):[];return m.length?rr(m):rr(oa.map(j=>String(j?.output_path||"").trim()))},[oa,ne.data]),va=i=>{const m=String(i||"").trim(),j=Qe.find(Z=>Z.paths.includes(m));z(j?.key||""),H.current&&H.current.scrollIntoView({block:"nearest",behavior:"smooth"})},Ma=q&&!!s&&ua&&!!mt&&["blocked","failed"].includes(Nt),Ia=q&&!!s&&ua&&!!mt&&Nt==="blocked",xn=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=B(()=>{const i=ne.data?.preview,m=String(h?.title||mt||"task").trim(),j=ka.length,Z=Math.max(0,j-(mt?1:0)),le=Zt.length;return{rootTitle:m,subtreeCount:j,descendantCount:Z,outputCount:le,previewBacked:!!ne.data?.preview,preservesUpstreamOutputs:typeof i?.preserves_upstream_outputs=="boolean"?i.preserves_upstream_outputs:!0}},[h,mt,ka.length,Zt.length,ne.data]),Qa=mm(Ie,ut),qa=q?(()=>{const i=Ud(bt,ae);return i.length?i:Bd(Array.isArray(xt.data)?xt.data:[],Ta)})():Array.isArray(lt.data?.events)?lt.data.events:Array.isArray(lt.data?.history)?lt.data.history:[],$a=B(()=>Fd(Array.isArray(xt.data)?xt.data:[],bt,q,Ta),[q,xt.data,s,bt]),rn=B(()=>{const i=[...$a,...I],m=new Set;return i.filter(j=>!j?.id||m.has(j.id)?!1:(m.add(j.id),!0)).sort((j,Z)=>Number(j.at||0)-Number(Z.at||0))},[$a,I]),Ha=rn.filter(i=>S==="all"?!0:i.source===S),sn=B(()=>Wd(Ha),[Ha]),on=B(()=>St.flatMap((i,m)=>{const j=Ae[m]||"";return(Array.isArray(i.data)?i.data:[]).map(le=>({sessionId:j,message:le}))}),[Ae,St]),Qn=B(()=>{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(ae.length)}),i.push({label:"completed nodes",value:String(Ms(Ie))}),i.push({label:"pending nodes",value:String(_d(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,ae.length,Ne.tasks.length]);B(()=>ao(Ie),[Ie]),fe(()=>{ce(i=>i&&Ae.includes(i)?i:Ae[0]||"")},[Ae]),fe(()=>{P(i=>i==="all"||i&&Ae.includes(i)?i:"all")},[Ae]),fe(()=>{Q([]),W("all"),A(""),v([]),Le(!0)},[s,K]);const Hn=Rt("");fe(()=>{!s||!Ne.tasks.length||Hn.current!==s&&(Hn.current=s,A(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 j=Rs(m);if(!j||j!==s)return;const Z=Ta(m),le=fn(m),nt=`automations:${j}:${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(K?`/api/engine/context/runs/${encodeURIComponent(K)}/events/stream?tail=50`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m||m.status==="ready")return;const j=`context:${String(m?.seq||"")}:${String(m?.event_type||"")}`,Z=eo(m?.created_at_ms||m?.timestamp_ms||m?.timestampMs)||Date.now();Q(le=>le.some(nt=>nt.id===j)?le:[...le.slice(-399),{id:j,source:"context",at:Z,event:m}])}catch{return}},{enabled:!!K}),en(s&&ee?`/event?sessionID=${encodeURIComponent(ee)}&runID=${encodeURIComponent(s)}`:"",i=>{try{const m=JSON.parse(String(i?.data||"{}"));if(!m)return;const j=Ta(m),Z=fn(m),le=[j||"event",String(m?.properties?.sessionID||m?.sessionID||ee||""),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(":");v(nt=>nt.some(Dt=>Dt.id===le)?nt:[...nt.slice(-499),{id:le,at:Z,event:m}])}catch{return}},{enabled:!!s&&!!ee}),en(s?"/api/global/event":"",i=>{try{const m=JSON.parse(String(i?.data||"{}")),j=Rs(m);if(!j||j!==s)return;const Z=Ta(m);if(!Z||Z==="server.connected"||Z==="engine.lifecycle.ready")return;const le=fn(m),nt=`global:${j}:${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,Re.length,Ye.length,$.length,Xe.length,Ot.length,Ft.length,!!M,!!s,!!ee,!!h,I.length,k.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 j=Zi(i?.schedule);E({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:j.scheduleKind==="cron"?"cron":"interval",cronExpression:j.cronExpression,intervalSeconds:String(j.intervalSeconds)})},Ga=i=>{const m=String(i?.status||"").trim().toLowerCase();return m==="paused"||m==="disabled"},Oa=l.length,kn=Re.length,Nn=Oa+kn,_n=B(()=>wm(Ie,k,I),[Ie,k,I]),Ea=B(()=>{const i=on.map(({sessionId:Z,message:le},nt)=>({id:`message:${Z}:${bm(le,nt)}`,kind:"message",sessionId:Z,at:fm(le),variant:hm(le),label:String(le?.info?.role||"session").trim()||"session",body:ps(le),raw:le,parts:gm(le),sessionLabel:qn(Z)})),m=Ld(k,ee).map(Z=>({...Z,sessionLabel:qn($i(Z.raw,ee))})),j=[...i,...m].sort((Z,le)=>Z.at-le.at);return C==="all"?j:j.filter(Z=>Z.sessionId===C)},[C,ee,on,k]);return fe(()=>{const i=Pe.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:[Nn," 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:Xu(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 j=Ye.find(le=>String(le?.automation_id||le?.routine_id||le?.id||"").trim()===m),Z=String(j?.run_id||j?.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:[kn," items"]})]}),Re.length>0?Re.map(i=>{const m=String(i?.automation_id||i?.automationId||"").trim(),j=String(i?.status||"draft").trim(),Z=j.toLowerCase()==="paused",le=cm(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(om(i)){u(i);return}pe(im(i))},disabled:!m,title:"Edit workflow automation","aria-label":"Edit workflow automation",children:e("i",{"data-lucide":"pencil"})}),e("span",{className:ea(j),children:j})]})]}),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:Xi(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 j=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:[j||"unknown run"," · running for ",Gs(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(j),children:[e("i",{"data-lucide":"bug"}),"Inspect"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:()=>ze.mutate({action:"pause",runId:j,family:j.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!j||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:j,family:j.startsWith("automation-v2-run-")?"v2":"legacy"}),disabled:!j||ze.isPending,children:[e("i",{"data-lucide":"play"}),"Resume"]})]})]},j||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 j=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:j||"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(j),children:[e("i",{"data-lucide":"bug"}),"Inspect"]})]})]})},`failed-${j||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,!Nn&&!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(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>c(""),children:e(Me.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 ",Gs(Ie)]}),q?e("div",{className:"tcp-subtle text-xs",children:["completed nodes: ",Ms(Ie)," · ","blocked nodes: ",dr(Ie)," · ","active sessions: ",qs(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]}),K?p.invalidateQueries({queryKey:["automations","run","context",K]}):Promise.resolve(),K?p.invalidateQueries({queryKey:["automations","run","context",K,"blackboard"]}):Promise.resolve(),K?p.invalidateQueries({queryKey:["automations","run","context",K,"events"]}):Promise.resolve(),K?p.invalidateQueries({queryKey:["automations","run","context",K,"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(K||"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(Gi,{tasks:Ne.tasks,currentTaskId:Ne.currentTaskId,selectedTaskId:O,onTaskSelect:i=>A(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:te,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:()=>A(""),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:qn(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,F?.workspace_inspection_used?e("span",{className:"tcp-badge-info",children:"workspace inspected"}):null,F?.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,he||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: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: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||L?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"})]})]}),F?.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(F?.verification_completed||0)," ","/"," ",Number(F?.verification_total||0)," ","checks ran"]}),Vt.length?e("div",{className:"grid gap-2",children:Vt.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,L?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:L})]}):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||xn||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:ne.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||_.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:()=>_.mutate({runId:s,taskId:String(h.id||""),reason:`requeued backlog task ${String(h.id||"")} from debugger`}),disabled:dt.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,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||de.isPending||dt.isPending||_.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||de.isPending||dt.isPending||_.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,xn?e("div",{className:"space-y-1",children:[e("button",{type:"button",className:"tcp-btn h-8 px-3 text-xs",onClick:()=>de.mutate({runId:s,nodeId:mt,reason:`requeued task ${mt} from debugger`}),disabled:Ve.isPending||Se.isPending||de.isPending||dt.isPending||_.isPending,children:de.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||F||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:F?.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:F?.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,F?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(F?.requested_tools)&&F.requested_tools.join(", ")||"n/a"]}),e("div",{children:["executed:"," ",Array.isArray(F?.executed_tools)&&F.executed_tools.join(", ")||"none"]}),e("div",{children:["workspace inspection:"," ",F?.workspace_inspection_used?"yes":"no"]}),e("div",{children:["web research:"," ",F?.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:ee?C==="all"?`Merged timeline across ${Ae.length||1} session${Ae.length===1?"":"s"}`:`Filtered to ${C}`:"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:C,onInput:i=>P(i.target.value),children:[e("option",{value:"all",children:"All sessions"}),Ae.map(i=>e("option",{value:i,title:i,children:qn(i)},i))]}):ee?e("span",{className:"tcp-badge-info",title:ee,children:qn(ee)}):null,ee?e("span",{className:"tcp-badge-info",title:ee,children:["live: ",hr(ee,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(),j=i.sessionId?` · ${i.sessionLabel}`:"";return`[${m}] ${i.label}${j}
|
|
2444
|
+
${i.body||aa(i.raw)}`}).join(`
|
|
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:()=>{Le(!0);const i=Pe.current;i&&(i.scrollTop=i.scrollHeight)},children:[e("i",{"data-lucide":"arrow-down"}),"Jump to latest"]})]})]}),e("div",{ref:Pe,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,j=m.scrollHeight-(m.scrollTop+m.clientHeight)<48;Le(j)},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 ${S==="all"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>W("all"),children:["all (",rn.length,")"]}),e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${S==="automations"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>W("automations"),children:"automations"}),q?e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${S==="context"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>W("context"),children:"context"}):null,e("button",{className:`tcp-btn h-7 flex-1 px-2 text-[11px] sm:flex-none ${S==="global"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>W("global"),children:"global"})]})]}),sn.length?e("div",{className:"grid gap-2 overflow-auto pr-1 sm:max-h-[12rem]",children:sn.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:[Vs(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:[_n.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:_n.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,xe.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:[xe.length," node",xe.length===1?"":"s"]})]}),e("div",{className:"grid gap-2",children:xe.map(({nodeId:i,guidance:m})=>{const j=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=qs(Ie)>0,_e=q&&!!s&&!ha&&(["blocked","failed","needs_repair"].includes(_a)||_a==="completed"&&(j.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:()=>A(`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||de.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||de.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,j.length?e("div",{className:"grid gap-1",children:j.map((Ca,ln)=>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-${ln}`))}):null,!j.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:H,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:ve===i.key?!0:void 0,className:ve===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:()=>z(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:Vs(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(on)].join(`
|
|
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: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,M?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>E(null),children:e(Me.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:M.name,onInput:i=>E(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:M.objective,onInput:i=>E(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:M.mode,onInput:i=>E(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 ${M.requiresApproval?"border-amber-400/60 bg-amber-400/10":""}`,role:"switch","aria-checked":M.requiresApproval,onClick:()=>E(i=>i&&{...i,requiresApproval:!i.requiresApproval}),children:[e("span",{className:"flex items-center gap-2",children:[e("i",{"data-lucide":M.requiresApproval?"shield-alert":"shield-check"}),M.requiresApproval?"Manual approvals enabled":"Fully automated enabled"]}),e("span",{className:`relative h-5 w-9 rounded-full transition ${M.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 ${M.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:M.scheduleKind,onInput:i=>E(m=>m&&{...m,scheduleKind:i.target.value}),children:[e("option",{value:"interval",children:"interval"}),e("option",{value:"cron",children:"cron"})]})]})}),M.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:M.cronExpression,onInput:i=>E(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:M.intervalSeconds,onInput:i=>E(m=>m&&{...m,intervalSeconds:i.target.value})})]})]}),e("div",{className:"tcp-confirm-actions mt-3",children:[e("button",{className:"tcp-btn",onClick:()=>E(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>M&&G.mutate(M),disabled:G.isPending,children:[e("i",{"data-lucide":"check"}),"Save"]})]})]})}):null,re?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>pe(null),children:e(Me.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:()=>pe(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=>pe(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=>pe(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 ${On(re.workspaceRoot)?"border-red-500/70 text-red-100":""}`,value:re.workspaceRoot,onInput:i=>pe(m=>m&&{...m,workspaceRoot:i.target.value})}),On(re.workspaceRoot)?e("div",{className:"text-xs text-red-300",children:On(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=>pe(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=>pe(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=>pe(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=>pe(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=>pe(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=>pe(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=>pe(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=>pe(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=>pe(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:()=>pe(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:()=>pe(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=>pe(m=>m&&{...m,customToolsText:i.target.value}),placeholder:`read
|
|
2449
|
+
write
|
|
2450
|
+
edit
|
|
2451
|
+
bash
|
|
2452
|
+
ls
|
|
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"}),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:()=>pe(j=>j&&{...j,selectedMcpServers:m?j.selectedMcpServers.filter(Z=>Z!==i.name):[...j.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:j=>pe(Z=>Z&&{...Z,nodes:Z.nodes.map(le=>le.nodeId===i.nodeId?{...le,objective:j.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:()=>pe(null),children:[e("i",{"data-lucide":"x-circle"}),"Cancel"]}),e("button",{className:"tcp-btn-primary",onClick:()=>re&&me.mutate(re),disabled:me.isPending,children:[e("i",{"data-lucide":"check"}),me.isPending?"Saving...":"Save"]})]})]})}):null,D?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>x(null),children:e(Me.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:D.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:D.automationId,family:D.family},{onSettled:()=>x(null)}),children:[e("i",{"data-lucide":"trash-2"}),Ke.isPending?"Deleting...":"Delete automation"]})]})]})}):null]})]})}function Im({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 D=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:D}),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:D,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:D,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},D)})]}):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 Cm({client:a,api:t,toast:n,navigate:r,providerStatus:s}){const d=ls().data?.aca_integration===!0,[u,p]=y("create"),[N,D]=y("simple"),[x,M]=y(""),[E,S]=y(null);return fe(()=>{try{const I=sessionStorage.getItem(Qs);if(!I)return;sessionStorage.removeItem(Qs);const Q=JSON.parse(I||"{}");Q?.tab==="running"&&p("running");const ee=String(Q?.runId||"").trim();ee&&M(ee)}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(I=>e("button",{onClick:()=>p(I.id),className:`flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium transition-all ${u===I.id?"bg-amber-500/20 text-amber-300 shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:[e("i",{"data-lucide":I.icon}),e("span",{children:I.label})]},I.id))}),e(Mt,{mode:"wait",children:e(Me.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},exit:{opacity:0,y:-6},transition:{duration:.15},children:u==="create"?e(Xt,{title:"Create an Automation",subtitle:"Describe what you want, pick a schedule, and Tandem handles the rest",children:e("div",{className:"grid gap-4",children:[e("div",{className:"rounded-xl border border-slate-700/50 bg-slate-950/50 p-4",children:[e("div",{className:"mb-2 text-xs font-medium uppercase tracking-[0.24em] text-slate-500",children:"Builder Mode"}),e("div",{className:"tcp-subtle text-xs",children:"Keep the simple wizard for quick automations, or switch to the advanced swarm builder for orchestrated mission planning."}),e("div",{className:"mt-3 flex flex-wrap gap-2",children:[e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${N==="simple"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>{D("simple"),S(null)},children:"Simple Wizard"}),e("button",{type:"button",className:`tcp-btn h-9 px-3 text-sm ${N==="advanced"?"border-amber-400/60 bg-amber-400/10 text-amber-300":""}`,onClick:()=>D("advanced"),children:"Advanced Swarm Builder"})]})]}),N==="advanced"?d?e(Lu,{client:a,api:t,toast:n,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel,editingAutomation:E,onShowAutomations:()=>{S(null),p("list")},onShowRuns:()=>{S(null),p("running")},onClearEditing:()=>S(null)}):e("div",{className:"rounded-2xl border border-amber-500/20 bg-amber-500/10 p-4",children:e("p",{className:"text-sm text-amber-200",children:[e("strong",{children:"Advanced mission builder"})," requires the external ACA (Hal900) integration. ACA is not currently connected. Use"," ",e("strong",{children:"simple mode"})," to create automations with engine-native features."]})}):e(Sm,{client:a,api:t,toast:n,navigate:r,defaultProvider:s.defaultProvider,defaultModel:s.defaultModel})]})}):u==="list"?e(Xt,{title:"My Automations",subtitle:"Installed packs, routines and run history",children:e(Xs,{client:a,toast:n,navigate:r,viewMode:"list",selectedRunId:x,onSelectRunId:M,onOpenRunningView:()=>p("running"),onOpenAdvancedEdit:I=>{S(I),D("advanced"),p("create")}})}):u==="running"?e(Xt,{title:"Live Running Tasks",subtitle:"Inspect active runs and open detailed event logs for each run",children:e(Xs,{client:a,toast:n,navigate:r,viewMode:"running",selectedRunId:x,onSelectRunId:M,onOpenRunningView:()=>p("running"),onOpenAdvancedEdit:I=>{S(I),D("advanced"),p("create")}})}):u==="optimize"?e(Xt,{title:"Workflow Optimization",subtitle:"Create and inspect overnight shadow-eval optimization campaigns",children:e(Hu,{client:a,toast:n})}):e(Xt,{title:"Teams & Approvals",subtitle:"Active agent teams and pending spawn approvals",children:e(Im,{client:a,toast:n})})},u)})]})}function Am(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function Pm(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 Tm(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 Rm(a,t){return String(a?.run_id||a?.runId||a?.id||`run-${t}`).trim()}function Mm(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 hs(a){return String(a?.status||"unknown").trim().toLowerCase()}function Zs(a){return String(a||"unknown").replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function qm(a){return!["completed","done","failed","cancelled"].includes(hs(a))}function $m(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=hs(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(ye,{tone:r,children:n})]}),e("div",{className:"mt-3 text-2xl font-semibold tracking-tight",children:t})]})}function Om({api:a,client:t}){const[n,r]=y("overview"),s=ls(),c=s.data?.aca_integration===!0,d=s.data?.engine_healthy===!0,u=s.data?.coding_workflows===!0,p=V({queryKey:["coding-workflows","health"],queryFn:()=>a("/api/system/health"),refetchInterval:u?15e3:!1,enabled:u}),N=V({queryKey:["coding-workflows","swarm"],queryFn:()=>a("/api/swarm/status").catch(()=>({status:"unknown",activeRuns:0})),refetchInterval:u?6e3:!1,enabled:u}),D=V({queryKey:["coding-workflows","workflow-context-runs"],queryFn:()=>a("/api/engine/context/runs?limit=16").catch(()=>({runs:[]})),refetchInterval:u?6e3:!1,enabled:u}),x=V({queryKey:["coding-workflows","mcp-servers"],queryFn:()=>t.mcp.list().catch(()=>({})),refetchInterval:u?1e4:!1,enabled:u}),M=V({queryKey:["coding-workflows","mcp-tools"],queryFn:()=>t.mcp.listTools().catch(()=>[]),refetchInterval:u?15e3:!1,enabled:u}),E=B(()=>Pm(x.data),[x.data]),S=B(()=>Tm(M.data),[M.data]),W=B(()=>Am(D.data,"runs").filter(A=>["workflow","bug_monitor_triage","coding","coding_workflow","task"].includes(String(A?.run_type||A?.runType||"").trim().toLowerCase())),[D.data]),I=W.filter(qm),Q=B(()=>$m(W),[W]),ee=!!(p.data?.engine?.ready||p.data?.engine?.healthy),ce=String(N.data?.status||"unknown"),C=E.some(O=>O.name.toLowerCase().includes("github")),P=[{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 u?e(nn,{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(ye,{tone:ee?"ok":"warn",children:ee?"Engine healthy":"Engine checking"}),e(ye,{tone:ce==="unknown"?"ghost":"info",children:["Swarm ",Zs(ce)]}),e(ye,{tone:C?"ok":"warn",children:C?"GitHub MCP connected":"GitHub MCP pending"}),e(ya,{tone:I.length?"live":"info",text:`${I.length} active runs`})]})]})})}),e("div",{className:"tcp-settings-tabs",children:P.map(O=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${n===O.id?"active":""}`,onClick:()=>r(O.id),children:[e("i",{"data-lucide":O.icon}),O.label]},O.id))}),n==="overview"?e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(sr,{label:"Workflow runs",value:W.length,helper:I.length?`${I.length} active`:"Idle",tone:I.length?"warn":"ok"}),e(sr,{label:"Connected MCP servers",value:E.length,helper:C?"GitHub available":"MCP pending",tone:C?"ok":"warn"}),e(sr,{label:"Registered tools",value:S.length,helper:"Tool surface",tone:S.length?"info":"ghost"}),e(sr,{label:"Engine mode",value:String(p.data?.engine?.mode||"unknown"),helper:String(p.data?.engine?.version||"n/a"),tone:ee?"ok":"warn"})]}):null,n==="board"?e("div",{className:"grid gap-4 xl:grid-cols-2 2xl:grid-cols-3",children:Q.map(O=>e(ot,{title:`${O.label} (${O.items.length})`,subtitle:O.hint,className:"h-full",children:O.items.length?e("div",{className:"grid gap-2",children:O.items.map((A,ve)=>{const z=hs(A);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:Mm(A)}),e("div",{className:"tcp-subtle mt-1 text-xs",children:String(A?.workspaceRoot||A?.workspace_root||"workspace")})]}),e(ye,{tone:O.id==="done"?"ok":O.id==="waiting"?"warn":"info",children:Zs(z)})]}),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(A?.run_type||A?.runType||"workflow")}),String(A?.run_id||A?.runId||"").trim()?e("span",{className:"rounded-full border border-white/10 px-2 py-1",children:String(A?.run_id||A?.runId).slice(0,12)}):null]})]},Rm(A,ve))})}):e(je,{text:"No runs in this lane yet."})},O.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(ye,{tone:"info",children:"Future tab: claim task"}),e(ye,{tone:"info",children:"Future tab: worker swarm"}),e(ye,{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:E.length?e("div",{className:"grid gap-2",children:E.map(O=>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:O.name}),e("div",{className:"tcp-subtle text-xs",children:[O.transport||"transport pending",O.lastError?` · ${O.lastError}`:""]})]}),e(ye,{tone:O.connected?"ok":O.enabled?"warn":"ghost",children:O.connected?"Connected":O.enabled?"Configured":"Disabled"})]},O.name))}):e(je,{text:"No MCP servers detected yet."})}),e(ot,{title:"Tool surface",subtitle:"Useful for GitHub, repo, and orchestration actions.",children:S.length?e("div",{className:"flex flex-wrap gap-2",children:[S.slice(0,20).map(O=>e(ye,{tone:"info",children:O},O)),S.length>20?e(ye,{tone:"ghost",children:["+",S.length-20," more"]}):null]}):e(je,{text:"No MCP tools discovered yet."})})]}):null]}):e(nn,{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:"Autonomous Coding"}),e("p",{className:"tcp-subtle mt-2 max-w-3xl",children:c?"External ACA is connected. Engine-native autonomous coding features are being loaded.":"External ACA not detected. Using engine-native autonomous coding."}),!d&&e("div",{className:"mt-3 rounded-2xl border border-yellow-500/20 bg-yellow-500/10 p-4",children:e("p",{className:"text-sm text-yellow-200",children:[e("strong",{children:"Engine not detected."})," Configure and start the Tandem engine to enable autonomous coding features. Use the"," ",e("a",{href:"/settings",className:"underline",children:"Settings"})," ","page to configure the engine connection."]})})]})})})})}function Em({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 D=(s.data||{})[p];if(!D)throw new Error(`No config found for ${p}`);await a.channels.put(p,D)},onSuccess:async()=>{t("ok","Channel reconfigured."),await n.invalidateQueries({queryKey:["channels"]})},onError:p=>t("err",p instanceof Error?p.message:String(p))}),d=r.data&&typeof r.data=="object"?r.data:{},u=Object.entries(d);return e("div",{className:"grid gap-4",children:e(Xt,{title:"Channels",subtitle:"Connector health and quick reconnect",children:e("div",{className:"grid gap-2",children:u.length?u.map(([p,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 Yt(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 Dm(a){return a?"ok":"ghost"}function jm(a){return at(a?.event_type||a?.type||a?.event||"workflow.event")}function Um({api:a,toast:t}){const n=ca(),[r,s]=y(""),[c,d]=y(""),[u,p]=y(""),[N,D]=y("context.task.created"),[x,M]=y(`{
|
|
2455
|
+
"event_id": "demo-task-1"
|
|
2456
|
+
}`),[E,S]=y([]),W=V({queryKey:["packs","list"],queryFn:()=>a("/api/engine/packs",{method:"GET"}).catch(()=>({packs:[]})),refetchInterval:15e3}),I=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}),ee=Yt(W.data,"packs"),ce=Yt(I.data,"workflows"),C=Yt(Q.data,"hooks"),P=B(()=>c||at(ee[0]?.pack_id||ee[0]?.name),[ee,c]),O=B(()=>u||at(ce[0]?.workflow_id),[u,ce]),A=V({queryKey:["workflows","runs",O],queryFn:()=>a(`/api/engine/workflows/runs${O?`?workflow_id=${encodeURIComponent(O)}&limit=20`:"?limit=20"}`,{method:"GET"}).catch(()=>({runs:[]})),refetchInterval:6e3}),ve=Yt(A.data,"runs"),z=V({queryKey:["packs","detail",P],enabled:!!P,queryFn:()=>a(`/api/engine/packs/${encodeURIComponent(P)}`,{method:"GET"})}),k=V({queryKey:["workflows","detail",O],enabled:!!O,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(O)}`,{method:"GET"})}),v=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))}),te=ke({mutationFn:q=>a(`/api/engine/workflows/${encodeURIComponent(q)}/run`,{method:"POST"}),onSuccess:async q=>{t("ok",`Workflow ${at(q?.run?.workflow_id||O)} started.`),await Promise.all([n.invalidateQueries({queryKey:["workflows"]}),n.invalidateQueries({queryKey:["workflows","runs"]})])},onError:q=>t("err",q instanceof Error?q.message:String(q))}),H=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))}),Pe=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=z.data?.pack||null,Le=k.data?.workflow||null,re=Yt(k.data,"hooks"),pe=H.data?.simulation||null;return en(`/api/engine/workflows/events${O?`?workflow_id=${encodeURIComponent(O)}`:""}`,q=>{try{const ge=JSON.parse(q.data);if(ge?.status==="ready")return;S(Te=>[...Te.slice(-59),{at:Date.now(),data:ge}])}catch{}},{enabled:!0}),e(nn,{className:"grid gap-4",children:[e(Oc,{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(ye,{tone:"info",children:[ee.length," installed packs"]}),e(ye,{tone:"warn",children:[ce.length," workflows"]}),e(ye,{tone:"ghost",children:[C.length," hooks"]})]})}),e(Dn,{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:ee.length?ee.map((q,ge)=>{const Te=at(q?.pack_id||q?.name||ge);return e("button",{type:"button",className:`tcp-list-item text-left ${Te===P?"border-amber-400/70":""}`,onClick:()=>d(Te),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:at(q?.name||Te)}),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||"")})]})]},Te)}):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:ce.length?ce.map(q=>{const ge=at(q?.workflow_id),Te=ge===O,Re=at(q?.source?.kind||"unknown");return e("button",{type:"button",className:`tcp-list-item text-left ${Te?"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-${Re==="pack"?"warn":"info"}`,children:Re})]}),e("div",{className:"tcp-subtle text-xs",children:[ge," · ",Yt(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()||v.isPending,onClick:()=>v.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||P)}),e(ye,{tone:"info",children:at($e?.installed?.version||"-")})]}),e("div",{className:"flex flex-wrap gap-2 text-xs",children:[e(ye,{tone:"ghost",children:[Number($e?.workflow_extensions?.workflow_count||0)," ","workflows"]}),e(ye,{tone:"ghost",children:[Number($e?.workflow_extensions?.workflow_hook_count||0)," ","hooks"]}),e(ye,{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"}),Yt($e?.workflow_extensions,"workflow_entrypoints").length?Yt($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(Dn,{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:!O||te.isPending,onClick:()=>O&&te.mutate(O),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||O)}),e(ye,{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:Yt(Le,"steps").length?Yt(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),Te=!!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:Pe.isPending,onClick:()=>Pe.mutate({bindingId:ge,enabled:!Te}),children:Te?"Disable":"Enable"})]}),e("div",{className:"mb-2 flex flex-wrap gap-2",children:[e(ye,{tone:Dm(Te),children:Te?"Enabled":"Disabled"}),e(ye,{tone:"ghost",children:[Yt(q,"actions").length," actions"]})]}),e("div",{className:"grid gap-1",children:Yt(q,"actions").map((Re,se)=>e("div",{className:"tcp-subtle text-xs",children:at(Re?.action||Re)},`${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:ve.length?ve.map((q,ge)=>{const Te=at(q?.status||"unknown"),Re=Te==="completed"?"ok":Te==="failed"?"err":Te==="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(ye,{tone:Re,children:Te})]}),e("div",{className:"tcp-subtle text-xs",children:["trigger: ",at(q?.trigger_event||"manual")]}),e("div",{className:"tcp-subtle text-xs",children:["actions: ",Yt(q,"actions").length]})]},at(q?.run_id||ge))}):e(je,{text:"No workflow runs have been recorded yet."})})})]})}),e(Dn,{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()||H.isPending,onClick:()=>H.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=>D(q.target.value),placeholder:"context.task.created"}),e("textarea",{className:"tcp-input min-h-[180px] font-mono text-xs",value:x,onInput:q=>M(q.target.value),spellCheck:!1}),pe?e("div",{className:"grid gap-3",children:[e("div",{className:"flex flex-wrap gap-2",children:Yt(pe,"canonical_events").map((q,ge)=>e(ye,{tone:"info",children:at(q)},`${at(q)}-${ge}`))}),e("div",{className:"grid gap-2",children:Yt(pe,"matched_bindings").length?Yt(pe,"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)," · ",Yt(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:Yt(pe,"planned_actions").length?Yt(pe,"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:()=>S([]),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:E.length?[...E].reverse().map((q,ge)=>{const Te=jm(q.data),Re=Te.endsWith(".failed")?"err":Te.endsWith(".completed")?"ok":Te.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:Te}),e(ye,{tone:Re,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 no(a){return a>=1?"bg-rose-500":a>=.8?"bg-amber-500":"bg-emerald-500"}function En(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=En(t,n),d=s?c>=.8?"bg-sky-400":"bg-cyan-500":no(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 Bm({budget:a}){const[t,n]=y(!1),r=a.limits_enforced===!1,s=Math.max(En(a.iterations_used,a.max_iterations),En(a.tokens_used,a.max_tokens),En(a.wall_time_secs,a.max_wall_time_secs),En(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":no(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 Vr(a,t=0){return String(a?.run_id||a?.runId||`run-${t}`).trim()}function ei(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 Fm(a,t=""){const n=String(t||"").trim(),r=[...Array.isArray(a)?a:[]].sort((d,u)=>ei(u)-ei(d));if(n){const d=r.find((u,p)=>Vr(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?Vr(c):""}function Lm(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=Vr(d,c);u&&(n[u]=d,r.push(u))}let s=a.selectedRunId;return s||(s=Fm(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]=ho(Lm,{runsById:{},orderedRunIds:[],selectedRunId:"",cursorsByRunId:{}});fe(()=>{r({type:"sync_runs",runs:Array.isArray(a)?a:[],preferredRunId:t})},[a,t]);const s=B(()=>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 Wm(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 zm({workspace:a,runIds:t,cursorToken:n,onEnvelope:r,onError:s}){const c=B(()=>[...new Set((t||[]).map(u=>String(u||"").trim()).filter(Boolean))],[t]),d=B(()=>{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=ts(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 Jm={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 Qm(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 ti(a){const t=Number(a||0);return!Number.isFinite(t)||t<=0?"Run":`Run ${new Date(t).toLocaleTimeString()}`}function Hm(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 Gm(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 Vm(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 Ym(a,t){const n=Fn(a).replace(/\/+$/,""),r=Fn(t).replace(/^\/+/,"");return n?r?`${n}/${r}`:n:r}function ai(a,t){const n=Fn(a).replace(/\/+$/,""),r=Fn(t);return!n||!r?!1:r===n?!0:r.startsWith(`${n}/`)}function ni(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 ri(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 Xm(a){return String(a?.event_type||a?.type||a?.event||"workflow.event").trim().toLowerCase()}function si(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 mn(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 Zm({api:a,toast:t,navigate:n}){const r=ca(),s=!!gi(),c=Rt(null),[d,u]=y(!0),[p,N]=y(!1),[D,x]=y(""),[M,E]=y(""),[S,W]=y(!1),[I,Q]=y(""),[ee,ce]=y(""),[C,P]=y(!1),[O,A]=y("4"),[ve,z]=y("3"),[k,v]=y("swarm.blackboard.default"),[te,H]=y(""),[Pe,$e]=y(""),[Le,re]=y(""),[pe,q]=y(""),[ge,Te]=y([]),[Re,se]=y(""),[Oe,qe]=y(""),[He,Y]=y(""),[Ze,ne]=y(!1);fe(()=>{u(!0),rt()},[]);const Ae=V({queryKey:["swarm","status"],queryFn:()=>a("/api/orchestrator/status"),refetchInterval:5e3}),St=V({queryKey:["swarm","runs",M],queryFn:()=>a(`/api/orchestrator/runs?workspace=${encodeURIComponent(M||"")}`),refetchInterval:6e3,enabled:!!Ae.data}),oe=Array.isArray(St.data?.runs)?St.data.runs:[],K=Km(oe,String(Ae.data?.runId||"").trim()),lt=K.selectedRunId,xt=K.setSelectedRunId,rt=K.clearSelectedRunId,Et=K.advanceCursor,Fe=d?"":String(lt||"").trim(),Bt=K.orderedRuns,At=B(()=>{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=B(()=>Wm(K.cursorsByRunId),[K.cursorsByRunId]),We=String(M||Ae.data?.workspaceRoot||"").trim(),ze=B(()=>{const f=String(Fe||"").trim();return f?[f]:[]},[Fe]),tt=Rt(0),be=ft(f=>{const L=String(f?.kind||"").trim().toLowerCase(),he=String(f?.run_id||f?.runId||"").trim();if(Fe&&he&&he!==Fe)return;const De=Number(f?.seq||0);he&&De>0&&(L==="context_run_event"||L==="blackboard_patch")&&Et(he,L,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]);zm({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",I],enabled:S&&!!I,queryFn:()=>a(`/api/orchestrator/workspaces/list?dir=${encodeURIComponent(I)}`)}),de=String(Se.data?.runStatus||Se.data?.run?.status||Ae.data?.status||"idle").trim().toLowerCase(),dt=B(()=>Hi(Se.data),[Se.data]),_=dt.tasks,G=B(()=>({...Jm,...Se.data?.budget||{}}),[Se.data?.budget]),me=String(ni(Se.data?.run)||ni(At)||(Fe?"":String(Ae.data?.workspaceRoot||M||""))).trim();fe(()=>{me&&($e(f=>!f||!ai(me,f)?me:f),re(f=>ai(me,f)?f:""))},[me]);const Ke=Array.isArray(Ve.data?.directories)?Ve.data.directories:[],l=String(ee||"").trim().toLowerCase(),b=B(()=>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||I||"").trim(),$=V({queryKey:["swarm","workspace-files",me,Pe],enabled:!!me&&!!Pe,queryFn:async()=>{const f=await a(`/api/orchestrator/workspaces/files?workspaceRoot=${encodeURIComponent(me)}&dir=${encodeURIComponent(Pe)}`).catch(()=>({directories:[],files:[],parent:null,dir:Pe})),L=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||Ym(me,String(Be?.name||""))}});return{ok:!0,dir:String(f?.dir||Pe),parent:f?.parent||null,directories:L,files:De,fileAccessAllowed:!0}},refetchInterval:1e4}),Ye=V({queryKey:["swarm","workspace-file",me,Le],enabled:!!me&&!!Le,queryFn:async()=>a(`/api/orchestrator/workspaces/read?workspaceRoot=${encodeURIComponent(me)}&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=Vm(Le),ae=["md","markdown","mdx"].includes(bt),Ne=["html","htm"].includes(bt);fe(()=>{Ze&&!Ne&&ne(!1)},[Ne,Ze]);const h=B(()=>_.map(f=>`${f.id}:${f.state}:${f.error_message||""}`).join("|"),[_]),U=B(()=>_.find(f=>f.id===Oe)||null,[Oe,_]),J=B(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[];let L=null,he=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);(!L||zt>=he)&&(L={sessionId:_t,event:De},he=zt)}return L},[Se.data?.events]),F=B(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[];for(let L=f.length-1;L>=0;L-=1){const he=f[L],De=String(he?.type||"").trim().toLowerCase();if(!["task_started","step_started","task_completed","step_completed"].includes(De))continue;const Be=he?.payload&&typeof he.payload=="object"?he.payload:{},it=String(Be?.session_id||"").trim();if(it)return it}return String(J?.sessionId||"").trim()},[J?.sessionId,Se.data?.events]),X=B(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[],L=ri(f),he=[];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(L[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(he.push({id:`${String(Be?.seq||De)}-${it}`,type:it,title:Zt||it,detail:va,at:Number(Be?.ts_ms||0)}),he.length>=12)break}return he},[Se.data?.events]),we=B(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[];for(let L=f.length-1;L>=0;L-=1){const he=f[L],De=String(he?.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(F||"")],queryFn:()=>a(`/api/engine/session/${encodeURIComponent(String(F||""))}`),refetchInterval:6e3,enabled:!!F}),st=B(()=>{const f=Ti(Ue.data,"Assistant");for(let L=f.length-1;L>=0;L-=1)if(f[L]?.role==="assistant"&&String(f[L]?.text||"").trim())return String(f[L]?.text||"").trim();return""},[Ue.data]),vt=B(()=>{const f=Array.isArray(Ue.data)?Ue.data:Array.isArray(Ue.data?.messages)?Ue.data.messages:[],L=[];for(let he=f.length-1;he>=0;he-=1){const De=f[he],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(L.push(va),L.length>=10)return L}}return L},[Ue.data]),It=B(()=>{const f=Array.isArray(Se.data?.events)?Se.data.events:[],L=ri(f),he=[];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(L[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(he.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}),he.length>=8)break}return he},[Se.data?.events]),et=B(()=>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||k||"").trim(),Lt=V({queryKey:["workflow","detail",yt],enabled:!!yt,queryFn:()=>a(`/api/engine/workflows/${encodeURIComponent(yt)}`),refetchInterval:15e3}),Ht=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(Ht.data?.runs)?Ht.data.runs:[],Gt=B(()=>{const f={};for(const L of Ct){const he=mn(L);if(!he)continue;const De=f[he]||{runs:0,failed:0};De.runs+=1,String(L?.status||"").trim().toLowerCase()==="failed"&&(De.failed+=1),f[he]=De}return f},[Ct]),kt=B(()=>Re?Ct.filter(f=>mn(f)===Re):Ct,[Re,Ct]),Ge=B(()=>{const f=[];for(const L of kt){const he=String(L?.run_id||"").trim(),De=mn(L);for(const Be of Array.isArray(L?.actions)?L.actions:[])f.push({id:`${he}:${String(Be?.action_id||Be?.action||f.length)}`,runId:he,action:String(Be?.action||"unknown action"),status:String(Be?.status||"unknown"),detail:String(Be?.detail||""),output:Be?.output,updatedAt:Number(Be?.updated_at_ms||L?.updated_at_ms||0),taskId:String(Be?.task_id||De||"").trim()})}return f.sort((L,he)=>he.updatedAt-L.updatedAt),f},[kt]);fe(()=>{const f=kt;if(!f.length){q("");return}f.some(he=>{const De=String(he?.run_id||"").trim();return De&&De===pe})||q(String(f[0]?.run_id||"").trim())},[kt,pe]);const Ce=V({queryKey:["workflow","run",pe],enabled:!!pe,queryFn:()=>a(`/api/engine/workflows/runs/${encodeURIComponent(pe)}`),refetchInterval:5e3}).data?.run||null;fe(()=>{const f=mn(Ce);f&&se(f)},[Ce?.run_id,Ce?.source_event_id]),fe(()=>{Te([])},[yt]),en(`/api/engine/workflows/events${yt?`?workflow_id=${encodeURIComponent(yt)}`:""}`,f=>{try{const L=JSON.parse(f.data);if(L?.status==="ready")return;Te(he=>[...he.slice(-79),{at:Date.now(),data:L}])}catch{}},{enabled:!!yt});const xe=ke({mutationFn:()=>{const f=String(D||"").trim(),L=String(M||"").trim();if(!f)throw new Error("Enter a prompt first.");if(!L)throw new Error("Set workspace path first.");return a("/api/orchestrator/start",{method:"POST",body:JSON.stringify({objective:f,workspaceRoot:L,maxTasks:Number(O||4),maxAgents:Number(ve||3),workflowId:String(k||"swarm.blackboard.default").trim(),requireLlmPlan:!0,allowLocalPlannerFallback:!1,verificationMode:"strict"})})},onSuccess:async f=>{const L=String(f?.runId||"").trim();L&&xt(L),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:L})=>a(f,{method:"POST",body:JSON.stringify(L)}),onSuccess:async(f,L)=>{if(L.path==="/api/orchestrator/request_revision"){const he=String(f?.runId||"").trim();he&&(xt(he),H("")),t("ok","Reworked plan created.")}L.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 L=String(f||"").trim();if(!L)throw new Error("Missing run id.");return await a("/api/orchestrator/cancel",{method:"POST",body:JSON.stringify({runId:L})}).catch(()=>null),await a("/api/orchestrator/runs/hide",{method:"POST",body:JSON.stringify({runIds:[L]})}).catch(()=>null),L},onSuccess:async()=>{rt(),u(!0),H(""),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),H("")},[rt]);fe(()=>{const f=c.current;f&&xa(f)},[d,p,Bt,Fe,de,Pe,Xe.length,Ot.length,Le,Pt,Oe,He,Ze,h]);const ia=!Fe,ba=de==="planning"||de==="queued",Kt=de==="awaiting_approval",Vt=["completed","failed","cancelled"].includes(de),mt=de==="running",ua=de==="paused",na=de==="failed"||de==="blocked",Nt=["queued","planning","awaiting_approval","running","paused","blocked"].includes(de),Je=e(la,{children:[e(Me.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,L)=>{const he=String(f?.run_id||f?.runId||`run-${L}`),De=he===Fe;return e(Me.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(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:ti(Hm(f))})]}),e("span",{className:"tcp-subtle line-clamp-2 block text-[11px]",children:String(f?.objective||"").trim()||"No objective"})]})},he)})}),Bt.length?null:e("p",{className:"chat-rail-empty px-1 py-2",children:"No runs yet."})]})]}),e(Mt,{children:p?e(Me.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(D||"").trim().length>0&&String(M||"").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(L=>!L),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:D,onInput:L=>x(L.target.value)}),e("div",{className:"grid gap-2 md:grid-cols-[auto_1fr]",children:[e("button",{className:"tcp-btn",onClick:()=>{const L=String(M||Ae.data?.workspaceRoot||"/").trim();Q(L||"/"),ce(""),W(!0)},children:[e("i",{"data-lucide":"folder-open"}),"Browse"]}),e("input",{className:"tcp-input",readOnly:!0,placeholder:"No workspace selected. Use Browse.",value:M})]}),e("div",{className:"tcp-subtle text-xs",children:["Selected folder: ",M||"none"]}),M?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:()=>xe.mutate(),disabled:xe.isPending||!f,children:[e("i",{"data-lucide":"send"}),"Send"]}),e("button",{className:"tcp-btn",type:"button",onClick:()=>P(L=>!L),children:[e("i",{"data-lucide":"sliders-horizontal"}),C?"Hide Advanced":"Show Advanced"]})]}),C?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:O,onInput:L=>A(L.target.value),title:"max tasks"}),e("input",{className:"tcp-input",type:"number",min:"1",max:"16",value:ve,onInput:L=>z(L.target.value),title:"max agents"}),e("input",{className:"tcp-input",value:k,onInput:L=>v(L.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]})]})})]}),S?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&&(E(R),W(!1),ce(""),t("ok",`Workspace selected: ${R}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{W(!1),ce("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ee,onInput:L=>ce(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:b.length?b.map(L=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>Q(String(L?.path||"")),children:[e("i",{"data-lucide":"folder-open"}),String(L?.name||L?.path||"")]},String(L?.path||L?.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(de),children:de||"unknown"}),e("span",{className:"inline-flex items-center gap-1 tcp-subtle",children:[e("i",{"data-lucide":"history"}),e("span",{children:ti(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: ",we]})]}),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:te,onInput:f=>H(f.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",disabled:!te.trim(),onClick:()=>ut.mutate({path:"/api/orchestrator/request_revision",body:{runId:Fe,feedback:te,maxTasks:Number(O||4),maxAgents:Number(ve||3),workflowId:k}}),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,Vt?e("div",{className:"mb-3 rounded-lg border border-slate-700/60 bg-slate-900/25 p-2 text-xs tcp-subtle",children:de==="failed"?"This run is failed. Continue the run or retry a failed task.":`This run is ${de}. 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:!me,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:!me,onClick:()=>{me&&$e(me)},children:e("i",{"data-lucide":"home"})})]}),e("div",{className:"mb-2 tcp-subtle text-[11px]",style:{overflowWrap:"anywhere"},children:Pe||me||"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 L=String(f?.path||"");return e("button",{className:"tcp-list-item text-left",onClick:()=>$e(L),children:e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":"folder-open"}),e("span",{children:String(f?.name||L)})]})},`dir-${L}`)}),Ot.map(f=>{const L=String(f?.path||"");return e("button",{className:`tcp-list-item text-left ${L===Le?"border-amber-400/70":""}`,onClick:()=>re(L),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||L)})]}),e("span",{className:"tcp-subtle shrink-0 text-[11px]",children:Gm(f?.size)})]})},`file-${L}`)}),!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:()=>ne(!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"})}):ae?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:gn(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(si(f)),t("ok","Copied verification feedback.")}catch(L){t("err",L instanceof Error?L.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"})}),F?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(Bm,{budget:G})}),e(Gi,{tasks:_,currentTaskId:dt.currentTaskId,selectedTaskId:Re,workflowSummaryByTaskId:Gt,onTaskSelect:f=>{const L=Re===f.id?"":f.id;se(L),qe(f.id)},onRetryTask:f=>ut.mutate({path:"/api/orchestrator/retry",body:{runId:Fe,stepId:f.id}})}),Re?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:Re})," is filtering workflow runs and event stream."]})]}):null,Re?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,L)=>{const he=String(f?.run_id||`workflow-run-${L}`).trim(),De=he===pe,Be=String(f?.status||"unknown").trim(),it=mn(f);return e("button",{type:"button",className:`tcp-list-item text-left ${De?"border-amber-400/70":""}`,onClick:()=>q(he),children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:he}),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]})]},he)}):e(je,{text:Re?"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,L)=>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")}-${L}`)):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:()=>Te([]),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 L=mn(f.data?.properties||{});if(Re&&L&&L!==Re)return!1;if(!pe)return!0;const he=String(f.data?.properties?.runID||"").trim();return!he||he===pe}).reverse().map((f,L)=>{const he=Xm(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(he.endsWith(".failed")?"failed":he.endsWith(".completed")?"completed":"running"),children:he}),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}-${L}`)})}):e("div",{className:"tcp-subtle text-xs",children:"No workflow events streamed for this run yet."})]}),e(Mt,{children:[U?e(Me.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:()=>qe("")}),e(Me.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:()=>qe(""),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:Qm(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)]}),Gt?.[U.id]?e("div",{className:"tcp-subtle",children:["workflow runs:"," ",Gt[U.id].runs,Gt[U.id].failed?`, failed ${Gt[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),qe("")},children:"Focus task"}),e("button",{className:"tcp-btn",onClick:()=>qe(""),children:"Close"})]})]})]}):null,et?e(Me.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(Me.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(si(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(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>ne(!1),children:e(Me.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:()=>ne(!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}),S?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&&(E(R),W(!1),ce(""),t("ok",`Workspace selected: ${R}`))},children:[e("i",{"data-lucide":"badge-check"}),"Select This Folder"]}),e("button",{className:"tcp-btn",onClick:()=>{W(!1),ce("")},children:[e("i",{"data-lucide":"x"}),"Close"]})]}),e("div",{className:"mb-2",children:e("input",{className:"tcp-input",placeholder:"Type to filter folders...",value:ee,onInput:f=>ce(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 ep(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function tp({api:a,toast:t}){const n=ca(),[r,s]=y("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=ep(c.data,"files");return e("div",{className:"grid gap-4",children:e(Xt,{title:"Files",subtitle:"Browse and delete uploaded files",children:[e("div",{className:"mb-3 flex gap-2",children:[e("input",{className:"tcp-input",value:r,onInput:p=>s(p.target.value),placeholder:"uploads"}),e("button",{className:"tcp-btn",onClick:()=>c.refetch(),children:[e("i",{"data-lucide":"refresh-cw"}),"Refresh"]})]}),e("div",{className:"grid gap-2",children:u.length?u.map((p,N)=>{const D=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:D}),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(D),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})})]},D)}):e(je,{text:"No files found for this directory."})})]})})}function ap(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function np({client:a,toast:t}){const n=ca(),[r,s]=y(""),[c,d]=y(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=ap(u.data,"items"),D=B(()=>N.map((x,M)=>{const E=String(x?.id||`mem-${M}`),S=String(x?.text||x?.content||x?.value||""),W=S.length>340?`${S.slice(0,340)}...`:S;return{id:E,text:S,compact:W,html:gn(S)}}),[N]);return e(nn,{className:"grid gap-4",children:e(ot,{title:"Memory",subtitle:"Search recent records and open full entry details inline.",actions:e(la,{children:[e(ye,{tone:"info",children:[D.length," results"]}),r.trim()?e(ye,{tone:"ghost",children:["Filter: ",r]}):e(ye,{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:D.length?D.map(x=>{const M=c===x.id;return e(Me.article,{layout:!0,className:`tcp-list-item cursor-pointer ${M?"border-amber-500/60":""}`,onClick:()=>d(M?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(ye,{tone:M?"info":"ghost",children:M?"expanded":"compact"}),e("button",{className:"tcp-btn-danger h-7 px-2 text-xs",onClick:E=>{E.stopPropagation(),p.mutate(x.id)},children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]}),e(Mt,{initial:!1,mode:"wait",children:M?e(Me.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(Me.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 ro=[{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 rp(a,t){return Array.isArray(a)?a:Array.isArray(a?.[t])?a[t]:[]}function sp(a){const t=String(a||"").trim();return t?t.startsWith("/")?"":"Workspace root must be an absolute path.":"Workspace root is required."}function ip(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 op(a,t){const n=String(t||"").trim();if(n)return{type:"cron",cron_expression:n,timezone:"UTC"};const r=ro.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 lp(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 cp({client:a,toast:t}){const n=ca(),r=Rt(null),[s,c]=y("Daily Engineering Standup"),[d,u]=y(""),[p,N]=y("Every morning"),[D,x]=y(""),[M,E]=y("docs/standups/{{date}}.md"),[S,W]=y([]),[I,Q]=y(null),ee=V({queryKey:["teams","standup","templates"],queryFn:()=>a?.agentTeams?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:12e3}),ce=V({queryKey:["teams","standup","health"],queryFn:()=>a?.health?.().catch(()=>({}))??Promise.resolve({}),refetchInterval:3e4});fe(()=>{const A=String(ce.data?.workspaceRoot||ce.data?.workspace_root||"").trim();A&&u(ve=>ve||A)},[ce.data]);const C=B(()=>rp(ee.data,"templates").map(lp).filter(A=>!!A),[ee.data]),P=ke({mutationFn:async()=>{const A=String(s||"").trim(),ve=String(d||"").trim();if(!A)throw new Error("Standup name is required.");const z=sp(ve);if(z)throw new Error(z);if(!S.length)throw new Error("Select at least one participant template.");return await a?.agentTeams?.composeStandup?.({name:A,workspaceRoot:ve,schedule:op(p,D),participantTemplateIds:S,reportPathTemplate:String(M||"").trim()||void 0})||null},onSuccess:A=>{Q(A?.automation||null)},onError:A=>t("err",A instanceof Error?A.message:String(A))}),O=ke({mutationFn:async()=>{const A=I||(await P.mutateAsync())?.automation;if(!A)throw new Error("Standup compose failed.");return a?.automationsV2?.create?.(A)},onSuccess:async()=>{t("ok","Agent standup automation created."),Q(null),await n.invalidateQueries({queryKey:["automations"]})},onError:A=>t("err",A instanceof Error?A.message:String(A))});return fe(()=>{const A=r.current;A&&xa(A)},[s,d,p,D,M,S.join(","),C.length,P.isPending,O.isPending,!!I]),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:A=>c(A.target.value)}),e("input",{className:"tcp-input",placeholder:"/absolute/workspace/root",value:d,onInput:A=>u(A.target.value)}),e("select",{className:"tcp-input",value:p,onInput:A=>N(A.target.value),children:ro.map(A=>e("option",{value:A.label,children:A.label},A.label))}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"Custom cron (optional)",value:D,onInput:A=>x(A.target.value)})]}),e("input",{className:"tcp-input font-mono text-sm",placeholder:"docs/standups/{{date}}.md",value:M,onInput:A=>E(A.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"}),C.length?e("div",{className:"grid gap-2 md:grid-cols-2",children:C.map(A=>{const ve=S.includes(A.templateId);return e("button",{type:"button",className:`tcp-list-item text-left transition-all ${ve?"border-emerald-400/60 bg-emerald-400/10":""}`,onClick:()=>W(z=>z.includes(A.templateId)?z.filter(k=>k!==A.templateId):[...z,A.templateId]),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:A.displayName}),e("span",{className:"tcp-badge-info",children:A.role})]}),e("div",{className:"tcp-subtle mt-1 text-xs",children:A.templateId}),A.modelLabel?e("div",{className:"mt-2 text-xs text-emerald-200",children:A.modelLabel}):null]},A.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:P.isPending||!C.length,onClick:()=>P.mutate(),children:[e("i",{"data-lucide":"file-search"}),P.isPending?"Composing…":"Preview Standup Workflow"]}),e("button",{type:"button",className:"tcp-btn-primary",disabled:O.isPending||!C.length,onClick:()=>O.mutate(),children:[e("i",{"data-lucide":"rocket"}),O.isPending?"Creating…":"Create Standup Automation"]})]}),I?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(I?.name||"Standup preview")}),e("span",{className:"tcp-badge-info",children:[Array.isArray(I?.flow?.nodes)?I.flow.nodes.length:0," nodes"]})]}),e("div",{className:"grid gap-2 text-xs text-slate-300",children:[e("div",{children:["schedule: ",ip(I?.schedule)]}),e("div",{children:["report:"," ",String(I?.metadata?.standup?.report_path_template||M)]}),e("div",{children:["participants:"," ",String((I?.metadata?.standup?.participant_template_ids||S).join(", "))]})]})]}):null]})}const ii=["worker","reviewer","tester","watcher","delegator","committer","orchestrator"],dp={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."},up=["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 mp(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 pp(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 oi({client:a,toast:t}){const n=ca(),r=a?.agentTeams,s=Rt(null),[c,d]=y(or),[u,p]=y(null),N=Rt(null),x=ls().data?.aca_integration===!0,M=V({queryKey:["teams","templates"],queryFn:()=>r?.listTemplates?.().catch(()=>({templates:[]}))??Promise.resolve({templates:[]}),refetchInterval:8e3}),E=V({queryKey:["teams","instances"],queryFn:()=>r?.listInstances?.().catch(()=>({instances:[]}))??Promise.resolve({instances:[]}),refetchInterval:8e3}),S=V({queryKey:["teams","approvals"],queryFn:()=>r?.listApprovals?.().catch(()=>({spawnApprovals:[]}))??Promise.resolve({spawnApprovals:[]}),refetchInterval:6e3}),W=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:pp(c)})},onSuccess:async()=>{t("ok",u?"Template updated.":"Template created."),d(or),p(null),await n.invalidateQueries({queryKey:["teams"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),I=ke({mutationFn:v=>r?.deleteTemplate?.(v),onSuccess:async()=>{t("ok","Template deleted."),u&&(p(null),d(or)),await n.invalidateQueries({queryKey:["teams"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),Q=ke({mutationFn:({requestId:v,decision:te})=>te==="approve"?r?.approveSpawn?.(v):r?.denySpawn?.(v),onSuccess:async()=>{t("ok","Approval updated."),await n.invalidateQueries({queryKey:["teams"]})},onError:v=>t("err",v instanceof Error?v.message:String(v))}),ee=B(()=>Ur(M.data,"templates").map(mp).filter(v=>v.templateId),[M.data]),ce=Ur(E.data,"instances"),C=Ur(S.data,"spawnApprovals"),P=!!(u||c.templateId||c.displayName||c.systemPrompt),O=c.displayName.trim()||c.templateId.trim()||"New Agent",A=O.slice(0,1).toUpperCase()||"A",ve=dp[c.role],z=c.avatarUrl.trim();fe(()=>{const v=s.current;v&&xa(v)},[ee.length,ce.length,C.length,c.role,c.templateId,c.displayName,c.avatarUrl,c.modelProvider,c.modelId,c.systemPrompt,u,W.isPending,I.isPending,Q.isPending]);const k=v=>{if(!v)return;if(v.size>10*1024*1024){t("err","Avatar image is too large (max 10 MB).");return}const te=new FileReader;te.onload=()=>{const H=typeof te.result=="string"?te.result:"";if(!H){t("err","Failed to read avatar image.");return}d(Pe=>({...Pe,avatarUrl:H}))},te.onerror=()=>t("err","Failed to read avatar image."),te.readAsDataURL(v)};return e("div",{ref:s,className:"grid gap-4",children:[x&&e(Xt,{title:"Agent Standup",subtitle:"Compose scheduled standups from the same saved agents you manage here",children:e(cp,{client:a,toast:t})}),e("div",{className:"grid gap-4 xl:grid-cols-2",children:[e(Xt,{title:"Agents",subtitle:"Create reusable agent personalities, prompts, and default models for automation workflows",children:e("div",{className:"grid gap-3",children:[e("div",{className:"rounded-2xl border border-cyan-500/20 bg-cyan-500/5 p-4",children:[e("div",{className:"text-xs font-medium uppercase tracking-[0.24em] text-cyan-300",children:"Reusable Personalities"}),e("div",{className:"mt-2 text-sm text-slate-300",children:"Each saved agent defines a persistent personality for automation workflows. Define who the agent is, what kind of work it owns, and which default model it should use. These personalities can be reused in standups and other workflow responses."})]}),e("div",{className:"grid gap-2 md:grid-cols-2",children:[e("input",{className:"tcp-input",placeholder:"template-id",value:c.templateId,disabled:!!u,onInput:v=>d(te=>({...te,templateId:v.target.value}))}),e("input",{className:"tcp-input",placeholder:"Display name",value:c.displayName,onInput:v=>d(te=>({...te,displayName:v.target.value}))}),e("select",{className:"tcp-input",value:c.role,onInput:v=>d(te=>({...te,role:v.target.value})),children:ii.map(v=>e("option",{value:v,children:v},v))}),e("input",{className:"tcp-input",placeholder:"Avatar URL or upload (optional)",value:c.avatarUrl,onInput:v=>d(te=>({...te,avatarUrl:v.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model provider (optional)",value:c.modelProvider,onInput:v=>d(te=>({...te,modelProvider:v.target.value}))}),e("input",{className:"tcp-input",placeholder:"Model ID (optional)",value:c.modelId,onInput:v=>d(te=>({...te,modelId:v.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:up.map(v=>e("button",{type:"button",className:"tcp-btn h-auto min-h-8 px-3 py-2 text-left text-xs",onClick:()=>d(te=>({...te,systemPrompt:v})),children:"Use Example"},v))})]}),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:z?e("img",{src:z,alt:O,className:"h-full w-full object-cover"}):A}),e("div",{className:"min-w-0",children:[e("div",{className:"flex flex-wrap items-center gap-2",children:[e("strong",{className:"text-white",children:O}),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:ve})]})]}),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(v=>({...v,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:v=>{k(v.target.files?.[0]||null),v.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:v=>d(te=>({...te,systemPrompt:v.target.value}))}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{type:"button",className:"tcp-btn",disabled:W.isPending,onClick:()=>W.mutate(),children:[e("i",{"data-lucide":"save"}),u?"Update Agent":"Create Agent"]}),P&&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:[ee.length," saved"]})]}),ee.length?ee.map(v=>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:v.displayName||v.templateId}),e("span",{className:"tcp-badge-info",children:v.role}),v.modelProvider&&v.modelId?e("span",{className:"tcp-badge-ok",children:[v.modelProvider,"/",v.modelId]}):null]}),e("div",{className:"tcp-subtle text-xs",children:v.templateId}),v.systemPrompt?e("div",{className:"mt-2 line-clamp-4 text-xs text-slate-300",children:v.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(v.templateId),d({templateId:v.templateId,displayName:v.displayName,avatarUrl:v.avatarUrl,role:ii.includes(v.role)?v.role:"worker",systemPrompt:v.systemPrompt,modelProvider:v.modelProvider,modelId:v.modelId})},children:[e("i",{"data-lucide":"pencil"}),"Edit"]}),e("button",{type:"button",className:"tcp-btn-danger h-7 px-2 text-xs",onClick:()=>I.mutate(v.templateId),children:[e("i",{"data-lucide":"trash-2"}),"Delete"]})]})]})},v.templateId)):e(je,{title:"No agents yet",text:"Create your first saved personality here, then reuse it across automation workflows and standups."})]})]})}),e(Xt,{title:"Team Instances",subtitle:"Running collaborative agent instances",children:e("div",{className:"grid gap-2",children:ce.length?ce.map((v,te)=>e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(v?.template_id||v?.templateID||v?.instance_id||"Instance")}),e("span",{className:"tcp-badge-info",children:String(v?.status||"active")})]}),e("div",{className:"tcp-subtle text-xs",children:["mission: ",String(v?.mission_id||v?.missionID||"n/a")]})]},String(v?.instance_id||v?.id||te))):e(je,{text:"No team instances found."})})}),e(Xt,{title:"Spawn Approvals",subtitle:"Pending team approval requests",children:e("div",{className:"grid gap-2",children:C.length?C.map((v,te)=>{const H=String(v?.approval_id||v?.request_id||v?.id||`request-${te}`);return e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 font-medium",children:String(v?.reason||v?.title||H)}),e("div",{className:"tcp-subtle text-xs",children:H}),e("div",{className:"mt-2 flex gap-2",children:[e("button",{type:"button",className:"tcp-btn h-7 px-2 text-xs",onClick:()=>Q.mutate({requestId:H,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:()=>Q.mutate({requestId:H,decision:"deny"}),children:[e("i",{"data-lucide":"x"}),"Deny"]})]})]},H)}):e(je,{text:"No pending approvals."})})})]})]})}function lr(a){return a?.type||a?.event||"event"}function li(a){const t=String(a||"").trim().toLowerCase();return["server.connected","engine.lifecycle.ready","engine.heartbeat","engine.lifecycle.heartbeat"].includes(t)}function ci(a){return String(a?.type||a?.event||"").trim()==="context.run.stream"&&String(a?.run_id||a?.runId||"").trim().startsWith("workflow-")}function hp({client:a,toast:t,navigate:n}){const[r,s]=y([]),[c,d]=y(""),[u,p]=y("all"),[N,D]=y(!0),[x,M]=y(null),E=B(()=>!x||!ci(x.data)?"":String(x.data?.run_id||x.data?.runId||"").trim(),[x]),S=V({queryKey:["feed","workflow-context-run",E],enabled:!!E,queryFn:()=>Qt(`/api/engine/context/runs/${encodeURIComponent(E)}`).catch(()=>({run:null}))}),W=V({queryKey:["feed","workflow-context-blackboard",E],enabled:!!E,queryFn:()=>Qt(`/api/engine/context/runs/${encodeURIComponent(E)}/blackboard`).catch(()=>({blackboard:null}))});en("/api/global/event",C=>{try{const P=JSON.parse(C.data);s(O=>[...O.slice(-299),{at:Date.now(),data:P}])}catch{}},{enabled:!0});const I=B(()=>{const C=new Map;for(const P of r){const O=lr(P.data);N&&li(O)||C.set(O,(C.get(O)||0)+1)}return[...C.entries()].sort((P,O)=>O[1]-P[1])},[r,N]),Q=B(()=>{const C=c.trim().toLowerCase();return r.filter(P=>{const O=lr(P.data);return N&&li(O)||u!=="all"&&O!==u?!1:C?`${O} ${JSON.stringify(P.data||{})}`.toLowerCase().includes(C):!0}).slice(-240).reverse()},[r,c,u,N]);async function ee(C){try{const P=await Qt("/api/engine/packs/install",{method:"POST",body:JSON.stringify({path:C,source:{kind:"control_panel_feed",event:"pack.detected"}})});t("ok",`Installed ${P?.installed?.name||"pack"}`)}catch(P){t("err",P instanceof Error?P.message:String(P))}}async function ce(C){try{const P=await Qt("/api/engine/packs/install-from-attachment",{method:"POST",body:JSON.stringify({attachment_id:String(C?.properties?.attachment_id||C?.attachment_id||""),path:String(C?.properties?.path||C?.path||""),connector:String(C?.properties?.connector||C?.connector||"")||void 0,channel_id:String(C?.properties?.channel_id||C?.channel_id||"")||void 0,sender_id:String(C?.properties?.sender_id||C?.sender_id||"")||void 0})});t("ok",`Installed ${P?.installed?.name||"pack"}`)}catch(P){t("err",P instanceof Error?P.message:String(P))}}return e(nn,{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:C=>d(C.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:()=>D(C=>!C),children:[e("i",{"data-lucide":N?"filter":"filter-x"}),N?"Hide noise":"Show noise"]}),I.slice(0,8).map(([C,P])=>e(Ar,{active:u===C,onClick:()=>p(C),children:[e("i",{"data-lucide":"activity"}),C," (",P,")"]},C))]}),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((C,P)=>{const O=lr(C.data),A=String(O).startsWith("pack."),ve=ci(C.data),z=String(C.data?.properties?.path||C.data?.path||""),k=String(C.data?.properties?.attachment_id||C.data?.attachment_id||"");return e("article",{className:"tcp-list-item cursor-pointer",onClick:()=>M(C),children:[e("div",{className:"flex items-center justify-between gap-2",children:[e("strong",{children:O}),e("div",{className:"flex items-center gap-2",children:[ve?e("span",{className:"tcp-badge-warn",children:"workflow context"}):null,e("span",{className:"tcp-badge-info",children:new Date(C.at).toLocaleTimeString()})]})]}),e("p",{className:"tcp-subtle mt-1 text-xs",children:ve?`run: ${String(C.data?.run_id||C.data?.runId||"n/a")}`:`session: ${String(C.data?.sessionID||C.data?.sessionId||"n/a")}`}),ve?e("p",{className:"tcp-subtle mt-1 text-xs",children:["kind: ",String(C.data?.kind||"context_run_event")," · seq:"," ",String(C.data?.seq||"-")]}):null,A?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:v=>{v.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open pack library"]}),z?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:v=>{v.stopPropagation(),ee(z)},children:[e("i",{"data-lucide":"download"}),"Install from path"]}):null,z&&k?e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:v=>{v.stopPropagation(),ce(C.data)},children:[e("i",{"data-lucide":"paperclip"}),"Install attachment"]}):null]}):null,ve?e("div",{className:"mt-2 flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:v=>{v.stopPropagation(),n("orchestrator")},children:[e("i",{"data-lucide":"workflow"}),"Open orchestrator"]}),e("button",{className:"tcp-btn h-7 px-2 text-xs",onClick:v=>{v.stopPropagation(),n("packs-detail")},children:[e("i",{"data-lucide":"package"}),"Open workflow lab"]})]}):null]},`${C.at}-${P}`)}):e(je,{text:"No events have arrived yet."})})]}),e(br,{open:!!x,onClose:()=>M(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()})]}),E?e("div",{className:"tcp-list-item",children:[e("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e("strong",{children:String(S.data?.run?.objective||E)}),e("span",{className:"tcp-badge-info",children:String(S.data?.run?.status||"unknown")})]}),e("div",{className:"tcp-subtle text-xs",children:["tasks:"," ",Array.isArray(W.data?.blackboard?.tasks)?W.data.blackboard.tasks.length:0," · ","artifacts:"," ",Array.isArray(W.data?.blackboard?.artifacts)?W.data.blackboard.artifacts.length:0]})]}):null,e("pre",{className:"tcp-code",children:aa(x.data)}),E?e("pre",{className:"tcp-code",children:aa({run:S.data?.run||null,blackboard:W.data?.blackboard||null})}):null]}):null})]})}function gp({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 fp({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(Me.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(gp,{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(Me.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 bp=new Set(["openai","openrouter","anthropic","ollama","groq","mistral","together","azure","bedrock","vertex","copilot","cohere"]),vp=[{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"]}],yp=["websearch","webfetch","webfetch_html","memory_search","memory_store","memory_list"];function _r(a){try{return new URL(a)}catch{return null}}function Yr(a){return String(a||"").trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"mcp-server"}function di(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 Yr(s)}function so(a){const t=_r(a);return t?String(t.hostname||"").toLowerCase().endsWith("composio.dev"):!1}function pn(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 wp(a){return a.map(t=>({key:String(t?.key||"").trim(),value:String(t?.value||"").trim()}))}function xp(a,t){const n={...a};for(const r of wp(t))!r.key||!r.value||(n[r.key]=r.value);return n}function kp({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()}`}:so(r)?{"x-api-key":s}:{Authorization:`Bearer ${s.replace(/^bearer\s+/i,"").trim()}`}}function Np(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>":so(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 _p(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 Sp(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 Ip(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 ui(){return{enabled_tools:[],disabled_tools:[],enabled_mcp_servers:[]}}function bn(a){return Array.from(new Set(a.map(t=>t.trim()).filter(Boolean)))}function mi(a){const t=a&&typeof a=="object"?a:{};return{enabled_tools:Array.isArray(t.enabled_tools)?bn(t.enabled_tools.map(n=>String(n))):[],disabled_tools:Array.isArray(t.disabled_tools)?bn(t.disabled_tools.map(n=>String(n))):[],enabled_mcp_servers:Array.isArray(t.enabled_mcp_servers)?bn(t.enabled_mcp_servers.map(n=>String(n))):[]}}function Cp(a,t){return a.disabled_tools.includes(t)?!1:a.enabled_tools.length===0||a.enabled_tools.includes(t)}function Ap(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?bn([...s,t]):[]}:{...a,disabled_tools:bn([...r,t]),enabled_tools:s.length>0?s.filter(c=>c!==t):s}}function Pp(a,t,n){const r=a.enabled_mcp_servers.filter(s=>s!==t);return{...a,enabled_mcp_servers:n?bn([...r,t]):r}}function io(a,t){return a!=="public_demo"?!0:yp.includes(t)}function Tp(a,t,n){return io(n,t)&&Cp(a,t)}function Rp(a){const t=String(a||"").split(",").map(n=>n.trim()).filter(Boolean);return t.length?t:["*"]}function Mp(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 qp(a,t){const n=String(a?.catalog_message||"").trim();return n||`Default model: ${t||"none"}`}function pi({client:a,api:t,toast:n,navigate:r,currentRoute:s,identity:c,themes:d,setTheme:u,themeId:p,refreshProviderStatus:N,refreshIdentityStatus:D}){const x=ca(),M=Rt(null),[E,S]=y({}),[W,I]=y(String(c?.botName||"Tandem")),[Q,ee]=y(String(c?.botAvatarUrl||"")),[ce,C]=y("Control Center"),[P,O]=y("providers"),[A,ve]=y("auto"),[z,k]=y(""),[v,te]=y(""),[H,Pe]=y("10000"),[$e,Le]=y(""),[re,pe]=y(""),[q,ge]=y(!1),[Te,Re]=y(!1),[se,Oe]=y(!1),[qe,He]=y("custom"),[Y,Ze]=y(""),[ne,Ae]=y(""),[St,oe]=y(""),[K,lt]=y(!0),[xt,rt]=y({}),[Et,Fe]=y({}),[Bt,At]=y(!1),[$t,We]=y(""),[ze,tt]=y(""),[be,Se]=y("none"),[Ve,de]=y(""),[dt,_]=y(""),[G,me]=y(""),[Ke,l]=y([]),[b,T]=y(!0),[R,$]=y(""),[Ye,Xe]=y("manual"),[Ot,Ft]=y(""),[Ie,Pt]=y(!1),[bt,ae]=y(!1),[Ne,h]=y(""),[U,J]=y(""),[F,X]=y(""),[we,Ue]=y("auto"),[st,vt]=y(""),[It,et]=y(""),[yt,Lt]=y(!0),[Ht,Ct]=y(!1),[Gt,kt]=y(!0),[Ge,da]=y(!1),[Ce,xe]=y(""),[ut,Qe]=y(""),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 w=a?.identity;return w?.patch?w.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||{},w=o?.aliases||{},ue=String(o?.canonicalName||o?.canonical_name||c?.botName||"Tandem").trim(),Ee=String(o?.avatarUrl||o?.avatar_url||c?.botAvatarUrl||"").trim(),ct=String(w?.controlPanel||w?.control_panel||"").trim();I(ue||"Tandem"),ee(Ee),C(ct||"Control Center")},[c?.botAvatarUrl,c?.botName,Kt.data]),fe(()=>{s==="mcp"&&O("mcp"),s==="channels"&&O("channels"),s==="bug-monitor"&&O("bug_monitor")},[s]);const Vt=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=B(()=>mt.data?.providers||{},[mt.data?.providers]),na=B(()=>Object.entries(ua).filter(([o])=>{const w=o.trim().toLowerCase();return w&&!bp.has(w)}).map(([o,w])=>({id:o,url:String(w?.url||"").trim(),model:String(w?.default_model||w?.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&&(ve(String(o.backend||"auto").trim()||"auto"),k(String(o.tandem_url||"").trim()),te(String(o.searxng_url||"").trim()),Pe(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,L]=y(null),he=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=>{L(o),n("ok","Browser smoke test passed."),await Je.refetch()},onError:o=>{L(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}),xn=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 w=>[w,mi(await t(`/api/engine/channels/${w}/tool-preferences`,{method:"GET"}).catch(()=>ui()))]));return Object.fromEntries(o)},refetchInterval:15e3}),Jn=ke({mutationFn:async({providerId:o,modelId:w})=>a.providers.setDefaults(o,w),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:w,modelId:ue,apiKey:Ee,makeDefault:ct})=>{const Tt=o.trim().toLowerCase(),Wt=w.trim(),sa=ue.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(F||"").trim()||null,provider_preference:String(we||"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:Ht,auto_comment_on_matched_open_issues:Gt,label_mode:"reporter_only"}})}),onSuccess:async()=>{n("ok","Bug Monitor settings saved."),await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})])},onError:o=>{const w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),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 w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),$a=ke({mutationFn:async({draftId:o,decision:w})=>t(`/api/engine/bug-monitor/drafts/${encodeURIComponent(o)}/${w}`,{method:"POST",body:JSON.stringify({reason:`${w}d from control panel settings`})}),onSuccess:async(o,w)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor draft ${w.decision==="approve"?"approved":"denied"}.`)},onError:o=>{const w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),rn=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 w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),Ha=ke({mutationFn:async({action:o})=>t(`/api/engine/bug-monitor/${o}`,{method:"POST"}),onSuccess:async(o,w)=>{await Promise.all([x.invalidateQueries({queryKey:["settings","bug-monitor"]})]),n("ok",`Bug Monitor ${w.action==="pause"?"paused":"resumed"}.`)},onError:o=>{const w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),sn=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 w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),on=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 w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),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 w=o instanceof Error?o.message:String(o?.detail||o?.error||o);n("err",w)}}),Hn=ke({mutationFn:({providerId:o,apiKey:w})=>a.providers.setApiKey(o,w),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(""),pe(""),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 w=(Kt.data?.identity?.bot||{})?.aliases||{},ue=String(W||"").trim();if(!ue)throw new Error("Bot name is required.");const Ee=String(Q||"").trim(),ct=String(ce||"").trim();return ba({identity:{bot:{canonical_name:ue,avatar_url:Ee||null,aliases:{...w,control_panel:ct||void 0}}}})},onSuccess:async()=>{n("ok","Identity updated."),await Promise.all([x.invalidateQueries({queryKey:["settings","identity"]}),D()])},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:w})=>"reset"in w?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(w)}),onSuccess:async(o,w)=>{await x.invalidateQueries({queryKey:["settings","channels","tool-preferences"]}),n("ok",`Saved ${w.channel} channel tool scope.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),kn=ke({mutationFn:async o=>{const w=xt[o];if(!w)throw new Error(`No draft found for ${o}.`);const ue={allowed_users:Rp(w.allowedUsers),mention_only:!!w.mentionOnly,security_profile:String(w.securityProfile||"operator").trim()||"operator"},Ee=String(w.botToken||"").trim();if(Ee&&(ue.bot_token=Ee),o==="telegram"&&(ue.style_profile=String(w.styleProfile||"default").trim()||"default"),o==="discord"&&(ue.guild_id=String(w.guildId||"").trim()),o==="slack"){const ct=String(w.channelId||"").trim();if(!ct&&!Ia.data?.slack?.channel_id)throw new Error("Slack channel ID is required.");ct&&(ue.channel_id=ct)}return a.channels.put(o,ue)},onSuccess:async(o,w)=>{n("ok",`Saved ${w} channel settings.`),Fe(ue=>({...ue,[w]:null})),rt(ue=>({...ue,[w]:{...ue[w],botToken:""}})),await Ga()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),Nn=ke({mutationFn:async o=>a.channels.delete(o),onSuccess:async(o,w)=>{n("ok",`Removed ${w} channel settings.`),Fe(ue=>({...ue,[w]:null})),rt(ue=>({...ue,[w]:Fr(w,null)})),await Ga()},onError:o=>n("err",o instanceof Error?o.message:String(o))}),_n=ke({mutationFn:async o=>{const w=xt[o],ue={bot_token:String(w?.botToken||"").trim()||void 0};return a.channels.verify(o,ue)},onSuccess:(o,w)=>{Fe(ue=>({...ue,[w]:o})),n("ok",`${w} 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:w})=>{if(!w)throw new Error("No MCP server selected.");if(o==="connect")return a.mcp.connect(w.name);if(o==="disconnect")return a.mcp.disconnect(w.name);if(o==="refresh")return a.mcp.refresh(w.name);if(o==="toggle-enabled")return a.mcp.setEnabled(w.name,!w.enabled);if(o==="delete")return t(`/api/engine/mcp/${encodeURIComponent(w.name)}`,{method:"DELETE"});throw new Error(`Unknown action: ${o}`)},onSuccess:async(o,w)=>{await Ea(),w.action==="connect"&&n("ok",`Connected ${w.server?.name}.`),w.action==="disconnect"&&n("ok",`Disconnected ${w.server?.name}.`),w.action==="refresh"&&n("ok",`Refreshed ${w.server?.name}.`),w.action==="toggle-enabled"&&n("ok",`${w.server?.enabled?"Disabled":"Enabled"} ${w.server?.name}.`),w.action==="delete"&&n("ok",`Deleted ${w.server?.name}.`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),m=ke({mutationFn:async()=>{const o=String(ze||"").trim(),w=di(o),ue=Yr($t||w);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=kp({authMode:be,token:Ve,customHeader:dt,transport:o}),ct=xp(Ee,Ke),Tt=String(G||"").trim();pn(o)&&Tt&&(ct["X-MCP-Toolsets"]=Tt);const Wt={name:ue,transport:o,enabled:!0};Object.keys(ct).length&&(Wt.headers=ct);const sa=String(R||"").trim();if(sa&&sa!==ue&&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"),de(""),_(""),me(""),l([]),T(!0),$(""),n("ok",`Saved MCP "${o}".`)},onError:o=>n("err",o instanceof Error?o.message:String(o))}),j=o=>{if(!o)return;if(o.size>10*1024*1024){n("err","Avatar image is too large (max 10 MB).");return}const w=new FileReader;w.onload=()=>{const ue=typeof w.result=="string"?w.result:"";if(!ue){n("err","Failed to read avatar image.");return}ee(ue)},w.onerror=()=>n("err","Failed to read avatar image."),w.readAsDataURL(o)},Z=Array.isArray(Vt.data?.all)?Vt.data.all:[];fe(()=>{const o=na.find(w=>w.isDefault)||na[0];o&&(He(w=>w.trim()&&w.trim().toLowerCase()!=="custom"?w:o.id),Ze(w=>w.trim()?w:o.url),Ae(w=>w.trim()?w:o.model),lt(String(mt.data?.default||"").trim().toLowerCase()===o.id.trim().toLowerCase()))},[na,mt.data?.default]);const le=B(()=>_p(Be.data),[Be.data]),nt=B(()=>Sp(it.data),[it.data]),Dt=B(()=>Ip(_t.data?.catalog||_t.data||null),[_t.data]),Na=B(()=>new Set(le.map(o=>o.name.toLowerCase())),[le]),_a=B(()=>{const o=String(Ot||"").trim().toLowerCase();return Dt.servers.filter(w=>o?w.name.toLowerCase().includes(o)||w.slug.toLowerCase().includes(o)||w.transportUrl.toLowerCase().includes(o):!0).slice(0,36)},[Dt.servers,Ot]),ha=le.filter(o=>o.connected).length,_e=B(()=>oa.data?.status||{},[oa.data]),ra=B(()=>Array.isArray(ka.data?.drafts)?ka.data.drafts||[]:[],[ka.data]),Ca=B(()=>Array.isArray(Zt.data?.incidents)?Zt.data.incidents||[]:[],[Zt.data]),ln=B(()=>Array.isArray(va.data?.posts)?va.data.posts||[]:[],[va.data]),Sa=B(()=>le.find(o=>o.name.toLowerCase()===String(F||"").trim().toLowerCase())||null,[F,le]),jt=B(()=>Z.find(o=>String(o?.id||"").toLowerCase()===String(st||"").trim().toLowerCase())||null,[st,Z]),Sn=B(()=>{const o=jt&&typeof jt=="object"?jt.models||{}:{};return Object.keys(o).sort((w,ue)=>w.localeCompare(ue))},[jt]),cn=Array.isArray(Je.data?.blocking_issues)?Je.data?.blocking_issues||[]:[],In=Array.isArray(Je.data?.recommendations)?Je.data?.recommendations||[]:[],Vn=Array.isArray(Je.data?.install_hints)?Je.data?.install_hints||[]:[],Cn=["telegram","discord","slack"],Sr=Cn.filter(o=>!!xn.data?.[o]?.connected).length,Ir=Array.isArray(Ma.data?.directories)?Ma.data.directories:[],Yn=String(ut||"").trim().toLowerCase(),fs=B(()=>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),ae(!!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(w=>{const ue={...w};for(const Ee of Cn)ue[Ee]||(ue[Ee]=Fr(Ee,o[Ee]));return ue})},[Ia.data]);const bs=(o,w)=>{const ue=String(w||"").trim();ue&&Jn.mutate({providerId:o,modelId:ue})},Zn=o=>{if(o){Xe("manual");const w=o.headers&&typeof o.headers=="object"?o.headers:{},ue=Object.keys(w),Ee=ue.find(gt=>String(gt).toLowerCase()==="authorization"),ct=ue.find(gt=>String(gt).toLowerCase()==="x-api-key"),Tt=ue.find(gt=>String(gt).toLowerCase()==="x-mcp-toolsets"),Wt=ue.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(w[ct]||"").trim()):Ee?(sa="bearer",ht=String(w[Ee]||"").replace(/^bearer\s+/i,"").trim()):Wt.length===1&&(sa="custom",pt=Wt[0],ht=String(w[Wt[0]]||"").trim()),$(o.name),We(o.name),tt(o.transport||""),T(o.connected||!1),me(Tt?String(w[Tt]||"").trim():pn(o.transport||"")?"default":""),Se(sa),_(pt),de(ht);const Da=new Set([Ee,ct,Tt,sa==="custom"?pt:""].filter(Boolean).map(gt=>String(gt).toLowerCase()));l(ue.filter(gt=>!Da.has(String(gt).toLowerCase())).map(gt=>({key:gt,value:String(w[gt]||"").trim()})))}else Xe("catalog"),$(""),We(""),tt(""),Se("none"),_(""),de(""),me(""),l([]),T(!0);At(!0)},vs=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.")},ys=[{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"}],co=B(()=>Np(be,Ve,dt,ze),[be,dt,Ve,ze]),uo=B(()=>pn(ze),[ze]);return fe(()=>{const o=M.current;o?xa(o):xa()},[P,Ie,bt,Ne,F,_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,sn.isPending,rn.isPending,Qa.isPending,i.isPending,ea.isPending]),e(nn,{className:"grid gap-4",children:e("div",{ref:M,className:"grid gap-4",children:[e("div",{className:"tcp-settings-tabs",children:ys.map(o=>e("button",{type:"button",className:`tcp-settings-tab tcp-settings-tab-underline ${P===o.id?"active":""}`,onClick:()=>O(o.id),children:[e("i",{"data-lucide":o.icon}),o.label]},o.id))}),e(Dn,{main:e(Mc,{className:"grid gap-4",children:[P==="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(ye,{tone:String(mt.data?.default||"").trim()?"ok":"warn",children:["Default: ",String(mt.data?.default||"none")]}),e(ye,{tone:"info",children:[String(Vt.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(ye,{tone:na.length?"ok":"info",children:[na.length," configured"]})]}),e("form",{className:"grid gap-3",onSubmit:o=>{o.preventDefault(),pa.mutate({providerId:qe,url:Y,modelId:ne,apiKey:St,makeDefault:K})},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:qe,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:ne,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:K,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(ye,{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(ye,{tone:"info",children:[String(Vt.data?.connected?.length||0)," connected"]})]})}),e(Mt,{initial:!1,children:se?e(Me.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 w=String(o?.id||""),ue=Object.keys(o?.models||{}),Ee=String(mt.data?.providers?.[w]?.default_model||ue[0]||""),ct=String(E[w]??Ee).trim(),Tt=ct.toLowerCase(),Wt=ue.filter(gt=>Tt?gt.toLowerCase().includes(Tt):!0).slice(0,80),sa=Mp(o,ue.length),pt=qp(o,Ee),ht=Ii[w]||null,Da=String(ht?.keyUrl||"").trim();return e(Me.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:w}),e("div",{className:"tcp-subtle text-xs",children:pt})]}),e(ye,{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(),bs(w,ct)},children:[e("div",{className:"flex gap-2",children:[e("input",{className:"tcp-input",value:ct,placeholder:`Type model id for ${w}`,onInput:gt=>S(Aa=>({...Aa,[w]: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:()=>{S(Aa=>({...Aa,[w]:gt})),bs(w,gt)},children:gt},gt)):e("div",{className:"tcp-subtle px-2 py-1 text-xs",children:ue.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"),ws=String(Aa?.value||"").trim();ws&&(Hn.mutate({providerId:w,apiKey:ws}),Aa.value="")},className:"flex gap-2",children:[e("input",{name:"apiKey",className:"tcp-input",placeholder:String(ht?.placeholder||`Set ${w} API key`)}),e("button",{className:"tcp-btn",type:"submit",children:[e("i",{"data-lucide":"save"}),"Save"]})]})]})]},w)}):e(je,{text:"No providers were detected from the engine catalog."})}):null})]})}):null,P==="search"?e(ot,{title:"Web Search",subtitle:"Configure the engine's `websearch` backend and provider keys.",actions:e(wa,{children:[e(ye,{tone:Nt.data?.settings?.has_brave_key?"ok":"warn",children:["Brave"," ",Nt.data?.settings?.has_brave_key?"configured":"missing"]}),e(ye,{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:A,tandem_url:z,searxng_url:v,timeout_ms:Number.parseInt(H||"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:A,onChange:o=>ve(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:H,onInput:o=>Pe(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:z,onInput:o=>k(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:v,onInput:o=>te(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(ye,{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:A,tandem_url:z,searxng_url:v,timeout_ms:Number.parseInt(H||"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:A,tandem_url:z,searxng_url:v,timeout_ms:Number.parseInt(H||"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(ye,{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=>pe(o.target.value)}),e("div",{className:"flex flex-wrap gap-2",children:[e("button",{className:"tcp-btn",onClick:()=>ea.mutate({backend:A,tandem_url:z,searxng_url:v,timeout_ms:Number.parseInt(H||"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:A,tandem_url:z,searxng_url:v,timeout_ms:Number.parseInt(H||"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,P==="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:()=>D().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:W||"Bot",className:"block h-full w-full object-cover"}):e("i",{"data-lucide":"cpu"})}),e("div",{children:[e("div",{className:"font-semibold",children:W||"Tandem"}),e("div",{className:"tcp-subtle text-xs",children:ce||"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:()=>ee(""),children:e("i",{"data-lucide":"trash-2"})})]})]})}),e("input",{className:"tcp-input",value:W,onInput:o=>I(o.target.value),placeholder:"Bot name"}),e("input",{className:"tcp-input",value:ce,onInput:o=>C(o.target.value),placeholder:"Control panel alias"}),e("input",{className:"tcp-input",value:Q,onInput:o=>ee(o.target.value),placeholder:"Avatar URL or data URL"}),e("input",{ref:qt,type:"file",accept:"image/*",className:"hidden",onChange:o=>j(o.target.files?.[0]||null)})]})}):null,P==="theme"?e(ot,{title:"Theme studio",subtitle:"Preview tiles with richer feedback and immediate switching.",children:e(fp,{themes:d,themeId:p,onChange:u})}):null,P==="channels"?e(ot,{title:"Channel connections",subtitle:"Telegram, Discord, and Slack delivery setup and live listener status.",actions:e(wa,{children:[e(ye,{tone:Sr?"ok":"warn",children:[Sr,"/",Cn.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:Cn.map(o=>{const w=Ia.data?.[o]||{},ue=xn.data?.[o]||{},Ee=xt[o]||Fr(o,w),ct=Et[o],Tt=mi(zn.data?.[o]||ui()),Wt=Ee.securityProfile==="public_demo",sa=!!w?.has_token||!!(Array.isArray(w?.allowed_users)&&w.allowed_users.length)||!!String(w?.guild_id||"").trim()||!!String(w?.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(ye,{tone:ue.connected?"ok":"warn",children:ue.connected?"Connected":ue.enabled?"Configured":"Disconnected"}),e(ye,{tone:w.has_token?"info":"warn",children:w.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:w.has_token?String(w.token_masked||"********"):`Paste ${o} bot token`,value:Ee.botToken,onInput:pt=>rt(ht=>({...ht,[o]:{...Ee,botToken:pt.target.value}}))}),w.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(ue.active_sessions||0),ue.last_error?` · Last error: ${ue.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:[vp.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=io(Ee.securityProfile,ht),gt=Tp(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:Ap(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:Pp(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:kn.isPending,onClick:()=>kn.mutate(o),children:[e("i",{"data-lucide":"save"}),"Save"]}),o==="discord"?e("button",{className:"tcp-btn",disabled:_n.isPending,onClick:()=>_n.mutate("discord"),children:[e("i",{"data-lucide":"shield-check"}),"Verify"]}):null,e("button",{className:"tcp-btn-danger",disabled:Nn.isPending||!sa,onClick:()=>Nn.mutate(o),children:[e("i",{"data-lucide":"trash-2"}),"Remove"]})]})]},o)})})}):null,P==="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(ye,{tone:ha?"ok":"warn",children:[ha,"/",le.length," connected"]}),e(ye,{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 w=Object.keys(o.headers||{}).filter(Boolean),ue=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(ye,{tone:o.connected?"ok":"warn",children:o.connected?"Connected":"Disconnected"}),e(ye,{tone:o.enabled?"info":"warn",children:o.enabled?"Enabled":"Disabled"}),e(ye,{tone:"info",children:[ue," 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:w.length?`Auth headers: ${w.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,P==="bug_monitor"?e(ot,{title:"Bug monitor",actions:e("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[e(ye,{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(ye,{tone:"warn",children:"Paused"}):null,e(ye,{tone:"info",children:[Number(_e.runtime?.pending_incidents||0)," incidents"]}),e(ye,{tone:"info",children:[Number(_e.pending_drafts||0)," pending drafts"]}),e(ye,{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:()=>{vs()},children:e("i",{"data-lucide":"copy"})}),e("button",{className:"tcp-icon-btn",title:"Open GitHub MCP guide","aria-label":"Open GitHub MCP guide",onClick:()=>Re(!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();xe(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:F,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:we,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 w=o.target.value;vt(w),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:Sn.map(o=>e("option",{value:o},o))}),e("div",{className:"tcp-subtle text-xs",children:st?Sn.length?`${Sn.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&&!Ht?"ring-1 ring-emerald-400/40":""}`,onClick:()=>{Lt(o=>!o),Ht&&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 ${Ht?"ring-1 ring-amber-400/40":""}`,onClick:()=>{Ct(o=>{const w=!o;return w&&Lt(!1),w})},children:[e("div",{className:"font-medium",children:"Require approval"}),e("div",{className:"tcp-subtle text-xs",children:Ht?"New drafts wait for a manual publish click.":"Approval gate disabled."})]}),e("button",{type:"button",className:`tcp-list-item text-left ${Gt?"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:Gt?"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:()=>Re(!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:()=>{vs()},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,w)=>e("div",{children:[String(o.capability_id||"unknown"),":"," ",String(o.tool_name||"unresolved")]},`${o.capability_id||"cap"}-${w}`))}):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,w)=>e("div",{children:[String(o.capability_id||"unknown"),":"," ",String(o.binding_tool_name||"unknown"),o.matched?" · matched":" · candidate"]},`${o.capability_id||"candidate"}-${w}`))}):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:"," ",Ht?"Manual publish":yt?"Auto-create":"Internal draft only"]}),e("div",{children:["Matched open issues:"," ",Gt?"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(ye,{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:sn.isPending,onClick:()=>sn.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(ye,{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:on.isPending,onClick:()=>on.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:rn.isPending,onClick:()=>rn.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"}),ln.length?e("div",{className:"grid gap-2",children:ln.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(ye,{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,P==="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:()=>he.mutate(),disabled:he.isPending,children:[e("i",{"data-lucide":"download"}),he.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"})]})]}),cn.length?e("div",{className:"mt-3 grid gap-2",children:cn.map((o,w)=>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"}-${w}`))}):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(Vt.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, ",Cn.length," available"]})]})]})}),e(ot,{title:"Quick access",subtitle:"Jump straight to the section you need.",children:e("div",{className:"grid gap-2",children:ys.map(o=>e("button",{className:"tcp-list-item flex items-center justify-between text-left",onClick:()=>O(o.id),children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":o.icon}),o.label]}),P===o.id?e(ye,{tone:"ok",children:"open"}):null]},o.id))})})]})}),e(br,{open:Te,onClose:()=>Re(!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(Me.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(Me.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&&xe(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:fs.length?fs.map(o=>e("button",{className:"tcp-list-item mb-1 w-full text-left",onClick:()=>xe(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:()=>he.mutate(),disabled:he.isPending,children:[e("i",{"data-lucide":"download"}),he.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:[cn.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Blocking issues"}),cn.map((o,w)=>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"}-${w}`))]}):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,In.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Recommendations"}),In.map((o,w)=>e("div",{className:"tcp-list-item text-sm",children:o},`browser-recommendation-${w}`))]}):null,Vn.length?e("div",{className:"grid gap-2",children:[e("div",{className:"text-sm font-medium",children:"Install hints"}),Vn.map((o,w)=>e("div",{className:"tcp-list-item text-sm",children:o},`browser-install-hint-${w}`))]}):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(Me.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(Me.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 w=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(ye,{tone:"info",children:[o.toolCount," tools"]}),e(ye,{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 ue=o.transportUrl,Ee=Yr(o.serverConfigName||o.slug||o.name);We(Ee),tt(ue),Se(Ee==="github"||pn(ue)?"bearer":"none"),me(Ee==="github"||pn(ue)?"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,w?e(ye,{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 w=o.target.value;if(tt(w),pn(w)&&!String(G||"").trim()&&me("default"),!String($t||"").trim()||$t==="mcp-server"){const ue=di(w);ue&&We(ue)}},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=>_(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=>de(o.target.value),placeholder:"token"}),e("div",{className:"tcp-subtle text-xs",children:co})]}),uo?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=>me(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,w)=>e("div",{className:"grid gap-2 md:grid-cols-[1fr_1fr_auto]",children:[e("input",{className:"tcp-input",value:o.key,onInput:ue=>l(Ee=>Ee.map((ct,Tt)=>Tt===w?{...ct,key:ue.target.value}:ct)),placeholder:"Header name"}),e("input",{className:"tcp-input",value:o.value,onInput:ue=>l(Ee=>Ee.map((ct,Tt)=>Tt===w?{...ct,value:ue.target.value}:ct)),placeholder:"Header value"}),e("button",{type:"button",className:"tcp-btn",onClick:()=>l(ue=>ue.filter((Ee,ct)=>ct!==w)),children:"Remove"})]},`mcp-header-${w}`))}):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 $p({routeId:a,pageProps:t}){switch(es(a)){case"chat":return e(kd,{...t});case"studio":return e(wu,{...t});case"automations":case"packs":case"teams":return e(Cm,{...t});case"coding":return e(Om,{...t});case"agents":return e(oi,{...t});case"channels":return e(Em,{...t});case"mcp":return e(pi,{...t});case"packs-detail":return e(Um,{...t});case"orchestrator":return e(Zm,{...t});case"files":return e(tp,{...t});case"memory":return e(np,{...t});case"teams-detail":return e(oi,{...t});case"feed":return e(hp,{...t});case"settings":return e(pi,{...t});default:return e(Hc,{...t})}}const Op={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 Ep({identity:a,currentRoute:t,providerLocked:n,navRoutes:r,onNavigate:s,onPaletteOpen:c,onThemeCycle:d,onLogout:u,statusBar:p,routeKey:N,children:D,providerGate:x}){const[M,E]=y(!1),[S,W]=y(!1),I=String(a.botAvatarUrl||"").trim(),Q=ki();fe(()=>{E(!1)},[t]),fe(()=>{try{xa()}catch{}},[t,M,p.bugMonitor?.enabled,p.bugMonitor?.monitoringActive,p.bugMonitor?.paused,p.bugMonitor?.pendingIncidents,p.bugMonitor?.blocked]),fe(()=>{W(!1)},[I]);const ee=Op[t]||{title:String(r.find(([z])=>z===t)?.[1]||"Control Panel"),subtitle:"Desktop-inspired operations UI for Tandem."},ce=B(()=>r.find(([z])=>z===t)||r[0],[t,r]),C=B(()=>{const z=p.bugMonitor;return z?.enabled?z.blocked?{toneClass:"blocked",label:"Bug Monitor blocked",shortLabel:"Blocked"}:z.paused?{toneClass:"paused",label:"Bug Monitor paused",shortLabel:"Paused"}:z.pendingIncidents>0?{toneClass:"incidents",label:`Bug Monitor incidents: ${z.pendingIncidents}`,shortLabel:`${z.pendingIncidents} incident${z.pendingIncidents===1?"":"s"}`}:z.monitoringActive?{toneClass:"watching",label:"Bug Monitor watching",shortLabel:"Watching"}:{toneClass:"ready",label:"Bug Monitor ready",shortLabel:"Ready"}:null},[p.bugMonitor]),P=()=>I&&!S?e("img",{src:I,alt:a.botName,className:"block h-full w-full object-cover",onError:()=>W(!0)}):e("span",{className:"text-sm font-semibold uppercase",children:String(a.botName||"T").trim().slice(0,1)||"T"}),O=()=>r.map(([z,k,v])=>{const te=t===z,H=n&&z!=="settings";return e("button",{type:"button",title:k,disabled:H,className:`tcp-rail-icon ${te?"active":""} ${H?"locked":""}`,onClick:()=>s(z),children:[te?e(Me.span,{layoutId:"tcp-icon-indicator",className:"tcp-rail-icon-indicator"}):null,e("i",{"data-lucide":v})]},z)}),A=(z=!1)=>r.map(([k,v,te])=>{const H=t===k,Pe=n&&k!=="settings";return e("button",{type:"button",disabled:Pe,className:`tcp-context-link ${H?"active":""} ${Pe?"locked":""}`,onClick:()=>{s(k),z&&E(!1)},children:[e("span",{className:"inline-flex items-center gap-2",children:[e("i",{"data-lucide":te}),e("span",{children:v})]}),H?e("span",{className:"tcp-context-link-dot"}):null]},k)}),ve=(z=!1)=>e(la,{children:[z?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:P()}),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 ${z?"":"xl:hidden"}`.trim(),children:[e("div",{className:"tcp-context-section-label",children:"Navigation"}),e("nav",{className:"grid gap-1",children:A(z)})]}),z?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"})]}),C?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 ${C.toneClass}`,title:p.bugMonitor?.lastError?`${C.label}: ${p.bugMonitor.lastError}`:C.label,onClick:()=>{s("bug-monitor"),z&&E(!1)},children:[e("i",{"data-lucide":"bug-play"}),e("span",{className:"tcp-bug-monitor-dot","aria-hidden":"true"}),e("span",{children:C.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(),z&&E(!1)},children:[e("i",{"data-lucide":"search"}),"Command palette"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{d(),z&&E(!1)},children:[e("i",{"data-lucide":"paint-bucket"}),"Cycle theme"]}),e("button",{type:"button",className:"tcp-btn w-full justify-start",onClick:()=>{u(),z&&E(!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:P()})}),e("nav",{className:"tcp-rail-nav",children:O()}),e("div",{className:"tcp-rail-footer",children:[e($n,{title:"Command palette",onClick:c,children:e("i",{"data-lucide":"search"})}),e($n,{title:"Cycle theme",onClick:d,children:e("i",{"data-lucide":"paint-bucket"})}),e($n,{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:ve(!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:()=>E(!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:ee.title}),e("div",{className:"tcp-subtle truncate text-xs",children:ce?.[1]||ee.subtitle})]}),C?e("button",{type:"button",className:`tcp-bug-monitor-pill ${C.toneClass}`,title:p.bugMonitor?.lastError?`${C.label}: ${p.bugMonitor.lastError}`:C.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:ee.title}),e("p",{className:"tcp-subtle mt-1 max-w-2xl",children:ee.subtitle})]}),e("div",{className:"tcp-topbar-status",children:[C?e("button",{type:"button",className:`tcp-bug-monitor-pill ${C.toneClass}`,title:p.bugMonitor?.lastError?`${C.label}: ${p.bugMonitor.lastError}`:C.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:C.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(Me.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:D},N)})]}),e(Mt,{children:M?e(Me.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:()=>E(!1)}),e(Me.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:ee.title})]}),e($n,{title:"Close",onClick:()=>E(!1),children:e("i",{"data-lucide":"x"})})]}),ve(!0)]})]}):null}),e(Mt,{children:x||null})]})}function oo(a){const t=String(a||"").trim().toLowerCase();return!!t&&t!=="ollama"&&t!=="local"}function Dp(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&&!oo(n);return r(a[n])||r(a.providers?.[n])}function jp(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(D=>String(D||"").trim().toLowerCase())),p=Dp(n,r),N=!!r&&!!c&&u.has(r.toLowerCase())&&(!oo(r)||p);return{ready:N,defaultProvider:r,defaultModel:c,connected:[...u],error:"",needsOnboarding:!N}}const gs="tandem_control_panel_token";function hi(){try{return localStorage.getItem(gs)||""}catch{return""}}function Up(a){try{localStorage.setItem(gs,a)}catch{}}function Bp(){try{localStorage.removeItem(gs)}catch{}}function Fp(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 jp(n,r,s)}catch(n){return{ready:!1,defaultProvider:"",defaultModel:"",connected:[],error:n instanceof Error?n.message:String(n),needsOnboarding:!0}}}})}function Lp(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 Qt("/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 Kp(a){return V({queryKey:["bug-monitor","status"],enabled:a,refetchInterval:a?1e4:!1,queryFn:async()=>{try{return await Qt("/api/engine/bug-monitor/status",{method:"GET"})}catch{return null}}})}function Wp(){const a=ca(),{toast:t}=Jc(),{route:n,navigate:r}=Wc(),[s,c]=y(Ac()),[d,u]=y(!1),[p,N]=y(!1),D=Rt(!1);fe(()=>{Pc(s)},[s]);const M=V({queryKey:["auth","me"],retry:!1,refetchInterval:3e4,queryFn:()=>Qt("/api/auth/me",{method:"GET"})}).isSuccess;fe(()=>{try{xa()}catch{}},[M,n]);const E=B(()=>M?new nc({baseUrl:"/api/engine",token:"session"}):null,[M]),S=Fp(E,M),W=Lp(E,M),I=Li(M),Q=Jd(M),ee=Kp(M),ce=ke({mutationFn:async({token:qe})=>{await Qt("/api/auth/login",{method:"POST",body:JSON.stringify({token:qe})})},onSuccess:(qe,He)=>{He.remember?Up(He.token):Bp(),a.invalidateQueries({queryKey:["auth","me"]}),t("ok","Signed in."),r("dashboard")},onError:qe=>{t("err",qe instanceof Error?qe.message:String(qe))}});fe(()=>{if(M||ce.isPending||D.current)return;const qe=hi().trim();if(!qe){D.current=!0;return}D.current=!0,ce.mutate({token:qe,remember:!0})},[M,ce]);const C=ft(async()=>{await Qt("/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]),P=B(()=>new Set(["chat","studio","agents","orchestrator","teams"]),[]),O=!!S.data?.needsOnboarding,A=M&&O;fe(()=>{if(!A){N(!1);return}P.has(n)&&(r("settings"),p||(N(!0),t("info","Set provider + default model first to unlock the control panel.")))},[P,r,p,A,n,t]);const ve=A&&P.has(n)?"settings":n,z=ft(async()=>{await a.invalidateQueries({queryKey:["provider","status"]})},[a]),k=ft(async()=>{await a.invalidateQueries({queryKey:["identity"]})},[a]),v=ft(qe=>{const He=Tc(qe);return c(He.id),He},[c]),te=W.data||{botName:"Tandem",botAvatarUrl:"",controlPanelName:"Tandem Control Panel"},H={client:E,api:Qt,toast:t,navigate:r,currentRoute:ve,providerStatus:{ready:!!S.data?.ready,defaultProvider:S.data?.defaultProvider||"",defaultModel:S.data?.defaultModel||"",connected:S.data?.connected||[],error:S.data?.error||"",needsOnboarding:!!S.data?.needsOnboarding},identity:te,refreshProviderStatus:z,refreshIdentityStatus:k,providerHints:Ii,themes:hn,setTheme:v,themeId:s},Pe=B(()=>{const qe=Ci.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 Qt("/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[...qe,...He]},[r,t]);if(Dc(()=>u(qe=>!qe)),!M)return e(Ec,{loginMutation:ce,savedToken:hi(),controlPanelName:te.controlPanelName,onCheckEngine:async()=>{const qe=await Qt("/api/system/health");return`Engine check: ${qe?.engine?.ready||qe?.engine?.healthy?"healthy":"unhealthy"} at ${qe?.engineUrl||"n/a"}`}});const $e=S.data?.ready?"tcp-badge-ok":"tcp-badge-warn",Le=S.data?.ready?`${S.data?.defaultProvider||"none"}/${S.data?.defaultModel||"none"}`:"provider setup required",re=ee.data||null,pe=!!re?.config?.enabled,q=Number(re?.runtime?.pending_incidents||0),ge=!!re?.runtime?.monitoring_active,Te=!!re?.runtime?.paused,Re=!!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(Ep,{identity:te,currentRoute:ve,providerLocked:A,navRoutes:Bc,onNavigate:r,onPaletteOpen:()=>u(!0),onThemeCycle:()=>v(Cc(s)),onLogout:C,statusBar:{engineHealthy:!!(I.data?.engine?.ready||I.data?.engine?.healthy),providerBadge:$e,providerText:Le,activeRuns:["planning","awaiting_approval","running"].includes(String(Q.data?.status||"").toLowerCase())?1:0,bugMonitor:pe?{enabled:!0,monitoringActive:ge,paused:Te,pendingIncidents:q,blocked:!Re,lastError:ge&&!se&&Oe?`Watching locally only. ${Oe}`:Oe}:null},routeKey:ve,providerGate:A&&ve!=="settings"?e(Me.div,{className:"tcp-confirm-overlay",initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},children:e(Me.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($p,{routeId:ve,pageProps:H})}),e(jc,{open:d,onClose:()=>u(!1),actions:Pe})]})}function zp(){return e(zc,{children:e(Wp,{})})}const Jp=new jl({defaultOptions:{queries:{retry:1,staleTime:5e3,refetchOnWindowFocus:!1}}}),lo=document.getElementById("app");if(!lo)throw new Error("Missing #app host");go(lo).render(e(fo,{children:e(vo,{client:Jp,children:e(zp,{})})}));
|